def steam64_ns2id(i): try: if 'profiles' in i: if i[-1] == '/': i = i[:-1] profile = SteamID.from_community_url(i) elif 'STEAM_0' in i: profile = SteamID.from_text(i) else: if 'id' in i: r = requests.get(i).text i = re.search('steamid...([0-9]*)', r).group(1) profile = SteamID.from_text('STEAM_0:1:{}'.format( int((int(i) - 76561197960265728) / 2))) except Exception as e: logger.error(e) else: steam64 = int(profile.as_64()) i_server = 0 if steam64 % 2 == 0 else 1 steam64 -= i_server if steam64 > 76561197960265728: steam64 -= 76561197960265728 steam64 /= 2 return int(steam64 * 2 + i_server)
async def convert(cls, ctx, argument): steam = ctx.cog.steam if "ISteamUser" not in list(steam._interfaces.keys()): raise BadArgument(_("ApiKey not set or incorrect.")) userapi = steam["ISteamUser"] if argument.startswith("http"): argument = argument.strip("/").split("/")[-1] if argument.isdigit(): id64 = argument else: if argument.startswith("STEAM_"): try: id64 = SteamID.from_text(argument).as_64() except SteamIDError: raise BadArgument(_("Incorrect SteamID32 provided.")) else: try: id64 = userapi.ResolveVanityURL(argument)["response"].get( "steamid", "") except JSONDecodeError: raise BadArgument( _("Unable to resolve {} into SteamID. " "Check your input or try again later.").format( argument)) if not id64.isnumeric(): raise BadArgument( _("User with SteamID {} not found.").format(argument)) try: profile = await ctx.bot.loop.run_in_executor( None, SteamUser, steam, id64) except IndexError: raise BadArgument( _("Unable to get profile for {} ({}). Check your input or try again later." ).format(argument, id64)) return profile
def auth_to_steam64(auth): auth = auth.strip() if 'steamcommunity.com/id/' in auth: return custom_url_to_steam3(auth) elif 'steamcommunity.com/profiles/' in auth: try: return True, SteamID.from_community_url(auth.rstrip('/')).as_64() except SteamIDError: return False, '' elif auth.startswith('1:0:') or auth.startswith('1:1'): return steam2_to_steam64('STEAM_' + auth) elif auth.startswith('STEAM_'): return steam2_to_steam64(auth) elif auth.startswith('7656119') and 'steam' not in auth: return True, auth elif auth.startswith('[U:1:'): suc, steam2 = steam3_to_steam2(auth) if suc: return steam2_to_steam64(steam2) else: return False, '' else: return custom_name_to_steam3(auth)
def handle(self, *args, **options): players = Player.objects.filter(avatar__isnull=True).order_by('-score') i = 0 ids = {} for player in players: ids[str(SteamID.from_text(player.id).as_64())] = player i += 1 if i >= 99: response = requests.get( FETCH_URL, params={ 'key': settings.STEAM_KEY, 'steamids': ','.join(ids.keys()), 'format': 'json', }, headers={ 'referer': 'http://ndix.vanyli.net', }, ) i = 0 if response.ok: print('fetched data') for pdata in response.json()['response']['players']: ids[pdata['steamid']].avatar = pdata['avatar'] ids[pdata['steamid']].nick = pdata['personaname'] ids[pdata['steamid']].save() sleep(5)
def build_steamid(steamid_unparsed): if str(steamid_unparsed).isdigit(): universe, steam_type, instance, account_number = bitstruct.unpack( "u8u4u20u32", bitstruct.pack("u64", long(steamid_unparsed)) ) # Bit confusing, but convert from ID64 to STEAM_0:A:B format # See https://developer.valvesoftware.com/wiki/SteamID instance = 0 if account_number % 2 == 1: instance = 1 account_number -= 1 account_number = long(account_number / 2) return SteamID(account_number, instance, steam_type, universe) return SteamID.from_text(steamid_unparsed)
async def convert(self, ctx, argument) -> str: steam = ctx.cog.steam if "ISteamUser" not in list(steam._interfaces.keys()): raise BadArgument("ApiKey not set or incorrect.") userapi = steam['ISteamUser'] if argument.startswith("http"): argument = argument.strip("/") argument = argument.split("/")[-1] if argument.isdigit(): id64 = argument else: if argument.startswith("STEAM_"): id64 = SteamID.from_text(argument).as_64() else: id64 = userapi.ResolveVanityURL(argument)["response"].get("steamid", "") if not id64.isnumeric(): raise BadArgument("User with SteamID {} not found.".format(argument)) return id64
def steam2_to_steam64(steam2): try: return True, SteamID.from_text(steam2).as_64() except SteamIDError: return False, ''
def community_url(self): return SteamID.from_text(self.id).community_url()
def sourcemod(self): self.conn.query("""SELECT * FROM sm_groups""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) roles = {} for raw in result: flags = ServerPermission().convert(raw['flags']) flags.save() role = Role.objects.get_or_create(name=raw['name'], default={ 'flags': flags, 'immunity': raw['immunity_level'] }) role.name = raw['name'] role.flags = flags role.immunity = raw['immunity_level'] role.save() roles[raw['id']] = role self.conn.query("""SELECT * FROM sm_admins""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) generated = {} for raw in result: try: steamid = SteamID.from_text(raw['identity']).as_64() except: print("Could not add admin {}".format(raw['name'])) continue query = User.objects.filter(username=steamid) if not query: user = User.objects.create_user(username=steamid) user.is_active = False user.is_steam = True populate(user) else: user = query[0] user.namespace = raw['user'] user.save() self.conn.query("""SELECT * FROM sm_admins_groups WHERE admin_id = {}""".format(raw['id'])) r = self.conn.store_result() groups = r.fetch_row(maxrows=0, how=1) if not groups and raw['flags']: if raw['flags'] in generated: role = generated[raw['flags']] else: role = Role() role.name = raw['flags'] role.flags = ServerPermission().convert(raw['flags']) role.flags.save() role.immunity = 0 role.save() generated[raw['flags']] = role m = Membership() m.user = user m.role = role m.save() elif groups: for group in groups: role = roles[group["group_id"]] m = Membership() m.user = user m.role = role m.save() return True
def sourceban(self): superuser = User.objects.filter(is_superuser=True) superuser = superuser[0] if superuser else None # get servers self.conn.query("""SELECT * FROM sb_servers""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) servers = {} for raw in result: if raw['enabled'] != 1: continue server, _ = Server.objects.get_or_create(ip=raw['ip'], port=raw['port']) server.password = raw['rcon'] server.name = "{}:{}".format(raw['ip'], raw['port']) server.save() try: conn = RCONBase(server, timeout=3) conn.connect() conn.authenticate(timeout=3) conn.close() servers[raw['sid']] = server except (valve.rcon.RCONTimeoutError, valve.rcon.RCONAuthenticationError, ConnectionError, TimeoutError, socket.timeout) as e: server.delete() print("Warning: Could not connect to server {}:{} ({})".format( raw['ip'], raw['port'], e)) continue # get groups self.conn.query("""SELECT * FROM sb_srvgroups""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) for raw in result: flags = ServerPermission().convert(raw['flags']) flags.save() role, _ = Role.objects.get_or_create(name=raw['name'], defaults={ 'flags': flags, 'immunity': raw['immunity'] }) role.immunity = raw['immunity'] role.flags = flags role.save() # get admins self.conn.query("""SELECT * FROM sb_admins""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) users = {0: User.objects.filter(is_superuser=True)[0]} generated = {} for raw in result: try: steamid = SteamID.from_text(raw['authid']).as_64() except: print("Could not add admin {}".format(raw['user'])) continue query = User.objects.filter(username=steamid) if not query: user = User.objects.create_user(username=steamid) user.is_active = False user.is_steam = True populate(user) else: user = query[0] user.namespace = raw['user'] user.save() if not raw['srv_group'] and raw['srv_flags']: m = Membership() m.user = user if raw['srv_flags'] in generated: m.role = generated[raw['srv_flags']] else: m.role = Role() m.role.immunity = 0 m.role.name = raw['srv_flags'] m.role.flags = ServerPermission().convert(raw['srv_flags']) m.role.flags.save() m.role.save() m.save() generated[raw['srv_flags']] = m.role elif raw['srv_group']: m = Membership() m.role = Role.objects.get(name=raw['srv_group']) m.user = user m.save() users[raw['aid']] = user # get bans self.conn.query("""SELECT * FROM sb_bans""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) for raw in result: try: steamid = SteamID.from_text(raw['authid']).as_64() except: print("Could not add ban of user {}".format(raw['name'])) continue query = User.objects.filter(username=steamid) if not query: user = User.objects.create_user(username=steamid) user.is_active = False user.is_steam = True populate(user) else: user = query[0] b = Punishment() b.is_banned = True b.user = user if raw['sid'] in servers: b.server = servers[raw['sid']] if raw['sid'] != 0 else None else: b.server = None if raw['aid'] in users: b.created_by = users[raw['aid']] elif superuser: b.created_by = superuser else: continue m.created_at = timezone.make_aware( datetime.datetime.fromtimestamp(raw['created'])) b.reason = raw['reason'][:255] b.length = datetime.timedelta( seconds=raw['length'] ) if raw['length'] > 0 and raw['length'] < 31540000 else None b.resolved = False if raw['created'] + raw['length'] < self.now.timestamp( ) and raw['length'] > 0: b.resolved = True if raw['RemovedOn']: b.resolved = True b.save() # get comms self.conn.query("""SELECT * FROM sb_comms""") r = self.conn.store_result() result = r.fetch_row(maxrows=0, how=1) for raw in result: try: steamid = SteamID.from_text(raw['authid']).as_64() except: print("Could not add mutegag of user {}".format(raw['name'])) continue query = User.objects.filter(username=steamid) if not query: user = User.objects.create_user(username=steamid) user.is_active = False user.is_steam = True populate(user) else: user = query[0] m = Punishment() m.user = user if raw['sid'] in servers: m.server = servers[raw['sid']] if raw['sid'] != 0 else None else: m.server = None if raw['aid'] in users: m.created_by = users[raw['aid']] elif superuser: m.created_by = superuser else: continue m.created_at = timezone.make_aware( datetime.datetime.fromtimestamp(raw['created'])) m.reason = raw['reason'][:255] m.length = datetime.timedelta( seconds=raw['length'] ) if raw['length'] > 0 and raw['length'] < 31540000 else None m.is_muted = True if raw['type'] == 1 else False m.is_gagged = True if raw['type'] == 2 else False m.resolved = False if raw['created'] + raw['length'] < self.now.timestamp( ) and raw['length'] > 0: m.resolved = True if raw['RemovedOn']: m.resolved = True m.save() return True
def player(steamid): steamid = int(steamid) if not steamid: return abort(404) data = {} with Database() as db: # Fetch all query data first player_stats = db.execute(ns2plus_queries.PLAYER_STATS, steamid).fetchall() if not player_stats: return abort(404) data.update(player_stats[0]) player_other_names = db.execute(ns2plus_queries.PLAYER_OTHER_NAMES, steamid).fetchall() data['other_names'] = [x['playerName'] for x in player_other_names] player_weapon_acc = db.execute(ns2plus_queries.PLAYER_WEAPON_ACC, steamid).fetchall() data['weapon_acc'] = {x['weapon']: x['acc'] for x in player_weapon_acc} player_wins = pd.DataFrame( db.execute(ns2plus_queries.PLAYER_WINS, steamid).fetchall()) # TODO: check formula data['steam_url'] = SteamID(int((data['steamId'] - 1) / 2), 1, 1, 0).community_url() # Winrate over time chart for team in (1, 2): df = player_wins[player_wins['teamNumber'] == team] shift = 30 - len(df) % 30 df = df.groupby((np.arange(len(df)) + shift) // 30).agg({ 'win': ['sum', 'count'], 'roundDate': ['last'] }) if len(df): df['winrate'] = df[('win', 'sum')] / df[('win', 'count')] data[f'team{team}_winrate'] = [{ 'x': p[2], 'y': int(p[3] * 100) } for p in df.values] # Activity chart q = [(ns2plus_queries.PLAYER_ACTIVITY, 'activity', steamid), (ns2plus_queries.SERVER_ACTIVITY, 'server_activity', None)] for query, key, arg in q: if arg: q = db.execute(query, arg).fetchall() else: q = db.execute(query).fetchall() df = pd.DataFrame(q) df['Datetime'] = pd.to_datetime(df['roundDate']) df = df.set_index('Datetime') df = df.hoursPlayed.resample('W').sum() data[key] = [{ 'x': x.to_pydatetime().strftime('%Y-%m-%d %H:%M:%S'), 'y': '%.2f' % y } for x, y in zip(list(df.index), list(df.values))] # Class time chart q = db.execute(ns2plus_queries.PLAYER_CLASSTIME, steamid).fetchall() data['classes'] = { c['class']: '%.2f' % c['classTime'] if c['classTime'] else 0 for c in q } lifeforms = ['Gorge', 'Lerk', 'Fade', 'Onos'] lifeforms_time = [(l, float(data['classes'][l])) for l in lifeforms] data['lifeform'] = max(lifeforms_time, key=lambda x: x[1])[0] return render_template('player.html', data=data)
def steamidify(steamid): try: return SteamID.from_text(steamid) except SteamIDError: return steamid
class SteamUser: """SteamCommunity profile""" def __init__(self, steam: API, player_id: str): self._steam = steam self._user = self._steam["ISteamUser"] self._player = self._steam["IPlayerService"] self._userdata = self._user.GetPlayerSummaries( player_id)["response"]["players"][0] self._bandata = self._user.GetPlayerBans(player_id)["players"][0] self._personastate = self._userdata.get("personastate", 0) visibilites = { 1: _("Private"), 2: _("Friends only"), 3: _("Public"), # Friends of friends 4: _("Users only"), 5: _("Public"), } acctypes = ["I", "U", "M", "G", "A", "P", "C", "g", "T", "", "a"] self.steamid64 = self._userdata.get("steamid") self.createdat = self._userdata.get("timecreated") self.personaname = self._userdata.get("personaname") self.profileurl = self._userdata.get("profileurl") self.avatar32 = self._userdata.get("avatar") self.avatar64 = self._userdata.get("avatarmedium") self.avatar184 = self._userdata.get("avatarfull") self.visibility = visibilites[self._userdata.get( "communityvisibilitystate", 1)] self.hasprofile = bool(self._userdata.get("profilestate")) self.lastlogoff = self._userdata.get("lastlogoff") self.comments = self._userdata.get("commentpermission") self.realname = self._userdata.get("realname") self.clanid = self._userdata.get("primaryclanid") self.gameid = self._userdata.get("gameid") gameserver = self._userdata.get("gameserverip") self.gameserver = gameserver if gameserver != any(["0.0.0.0:0", None ]) else None self.gameextrainfo = self._userdata.get("gameextrainfo") self.country = self._userdata.get("loccountrycode") self.state = self._userdata.get("locstatecode") self.cityid = self._userdata.get("loccityid") self.level = self._player.GetSteamLevel(player_id)["response"].get( "player_level", 0) self.communitybanned = self._bandata.get("CommunityBanned") self.VACbanned = self._bandata.get("VACBanned") self.VACbans = self._bandata.get("NumberOfVACBans") self.sincelastban = self._bandata.get("DaysSinceLastBan") self.gamebans = self._bandata.get("NumberOfGameBans") economyban = self._bandata.get("EconomyBan") self.economyban = economyban if economyban != "none" else None self.iduniverse = int(self.steamid64) >> 56 self.idpart = int(self.steamid64) & 0b1 self.accountnumber = (int(self.steamid64) & 0b11111111111111111111111111111110) >> 1 self.accountid = int( self.steamid64) & 0b11111111111111111111111111111111 self.idinstance = ( int(self.steamid64) & 0b1111111111111111111100000000000000000000000000000000) >> 32 self.idtype = ( int(self.steamid64) & 0b11110000000000000000000000000000000000000000000000000000) >> 52 self.steamid = "STEAM_{}:{}:{}".format(self.iduniverse, self.idpart, self.accountnumber) self.sid3 = "[{}:{}:{}]".format(acctypes[self.idtype], self.iduniverse, self.accountid) @classmethod async def convert(cls, ctx, argument): steam = ctx.cog.steam if "ISteamUser" not in list(steam._interfaces.keys()): raise BadArgument(_("ApiKey not set or incorrect.")) userapi = steam["ISteamUser"] argument = argument.replace("\\", "/") if (url_parsed := urlparse(argument)).scheme in ["http", "https"]: if url_parsed.netloc != "steamcommunity.com": raise BadArgument( _("{} is not a Steam Community domain name.").format( url_parsed.netloc)) argument = PurePosixPath(url_parsed.path).name if argument.isdigit(): id64 = argument else: if argument.startswith("STEAM_"): try: id64 = SteamID.from_text(argument).as_64() except SteamIDError: raise BadArgument(_("Incorrect SteamID32 provided.")) else: try: id64 = (userapi.ResolveVanityURL(argument).get( "response", {}).get("steamid", "")) except JSONDecodeError: raise BadArgument( _("Unable to resolve {} into SteamID. " "Check your input or try again later.").format( argument)) if not id64.isnumeric(): raise BadArgument( _("User with SteamID {} not found.").format(argument)) async with ctx.typing(): try: profile = await ctx.bot.loop.run_in_executor( None, SteamUser, steam, id64) except IndexError: raise BadArgument( _("Unable to get profile for {} ({}). Check your input or try again later." ).format(argument, id64)) return profile
def steamidTo64(steamid): return ValveSteamID.from_text(steamid).as_64()
r = requests.get(app.config['GAMESERVER_WEB_HOST'] + '/?request=getchatlist', auth=auth).json() except: pass else: for msg in r: if app.config['LINK_PREFIX'] in msg['message']: token = msg['message'].strip() user = models.User.query.filter_by(token=token).first() if user: if token == user.token: user.ns2_id = msg['steamId'] user.steam_id = int((msg['steamId'] - 1) / 2) user.steam_url = SteamID(user.steam_id, 1, 1, 0).community_url() user.token_used = datetime.datetime.now() while True: new_token = app.config['LINK_PREFIX'] + ''.join( random.choices( string.ascii_lowercase + string.digits, k=5)) token_exists = models.User.query.filter_by( token=new_token).first() if not token_exists: break user.token = new_token db.session.commit() logging.info(