def test_get_steam_id(self): """ Get a steam ID from a steam account name """ j = api.get_steam_id("acidfoo") self.assertEquals(j["response"]["success"], 1) self.assertEquals(j["response"]["steamid"], unicode(STEAM_ID))
def test_get_steam_id(self): """ Get a steam ID from a steam account name """ j = api.get_steam_id("acidfoo") self.assertEquals(j["response"]["success"], 1) self.assertEquals(j["response"]["steamid"], str(STEAM_ID))
def handleCommands(self, message): message = message.strip() args = message.split(" ") if len(args) != 2: return "Could not complete the dota command, wrong args. Usage: /dota nick number_of_matches\nor /dota lastmatch nick" operation = "" if message.find("lastmatch") >= 0: operation = "lastmatch" nick = args[1] elif message.find("matchinfo") >= 0: operation = "matchinfo" match_id = args[1] else: operation = "matchhistory" nick = args[0] n_of_matches = args[1] try: if operation != "matchinfo": # Get player account ID account_id = int(dota_api.get_steam_id(nick)["response"]["steamid"]) except: return "Failed to get steam id from " + nick if operation == "lastmatch": return ["photo", self.getMatchInfo(self.getLastMatchId(account_id))] elif operation == "matchinfo": return ["photo", self.getMatchInfo(match_id)] elif operation == "matchhistory": return ["text", [self.getInfoFromOldMatches(account_id, int(n_of_matches)), ""]]
async def recent(self, ctx, player): """Gets the link to player's latest match""" # Check it there is an api key set if not self.key: await self.bot.say( "Please set the dota 2 api key using [p]dota setkey command") raise RuntimeError( "Please set the dota 2 api key using [p]dota setkey command") # Required to check if user provided the ID or not def is_number(s): try: int(s) return True except ValueError: return False # Check if user provided the ID if is_number(player.strip()): # if he did - assign as-is account_id = player.strip() else: # if he did not - get the id from the vanity name account_id = api.get_steam_id(player)["response"] # Check if the result was correcct if (int(account_id["success"]) > 1): await self.bot.say("Player not found :(") else: account_id = account_id["steamid"] try: # Get the data from Dota API matches = api.get_match_history( account_id=account_id)["result"]["matches"] match = api.get_match_details(matches[0]["match_id"]) heroes = api.get_heroes() # Operation was a success dotaServes = True except: # Well... if anything fails... dotaServes = False print('Dota servers SO BROKEN!') # Proceed to data parsing if dotaServes: # Create a proper heroes list heroes = heroes["result"]["heroes"] def build_dict(seq, key): return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)) heroes = build_dict(heroes, "id") # Reassign match info for ease of use match = match["result"] # Construct message message = "Showing the most recent match for **" + player + "** (match id: **" + str( match["match_id"]) + "**)\n" if "radiant_win" in match and match["radiant_win"]: message += "**RADIANT WON**" else: message += "**DIRE WON**" m, s = divmod(match["duration"], 60) h, m = divmod(m, 60) message += " [" + "%d:%02d:%02d" % (h, m, s) + "]\n" # Create a list of played heroes played_heroes = [] for player in enumerate(match["players"]): played_heroes.append( heroes[player[1]["hero_id"]]["localized_name"]) # "table" will be used to store the finalized match data table = [] # Form Radiant team for i in range(0, 5): table.append([ played_heroes[i], str(match["players"][i]["kills"]) + "/" + str(match["players"][i]["deaths"]) + "/" + str(match["players"][i]["assists"]), played_heroes[5 + i], str(match["players"][5 + i]["kills"]) + "/" + str(match["players"][5 + i]["deaths"]) + "/" + str(match["players"][5 + i]["assists"]) ]) # Compose message message += "\n```" message += tabulate( table, headers=["Radiant Team", "K/D/A", "Dire Team", "K/D/A"], tablefmt="fancy_grid") message += "```" message += "\nDotabuff match link: http://www.dotabuff.com/matches/" + str( match["match_id"]) await self.bot.say(message) else: await self.bot.say( 'Oops.. Something is wrong with Dota2 servers, try again later!' )
async def recent(self, ctx, player): """Gets the link to player's latest match""" await self.bot.send_typing(ctx.message.channel) def is_number(s): try: int(s) return True except ValueError: return False if is_number(player.strip()): account_id = player.strip() else: account_id = api.get_steam_id(player)["response"] if (int(account_id["success"]) > 1): await self.bot.say("Player not found :(") else: account_id = account_id["steamid"] try: # Get the data from Dota API matches = api.get_match_history(account_id=account_id)["result"]["matches"] match = api.get_match_details(matches[0]["match_id"]) heroes = api.get_heroes() dotaServes = True except: # Well... if anything fails... dotaServes = False print('Dota servers SO BROKEN!') if dotaServes: # Create a proper heroes list heroes = heroes["result"]["heroes"] def build_dict(seq, key): return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)) heroes = build_dict(heroes, "id") # Reassign match info for ease of use match = match["result"] # Construct message message = "Showing the most recent match for **" + player + "** (match id: **" + str(match["match_id"]) + "**)\n" if "radiant_win" in match: message += "**RADIANT WON**" else: message += "**DIRE WON**" m, s = divmod(match["duration"], 60) h, m = divmod(m, 60) message += " [" + "%d:%02d:%02d" % (h, m, s) + "]\n" # Create a list of played heroes played_heroes = [] for player in enumerate(match["players"]): played_heroes.append(heroes[player[1]["hero_id"]]["localized_name"]) table = [] # Form Radiant team for i in range(0,5): table.append([ played_heroes[i], str(match["players"][i]["kills"]) + "/" + str(match["players"][i]["deaths"]) + "/" + str(match["players"][i]["assists"]), played_heroes[5+i], str(match["players"][5+i]["kills"]) + "/" + str(match["players"][5+i]["deaths"]) + "/" + str(match["players"][5+i]["assists"]) ]) message += "\n```" message += tabulate(table, headers=["Radiant Team", "K/D/A", "Dire Team", "K/D/A"], tablefmt="fancy_grid") message += "```" message += "\nDotabuff match link: http://www.dotabuff.com/matches/" + str(match["match_id"]) await self.bot.say(message) else: await self.bot.say('Oops.. Something is wrong with Dota2 servers, try again later!')
def run(self): api.set_api_key(self.steam_api_key) if not isinstance(self.steamid, int): # find by username self.steamid = int( api.get_steam_id(self.steamid)['response']['steamid']) hist = api.get_match_history(account_id=self.steamid)['result'] recent_matches = [] while len(recent_matches) < self.matches: recent_matches.append(hist['matches'].pop(0)) player_team_per_match = [] # create a list of tuples where each tuple is: # [match_id, bool] # The bool will be true if the player is on Radiant and alse if they # are on Dire. for match in recent_matches: this_match = [match['match_id']] for player in match['players']: # 64bit player ID long_id = player['account_id'] + 76561197960265728 if long_id == self.steamid: if player['player_slot'] < 128: this_match.append(True) else: this_match.append(False) player_team_per_match.append(this_match) outcomes = [] for match in player_team_per_match: if api.get_match_details( match[0])['result']['radiant_win'] == match[1]: outcomes.append(1) else: outcomes.append(0) wins = outcomes.count(1) losses = outcomes.count(0) win_percent = float(sum(outcomes) / float(len(outcomes))) * 100 if win_percent >= float(self.good_threshold): color = self.good_color elif win_percent <= float(self.bad_threshold): color = self.bad_color else: color = self.caution_color if self.screenname == 'retrieve': from urllib.request import urlopen import json response = urlopen( 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%s' % (self.steam_api_key, self.steamid)) screenname = json.loads(bytes.decode( response.read()))['response']['players'][0]['personaname'] else: screenname = self.screenname cdict = { "screenname": screenname, "wins": wins, "losses": losses, "win_percent": win_percent, } self.output = { "full_text": self.format.format(**cdict), "color": color }
async def recent(self, ctx, player): """Gets the link to player's latest match""" # Check it there is an api key set if not self.key: await self.bot.say( "Please set the dota 2 api key using [p]dota setkey command") raise RuntimeError( "Please set the dota 2 api key using [p]dota setkey command") # Required to check if user provided the ID or not def is_number(s): try: int(s) return True except ValueError: return False # Check if user provided the ID if is_number(player.strip()): # if he did - assign as-is account_id = player.strip() else: # if he did not - get the id from the vanity name account_id = api.get_steam_id(player)["response"] # Check if the result was correcct if (int(account_id["success"]) > 1): await self.bot.say("Player not found :(") else: account_id = account_id["steamid"] try: # Get the data from Dota API matches = api.get_match_history( account_id=account_id)["result"]["matches"] match = api.get_match_details(matches[0]["match_id"]) heroes = api.get_heroes() # Operation was a success dotaServes = True except: # Well... if anything fails... dotaServes = False print('Dota servers SO BROKEN!') # Proceed to data parsing if dotaServes: # relink for ease of use match = match["result"] # Create a proper heroes list heroes = heroes["result"]["heroes"] def build_dict(seq, key): return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)) heroes = build_dict(heroes, "id") # Create a list of played heroes played_heroes = [] for player in enumerate(match["players"]): played_heroes.append( heroes[player[1]["hero_id"]]["localized_name"]) # form teams teams = {'radiant': [], 'dire': []} for i in range(0, 5): teams['radiant'].append({ 'name': played_heroes[i], 'kills': str(match["players"][i]["kills"]), 'deaths': str(match["players"][i]["deaths"]), 'assists': str(match["players"][i]["assists"]) }) teams['dire'].append({ 'name': played_heroes[5 + i], 'kills': str(match["players"][5 + i]["kills"]), 'deaths': str(match["players"][5 + i]["deaths"]), 'assists': str(match["players"][5 + i]["assists"]) }) # Reassign match info for ease of use matchData = { 'id': match['match_seq_num'], 'teams': teams, 'data': match } await self.bot.send_message( ctx.message.channel, embed=self._build_match_embed(matchData)) else: await self.bot.say( 'Oops.. Something is wrong with Dota2 servers, try again later!' )
import sys from os.path import abspath, join, dirname import os # Some path fiddling to make sure we can access the module sys.path.append(abspath(join(abspath(dirname(__file__)), ".."))) from dota2py import api key = os.environ.get("DOTA2_API_KEY") if not key: raise NameError("Please set the DOTA2_API_KEY environment variable") api.set_api_key(key) # Get all the most recent match played by the player 'acidfoo' account_id = int(api.get_steam_id("acidfoo")["response"]["steamid"]) # Get a list of recent matches for the player matches = api.get_match_history(account_id=account_id)["result"]["matches"] # Get the full details for a match match = api.get_match_details(matches[0]["match_id"]) print 'Match information:\n%s' % (match, )
def run(self): api.set_api_key(self.steam_api_key) if not isinstance(self.steamid, int): # find by username self.steamid = int(api.get_steam_id(self.steamid)['response']['steamid']) hist = api.get_match_history(account_id=self.steamid)['result'] recent_matches = [] while len(recent_matches) < self.matches: recent_matches.append(hist['matches'].pop(0)) player_team_per_match = [] # create a list of tuples where each tuple is: # [match_id, bool] # The bool will be true if the player is on Radiant and alse if they # are on Dire. for match in recent_matches: this_match = [match['match_id']] for player in match['players']: # 64bit player ID long_id = player['account_id'] + 76561197960265728 if long_id == self.steamid: if player['player_slot'] < 128: this_match.append(True) else: this_match.append(False) player_team_per_match.append(this_match) outcomes = [] for match in player_team_per_match: if api.get_match_details(match[0])['result']['radiant_win'] == match[1]: outcomes.append(1) else: outcomes.append(0) wins = outcomes.count(1) losses = outcomes.count(0) win_percent = float(sum(outcomes) / float(len(outcomes))) * 100 if win_percent >= float(self.good_threshold): color = self.good_color elif win_percent <= float(self.bad_threshold): color = self.bad_color else: color = self.caution_color if self.screenname == 'retrieve': from urllib.request import urlopen import json response = urlopen( 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%s' % (self.steam_api_key, self.steamid)) screenname = json.loads(bytes.decode(response.read()))['response']['players'][0]['personaname'] else: screenname = self.screenname cdict = { "screenname": screenname, "wins": wins, "losses": losses, "win_percent": win_percent, "win_percent": "%.2f" % win_percent, } self.data = cdict self.output = { "full_text": self.format.format(**cdict), "color": color }
async def recent(self, ctx, player): """Gets the link to player's latest match""" # Check it there is an api key set if not self.key: await self.bot.say("Please set the dota 2 api key using [p]dota setkey command") raise RuntimeError("Please set the dota 2 api key using [p]dota setkey command") # Required to check if user provided the ID or not def is_number(s): try: int(s) return True except ValueError: return False # Check if user provided the ID if is_number(player.strip()): # if he did - assign as-is account_id = player.strip() else: # if he did not - get the id from the vanity name account_id = api.get_steam_id(player)["response"] # Check if the result was correcct if (int(account_id["success"]) > 1): await self.bot.say("Player not found :(") else: account_id = account_id["steamid"] try: # Get the data from Dota API matches = api.get_match_history(account_id=account_id)["result"]["matches"] match = api.get_match_details(matches[0]["match_id"]) heroes = api.get_heroes() # Operation was a success dotaServes = True except: # Well... if anything fails... dotaServes = False print('Dota servers SO BROKEN!') # Proceed to data parsing if dotaServes: # Create a proper heroes list heroes = heroes["result"]["heroes"] def build_dict(seq, key): return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)) heroes = build_dict(heroes, "id") # Reassign match info for ease of use match = match["result"] # Construct message message = "Showing the most recent match for **" + player + "** (match id: **" + str(match["match_id"]) + "**)\n" if "radiant_win" in match: message += "**RADIANT WON**" else: message += "**DIRE WON**" m, s = divmod(match["duration"], 60) h, m = divmod(m, 60) message += " [" + "%d:%02d:%02d" % (h, m, s) + "]\n" # Create a list of played heroes played_heroes = [] for player in enumerate(match["players"]): played_heroes.append(heroes[player[1]["hero_id"]]["localized_name"]) # "table" will be used to store the finalized match data table = [] # Form Radiant team for i in range(0,5): table.append([ played_heroes[i], str(match["players"][i]["kills"]) + "/" + str(match["players"][i]["deaths"]) + "/" + str(match["players"][i]["assists"]), played_heroes[5+i], str(match["players"][5+i]["kills"]) + "/" + str(match["players"][5+i]["deaths"]) + "/" + str(match["players"][5+i]["assists"]) ]) # Compose message message += "\n```" message += tabulate(table, headers=["Radiant Team", "K/D/A", "Dire Team", "K/D/A"], tablefmt="fancy_grid") message += "```" message += "\nDotabuff match link: http://www.dotabuff.com/matches/" + str(match["match_id"]) await self.bot.say(message) else: await self.bot.say('Oops.. Something is wrong with Dota2 servers, try again later!')