Refactoring

This commit is contained in:
stilmaniac 2020-06-26 23:46:13 +03:00
parent 2b541fde2c
commit 0c047fbaa8
5 changed files with 113 additions and 126 deletions

3
.gitignore vendored
View file

@ -1,2 +1,3 @@
env/ env/
.ini *.ini
__pycache__/

View file

@ -1,16 +0,0 @@
astroid==2.4.2
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
prompt-toolkit==1.0.14
pyconfigstore3==1.0.1
pyfiglet==0.8.post1
Pygments==2.6.1
PyInquirer==1.0.3
pylint==2.5.3
regex==2020.6.8
six==1.15.0
termcolor==1.1.0
toml==0.10.1
wcwidth==0.2.5
wrapt==1.12.1

0
src/__init__.py Normal file
View file

View file

@ -6,8 +6,6 @@ from pyconfigstore import ConfigStore
from PyInquirer import (Token, ValidationError, Validator, print_json, prompt, from PyInquirer import (Token, ValidationError, Validator, print_json, prompt,
style_from_dict) style_from_dict)
# from main import SteamGifts
try: try:
import colorama import colorama
colorama.init() colorama.init()
@ -56,7 +54,8 @@ def ask(type, name, message, validator=None, choices=[]):
return answers return answers
def main(): def run():
from main import SteamGifts as SG
def askCookie(): def askCookie():
cookie = ask(type='input', cookie = ask(type='input',
@ -75,12 +74,14 @@ def main():
config.read('config.ini') config.read('config.ini')
if not config['DEFAULT'].get('cookie'): if not config['DEFAULT'].get('cookie'):
cookie = askCookie() cookie = askCookie()
else:
re_enter_cookie = ask(type='confirm', re_enter_cookie = ask(type='confirm',
name='reenter', name='reenter',
message='Do you want to enter new cookie?')['reenter'] message='Do you want to enter new cookie?')['reenter']
if re_enter_cookie: if re_enter_cookie:
cookie = askCookie() cookie = askCookie()
else:
cookie = config['DEFAULT'].get('cookie')
gift_type = ask(type='list', gift_type = ask(type='list',
name='gift_type', name='gift_type',
@ -94,8 +95,9 @@ def main():
'New' 'New'
])['gift_type'] ])['gift_type']
# s = SteamGifts(cookie, gift_type) s = SG(cookie, gift_type)
# s.start() s.start()
if __name__ == '__main__': if __name__ == '__main__':
main() run()

View file

