def __init__(self, config): self._client = SteamClient() self._client.set_credential_location(config["steam_credential_location"]) self._cs = CSGOClient(self._client) self._ready = False @self._client.on("channel_secured") def send_login(): if self._client.relogin_available: self._client.relogin() @self._client.on("disconnected") def handle_disconnect(): logging.warning("disconnected from steam") if self._client.relogin_available: self._client.reconnect(maxdelay=10) @self._client.on('logged_on') def start_csgo(): logging.info("connecting to csgo") self._cs.launch() @self._cs.on('ready') def gc_ready(): logging.info("connected") self._ready = True self._client.cli_login(username=config["steam_bot_username"], password=config["steam_bot_password"]) while not self._ready: self._client.sleep(0.125)
def main(local_mode = True): try: steam_path = SteamDataReader.get_steam_installpath() except: print("Could not find steam install path") sys.exit(1) print("Steam path:",steam_path) if local_mode: steam_data_reader = SteamDataReaderLocal(steam_path) try: steamid = steam_data_reader.get_steam_id() if not steamid.is_valid(): steamid = SteamID(input_steamid()) if not steamid.is_valid(): print("Invalid steam id") sys.exit(2) print("SteamID:",steamid.as_32) except Exception as error: print(error) print("Switch to remote mode") local_mode = False if not local_mode: client = SteamClient() if client.cli_login() != EResult.OK: print("Login Error") sys.exit(3) else: print("Login Success") steam_data_reader = SteamDataReaderRemote(client) steamid = client.steam_id print("SteamID:",steamid.as_32) steam_grid_path = STEAM_GRIDPATH.format(steam_path,steamid.as_32) if not os.path.isdir(steam_grid_path): os.mkdir(steam_grid_path) print("Steam grid path:",steam_grid_path) missing_cover_app_dict = steam_data_reader.get_missing_cover_app_dict(not local_mode) print("Total games missing cover in library:",len(missing_cover_app_dict)) local_cover_appids = {int(file[:len(file)-5]) for file in os.listdir(steam_grid_path) if re.match(r"^\d+p.(png|jpg)$",file)} print("Total local covers found:",len(local_cover_appids)) local_missing_cover_appids = missing_cover_app_dict.keys() - local_cover_appids print("Total missing covers locally:",len(local_missing_cover_appids)) print("Finding covers from steamgriddb.com") local_missing_cover_appids = list(local_missing_cover_appids) local_missing_cover_appids.sort() total_downloaded = asyncio.run(download_covers_temp(local_missing_cover_appids,steam_grid_path,missing_cover_app_dict)) print("Total cover downloaded:",total_downloaded)
class csgo_client (object): def __init__(self, config): self._client = SteamClient() self._client.set_credential_location(config["steam_credential_location"]) self._cs = CSGOClient(self._client) self._ready = False @self._client.on("channel_secured") def send_login(): if self._client.relogin_available: self._client.relogin() @self._client.on("disconnected") def handle_disconnect(): logging.warning("disconnected from steam") if self._client.relogin_available: self._client.reconnect(maxdelay=10) @self._client.on('logged_on') def start_csgo(): logging.info("connecting to csgo") self._cs.launch() @self._cs.on('ready') def gc_ready(): logging.info("connected") self._ready = True self._client.cli_login(username=config["steam_bot_username"], password=config["steam_bot_password"]) while not self._ready: self._client.sleep(0.125) def send(self, *args, **kwargs): self._cs.send(*args, **kwargs) def wait_event(self, *args, **kwargs): return self._cs.wait_event(*args, **kwargs) def get_item_killcount(self, s, a, d): if not self._cs.connection_status == GCConnectionStatus.HAVE_SESSION: logging.warning("not connected to GC") raise ValueError("not connected to gc") self.send(ECsgoGCMsg.EMsgGCCStrike15_v2_Client2GCEconPreviewDataBlockRequest, { 'param_s': s, 'param_a': a, 'param_d': d, 'param_m': 0 }) response, = self.wait_event(ECsgoGCMsg.EMsgGCCStrike15_v2_Client2GCEconPreviewDataBlockResponse, timeout=2) if response.iteminfo.itemid != a: raise ValueError("mismatched req/rep") return response.iteminfo.killeatervalue
def setup(): client = SteamClient() try: client.login(username='', password='', auth_code='') except: error_message = traceback.format_exc() now = str(datetime.now()) print(now + ' - Error:\n' + error_message + '\n\n\n') time.sleep(60) setup() checkForUpdates(client)
def setup(): client = SteamClient() try: client.login(username=config.STEAM_USERNAME, password=config.STEAM_PASS) except: error_message = traceback.format_exc() now = str(datetime.now()) print(f'{now} - Error:\n{error_message}\n\n\n') time.sleep(60) setup() check_for_updates(client)
def setup(): client = SteamClient() try: client.anonymous_login() except: error_message = traceback.format_exc() now = str(datetime.now()) print(now + ' - Error:\n' + error_message + '\n\n\n') time.sleep(60) setup() checkForUpdates(client)
def get_product_info(self, apps=[], packages=[], *args, **kwargs): resp = {'apps': {}, 'packages': {}} # if we have cached info for all apps, just serve from cache if apps and all(map(self.has_cached_appinfo, apps)): self._LOG.debug("Serving appinfo from cache") for app_id in apps: resp['apps'][app_id] = self.get_cached_appinfo(app_id) apps = [] if apps or packages: self._LOG.debug("Fetching product info") fresh_resp = SteamClient.get_product_info(self, apps, packages, *args, **kwargs) if apps: for app_id, appinfo in fresh_resp['apps'].items(): if not appinfo['_missing_token']: UserCacheFile("appinfo/{}.json".format( app_id)).write_json(appinfo) resp = fresh_resp else: resp['packages'] = fresh_resp['packages'] return resp
def steam_login(username, password, two_factor_code): """Logs in to steam, returns logged in client if successful, raises SteamLoginException if not :param username: username of account :type username :class:`str` :param password: password of account :type password :class:`str` :param two_factor_code: valid 2FA code :type two_factor_code :class:`str` :return steam_client of logged in user :rtype `SteamClient` :raises `SteamLoginException` """ steam_client = SteamClient() # Make steam client object steam_client.login(username, password, two_factor_code=two_factor_code) # Log in if not steam_client.logged_on: # Login failed raise SteamLoginException('Login failed.') return steam_client
def _get_depot_list(self): """Get a list of depots for the app. Returns the list of depots """ result = [] client = SteamClient() client.anonymous_login() info = client.get_product_info(apps=[self.app_id]) for depot in list(info['apps'][self.app_id]['depots']): # Only store depots with numeric value if depot.isnumeric(): result.append(int(depot)) return result
def create(self, path): if not self._instantiated: self._instantiated = True self._cache = path + '/cache/' if not os.path.exists(self._cache): os.makedirs(self._cache) # Steam Client self._steamClient = SteamClient() # Hook Steam Client Events self._steamClient.on(SteamClient.EVENT_AUTH_CODE_REQUIRED, self.auth_code_prompt) self._steamClient.on("FriendMessagesClient.IncomingMessage#1", self.handle_message) self._steamClient.on(SteamClient.EVENT_LOGGED_ON, self.login_success) self._steamClient.on(SteamClient.EVENT_CHANNEL_SECURED, self.login_secured) self._steamClient.on(SteamClient.EVENT_ERROR, self.login_error) self._steamClient.on(SteamClient.EVENT_CONNECTED, self.connected) self._steamClient.on(SteamClient.EVENT_DISCONNECTED, self.disconnected) self._steamClient.on(SteamClient.EVENT_NEW_LOGIN_KEY, self.new_login_key) # Bind EndPoints RyderClient().addEndPoint('on_connect', self._run) RyderClient().addEndPoint('steamLogin', self._steamLoginData) RyderClient().addEndPoint('steam2fa',self._steam2faData)
def __init__(self): self.logged_on_once = False self.steam = client = SteamClient() client.set_credential_location(".") @client.on("error") def handle_error(result): print("Logon result: %s", repr(result)) @client.on("connected") def handle_connected(): print("Connected to %s", client.current_server_addr) @client.on("channel_secured") def send_login(): if self.logged_on_once and self.steam.relogin_available: self.steam.relogin() @client.on("logged_on") def handle_after_logon(): self.logged_on_once = True print("-"*30) print("Logged on as: %s", client.user.name) print("Community profile: %s", client.steam_id.community_url) print("Last logon: %s", client.user.last_logon) print("Last logoff: %s", client.user.last_logoff) print("-"*30) @client.on("disconnected") def handle_disconnect(): print("Disconnected.") if self.logged_on_once: print("Reconnecting...") client.reconnect(maxdelay=30) @client.on("reconnect") def handle_reconnect(delay): print("Reconnect in %ds...", delay) @client.on('auth_code_required') def auth_code_prompt(is_2fa, mismatch): if is_2fa: code = input("Enter 2FA Code: ") client.login(two_factor_code=code, **SC_STEAM_LOGIN) else: code = input("Enter Email Code: ") client.login(auth_code=code, **SC_STEAM_LOGIN)
def command(): client = SteamClient() client.set_credential_location(settings.STEAM_SENTRY_DIR) for index, username in enumerate(settings.STEAM_USERNAMES): click.echo(f"Logging into Steam as {username}...") client.cli_login(username=username, password=settings.STEAM_PASSWORDS[index]) time.sleep(5) # copy to correct location for `auth-ticket.js` src = os.path.join(settings.STEAM_SENTRY_DIR, f"{username}_sentry.bin") dest = os.path.join(settings.STEAM_SENTRY_DIR, f"sentry.{username}.bin") copy2(src, dest) click.echo("Login successful. Steam Guard should not prompt anymore") client.logout()
def init_steam(self): """ Starts Steam & SteamCDNAPI clients courtesy https://github.com/ValvePython/steam """ self.steamcli = steamcli = SteamClient() self.steamcli.teardown = False steamcli.set_credential_location("./secrets") @steamcli.on('error') def steam_error(result): LOG.error("SteamClient error: ", repr(result)) @steamcli.on('auth_code_required') def auth_code_prompt(is_2fa, mismatch): if is_2fa: code = input("Enter 2FA Code: ") steamcli.login(two_factor_code=code, **LOGON_DETAILS) else: code = input("Enter Email Code: ") steamcli.login(auth_code=code, **LOGON_DETAILS) @steamcli.on("disconnected") def handle_disconnect(): LOG.info("Disconnected.") if not steamcli.teardown and steamcli.relogin_available: LOG.info("Reconnecting...") steamcli.reconnect(maxdelay=30) @steamcli.on("error") def handle_error(result): LOG.info("Logon result: %s", repr(result)) @steamcli.on("channel_secured") def send_login(): if steamcli.relogin_available: steamcli.relogin() @steamcli.on("logged_on") def handle_after_logon(): LOG.info("Steam logon success, last logon: %s", steamcli.user.last_logon) LOG.info("Steam last logoff: %s", steamcli.user.last_logoff) steamcli.login(**LOGON_DETAILS) self.cdnapi = CDNClient(steamcli)
def __init__(self): self.logged_on_once = False self.steam = client = SteamClient() client.set_credential_location(".") @client.on("error") def handle_error(result): LOG.info("Logon result: %s", repr(result)) @client.on("connected") def handle_connected(): LOG.info("Connected to %s", client.current_server_addr) @client.on("channel_secured") def send_login(): if self.logged_on_once and self.steam.relogin_available: self.steam.relogin() @client.on("logged_on") def handle_after_logon(): self.logged_on_once = True LOG.info("-" * 30) LOG.info("Logged on as: %s", client.user.name) LOG.info("Community profile: %s", client.steam_id.community_url) LOG.info("Last logon: %s", client.user.last_logon) LOG.info("Last logoff: %s", client.user.last_logoff) LOG.info("-" * 30) @client.on("disconnected") def handle_disconnect(): LOG.info("Disconnected.") if self.logged_on_once: LOG.info("Reconnecting...") client.reconnect(maxdelay=30) @client.on("reconnect") def handle_reconnect(delay): LOG.info("Reconnect in %ds...", delay)
import json from steam.client import SteamClient from steam.client.cdn import CDNClient from steam.enums.emsg import EMsg import pandas as pd #Source #http://api.steampowered.com/ISteamApps/GetAppList/v0002/ mysteam = SteamClient() mysteam.anonymous_login() mycdn = CDNClient(mysteam) count=0 info=[] with open('steam_ids.json',encoding='utf-8') as json_file: data = json.load(json_file) counter=1000 for entry in data['applist']['apps']: try: if counter < 1: counter = 1000 out = pd.DataFrame(info) out.to_csv("depot_id_steam_checkpoint.csv") else: counter -= 1 print(entry['appid'],entry['name']) data = mycdn.get_app_depot_info(int(entry['appid'])) # print(data, type(data))
from __future__ import print_function from steam.client import SteamClient from steam.enums import EResult client = SteamClient() print("One-off login recipe") print("-" * 20) result = client.cli_login() if result != EResult.OK: print("Failed to login: %s" % repr(result)) raise SystemExit print("-" * 20) print("Logged on as:", client.user.name) print("Community profile:", client.steam_id.community_url) print("Last logon:", client.user.last_logon) print("Last logoff:", client.user.last_logoff) client.logout()
from steam.client import SteamClient from random import choice from threading import Thread from tkinter import messagebox from tkinter import Tk from tkinter.filedialog import askopenfilename from time import sleep import logging from datetime import datetime import os dirname = os.path.dirname(os.path.abspath(__file__)) client = SteamClient() #logging logging.basicConfig(filename=dirname + '\\sample.log', level=logging.INFO, filemode='w', format='%(asctime)s %(levelname)-8s %(message)s') logging.info(datetime.fromtimestamp(1576280665)) Tk().withdraw() messagebox.showinfo('Путь до файла', 'Введите путь до файла с login:pass') filepass = askopenfilename() messagebox.showinfo('Путь до файла', 'Введите путь до файла с именами') namepass = askopenfilename() with open(namepass) as f: names = f.readlines()
from steam.client import SteamClient, EMsg from steam.enums import EResult, ECurrencyCode client = SteamClient() @client.on(EMsg.ClientWalletInfoUpdate) def print_balance(msg): bucks, cents = divmod(msg.body.balance64, 100) print("Current balance is {:d}.{:02d} {:s}".format(bucks, cents, ECurrencyCode(msg.body.currency).name )) client.cli_login() client.disconnect()
from discord.ext import commands import threading import time import asyncio import config from steam.client import SteamClient from steam.enums import EResult client = SteamClient() #Steambot @client.on('connected') def connected(): print('Connected steambot\n') @client.on('chat_message') def handle_message(user, message_text): print('Got steam message: ' + str(message_text) + ' from: ' + user.name +' with steamid:' + str(user.steam_id)) user.send_message('Command not found, if there anything wrong, contact with my creator - fmouse, steamid = 76561198071680434') class MyBot(commands.Bot): async def on_ready(self): print(f'Ready {self.user}:{self.user.id}') async def on_message(self, message): print('Got discord message: ' + message.content + ' from: ' + str(message.author.nick) +'') client.get_user(76561198071680434).send_message('Got discord message: [' + message.content + '] from: [' + str(message.author.nick) +']') def run_bot_in_thread(): # Important to make an event loop for the new thread
print(e.fp.read()) soup = BeautifulSoup(matchPage, "html.parser") demoURL = "https://csgostats.gg" + soup.find( "span", class_="glyphicon glyphicon-facetime-video").find_parent( "a").get("href") req = urllib.request.Request(demoURL, headers=hdr) try: demoRes = urllib.request.urlopen(req) except urllib.error.HTTPError as e: demoRes = e.fp.read() if demoRes: soup = BeautifulSoup(demoRes, "html.parser") matchid = soup.find("a").get('href') codes.append(matchid[-len('CSGO-AKxQC-ftWKD-LAFyz-FQ8AH-CcyMM'):]) client = SteamClient() cs = CSGOClient(client) with open('./auth.json') as f: auth = json.load(f) @client.on('logged_on') def start_csgo(): cs.launch() @cs.on('ready') def gc_ready(): print('Ready') for code in codes:
def __init__(self, *args, **kwargs): if not cred_dir.exists(): cred_dir.mkdir() SteamClient.__init__(self, *args, **kwargs) _LOG = logging.getLogger('CachingSteamClient') self._bootstrap_cm_list_from_file()
def run_account(acc): client = SteamClient() client.set_credential_location('creds') cs = CSGOClient(client) profile = gevent.event.Event() matches = gevent.event.Event() events.append(profile) events.append(matches) @client.on('logged_on') def start_csgo(): print("Logged in!") cs.launch() print("Launched CS:GO") @client.on('new_login_key') def key(): print(f"New login key for {acc['username']}!") acc['login_key'] = client.login_key #@client.on(None) #def kek(msgtype, msg=None): # print(msgtype) # print(msg) @client.on(EMsg.ClientVACBanStatus) def vac_status(msg): acc['bans'] = msg.body.numBans @client.on(EMsg.ClientEmailAddrInfo) def email(msg): acc['email'] = msg.body.email_address @client.on(EMsg.ClientAccountInfo) def name(msg): acc['name'] = msg.body.persona_name @client.on(EMsg.ClientWalletInfoUpdate) def name(msg): if msg.body.currency: acc['wallet_balance'] = msg.body.balance64 acc['wallet_balance_delayed'] = msg.body.balance64_delayed acc['wallet_currency'] = msg.body.currency @cs.on('ready') def gc_ready(): print("CS:GO Ready!") cs.request_player_profile(cs.account_id) cs.request_recent_user_games(cs.account_id) print("Requested player profile info") @cs.on('recent_user_games') def got_matches(resp): if len(resp.matches) > 0: acc['last_mm'] = resp.matches[-1].matchtime matches.set() @cs.on('player_profile') def got_profile(response): if response.account_id == cs.account_id: print(f"Got {acc['username']} CS:GO profile!") acc['csgo_profile'] = json.loads(json_format.MessageToJson(response)) #cs.exit() #client.logout() profile.set() # def cleanup(): print(f'Logging in to {acc["username"]}') if 'login_key' not in acc or client.login(acc['username'], login_key=acc['login_key']) != 1: client.cli_login(acc['username'], acc['password'])
#!/usr/bin/env python import steam from steam.client import SteamClient from steam.client.cdn import CDNClient import os.path # Configure OS (Linux/Windows) system = "Linux" # Initialize SteamClient and login client = SteamClient() client.anonymous_login() # Initialize CDN client mycdn = CDNClient(client) # Try to find the correct depot needle = False for depot in mycdn.get_manifests(403240): if depot.name == 'Squad Dedicated Server Depot ' + system: needle = depot break # Check if the depot information could be found if needle: # Get the last update / creation time as string lastUpdate = str(needle.creation_time) # Initialize a default oldLastUpdate oldLastUpdate = 0
from __future__ import print_function from getpass import getpass from steam.client import SteamClient print("One-off login recipe") print("-"*20) LOGON_DETAILS = { 'username': input("Steam user: "******"Password: "******"Logon result:", repr(result)) @client.on('auth_code_required') def auth_code_prompt(is_2fa, mismatch): if is_2fa: code = input("Enter 2FA Code: ") client.login(two_factor_code=code, **LOGON_DETAILS) else: code = input("Enter Email Code: ") client.login(auth_code=code, **LOGON_DETAILS) try: client.login(**LOGON_DETAILS)
#%% library import from steam.client import SteamClient from dota2.client import Dota2Client import logging logging.basicConfig(format='[%(asctime)s] %(levelname)s %(name)s: %(message)s', level=logging.DEBUG) client = SteamClient() dota = Dota2Client(client) print("hello") @client.on('logged_on') def status_logged(): print('WE ARE LOGGED ON') @dota.on('ready') def do_dota_stuff(): print("the game is ready") client.cli_login() client.run_forever() #start_dota() print('life') @dota.on('my event')
from bs4 import BeautifulSoup from steam.client import SteamClient from steam.enums import EResult #The interval between checking for new posts refreshInterval = 15 #ARMA 3 Looking for a unit community forum unitForumURL = 'https://steamcommunity.com/app/107410/discussions/21/' #begin as empty string but is used to refrence if the found post is new or not oldPosts = [] #The URL for the discord Webhook url = "Replace Discord Webhook Here" #Creating the steam client client = SteamClient() #set location to store sentry files and other stuff client.set_credential_location(".") #logs into steam client client.cli_login() #creating a web session session = client.get_web_session() #allows to reconnect upon error @client.on("disconnected") def handle_disconnect(): if client.relogin_available: client.reconnect(maxdelay=30)
def main(): try: steam_path = SteamDataReader.get_steam_installpath() except: print("Could not find steam install path") sys.exit(1) print("Steam path:", steam_path) parser = argparse.ArgumentParser( description= 'Downloads missing covers for new steam UI. Covers are downloaded from steamgriddb.com' ) parser.add_argument('-l', '--local', action='store_true', dest='local_mode', help='Local mode, this is the default operation.') parser.add_argument( '-r', '--remote', action='store_true', dest='remote_mode', help= 'Remote mode, if both local and remote are specified, will try local mode first.' ) parser.add_argument('-m', '--minscore', dest='min_score', type=int, default=None, help='Set min score for a cover to be downloaded.') parser.add_argument( '-s', '--styles', dest='styles', type=str, default=None, help= 'Set styles of cover, can be comma separated list of alternate, blurred, white_logo, material or no_logo.' ) parser.add_argument( '-o', '--overwrite', action='store_true', dest='overwrite', help= 'Overwrite covers that are already present in local steam grid path.') parser.add_argument( '-d', '--delete-local', action='store_true', dest='delete_local', help='Delete local covers for games that already have official ones.') args = parser.parse_args() local_mode = True remote_fallback = True if not args.local_mode and args.remote_mode: local_mode = False elif args.local_mode and not args.remote_mode: remote_fallback = False if local_mode: steam_data_reader = SteamDataReaderLocal(steam_path) try: steamid = steam_data_reader.get_steam_id() if not steamid.is_valid(): steamid = SteamID(input_steamid()) if not steamid.is_valid(): print("Invalid steam id") sys.exit(2) print("SteamID:", steamid.as_32) except Exception as error: print(error) if remote_fallback: print("Switch to remote mode") local_mode = False else: sys.exit(2) if not local_mode: client = SteamClient() if client.cli_login() != EResult.OK: print("Login Error") sys.exit(3) else: print("Login Success") steam_data_reader = SteamDataReaderRemote(client) steamid = client.steam_id print("SteamID:", steamid.as_32) steam_grid_path = STEAM_GRIDPATH.format(steam_path, steamid.as_32) if not os.path.isdir(steam_grid_path): os.mkdir(steam_grid_path) print("Steam grid path:", steam_grid_path) missing_cover_app_dict = steam_data_reader.get_missing_cover_app_dict( not local_mode) print("Total games missing cover in library:", len(missing_cover_app_dict)) local_cover_map = { int(file[:len(file) - 5]): file for file in os.listdir(steam_grid_path) if re.match(r"^\d+p.(png|jpg)$", file) } local_cover_appids = set(local_cover_map.keys()) print("Total local covers found:", len(local_cover_appids)) local_missing_cover_appids = missing_cover_app_dict.keys( ) - local_cover_appids print("Total missing covers locally:", len(local_missing_cover_appids)) if args.overwrite: local_missing_cover_appids = set(missing_cover_app_dict.keys()) if args.delete_local: local_duplicate_cover_appids = local_cover_appids - missing_cover_app_dict.keys( ) print( f'Found {len(local_duplicate_cover_appids)} games already have official covers.' ) for appid in local_duplicate_cover_appids: path = os.path.join(steam_grid_path, local_cover_map[appid]) print(f'Deleting file {path}') os.remove(path) print("Finding covers from steamgriddb.com") local_missing_cover_appids = list(local_missing_cover_appids) local_missing_cover_appids.sort() total_downloaded = asyncio.run( download_covers(local_missing_cover_appids, steam_grid_path, missing_cover_app_dict, args)) print("Total cover downloaded:", total_downloaded)
#!/usr/bin/env python3 from bot_functions import * from steam.client import SteamClient, SteamID import dota2 from dota2.client import Dota2Client from dota2.enums import DOTA_GC_TEAM, DOTA_CM_PICK, EMatchOutcome import logging import sys client = SteamClient() dota = Dota2Client(client) # logging.basicConfig(format='[%(asctime)s] %(levelname)s %(name)s: %(message)s', level=logging.DEBUG) room_name = sys.argv[1] room_pass = sys.argv[2] params = sys.argv[3:] players = {} for i in range(0, len(params), 2): player_id = params[i] team = params[i + 1] players[int(player_id)] = {"team": team, "slot": None} @client.on('logged_on') def start_dota(): dota.launch()
def _handle_login_key(self, message): SteamClient._handle_login_key(self, message) with UserDataFile('client/%s.key' % self.username).open('w') as fp: fp.write(self.login_key)
def steam_start(self, bot): print('Steam is now logging on') bot.log.info('Steam is now logging on') bot.client = SteamClient() bot.client.set_credential_location('Login_details') # where to store sentry files and other stuff @bot.client.on('error') def handle_error(result): bot.log.error(f'Logon result: {repr(result)}') @bot.client.on('connected') def handle_connected(): bot.log.info(f'Connected to: {bot.client.current_server_addr}') @bot.client.on('reconnect') def handle_reconnect(delay): if bot.client is None: raise SystemExit bot.log.info(f'Reconnect in {delay}...') @bot.client.on('disconnected') def handle_disconnect(): bot.log.warning('Disconnected.') if bot.client is None: raise SystemExit if bot.client.relogin_available: bot.log.info('Reconnecting...') bot.client.reconnect(maxdelay=30) @bot.client.on('logged_on') def handle_after_logon(): bot.s_bot = bot.client.get_user(bot.bot64id) bot.logged_on = True bot.log.info(f'Logged on as: {bot.client.user.name}') @bot.client.on('chat_message') def handle_message(user, message_text): if user.steam_id == bot.bot64id: if message_text.startswith('Message from'): bot.user_message = message_text elif bot.current_time.split()[1] == '23:59' \ and message_text.startswith("You've made") \ or message_text.startswith("Trades today"): bot.daily = message_text else: bot.sbotresp = message_text if preferences.cli_login: bot.log.info('Logging in using cli_login') result = bot.client.cli_login(username=sensitive_details.username, password=sensitive_details.password) else: bot.log.info('Logging in using automatic') SA = guard.SteamAuthenticator(sensitive_details.secrets).get_code() result = bot.client.login(username=sensitive_details.username, password=sensitive_details.password, two_factor_code=SA) if result == EResult.TwoFactorCodeMismatch: sleep(2) result = bot.client.login(username=sensitive_details.username, password=sensitive_details.password, two_factor_code=SA) if result != EResult.OK: bot.log.fatal(f'Failed to login: {repr(result)}') raise SystemExit bot.client.run_forever()
gevent.monkey.patch_socket() gevent.monkey.patch_ssl() from steam import guard from steam.client import SteamClient from steam.enums import EResult print("\nSteam Bot") print("-" * 20) config = open("config.txt", "r+").read().splitlines() secrets = {'shared_secret': config[5], 'identity_secret': config[7]} SA = guard.SteamAuthenticator(secrets) client = SteamClient() @client.on("error") def handle_error(result): print("\nError", result) @client.on("connected") def handle_connected(): print("Logged on as", user) print("Auto accept friend requests is enabled.") print("Auto message is enabled.") print("-" * 20) print("Press Ctrl + C to exit")