def loopMatchIDDetails(): for match in matchids.find({}): time.sleep(1.2) match_details = api.get_match_details(match["match_id"]) if match_details != None: matches.insert(match_details) print 'Inserted match details for '+ str(match_details["result"]["match_id"])
def test_get_match_details(self): """ Get the full details from a match """ j = api.get_match_details(MATCH_ID) self.assertIn("result", j) self.assertEquals(j["result"]["match_id"], MATCH_ID) self.assertIn("players", j["result"])
def process_match_details(match_id): '''Get the details of the given match_id, check if it's valid, and if it is, add it as a record in the database and spawn a thread to download and parse the corresponding replay.''' gmd = api.get_match_details(match_id)['result'] if not is_valid_match(gmd): logger.debug('Not considering match %s.' % match_id) return match_collection.insert(gmd) game_mode = get_game_mode_string(gmd['game_mode']) logger.debug('Processed Match ID: %s - Game Mode: %s' % (match_id, game_mode))
async def check_game_status(self): while not self.client.is_closed: try: deletions = [] for match_id, game in self.predictions.items(): game_status = api.get_match_details(match_id)['result'] if 'radiant_win' in game_status: await self.resolve_game(match_id, game_status['radiant_win']) deletions.append(match_id) for m in deletions: self.predictions.pop(m, None) except: print('Could not fetch match data.') await asyncio.sleep(30)
def getSum(account_id,days,attribute): matches = findMatches(account_id) match_ids = [] attr_list = [] for i in range (0,25): if matches[i].has_key("match_id"): try: match = api.get_match_details(matches[i]["match_id"]) match_ids.append(matches[i]['match_id']) results = getResults(match,'players') attr_list.append(getPlayerVal(results,account_id,attribute)) except requests.exceptions.HTTPError as e: logging.error("request error:",str(e)) return zip(match_ids,attr_list)
def load_data(key, dest, start_point, num): api.set_api_key(key) match_id = start_point store = []; count = 0; file_index = 0; valid_mode = [0, 1, 2, 3, 4, 5] for i in range(num): try: match = api.get_match_details(match_id + i)["result"] if match["game_mode"] in valid_mode: match_collection.insert(match) except: continue if i% 500 == 0: print ("finished ", i)
def getSum(account_id, days, attribute): matches = findMatches(account_id) match_ids = [] attr_list = [] for i in range(0, 25): if matches[i].has_key("match_id"): try: print 'match: ', matches[i]["match_id"], 'player: ', account_id match = api.get_match_details(matches[i]["match_id"]) match_ids.append(matches[i]['match_id']) results = getResults(match, 'players') attr_list.append(getPlayerVal(results, account_id, attribute)) except requests.exceptions.HTTPError as e: print "REQUEST ERROR:", str(e) return zip(match_ids, attr_list)
def getMatchInfo(self, match_id): # Get match details match_details = dota_api.get_match_details(match_id) players = [] # Create List of Players player_count = 0 for player_json in match_details["result"]["players"]: # Create player with basic information (name, steam id, dota id, avatar) player = self.getPlayerInfo(self.dotaIdToSteamId(int(player_json["account_id"]))) player.hero_name = self.getHeroName(int(player_json["hero_id"])) player.hero_image = self.getHeroImage(int(player_json["hero_id"])) player.level = player_json["level"] player.kills = player_json["kills"] player.deaths = player_json["deaths"] player.assists = player_json["assists"] if player_count < 5: player.team = "radiant" else: player.team = "dire" players.append(player) player_count += 1 # Create an object of MatchImageCreator drawer = MatchImageCreator() drawer.players = players drawer.winner = "Radiant" if match_details["result"]["radiant_win"] == True else "Dire" drawer.match_id = match_id filename = drawer.drawMatchBoard() photo_file = open(filename, 'rb') os.remove(filename) caption = "http://www.dotabuff.com/matches/" + str(match_id) return [photo_file, caption]
def LOAD(data_folder): data = new_load_data(data_folder) add_lineups(data) add_players(data) teams_df, teams, teams_inversed = construct_teams(data) data = data.drop(get_dull_columns(), axis=1) data = data.drop(get_useless_columns(), axis=1) regenerate_list_of_match(data_folder) API_KEY = '0DED3F75E799ED36033051911B23BD79' api.set_api_key(API_KEY) final_matches = pd.read_csv(os.path.join(data_folder, "final_matches_id.csv"), header=None, names=[0, 'match_id']) final_matches_data = [] for match_id_ in final_matches['match_id']: final_matches_data.append(api.get_match_details(match_id=match_id_)['result']) data = append_data(data, final_matches_data) return data
def getInfoFromOldMatches(self, acc_id, n_of_matches): response_info = '' # Get a list of recent matches for the player matches = dota_api.get_match_history(account_id=acc_id)["result"]["matches"] if len(matches) <= 0: return "Failed to get matches" acc_id_32b = acc_id - 76561197960265728 match_count = 0 # Get the details for n matches match for match in matches: if match_count > n_of_matches - 1: break match_details = dota_api.get_match_details(match["match_id"]) player_count = 0 player_team = 'radiant' for player in match_details["result"]["players"]: if player["account_id"] == self.steamIdToDotaId(acc_id): if (player_count < 5): player_team = 'radiant' else: player_team = 'dire' break player_count = player_count + 1 if player_team == 'radiant' and match_details["result"]["radiant_win"] == True: victory = "won" elif player_team == 'dire' and match_details["result"]["radiant_win"] == False: victory = "won" else: victory = "lost" response_info = response_info + "Match id: " + str(match["match_id"]) + " - " + "Player " + victory + "!\n" match_count = match_count + 1 # Return the response return response_info
def getRecentMatches(self, start_match_id): try: gmh = api.get_match_history(start_at_match_id=start_match_id, league_id=self.league_id)['result'] except: sleep(5.0) return start_sequence_id error_code = gmh['status'] matches = gmh['matches'] self.logger.info('%d recent matches have been found' % (len(matches))) is_new_match_found = False for match in matches: match_id = match['match_id'] if self.current_match_id is None: self.current_match_id = match_id else: self.current_match_id = min(self.current_match_id, match_id) #if self.collection.find_one({'match_id':match_id}) != None: # self.logger.info('Same match %s found' % (match_id)) # continue self.total_games += 1 is_new_match_found = True print match_id try: match = api.get_match_details(match_id)['result'] if(not self.is_valid_match(match)): continue self.total_selected_games += 1 sleep(1.0) self.process_match_details(match, match_id) except Exception as e: self.logger.info("Failed in obtain match: %s, since %s" % (str(match_id), str(e))) self.logger.info('Total: %d, Selected: %d, Yasp: %d' % (self.total_games, self.total_selected_games, self.yasp_games)) self.current_match_id -= 1 return is_new_match_found
def info_partida(self,id): try: match = api.get_match_details(id)["result"] except requests.RequestException as erro: print("\n *********************************\n") print(erro) print("\n Problema na coleta desta partida... O procedimento continua.") print(" \n*********************************\n") return pd.DataFrame() info = {"id":[match["match_id"]], "radiant_win":[match["radiant_win"]], "tempo":[ match["duration"]/60 ], "modo_jogo":[match["game_mode"]], "data_inicio":[match["start_time"]]} leaver = 0 for p in match["players"]: if p["player_slot"] <= 4: info[ "RH_" + str(p["hero_id"])]=[1] leaver += int(p["leaver_status"]) for j in self.info_heroi: info["RH_" + str(p["hero_id"]) +"_"+ j] =p[j] else: info[ "DH_" + str(p["hero_id"])]=[1] leaver += int(p["leaver_status"]) for j in self.info_heroi: info["DH_" + str(p["hero_id"]) +"_"+ j] =p[j] if leaver>0: return pd.DataFrame() else: return pd.DataFrame.from_dict(info)
logger.debug("Cannot find any matches in data") return False return True def filter_match_detail(match_detail): match_detail_filtered = { 'match_id' : match_detail['match_id'], 'radiant_win' : match_detail['radiant_win'] } match_detail_filtered['players'] = [] for i, player in enumerate(match_detail['players']): player_detail = { 'player_slot' : player['player_slot'], 'hero_id': player['hero_id'] } match_detail_filtered['players'].append(player_detail) return match_detail_filtered if __name__ == '__main__': client = MongoClient('mongodb://localhost:27017/') db = client.merlin count = 0; data = api.get_match_history(skill=3, min_players=10)['result'] if data_valid(data): for match in data['matches']: match_detail = api.get_match_details(match['match_id'])['result'] if match_valid(match_detail): db.matches.insert(filter_match_detail(match_detail)) count += 1 logger.info("Added %s new matches" % count); logger.info("Currently at %s matches in the database" % db.matches.count())
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!' )
def run(self): api.set_api_key(self.steam_api_key) 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": "%.2f" % win_percent, } self.output = { "full_text": self.format.format(**cdict), "color": color }
def update_dota(self): # Get a list of recent matches for the player total_added = 0 api.set_api_key(AbstractResponse.key) current_time = int(time.time()) last_update_time = AbstractResponse.get_last_update_time() new_records = "" for name, account_id in AbstractResponse.GroupMetoDOTA.items(): print "Starting: {0}".format(name) # Get a list of recent matches for the player matches = api.get_match_history(account_id=account_id)["result"]["matches"] #Go through every match for match in matches: print "\tChecking: " + str(match["match_id"]) if match["start_time"] < last_update_time["last_update"]: print "\tWe've seen these matches" break if (not AbstractResponse.has_dotaMatch(match["match_id"])): single_match = api.get_match_details(match["match_id"])["result"] print "\t\tAdding: " + str(single_match["match_id"]) AbstractResponse.add_dotaMatch(single_match) total_added += 1 #Did this match set any new records# ? for player in single_match["players"]: #Is this a player we are tracking? if AbstractResponse.has_dotaID_num(int(player["account_id"])): #Yes! Check if they broke a record old_record = AbstractResponse.get_record(player["hero_id"]) print player["hero_id"] hero_dict = data.get_hero_name(player["hero_id"]) if not hero_dict: print("For hero id = {}, not in dota2py".format(player["hero_id"])) continue hero_name = data.get_hero_name(player["hero_id"])["localized_name"] player_name = AbstractResponse.dotaID_to_name(int(player["account_id"])) if old_record is None: #this is auto a new record! new_record = {"hero_id": player["hero_id"], "max_kills": player["kills"], "max_kills_player": player["account_id"], "max_deaths": player["deaths"], "max_deaths_player": player["account_id"], "max_GPM": player["gold_per_min"], "max_GPM_player": player["account_id"], "min_GPM": player["gold_per_min"], "min_GPM_player": player["account_id"], "max_XPM": player["xp_per_min"], "max_XPM_player": player["account_id"], "min_XPM": player["xp_per_min"], "min_XPM_player": player["account_id"], } AbstractResponse.set_record(new_record) else: #There is an existing record.. Lets see if this match was a game changer new_record = old_record.copy() if old_record["max_kills"] < player["kills"]: new_records += "{0} just got {1} kills with {2}, a new record!\n".format(player_name, player["kills"], hero_name ) new_record["max_kills"] = player["kills"] new_record["max_kills_player"] = player["account_id"] if old_record["max_deaths"] < player["deaths"]: new_records += "{0} just got {1} deaths with {2}, a new low!\n".format(player_name, player["deaths"], hero_name ) new_record["max_deaths"] = player["deaths"] new_record["max_deaths_player"] = player["account_id"] if old_record["max_GPM"] < player["gold_per_min"]: new_records += "{0} just got {1} GPM with {2}, a new record!\n".format(player_name, player["gold_per_min"], hero_name ) new_record["max_GPM"] = player["gold_per_min"] new_record["max_GPM_player"] = player["account_id"] if old_record["min_GPM"] > player["gold_per_min"]: new_records += "{0} just got {1} GPM with {2}, a new low!\n".format(player_name, player["gold_per_min"], hero_name ) new_record["min_GPM"] = player["gold_per_min"] new_record["min_GPM_player"] = player["account_id"] if old_record["max_XPM"] < player["xp_per_min"]: new_records += "{0} just got {1} XPM with {2}, a new record!\n".format(player_name, player["xp_per_min"], hero_name ) new_record["max_XPM"] = player["xp_per_min"] new_record["max_XPM_player"] = player["account_id"] if old_record["min_XPM"] > player["xp_per_min"]: new_records += "{0} just got {1} XPM with {2}, a new low!\n".format(player_name, player["xp_per_min"], hero_name ) new_record["min_XPM"] = player["xp_per_min"] new_record["min_XPM_player"] = player["account_id"] AbstractResponse.set_record(new_record) else: print "\t Was Duplicate" print "Updated {0} Matches".format(total_added) if last_update_time == None: time_dict = {'last_update' : current_time} else: time_dict = last_update_time.copy() time_dict["last_update"] = current_time AbstractResponse.set_last_update_time(time_dict) return new_records
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, )
from __future__ import division from dota2py import api import time import sys API_KEY = sys.argv[1] # Stick your API key here, obtain it at account_id = ACCOUNT_ID = '9372254' # My account ID api.set_api_key(API_KEY) matches = api.get_match_history(account_id=account_id, date_min=time.time() - 604800)['result']['matches'] total_games = 0 games_won = 0 for match in matches: match_details = api.get_match_details(match.get('match_id'))['result'] if match.get('lobby_type') is 5: continue radiant_win = match_details['radiant_win'] players = match_details.get('players') team_radiant = None match_won = None for player in players: # This is the player if player.get('account_id') == account_id: if player.get('player_slot') < 5: team_radiant = True else: team_radiant = False if team_radiant and radiant_win:
# fetch existing match details from mongo all_match_details = {} for match_id in match_ids_details_fetched: all_match_details[match_id] = ti5_match_details.find({"match_id": match_id})[0] # fetch match details for derived match_ids # trying to do this in chunks now, since bulk fetches failed multiple times to_remove = [] i = 0 iteration = 1 while match_ids: print(ctime(), "Iteration 1 - Matches remaining to be fetched", len(match_ids)) for match_id in match_ids: try: cur_response = api.get_match_details(match_id=match_id) if not 'match_id' in cur_response['result']: print("Match id", match_id, ":", "Unsuccessful fetch / bad id") else: # successful data fetch all_match_details[match_id] = cur_response['result'] to_remove.append(match_id) print("Matches fetched = #", len(all_match_details), sep="") except: print("Match id", match_id, ":", "Unsuccessful fetch / bad id") sleep(3) for match_id in to_remove: match_ids.remove(match_id) iteration += 1 for match in all_match_details:
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 get_gmd_from_api(match_id): try: gmd = api.get_match_details(match_id)['result'] except requests.exceptions.HTTPError: return None return gmd
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 respond(self): if random.random() < ResponseLast.SASS_PERCENTAGE: print("#last - sassy override") return "Bitch, you can't last for shit" print "Starting" canonical_name = ( key for key, value in AbstractResponse.GroupMeIDs.items() if value == self.msg.sender_id).next() if not AbstractResponse.has_steamID(canonical_name): return "I don't know your SteamID! Set it with '#set ID'" if not AbstractResponse.has_dotaID(canonical_name): return "I don't know your DOTA ID! Set it with '#setDota ID'" print "Setting Key & Account ID" api.set_api_key(AbstractResponse.key) account_id = AbstractResponse.name_to_steamID(canonical_name) print "Got Account ID" # 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"]) match_id = match['result']['match_id'] dotabuff_link = ResponseLast.DOTABUFF_LINK_TEMPLATE.format(id=match_id) print "Got Match Details" player_num = 0 for x in match["result"]["players"]: if int(x["account_id"]) == AbstractResponse.name_to_dotaID( canonical_name): out = "" print "Got self.sender Data" #Stats? print player_num msg = ResponseLast.match_performance_template.format( hero=data.get_hero_name(x["hero_id"])["localized_name"], k=str(x["kills"]), d=str(x["deaths"]), a=str(x["assists"]), GPM=str(x["gold_per_min"]), level=str(x["level"])) out += msg + "\n" #Items? finalItems = "Your items: " for itemNum in range(0, 6): if x["item_" + str(itemNum)] != 0 and x[ "item_" + str(itemNum)] is not None: try: finalItems += str( data.get_item_name( x["item_" + str(itemNum)])["name"]) + ", " except: finalItems += "unknown item ({}), ".format( x["item_" + str(itemNum)]) out += finalItems + "\n" #Win? #@todo fix this to incorporate woody's bugfix if player_num < 5 and match["result"]["radiant_win"]: out += "You Won! " elif player_num > 4 and not match["result"]["radiant_win"]: out += "You Won! " else: out += "You Lost.... Bitch " out += str(match_id) + " " + dotabuff_link return out player_num = player_num + 1
def insert_Match_Detail(matches): details_bucket = [] for match in matches: details = api.get_match_details(match_id=match) details_bucket.append(details) db.nemaBIG.insert(details)
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 }
def update_dota(self): # Get a list of recent matches for the player total_added = 0 api.set_api_key(AbstractResponse.key) current_time = int(time.time()) last_update_time = AbstractResponse.get_last_update_time() new_records = "" for name, account_id in AbstractResponse.GroupMetoDOTA.items(): print "Starting: {0}".format(name) # Get a list of recent matches for the player matches = api.get_match_history( account_id=account_id)["result"]["matches"] #Go through every match for match in matches: print "\tChecking: " + str(match["match_id"]) if match["start_time"] < last_update_time["last_update"]: print "\tWe've seen these matches" break if (not AbstractResponse.has_dotaMatch(match["match_id"])): single_match = api.get_match_details( match["match_id"])["result"] print "\t\tAdding: " + str(single_match["match_id"]) AbstractResponse.add_dotaMatch(single_match) total_added += 1 #Did this match set any new records# ? for player in single_match["players"]: #Is this a player we are tracking? if AbstractResponse.has_dotaID_num( int(player["account_id"])): #Yes! Check if they broke a record old_record = AbstractResponse.get_record( player["hero_id"]) print player["hero_id"] hero_dict = data.get_hero_name(player["hero_id"]) if not hero_dict: print( "For hero id = {}, not in dota2py".format( player["hero_id"])) continue hero_name = data.get_hero_name( player["hero_id"])["localized_name"] player_name = AbstractResponse.dotaID_to_name( int(player["account_id"])) if old_record is None: #this is auto a new record! new_record = { "hero_id": player["hero_id"], "max_kills": player["kills"], "max_kills_player": player["account_id"], "max_deaths": player["deaths"], "max_deaths_player": player["account_id"], "max_GPM": player["gold_per_min"], "max_GPM_player": player["account_id"], "min_GPM": player["gold_per_min"], "min_GPM_player": player["account_id"], "max_XPM": player["xp_per_min"], "max_XPM_player": player["account_id"], "min_XPM": player["xp_per_min"], "min_XPM_player": player["account_id"], } AbstractResponse.set_record(new_record) else: #There is an existing record.. Lets see if this match was a game changer new_record = old_record.copy() if old_record["max_kills"] < player["kills"]: new_records += "{0} just got {1} kills with {2}, a new record!\n".format( player_name, player["kills"], hero_name) new_record["max_kills"] = player["kills"] new_record["max_kills_player"] = player[ "account_id"] if old_record["max_deaths"] < player["deaths"]: new_records += "{0} just got {1} deaths with {2}, a new low!\n".format( player_name, player["deaths"], hero_name) new_record["max_deaths"] = player["deaths"] new_record["max_deaths_player"] = player[ "account_id"] if old_record["max_GPM"] < player[ "gold_per_min"]: new_records += "{0} just got {1} GPM with {2}, a new record!\n".format( player_name, player["gold_per_min"], hero_name) new_record["max_GPM"] = player[ "gold_per_min"] new_record["max_GPM_player"] = player[ "account_id"] if old_record["min_GPM"] > player[ "gold_per_min"]: new_records += "{0} just got {1} GPM with {2}, a new low!\n".format( player_name, player["gold_per_min"], hero_name) new_record["min_GPM"] = player[ "gold_per_min"] new_record["min_GPM_player"] = player[ "account_id"] if old_record["max_XPM"] < player["xp_per_min"]: new_records += "{0} just got {1} XPM with {2}, a new record!\n".format( player_name, player["xp_per_min"], hero_name) new_record["max_XPM"] = player[ "xp_per_min"] new_record["max_XPM_player"] = player[ "account_id"] if old_record["min_XPM"] > player["xp_per_min"]: new_records += "{0} just got {1} XPM with {2}, a new low!\n".format( player_name, player["xp_per_min"], hero_name) new_record["min_XPM"] = player[ "xp_per_min"] new_record["min_XPM_player"] = player[ "account_id"] AbstractResponse.set_record(new_record) else: print "\t Was Duplicate" print "Updated {0} Matches".format(total_added) if last_update_time == None: time_dict = {'last_update': current_time} else: time_dict = last_update_time.copy() time_dict["last_update"] = current_time AbstractResponse.set_last_update_time(time_dict) return new_records
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!' )
def respond(self): if random.random() < ResponseLast.SASS_PERCENTAGE: print("#last - sassy override") return "Bitch, you can't last for shit" print "Starting" canonical_name = (key for key,value in AbstractResponse.GroupMeIDs.items() if value==self.msg.sender_id).next() if not AbstractResponse.has_steamID(canonical_name): return "I don't know your SteamID! Set it with '#set ID'" if not AbstractResponse.has_dotaID(canonical_name): return "I don't know your DOTA ID! Set it with '#setDota ID'" print "Setting Key & Account ID" api.set_api_key(AbstractResponse.key) account_id = AbstractResponse.name_to_steamID(canonical_name) print "Got Account ID" # 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"]) match_id = match['result']['match_id'] dotabuff_link = ResponseLast.DOTABUFF_LINK_TEMPLATE.format(id=match_id) print "Got Match Details" player_num = 0 for x in match["result"]["players"]: if int(x["account_id"]) == AbstractResponse.name_to_dotaID(canonical_name): out = "" print "Got self.sender Data" #Stats? print player_num msg = ResponseLast.match_performance_template.format(hero=data.get_hero_name(x["hero_id"])["localized_name"], k=str(x["kills"]), d=str(x["deaths"]), a=str(x["assists"]), GPM=str(x["gold_per_min"]), level=str(x["level"]) ) out += msg + "\n" #Items? finalItems = "Your items: " for itemNum in range(0, 6): if x["item_" + str(itemNum)] != 0 and x["item_" + str(itemNum)] is not None: try: finalItems += str(data.get_item_name(x["item_" + str(itemNum)])["name"]) + ", " except: finalItems += "unknown item, " out += finalItems + "\n" #Win? #@todo fix this to incorporate woody's bugfix if player_num < 5 and match["result"]["radiant_win"]: out += "You Won! " elif player_num > 4 and not match["result"]["radiant_win"]: out += "You Won! " else: out += "You Lost.... Bitch " out += str(match_id) + " " + dotabuff_link return out player_num = player_num + 1