@ -4,129 +4,129 @@ import requests
import json import json
import threading import threading
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from time import sleep from time import sleep
from random import randint from random import randint
from requests import RequestException from requests import RequestException
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
CONFIG_DEFAULT = { from cli import log
'cookie': 'Paste you cookie here',
'sleeptime': 900
class SteamGifts:
def __init__(self, cookie, gifts_type):
self.cookie = {
'PHPSESSID': cookie
}
self.gifts_type = gifts_type
self.base = "https://www.steamgifts.com"
self.session = requests.Session()
self.filter_url = {
'All': "search?page=%d",
'Wishlist': "search?page=%d&type=wishlist",
'Recommended': "search?page=%d&type=recommended",
'Copies': "search?page=%d&copy_min=2",
'DLC': "search?page=%d&dlc=true",
'New': "search?page=%d&type=new"
} }
def exitMessage(msg): def requests_retry_session(
print(msg) self,
input() retries=5,
sys.exit() backoff_factor=0.3
):
session = self.session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=(500, 502, 504),
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def readConfig(): def get_soup_from_page(self, url):
config = configparser.ConfigParser() r = self.requests_retry_session().get(url)
r = requests.get(url, cookies=self.cookie)
def initConfig():
config['STEAMGIFTS'] = CONFIG_DEFAULT
with open('config.ini', 'w') as configfile:
config.write(configfile)
if not len(config.read('config.ini')):
initConfig()
exitMessage('Init file was created. Please, look into it and set up your cookie.')
elif list(CONFIG_DEFAULT.keys()) != list(config['STEAMGIFTS'].keys()):
initConfig()
exitMessage('Init file was reinitialised due to incorrect format. Please, look into it and set up your cookie.')
global timeout, cookies
timeout = config['STEAMGIFTS']['sleeptime']
cookies = {'PHPSESSID': config['STEAMGIFTS']['cookie']}
pages = 1
def get_soup_from_page(url):
r = requests.get(url, cookies=cookies)
soup = BeautifulSoup(r.text, 'html.parser') soup = BeautifulSoup(r.text, 'html.parser')
return soup return soup
def get_page(): def update_info(self):
global xsrf_token, points soup = self.get_soup_from_page(self.base)
try: self.xsrf_token = soup.find('input', {'name': 'xsrf_token'})['value']
soup = get_soup_from_page('https://www.steamgifts.com') self.points = int(soup.find('span', {'class': 'nav__points'}).text) # storage points
xsrf_token = soup.find('input', {'name': 'xsrf_token'})['value'] def get_game_content(self, page=1):
points = soup.find('span', {'class': 'nav__points'}).text # storage points n = page
except RequestException: while True:
print('Cant connect to the site') txt = "⚙️ Retrieving games from %d page." % n
print('Waiting 2 minutes and reconnect...') log(txt, "magenta")
sleep(120)
get_page()
except TypeError:
print('Cant recognize your cookie value.')
sleep(30)
sys.exit(0)
filtered_url = self.filter_url[self.gifts_type] % n
paginated_url = f"{self.base}/giveaways/{filtered_url}"
# get codes of the games soup = self.get_soup_from_page(paginated_url)
def get_games():
global game_name
global pages
n = 1 game_list = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['giveaway__row-inner-wrap'])
while n <= pages:
print('Proccessing games from %d page.' % n)
soup = get_soup_from_page('https://www.steamgifts.com/giveaways/search?page=' + str(n)) for item in game_list:
if self.points == 0:
try: log("🛋️ Sleeping to get 6 points", "yellow")
gifts_list = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['giveaway__row-inner-wrap']) sleep(900)
self.get_game_content(page=n)
for item in gifts_list:
if int(points) == 0:
print('> Sleeping to get 6 points')
sleep(timeout)
get_games()
break break
game_cost = item.find_all('span', {'class': 'giveaway__heading__thin'}) game_cost = item.find_all('span', {'class': 'giveaway__heading__thin'})[-1]
last_div = None if game_cost:
for last_div in game_cost: game_cost = game_cost.getText().replace('(', '').replace(')', '').replace('P', '')
pass else:
if last_div:
game_cost = last_div.getText().replace('(', '').replace(')', '').replace('P', '')
game_name = item.find('a', {'class': 'giveaway__heading__name'}).text.encode('utf-8')
if int(points) - int(game_cost) < 0:
print('Not enough points to enter: ' + game_name)
continue continue
elif int(points) - int(game_cost) > 0:
entry_gift(item.find('a', {'class': 'giveaway__heading__name'})['href'].split('/')[2]) game_name = item.find('a', {'class': 'giveaway__heading__name'}).text
if self.points - int(game_cost) < 0:
txt = f"⛔ Not enough points to enter: {game_name}"
log(txt, "red")
continue
elif self.points - int(game_cost) >= 0:
game_id = item.find('a', {'class': 'giveaway__heading__name'})['href'].split('/')[2]
res = self.entry_gift(game_id)
if res:
txt = f"🎉 One more game! Have just entered {game_name}"
log(txt, "green")
# sleep(randint(10, 30))
n = n+1 n = n+1
except AttributeError:
break
print('List of games is ended. Waiting 2 min to update...')
log("🛋️ List of games is ended. Waiting 2 min to update...", "yellow")
sleep(120) sleep(120)
get_page() self.start()
get_games()
def entry_gift(self, game_id):
def entry_gift(code): payload = {'xsrf_token': self.xsrf_token, 'do': 'entry_insert', 'code': game_id}
payload = {'xsrf_token': xsrf_token, 'do': 'entry_insert', 'code': code} entry = requests.post('https://www.steamgifts.com/ajax.php', data=payload, cookies=self.cookie)
entry = requests.post('https://www.steamgifts.com/ajax.php', data=payload, cookies=cookies)
json_data = json.loads(entry.text) json_data = json.loads(entry.text)
get_page() self.update_info()
# print(json_data)
# updating points after entered a giveaway
if json_data['type'] == 'success': if json_data['type'] == 'success':
print('> Bot has entered giveaway: ' + game_name.decode("utf-8")) return True
sleep(randint(10, 30))
if __name__ == '__main__': def start(self):
readConfig() self.update_info()
get_page() if self.points > 0:
get_games() txt = "🤖 Hoho! I am back! You have %d points. Lets hack." % self.points
log(txt, "blue")
self.get_game_content()