def get_heroes_images(self, size="lg", force=False, ratio=1.0): """ Get all the hero images and store them in data/images """ loc = "data/images_{}".format(size) if not os.path.exists(loc): os.makedirs(loc) os.chdir(loc) log.basicConfig(level=log.INFO) log.warning("Downloading all hero images. This will take a few minutes.") for hero in api.get_heroes()["result"]["heroes"]: # if the hero is Abyssal Underlord, ignore because he's not in the game yet if hero["name"].find("abyssal_underlord") != -1: continue if not os.path.exists("{}.png".format(hero["localized_name"])) or force: if ratio == 1.0: with open("{}.png".format(hero["localized_name"]), "wb") as outfile: log.info("Getting hero image from {}".format(api.get_hero_image_url(hero["name"][len("npc_dota_hero_"):]))) outfile.write(urllib2.urlopen(api.get_hero_image_url(hero["name"][len("npc_dota_hero_"):], image_size=size)).read()) outfile.close() else: log.info("Getting hero image from {}".format(api.get_hero_image_url(hero["name"][len("npc_dota_hero_"):]))) img = Image.open(cStringIO.StringIO(urllib2.urlopen(api.get_hero_image_url(hero["name"][len("npc_dota_hero_"):])).read())) img = img.resize((int(89 * ratio), int(50 * ratio)), Image.ANTIALIAS) img.save("{}.png".format(hero["localized_name"]))
def test_get_heroes(self): """ Get list of hero identifiers """ j = api.get_heroes() self.assertIn("result", j) heroes = j["result"]["heroes"] hero = heroes[0] self.assertIn("localized_name", hero) self.assertIn("name", hero) self.assertIn("id", hero)
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 createHeroCollection(): data = api.get_heroes() for i in range(0, int(data['result']['count'])): pprint.pprint(data['result']['heroes'][i]) print i heroes.insert(data['result']['heroes'][i])
async def match(self, ctx, matchId): """Gets the match results by id""" # 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 not is_number(matchId.strip()): return self.bot.say('Please provide a numeric match id') # if he did - assign as-is match_id = matchId.strip() try: # Get the data from Dota API match = api.get_match_details(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_id, '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 os, urllib2, cStringIO from dota2py import api import Image if ___name__ == "__main__": if not os.path.exists("../data/images"): os.makedirs("../data/images") os.chdir("../data/images") scale = 50/1080.0 for hero in api.get_heroes()["result"]["heroes"]: if "abyssal_underlord" in hero["name"]: continue #if not os.path.exists("{}.png".format(hero["localized_name"])): print api.get_hero_image_url(hero["name"][len("npc_dota_hero_"):], "lg") img = Image.open(cStringIO.StringIO(urllib2.urlopen(api.get_hero_image_url(hero["name"][len("npc_dota_hero_"):])).read())) img = img.resize((89, 50), Image.ANTIALIAS) img.save("{}.png".format(hero["localized_name"]))
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!')
def faz_tabela_herois(self): herois = pd.DataFrame.from_dict(api.get_heroes()["result"]["heroes"]) herois.columns = ["id","heroi", "nome" ] return herois
def getHeroes(self): return pd.DataFrame.from_dict( api.get_heroes()["result"]["heroes"] ).sort_values("id")