Refactoring
This commit is contained in:
parent
2b541fde2c
commit
0c047fbaa8
5 changed files with 113 additions and 126 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -1,2 +1,3 @@
|
|||
env/
|
||||
.ini
|
||||
*.ini
|
||||
__pycache__/
|
|
@ -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
0
src/__init__.py
Normal file
16
src/cli.py
16
src/cli.py
|
@ -6,8 +6,6 @@ from pyconfigstore import ConfigStore
|
|||
from PyInquirer import (Token, ValidationError, Validator, print_json, prompt,
|
||||
style_from_dict)
|
||||
|
||||
# from main import SteamGifts
|
||||
|
||||
try:
|
||||
import colorama
|
||||
colorama.init()
|
||||
|
@ -56,7 +54,8 @@ def ask(type, name, message, validator=None, choices=[]):
|
|||
return answers
|
||||
|
||||
|
||||
def main():
|
||||
def run():
|
||||
from main import SteamGifts as SG
|
||||
|
||||
def askCookie():
|
||||
cookie = ask(type='input',
|
||||
|
@ -75,12 +74,14 @@ def main():
|
|||
config.read('config.ini')
|
||||
if not config['DEFAULT'].get('cookie'):
|
||||
cookie = askCookie()
|
||||
|
||||
else:
|
||||
re_enter_cookie = ask(type='confirm',
|
||||
name='reenter',
|
||||
message='Do you want to enter new cookie?')['reenter']
|
||||
if re_enter_cookie:
|
||||
cookie = askCookie()
|
||||
else:
|
||||
cookie = config['DEFAULT'].get('cookie')
|
||||
|
||||
gift_type = ask(type='list',
|
||||
name='gift_type',
|
||||
|
@ -94,8 +95,9 @@ def main():
|
|||
'New'
|
||||
])['gift_type']
|
||||
|
||||
# s = SteamGifts(cookie, gift_type)
|
||||
# s.start()
|
||||
s = SG(cookie, gift_type)
|
||||
s.start()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
run()
|
188
src/main.py
188
src/main.py
|
@ -4,129 +4,129 @@ import requests
|
|||
import json
|
||||
import threading
|
||||
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util import Retry
|
||||
from time import sleep
|
||||
from random import randint
|
||||
from requests import RequestException
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
CONFIG_DEFAULT = {
|
||||
'cookie': 'Paste you cookie here',
|
||||
'sleeptime': 900
|
||||
from cli import log
|
||||
|
||||
|
||||
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©_min=2",
|
||||
'DLC': "search?page=%d&dlc=true",
|
||||
'New': "search?page=%d&type=new"
|
||||
}
|
||||
|
||||
def exitMessage(msg):
|
||||
print(msg)
|
||||
input()
|
||||
sys.exit()
|
||||
def requests_retry_session(
|
||||
self,
|
||||
retries=5,
|
||||
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():
|
||||
config = configparser.ConfigParser()
|
||||
|
||||
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)
|
||||
def get_soup_from_page(self, url):
|
||||
r = self.requests_retry_session().get(url)
|
||||
r = requests.get(url, cookies=self.cookie)
|
||||
soup = BeautifulSoup(r.text, 'html.parser')
|
||||
return soup
|
||||
|
||||
def get_page():
|
||||
global xsrf_token, points
|
||||
def update_info(self):
|
||||
soup = self.get_soup_from_page(self.base)
|
||||
|
||||
try:
|
||||
soup = get_soup_from_page('https://www.steamgifts.com')
|
||||
self.xsrf_token = soup.find('input', {'name': 'xsrf_token'})['value']
|
||||
self.points = int(soup.find('span', {'class': 'nav__points'}).text) # storage points
|
||||
|
||||
xsrf_token = soup.find('input', {'name': 'xsrf_token'})['value']
|
||||
points = soup.find('span', {'class': 'nav__points'}).text # storage points
|
||||
except RequestException:
|
||||
print('Cant connect to the site')
|
||||
print('Waiting 2 minutes and reconnect...')
|
||||
sleep(120)
|
||||
get_page()
|
||||
except TypeError:
|
||||
print('Cant recognize your cookie value.')
|
||||
sleep(30)
|
||||
sys.exit(0)
|
||||
def get_game_content(self, page=1):
|
||||
n = page
|
||||
while True:
|
||||
txt = "⚙️ Retrieving games from %d page." % n
|
||||
log(txt, "magenta")
|
||||
|
||||
filtered_url = self.filter_url[self.gifts_type] % n
|
||||
paginated_url = f"{self.base}/giveaways/{filtered_url}"
|
||||
|
||||
# get codes of the games
|
||||
def get_games():
|
||||
global game_name
|
||||
global pages
|
||||
soup = self.get_soup_from_page(paginated_url)
|
||||
|
||||
n = 1
|
||||
while n <= pages:
|
||||
print('Proccessing games from %d page.' % n)
|
||||
game_list = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['giveaway__row-inner-wrap'])
|
||||
|
||||
soup = get_soup_from_page('https://www.steamgifts.com/giveaways/search?page=' + str(n))
|
||||
|
||||
try:
|
||||
gifts_list = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['giveaway__row-inner-wrap'])
|
||||
|
||||
for item in gifts_list:
|
||||
if int(points) == 0:
|
||||
print('> Sleeping to get 6 points')
|
||||
sleep(timeout)
|
||||
get_games()
|
||||
for item in game_list:
|
||||
if self.points == 0:
|
||||
log("🛋️ Sleeping to get 6 points", "yellow")
|
||||
sleep(900)
|
||||
self.get_game_content(page=n)
|
||||
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
|
||||
for last_div in game_cost:
|
||||
pass
|
||||
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)
|
||||
if game_cost:
|
||||
game_cost = game_cost.getText().replace('(', '').replace(')', '').replace('P', '')
|
||||
else:
|
||||
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
|
||||
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)
|
||||
get_page()
|
||||
get_games()
|
||||
self.start()
|
||||
|
||||
|
||||
def entry_gift(code):
|
||||
payload = {'xsrf_token': xsrf_token, 'do': 'entry_insert', 'code': code}
|
||||
entry = requests.post('https://www.steamgifts.com/ajax.php', data=payload, cookies=cookies)
|
||||
def entry_gift(self, game_id):
|
||||
payload = {'xsrf_token': self.xsrf_token, 'do': 'entry_insert', 'code': game_id}
|
||||
entry = requests.post('https://www.steamgifts.com/ajax.php', data=payload, cookies=self.cookie)
|
||||
json_data = json.loads(entry.text)
|
||||
|
||||
get_page()
|
||||
# print(json_data)
|
||||
self.update_info()
|
||||
|
||||
# updating points after entered a giveaway
|
||||
if json_data['type'] == 'success':
|
||||
print('> Bot has entered giveaway: ' + game_name.decode("utf-8"))
|
||||
sleep(randint(10, 30))
|
||||
return True
|
||||
|
||||
if __name__ == '__main__':
|
||||
readConfig()
|
||||
def start(self):
|
||||
self.update_info()
|
||||
|
||||
get_page()
|
||||
get_games()
|
||||
if self.points > 0:
|
||||
txt = "🤖 Hoho! I am back! You have %d points. Lets hack." % self.points
|
||||
log(txt, "blue")
|
||||
|
||||
self.get_game_content()
|
||||
|
|
Loading…
Reference in a new issue