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)
Beispiel #2
0
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)
Beispiel #3
0
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
    cs.launch()


@cs.on('ready')
def gc_ready():
    print('Ready')
    for code in codes:
        meme = csgo.sharecode.decode(code)
        print(meme)
        cs.request_full_match_info(meme['matchid'], meme['outcomeid'],
                                   meme['token'])
        response, = cs.wait_event('full_match_info')
        site = response.matches[0].roundstatsall[-1].map
        file_name = f"./unprocessed/{meme['matchid']}_{meme['outcomeid']}_{meme['token']}"
        print(site)
        print(file_name)
        req = urllib.request.Request(site, headers=hdr)
        try:
            with urllib.request.urlopen(req) as res, open(file_name,
                                                          'wb') as out_file:
                shutil.copyfileobj(res, out_file)
        except urllib.error.HTTPError as e:
            print(e)

    cs.exit()
    cs.emit('meme')


client.login(username=auth['usr'], password=auth['pass'])
cs.wait_event('meme')
Beispiel #5
0
}

client = SteamClient()

@client.on('error')
def error(result):
    print("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)
except:
    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()
Beispiel #6
0
        print("\nReconnecting...")
        client.reconnect(maxdelay=30)


@client.friends.on("friend_invite")
def accept_invite(user):
    client.friends.add(user)
    if user.name == None:
        print("\nAdded:", user.steam_id)
    else:
        print("\nAdded:", user.name)
    gevent.sleep(2)
    user.send_message(config[9])


try:
    result = client.login(username=config[1],
                          password=config[3],
                          two_factor_code=SA.get_code())

    if result != EResult.OK:
        print("Failed to login:"******"Logout")
        client.logout()
    raise SystemExit
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'])
Beispiel #8
0
@client.on(EMsg.ServiceMethod)
def handle_games_played(msg):
    if hasattr(msg.body, 'games'):
        print(f'Now playing {msg.body.games[0].appid}')


@client.on(EMsg.ClientPersonaState)
def handle_persona_state(msg):
    for f in msg.body.friends:
        if f.friendid == sl.friend and not f.gameid:
            print(f'{f.player_name} no longer in game')
            sl.clear()
            client.games_played(app_ids)
            break


try:
    two_factor_code = generate_twofactor_code(base64.b64decode(SHARED_SECRET))
    result = client.login(USERNAME, PASSWORD, None, None, two_factor_code)

    if result != EResult.OK:
        print(f'Failed to login: {repr(result)}')
        raise SystemExit

    client.run_forever()

except KeyboardInterrupt:
    if client.connected:
        print("Logout")
        client.logout()
Beispiel #9
0
    def start_bot(self, credentials):
        client = SteamClient()
        dota = Dota2Client(client)

        self.bots.append(dota)

        client.verbose_debug = True
        dota.verbose_debug = True

        @client.on('logged_on')
        def start_dota():
            dota.launch()

        # TODO: don't try to relogin if we disconnected by KeyboardInterrupt
        @client.on('disconnected')
        def handle_disconnect():
            print('Disconnected: %s' % credentials['login'])

            delay = 30
            print('Trying to login again in %d sec...' % delay)
            gevent.sleep(delay)

            client.login(credentials['login'], credentials['password'])
            client.run_forever()

        @dota.on('ready')
        def dota_started():
            print('Logged in: %s %s' % (dota.steam.username, dota.account_id))

            # register this bot as a player in db
            player, created = Player.objects.get_or_create(
                dota_id=dota.account_id,
                defaults={
                    'name': dota.steam.username,
                    'dota_mmr': random.randrange(3000, 6000, 500)
                })
            print('Bot %s (%d MMR, %s), was already in DB: %s' %
                  (player.name, player.dota_mmr, player.dota_id, not created))

            # if lobby is hung up from previous session, leave it
            dota.leave_practice_lobby()
            dota.join_practice_lobby(self.lobby, self.password)

        @dota.on(dota2.features.Lobby.EVENT_LOBBY_NEW)
        def lobby_new(lobby):
            print('%s joined lobby %s' % (dota.steam.username, lobby.lobby_id))

            ind = self.bots.index(dota)

            if ind == 0:
                # let first bot listen to lobby chat
                dota.channels.join_lobby_channel()

            team = ind // 5
            slot = ind % 5 + 1
            dota.join_practice_lobby_team(slot, team)

        @dota.on(dota2.features.Lobby.EVENT_LOBBY_CHANGED)
        def lobby_changed(lobby):
            if dota != self.bots[0]:
                return

            players = [
                player for player in lobby.members
                if player.team in (DOTA_GC_TEAM.GOOD_GUYS,
                                   DOTA_GC_TEAM.BAD_GUYS)
            ]

            if len(players) == 0 and self.balance_team1:
                print()
                print('All bots jumped to unassigned')
                self.join_balance_slots()

        @dota.channels.on(dota2.features.chat.ChannelManager.EVENT_MESSAGE)
        def chat_message(channel, msg_obj):
            text = msg_obj.text
            if channel.type != DOTAChatChannelType_t.DOTAChannelType_Lobby:
                return  # ignore postgame and other chats

            # process known commands
            if text.startswith('Team 1'):
                self.balance_ready(text)

        client.login(credentials['login'], credentials['password'])
        client.run_forever()
Beispiel #10
0
class AuthAccount:
    def __init__(self):
        self.client = SteamClient()
        # self.client.set_credential_location(rf"{os.path.abspath(os.curdir)}/lib/data/")
        self.accounts = Accounts()
        self.code = False
        self.code_needed = ""

    def login(self, username, password, two_factor_code=None, email_code=None):

        account_in_base = self.accounts.check_account(username)

        if two_factor_code is not None:
            resp = self.client.login(username=username, password=password, two_factor_code=two_factor_code)
            response = self.check_login_response(resp, username, password, account_in_base)
            print(f"Two factor code is not none: {response}, {resp}")
            if response == "2FA Mismatch":
                return "2FA Mismatch"
            elif response == "Successfully logged in":
                return "Successfully logged in"

        elif email_code is not None:
            resp = self.client.login(username=username, password=password, auth_code=email_code)
            response = self.check_login_response(resp, username, password, account_in_base)
            print(f"Email code is not none: {response}, {resp}")
            if response == "Need Email Code":
                return "Account logon denied"
            elif response == "Successfully logged in":
                return "Successfully logged in"
        else:
            pass

        if account_in_base == "OK":
            try:
                login_key = self.accounts.get_login_key(username)
                resp = self.client.login(username=username, login_key=login_key)
                print(resp)
                response = self.check_login_response(resp, username, password, account_in_base)
                print(f"Account in base is OK: {response}, {resp}")
                if response == "Need 2FA Code":
                    return "Need 2FA Code"
                elif response == "Need Email Code":
                    return "Need Email Code"
                elif response == "Rate Limit Exceeded":
                    return "Rate Limit Exceeded"
                elif response == "Successfully logged in":
                    return "Successfully logged in"
            except RuntimeError:
                pass

        else:
            try:
                resp = self.client.login(username=username, password=password)
                response = self.check_login_response(resp, username, password, account_in_base)
                print(f"Account not in base: {response}, {resp}")
                if response == "Need 2FA Code":
                    return "Need 2FA Code"
                elif response == "Need Email Code":
                    return "Need Email Code"
                elif response == "Rate Limit Exceeded":
                    return "Rate Limit Exceeded"
                elif response == "Successfully logged in":
                    return "Successfully logged in"
            except RuntimeError:
                pass

    def check_login_response(self, response, username, password, account_in_base):
        if response == EResult.OK:
            return "Successfully logged in"

        elif response == EResult.InvalidPassword:
            if account_in_base == "OK":
                resp = self.client.login(username=username, password=password)
                self.check_login_response(resp, username, password, account_in_base)
            else:
                return 'Invalid Password'

        elif response == EResult.AccountLoginDeniedNeedTwoFactor:
            return "Need 2FA Code"

        elif response == EResult.AccountLogonDenied:
            return "Need Email Code"

        elif response == EResult.TwoFactorCodeMismatch:
            return "2FA Mismatch"

        elif response == EResult.RateLimitExceeded:
            return "Rate Limit Exceeded"
Beispiel #11
0
class SteamNotifier(object, metaclass=Singleton):
    _instantiated = False
    _running = False
    _notification = None

    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 setupNotificationHandlerHook(self, notification):
        self._notification = notification

    def _run(self):
        # Start Login Sequence
        if not self._running:
            self._running = True
            self._steamClient.set_credential_location(self._cache)
            if os.path.exists(self._cache + 'steam.txt'):
                f = open(self._cache + 'steam.txt', 'r')
                data = f.readlines()
                f.close()
                gevent.spawn_later(2, SteamClient.login, self._steamClient, username=data[0].replace('\n',''), login_key=data[1])
            else:
                if self._notification != None:
                    self._notification('Steam', 'Login', 'Requesting Login Data')
                RyderClient().send("[\"steamLogin\"]")

    def _steamLoginData(self, data):
        print('Steam login data received')
        self._login_data = [data[1], data[2]]
        self._steamClient.login(username=self._login_data[0], password=self._login_data[1])

    def _steam2faData(self, data):
        print("Steam 2FA data received")
        self._steamClient.login(two_factor_code=data[1], username=self._login_data[0], password=self._login_data[1])

    # Handle SteamClient events
    def connected(self):
        print("Connected")

    def disconnected(self):
        print("Disconnected")
        if self._steamClient.relogin_available:
            if self._notification != None:
                self._notification('Steam', self._steamClient.username, 'Connection lost! Re-trying...')
            self._steamClient.reconnect(maxdelay=30)

    def login_secured(self):
        print("Login secured")
        if self._steamClient.relogin_available:
            self._steamClient.relogin()

    def login_error(self, data):
        print("Login error")
        print(data)
        if data == EResult.InvalidPassword:
            if self._notification != None:
                self._notification('Steam', 'Login', 'Requesting Login Data')
            RyderClient().send("[\"steamLogin\"]")

    def auth_code_prompt(self, is2fa, code_mismatch):
        print("Steam2FA Required")
        if self._notification != None:
            self._notification('Steam', 'Login', 'Requesting 2 Factor Authentication')
        RyderClient().send("[\"steam2fa\"]")

    def handle_message(self, msg):
        if msg.body.chat_entry_type == EChatEntryType.ChatMsg and not msg.body.local_echo:
            user = self._steamClient.get_user(msg.body.steamid_friend)
            text = msg.body.message
            if self._notification != None:
                self._notification('Steam', user.name, text)

    def login_success(self):
        print("Login successfull")
        self._steamClient.change_status(persona_state = EPersonaState.Invisible)
        if self._notification != None:
            self._notification('Steam', self._steamClient.username, 'Logged in!')

    def new_login_key(self):
        print("New login key")
        f = open(self._cache + 'steam.txt', 'w')
        f.write(self._steamClient.username + '\n' + self._steamClient.login_key)
        f.close()