def convert_from_vanity_url_to_SteamID(self, user_string): """ Tries to create a SteamID object via the URL. """ if user_string.isdigit(): return SteamID.from_url( "http://steamcommunity.com/profiles/{}".format(user_string)) else: return SteamID.from_url( "http://steamcommunity.com/id/{}".format(user_string))
async def steam(ctx, *args): """Link your steam account to your profile !steam < steam link >""" author = ctx.author.mention if len(args) == 0: await ctx.send(f"{author}, incorrect format please see !help steam") elif len(args) > 1: await ctx.send(f"{author}, inccorect format please see !help steam") else: steamID = str(SteamID.from_url(f"{args[0]}", http_timeout=10)) if steamID == "None": await ctx.send(f"{author}, sorry that is not a valid link.") else: conn = sql.connect("data.db") cursor = conn.cursor() if cursor.execute( f"SELECT * FROM users WHERE nickname = '{ctx.author}';" ).fetchone() == None: cursor.execute( f"""INSERT INTO users(steamID, nickname) VALUES ('{steamID}','{ctx.author}')""" ) else: cursor.execute( f"UPDATE users SET steamID = '{steamID}' WHERE nickname = '{ctx.author}'" ) conn.commit() await ctx.send(f"{author}, success you're accounts are now linked." )
async def steamid(self, ctx, communityid:str): """Gets a steam id in all formats""" await ctx.channel.trigger_typing() steamID = SteamID.from_url("http://steamcommunity.com/id/{}".format(communityid)) if steamID is None: steamID = SteamID(communityid) try: name = steamAPI.ISteamUser.GetPlayerSummaries_v2(steamids=steamID)["response"]["players"][0]["personaname"] except IndexError: await ctx.send("User not found! Make sure you are using steam community IDs!") return await ctx.send(xl.format("Steam ID formats for {}:\nSteamID2: {}\nSteamID2Zero: {}\nSteamID3: {}\nSteamID32: {}\nSteamID64: {}").format(name, steamID.as_steam2, steamID.as_steam2_zero, steamID.as_steam3, steamID.as_32, steamID.as_64))
def idMapping(identifier): if identifier == None: return None elif re.match(r"https://steamcommunity\.com/id/[^/]+/", identifier) != None: return SteamID.from_url(identifier) elif re.match(r"https://steamcommunity\.com/profiles/[^/]+/", identifier) != None: return SteamID(identifier[36:-1]) elif re.match(r"\d+", identifier) != None: return SteamID(identifier) elif re.match(r"\w+", identifier) != None: return SteamID.from_url("https://steamcommunity.com/id/" + identifier) else: return None
async def steamuser(self, ctx, communityid:str): """Gets steam profile information on a user with the specified community ID""" await ctx.channel.trigger_typing() steamID = SteamID.from_url("http://steamcommunity.com/id/{}".format(communityid)) if steamID is None: steamID = communityid try: steamUser = steamAPI.ISteamUser.GetPlayerSummaries_v2(steamids=steamID)["response"]["players"][0] except IndexError: await ctx.send("User not found! Make sure you are using steam community IDs!") return bans = steamAPI.ISteamUser.GetPlayerBans_v1(steamids=steamID)["players"][0] vacBanned = bans["VACBanned"] communityBanned = bans["CommunityBanned"] ban_info = {"VAC Banned":vacBanned, "Community Banned":communityBanned} if vacBanned: ban_info["VAC Bans"] = bans["NumberOfVACBans"] ban_info["Days Since Last VAC Ban"] = bans["DaysSinceLastBan"] if steamUser["communityvisibilitystate"] != 3: embed = make_list_embed(ban_info) embed.description = "This profile is private." embed.title = steamUser["personaname"] embed.color = 0xFF0000 embed.url = steamUser["profileurl"] embed.set_thumbnail(url=steamUser["avatarfull"]) await ctx.send(embed=embed) return groupCount = len(steamAPI.ISteamUser.GetUserGroupList_v1(steamid=steamID)["response"]["groups"]) games = requests.get("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={}&steamid={}&include_played_free_games=1%format=json".format(config._steamAPIKey, steamID)).json()["response"] gamesPlayed = games["game_count"] state = EPersonaState(steamUser["personastate"]).name gameName = None if "gameid" in steamUser.keys(): state = "In-game" gameID = steamUser["gameid"] gameName = requests.get("http://store.steampowered.com/api/appdetails?appids={}".format(gameID)).json()[gameID]["data"]["name"] lastOnline = format_time(datetime.fromtimestamp(steamUser["lastlogoff"])) creationDate = format_time(datetime.fromtimestamp(steamUser["timecreated"])) fields = {"Status":state, "Created on":creationDate, "Group Count":groupCount, "Games Owned":gamesPlayed} if state == EPersonaState.Offline.name: fields["Last Online"] = lastOnline if gameName: fields["Currently Playing"] = gameName if "primaryclanid" in steamUser.keys(): fields["Primary Group Name"] = etree.fromstring(requests.get("http://steamcommunity.com/gid/{}/memberslistxml".format(steamUser["primaryclanid"])).text).find("groupDetails/groupName").text fields.update(ban_info) embed = make_list_embed(fields) embed.title = steamUser["personaname"] embed.color = 0xFF0000 embed.url = steamUser["profileurl"] embed.set_thumbnail(url=steamUser["avatarfull"]) await ctx.send(embed=embed)
def convert_id_from_url(the_url): uid = SteamID.from_url(the_url, http_timeout=20) wait_time = time.time() + 21 while True: if time.time() < wait_time and uid == None: continue elif uid != None: converted_ID = uid.as_steam3 first_trim = converted_ID.replace("[U:1:", "") trimmed_id = first_trim.replace("]", "") return trimmed_id else: raise ValueError( "The url you provided is either incorrect or invalid")
async def steamid(self, ctx, communityid: str): """Gets a steam id in all formats""" await ctx.channel.trigger_typing() steamID = SteamID.from_url( "http://steamcommunity.com/id/{}".format(communityid)) if steamID is None: steamID = SteamID(communityid) try: name = steamAPI.ISteamUser.GetPlayerSummaries_v2( steamids=steamID)["response"]["players"][0]["personaname"] except IndexError: await ctx.send( "User not found! Make sure you are using steam community IDs!") return await ctx.send( xl.format( "Steam ID formats for {}:\nSteamID2: {}\nSteamID2Zero: {}\nSteamID3: {}\nSteamID32: {}\nSteamID64: {}" ).format(name, steamID.as_steam2, steamID.as_steam2_zero, steamID.as_steam3, steamID.as_32, steamID.as_64))
async def whois(self, ctx, service=None, username=None): if service == None: await ctx.send( 'Usage `$whois service username`\nCheck $services for more info' ) else: try: with open('matchacat/matchacat.json', 'r') as f: matchacatJSON = json.load(f) except: await ctx.send('There was an error reading/writing to the JSON' ) e = sys.exc_info() print(e) if service == self.services[2]: #Showdown username = username.lower() for user in matchacatJSON['users'].items(): print(user) if user[1].get('PSuser') == username: await ctx.send('<@{}>'.format(user[0])) break else: await ctx.send('No Discord user found.') elif (service == self.services[1]) and cfg.getboolean( "minecraft", "WhiteList"): #Minecraft discordID = mcutil.rsearch(username) if discordID != None: await ctx.send('<@{}>'.format(discordID)) else: await ctx.send('Could not find a user by that name.') elif service == self.services[0]: #steam print(username) username = str(SteamID.from_url(username).as_64) print(username) for user in matchacatJSON['users'].items(): print(user) if user[1].get('steamID') == username: await ctx.send('<@{}>'.format(user[0])) break else: await ctx.send('No Discord user found.')
def search(request): if request.method == 'POST' and request.POST['chatquery']: q = request.POST['chatquery'] if validators.url(q): try: steamid64 = SteamID.from_url(q) steamid2 = steamid64.as_steam2 except AttributeError: error = "Please enter a valid steam url" return render(request, 'chat/chat.html', {'error': error}) elif q.startswith("STEAM_") or q.isdigit(): try: steamid64 = SteamID(q) steamid2 = steamid64.as_steam2 except (TypeError, ValueError) as e: error = "Player not in database" return render(request, 'chat/chat.html', {'error': error}) else: error = """ Invalid input. Enter a steamid or steam community link Some examples of valid input: http://steamcommunity.com/id/wh1te909/ http://steamcommunity.com/profiles/76561198041802416 STEAM_1:0:12345678 76561198041802416 """ return render(request, 'chat/chat.html', {'error': error}) results = Chatlogs.objects.using('Chatlogs').filter( steamid=steamid2).order_by('-date') if not results.exists(): error = "Player not in database" return render(request, 'chat/chat.html', {'error': error}) else: return render(request, 'chat/chat.html', { 'results': results, 'steamid2': steamid2 }) else: return render(request, 'chat/chat.html')
async def steamuser(self, ctx, communityid: str): """Gets steam profile information on a user with the specified community ID""" await ctx.channel.trigger_typing() steamID = SteamID.from_url( "http://steamcommunity.com/id/{}".format(communityid)) if steamID is None: steamID = communityid try: steamUser = steamAPI.ISteamUser.GetPlayerSummaries_v2( steamids=steamID)["response"]["players"][0] except IndexError: await ctx.send( "User not found! Make sure you are using steam community IDs!") return bans = steamAPI.ISteamUser.GetPlayerBans_v1( steamids=steamID)["players"][0] vacBanned = bans["VACBanned"] communityBanned = bans["CommunityBanned"] ban_info = { "VAC Banned": vacBanned, "Community Banned": communityBanned } if vacBanned: ban_info["VAC Bans"] = bans["NumberOfVACBans"] ban_info["Days Since Last VAC Ban"] = bans["DaysSinceLastBan"] if steamUser["communityvisibilitystate"] != 3: embed = make_list_embed(ban_info) embed.description = "This profile is private." embed.title = steamUser["personaname"] embed.color = 0xFF0000 embed.url = steamUser["profileurl"] embed.set_thumbnail(url=steamUser["avatarfull"]) await ctx.send(embed=embed) return groupCount = len( steamAPI.ISteamUser.GetUserGroupList_v1( steamid=steamID)["response"]["groups"]) games = requests.get( "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={}&steamid={}&include_played_free_games=1%format=json" .format(config._steamAPIKey, steamID)).json()["response"] gamesPlayed = games["game_count"] state = EPersonaState(steamUser["personastate"]).name gameName = None if "gameid" in steamUser.keys(): state = "In-game" gameID = steamUser["gameid"] gameName = requests.get( "http://store.steampowered.com/api/appdetails?appids={}". format(gameID)).json()[gameID]["data"]["name"] lastOnline = format_time( datetime.fromtimestamp(steamUser["lastlogoff"])) creationDate = format_time( datetime.fromtimestamp(steamUser["timecreated"])) fields = { "Status": state, "Created on": creationDate, "Group Count": groupCount, "Games Owned": gamesPlayed } if state == EPersonaState.Offline.name: fields["Last Online"] = lastOnline if gameName: fields["Currently Playing"] = gameName if "primaryclanid" in steamUser.keys(): fields["Primary Group Name"] = etree.fromstring( requests.get( "http://steamcommunity.com/gid/{}/memberslistxml".format( steamUser["primaryclanid"])).text).find( "groupDetails/groupName").text fields.update(ban_info) embed = make_list_embed(fields) embed.title = steamUser["personaname"] embed.color = 0xFF0000 embed.url = steamUser["profileurl"] embed.set_thumbnail(url=steamUser["avatarfull"]) await ctx.send(embed=embed)
async def adduser(self, ctx, service=None, username=None): discordID = str(ctx.message.author.id) if (service == None) or (not service in self.services): await ctx.send(', '.join(self.services)) await ctx.send( "If you are confused about how to use a service with commands type `$service service`" ) elif (username == None): await ctx.send('You need to enter something for a username.') elif (service == self.services[0]): #steam #we need to figure out if the 'username' variable is a steamID, steamID64 or a profileurl. if username.startswith('steamcommunity.com/'): username = '******' + username username = SteamID.from_url(username).id elif (username.startswith('https://steamcommunity.com/')) or ( username.startswith('http://steamcommunity.com/')): try: username = SteamID.from_url(username).id except: e = sys.exc_info()[0] print(e) await ctx.send(username) try: int( username ) #this will throw an exception if username is not a number and therefore not a steamID username = SteamID( username ).as_64 #We want a steam64 ID, this will make sure we have that. except: await ctx.send(username + ' is not a steamID or steam profile URL') else: try: matchacatJSON = json.load( open('matchacat/matchacat.json', 'r')) #matchacatJSON['services']['steam'].update({str(username) : str(discordID)})#Makes reverse searching easier. if matchacatJSON['users'].get(discordID, None) == None: matchacatJSON['users'].update( {discordID: { 'steamID': username }}) else: matchacatJSON['users'][discordID]['steamID'] = str( username) open("matchacat/matchacat.json", "r+").write( json.dumps(matchacatJSON, sort_keys=True, indent=2, separators=(',', ': '))) except: await ctx.send( 'There was an error reading/writing to the JSON') e = sys.exc_info() print(e) else: await ctx.send('Successfully added') elif (service == self.services[1]) and cfg.getboolean( "minecraft", "WhiteList"): #minecraft if mcutil.whitelist( ctx.message.author, username ): #This whitelists the user to our minecraft server await ctx.send('You were whitelisted to our server.') else: await ctx.send( 'There was an error and we could not whitelist you, make sure you entered your username correctly then try again or contact an admin for assistance.' ) elif service == self.services[2]: #Pokemon Showdown with open('matchacat/matchacat.json', 'r+') as f: matchacatJSON = json.load(f) PSuser = username.lower().replace( " ", "" ) #Little known fact, you can enter spaces into an argument by wrapping it with quotes, we don't want that. if matchacatJSON['users'].get(discordID, None) != None: matchacatJSON['users'][discordID]['PSuser'] = PSuser else: matchacatJSON['users'].update( {discordID: { 'PSuser': PSuser }}) with open('matchacat/matchacat.json', 'w') as f: f.write( json.dumps(matchacatJSON, sort_keys=True, indent=2, separators=(',', ': '))) await ctx.send('Added')
def com_net_steam_id_from_user(user_name): return SteamID.from_url('https://steamcommunity.com/id/%s', (user_name,))
def stats(request): if request.method == 'POST' and request.POST['statsquery']: q = request.POST['statsquery'] if validators.url(q): try: steamid64 = SteamID.from_url(q) steamid2 = steamid64.as_steam2 except AttributeError: error = "Please enter a valid steam url" return render(request, 'stats/stats.html', {'error': error}) elif q.startswith("STEAM_") or q.isdigit(): try: steamid64 = SteamID(q) steamid2 = steamid64.as_steam2 except (TypeError, ValueError) as e: error = "Player not in database" return render(request, 'stats/stats.html', {'error': error}) else: error = """ Invalid input. Enter a steamid or steam community link Some examples of valid input: http://steamcommunity.com/id/wh1te909/ http://steamcommunity.com/profiles/76561198041802416 STEAM_1:0:12345678 76561198041802416 """ return render(request, 'stats/stats.html', {'error': error}) results = PlayerAnalytics.objects.using('Analytics').filter( auth=steamid2) if not results.exists(): error = "Player not in database" return render(request, 'stats/stats.html', {'error': error}) else: try: file = urllib.request.urlopen( "http://steamcommunity.com/profiles/{}/?xml=1".format( steamid64)) data = file.read() file.close() data = xmltodict.parse(data) picture = data["profile"]["avatarIcon"] player_name = data["profile"]["steamID"] except ExpatError: error = "Player not in database" return render(request, 'stats/stats.html', {'error': error}) playtime = int( PlayerAnalytics.objects.using('Analytics').filter( auth=steamid2).aggregate(Sum('duration'))['duration__sum'] / 3600) if playtime == 0: playtime = "< 1" country = PlayerAnalytics.objects.using('Analytics').only( 'country_code3').filter(auth=steamid2).last() city = PlayerAnalytics.objects.using('Analytics').only( 'city').filter(auth=steamid2).last() region = PlayerAnalytics.objects.using('Analytics').only( 'region').filter(auth=steamid2).last() steam_profile = "http://steamcommunity.com/profiles/{}".format( steamid64) connections = Usertrack.objects.using('Usertrack').filter( steamid=steamid2).aggregate( Sum('connections'))['connections__sum'] top_server = PlayerAnalytics.objects.using('Analytics').raw( 'select id, server_ip, count(*) as c from player_analytics where auth = %s group by server_ip order by c desc limit 1', [steamid2]) top_map = PlayerAnalytics.objects.using('Analytics').raw( 'select id, map, count(*) as d from player_analytics where auth = %s group by map order by d desc limit 1', [steamid2]) flags = city = PlayerAnalytics.objects.using('Analytics').only( 'flags').filter(auth=steamid2).last() return render( request, 'stats/stats.html', { 'playtime': playtime, 'steamid2': steamid2, 'picture': picture, 'player_name': player_name, 'steam_profile': steam_profile, 'connections': connections, 'country': country, 'city': city, 'region': region, 'top_server': top_server, 'flags': flags, 'top_map': top_map }) else: return render(request, 'stats/stats.html')
async def rank(ctx, *args): """Shows all !rank commands !rank < @mention > !rank < steam profile link > !rank < number > !rank < steam 64 id >""" conn = sql.connect("data.db") cursor = conn.cursor() data = cursor.execute("SELECT * FROM data").fetchall() author = ctx.author.mention gotID = False steamID = "" if len(args) == 0: await ctx.send(f"{author}, that is not valid type !help rank") elif len(args) > 1: await ctx.send(f"{author}, you can only have 1 argument") else: queried = args[0] if queried.isdigit() is True: if queried[0:6] == "765611": steamID = queried gotID = True else: for i in data: if i[1] == int(queried): steamID = i[0] gotID = True else: if queried[:30] == "https://steamcommunity.com/id/": steamID = str(SteamID.from_url(queried, http_timeout=10)) gotID = True elif queried[:36] == "https://steamcommunity.com/profiles/": steamID = str(SteamID.from_url(queried, http_timeout=10)) gotID = True elif queried[0] == '<' and queried[-1:] == '>': user = await commands.MemberConverter().convert(ctx, args[0]) try: steamID = cursor.execute( f"SELECT steamID FROM users WHERE nickname = '{user}'" ).fetchone()[0] if steamID is not None: gotID = True except: await ctx.send("That person hasn't linked their steam") else: await ctx.send("Sorry that is not valid see !help ranks") if gotID is True: for i in data: if i[0] == steamID: url = f"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key={steamWebAPI}&format=json&steamids={steamID}" data = json.loads( urllib.request.urlopen(url).read().decode("UTF-8")) picture = data["response"]["players"][0]["avatarfull"] embed = discord.Embed(color=chooseColour(i[1])) embed.set_author( name= f'{data["response"]["players"][0]["personaname"]}\'s Stats', icon_url=data["response"]["players"][0]["avatar"]) embed.add_field( name="Name", value= f"[{data['response']['players'][0]['personaname']}]({data['response']['players'][0]['profileurl']})", inline=True) embed.add_field(name="Place", value=i[1], inline=True) embed.add_field(name="Total Score", value=i[2], inline=True) embed.add_field(name="Average Accuracy", value=i[3], inline=True) embed.add_field(name="Average Misses", value=i[4], inline=True) embed.add_field(name="Last Updated", value=i[5], inline=True) embed.set_thumbnail(url=picture) embed.set_footer(text="Made By MighTy") await ctx.send(embed=embed)
def parser(request): total = Usertrack.objects.using('Usertrack').count() if request.method == 'POST' and request.POST['query']: q = request.POST['query'] if validators.url(q): try: steamid64 = SteamID.from_url(q) steamid2 = steamid64.as_steam2 except AttributeError: error = "Please enter a valid steam url" return render(request, 'parserxlaw/parser.html', {'error': error}) elif q.startswith("STEAM_") or q.isdigit(): try: steamid64 = SteamID(q) steamid2 = steamid64.as_steam2 except (TypeError, ValueError) as e: error = "Player not in database" return render(request, 'parserxlaw/parser.html', {'error': error}) elif validators.ip_address.ipv4(q): results = Usertrack.objects.using('Usertrack').filter( ip=q).order_by('-lastupdated') if not results.exists(): error = "IP address not in database" return render(request, 'parserxlaw/parser.html', {'error': error}) else: icons = {} names = {} vacs = {} steamid_list = [] for x in results: steamid_list.append(x.steamid) steamid_list = set(steamid_list) for i in steamid_list: icons[i] = xmlGetInfo(i, "avatarIcon") names[i] = xmlGetInfo(i, "steamID") vacs[i] = xmlGetVac(i) return render( request, 'parserxlaw/parser.html', { 'results': results, 'icons': icons, 'names': names, 'vacs': vacs, 'q': q, 'total': total }) else: error = """ Invalid input. Enter a steamid, steam community link or IP address Some examples of valid input: http://steamcommunity.com/id/wh1te909/ http://steamcommunity.com/profiles/76561198041802416 72.19.25.123 STEAM_1:0:12345678 76561198041802416 """ return render(request, 'parserxlaw/parser.html', {'error': error}) # get all the IP addresses for the steamid and put them in list # then grab all steamids for each ip to get alt accounts allips = Usertrack.objects.using('Usertrack').only('ip').filter( steamid=steamid2) if allips: ip_array = [] for ip in allips: ip_array.append(ip.ip) # remove duplicates values = set(ip_array) queries = [Q(ip=value) for value in values] query = queries.pop() for item in queries: query |= item # if client is searching for alt accounts if request.POST['type'] == 'alt': results = Usertrack.objects.using('Usertrack').filter( query).order_by('-lastupdated') # if client is searching for just ip addresses elif request.POST['type'] == 'ipaddr': results = Usertrack.objects.using('Usertrack').filter( steamid=steamid2).order_by('-lastupdated') else: pass else: error = "Player not in database" return render(request, 'parserxlaw/parser.html', {'error': error}) icons = {} names = {} vacs = {} steamid_list = [] for x in results: steamid_list.append(x.steamid) steamid_list = set(steamid_list) for i in steamid_list: icons[i] = xmlGetInfo(i, "avatarIcon") names[i] = xmlGetInfo(i, "steamID") vacs[i] = xmlGetVac(i) return render( request, 'parserxlaw/parser.html', { 'results': results, 'icons': icons, 'names': names, 'vacs': vacs, 'q': q, 'total': total }) else: return render(request, 'parserxlaw/parser.html', {'total': total})