def busca_ids(self): ids=[] try: if len(self.ids) < 1: partidas = api.get_match_history(game_mode=self.game_mode, account_id=self.account_id, min_players=10 ) ids = [i["match_id"] for i in partidas["result"]["matches"] ] else: partidas = api.get_match_history(game_mode=self.game_mode, account_id=self.account_id, min_players=10, start_at_match_id=min(self.ids) ) ids += [i["match_id"] for i in partidas["result"]["matches"]] except requests.HTTPError as erro: print(erro) return ids
def test_match_history(self): """ Get a list of the latest matches """ j = api.get_match_history() self.assertEquals(j["result"]["status"], 1) self.assertIn("matches", j["result"])
def pega_ids(self, hist=False): ids = [] while len(ids)<=1: try: if not hist: partidas = api.get_match_history(skill=self.skill, game_mode=self.game_mode, min_players=10) else: partidas = api.get_match_history(skill=self.skill, game_mode=self.game_mode, min_players=10, start_at_match_id=hist ) ids = [i["match_id"] for i in partidas["result"]["matches"] ] except requests.RequestException as erro: print(erro) return ids
def loopMatchIDCollection(): global endOfPageID time.sleep(1.2) #sleep for api limits match_ids = api.get_match_history(start_at_match_id=endOfPageID) for i in range(0, 25): if i == 24: endOfPageID = match_ids["result"]["matches"][i]["match_id"]-1 print "end of page id "+ str(endOfPageID) matchids.insert(match_ids["result"]["matches"][i]) print 'Inserted match ID: '+str(match_ids["result"]["matches"][i]["match_id"])
def get_gmh_from_api(self): try: gmh = api.get_match_history(skill=self._skill, min_players=10)['result'] except requests.exceptions.HTTPError: return None error_code = gmh['status'] if error_code is not 1: return None return gmh
def main(): '''The main entry point of dotabot.''' start_match_id = None print('Start items in database: ', count_items_in_collection()) while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(1.0) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) print('Aquiring new matches') #gmh = api.get_match_history(start_at_match_id=start_match_id, #skill=3, #game_mode=2, #min_players=10)['result'] gmh = api.get_match_history(skill=3, game_mode=2, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GMH query at match_id %s had error code %s. Retrying.' % ( start_match_id, error_code) logger.debug(msg) continue if len(matches) is 1: logger.debug('Finished processing all 500 most recent matches.') for match in matches: match_id = match['match_id'] last_match_id = match_id if match_collection.find_one({'match_id': match_id}) != None: logger.debug('Encountered match %s already in database.' % match_id) # exit loop so we don't process already stored games continue while True: try: process_match_details(match_id) except: print( 'Unable to process match: 503 Server Error: Service Unavailable' ) continue break print('Items in database: ', count_items_in_collection()) logger.debug('Match_id of last match of GMH query: %s' % last_match_id) # We don't want to record the last match twice, so subtract 1 start_match_id = last_match_id - 1
def latest_matches(account_id=None, start_at_match_id=None, matches_requested=500, fetch_delay=1, debug=True, **kwargs): """ Returns data for most recent matches according to given kwargs Rate limits the API requests according to `fetch_delay` (in seconds) Output : last_response_status, last_response_detail, match_history """ # tracking variables matches_fetched = 0 last_match_id = start_at_match_id last_response_status = 1 match_history = [] last_response_detail = "Fetch successful" while last_response_status == 1 and matches_fetched < matches_requested: cur_response = api.get_match_history(account_id=account_id, start_at_match_id=last_match_id, **kwargs) last_response_status = cur_response['result']['status'] if not last_response_status == 1: # unsuccessful query if not 'statusDetail' in cur_response['result']: last_response_detail = "Unknown error" else: last_response_detail = cur_response['result']['statusDetail'] break else: # successful data fetch cur_matches = cur_response['result']['matches'] if len(cur_matches) >= 1: if not match_history: # very first fetch match_history.extend(cur_matches) matches_fetched += len(cur_matches) else: # 2nd fetch onwards, ignore the first common match match_history.extend(cur_matches[1:]) matches_fetched += len(cur_matches) - 1 if len(cur_matches) == 1 and cur_matches[0]['match_id'] == last_match_id: break else: break last_match_id = cur_matches[-1]['match_id'] if debug: print("Matches fetched - #{}...".format(matches_fetched)) wait_for_next_fetch(fetch_delay) if debug: print("{0}: {1}".format(last_response_status, last_response_detail)) return {'status':last_response_status, 'statusDetail':last_response_detail, 'matches':match_history}
def buscando(self): matches = pd.DataFrame(columns=["match_id", "start_time", "lobby_type"]) while True: try: partidas = api.get_match_history(skill=self.skill, game_mode=self.game_mode, min_players=self.min_players) for i in partidas["result"]["matches"]: match = { "match_id":[i["match_id"]], "start_time":[i["start_time"]], "lobby_type":[i["lobby_type"]] } matches = matches.append(pd.DataFrame.from_dict(match)) break except requests.RequestException as erro: pass return matches
def main(start_match_id): '''The main entry point of dotabot.''' global date_max while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(1.0) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) gmh = api.get_match_history(start_at_match_id=start_match_id, skill=3, date_min=DATE_MIN, date_max=date_max, game_mode=2, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GetMatchHistory query starting at match_id %s returned error code %s. Retrying.' % ( start_match_id, error_code) logger.debug(msg) send_email(msg, subject='GMH query failed (script still running)') continue if len(matches) is 0: msg = 'Zero matches for GMH query with start_at_match_id=%s: \n\n %s' % ( start_match_id, gmh) logger.debug(msg) send_email( msg, subject='GMH query had zero matches (forced script to crash)') exit(-1) for match in matches: sleep(1.0) process_match_details(match['match_id']) tail_match = matches[-1] date_max = tail_match['start_time'] tail_match_id = tail_match['match_id'] logger.debug('Match_id of last match of GMH query: %s' % last_match_id) logger.debug('Date of last match of GMH query: %s' % date_max) # We don't want to record the tail match twice, so subtract 1 start_match_id = tail_match_id - 1
def main(): '''The main entry point of dotabot.''' start_match_id = None while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(1.0) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) gmh = api.get_match_history(start_at_match_id=start_match_id, skill=3, game_mode=2, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GMH query at match_id %s had error code %s. Retrying.' % ( start_match_id, error_code) logger.debug(msg) continue if len(matches) is 0: logger.debug('Finished processing all 500 most recent matches.') exit(0) for match in matches: match_id = match['match_id'] if match_collection.find_one({'match_id': match_id}) != None: logger.debug( 'Encountered match %s already in database, exiting.' % match_id) continue sleep(1.0) process_match_details(match_id) last_match_id = matches[-1]['match_id'] logger.debug('Match_id of last match of GMH query: %s' % last_match_id) # We don't want to record the last match twice, so subtract 1 start_match_id = last_match_id - 1
def main(): '''The main entry point of dotabot.''' valid_mode = [0,1,2,3,4,5] mode_start_id = {0:None, 1:None, 2:None, 3:None, 4:None, 5:None} while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(0.1) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) for mode in valid_mode: start_match_id = mode_start_id[mode] gmh = api.get_match_history(start_at_match_id=start_match_id, skill=2, game_mode=mode, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GMH query at match_id %s had error code %s. Retrying.' % (start_match_id, error_code) logger.debug(msg) continue if len(matches) is 0: logger.debug('Finished processing all 500 most recent matches.') exit(0) for match in matches: match_id = match['match_id'] if match_collection.find_one({'match_id':match_id}) != None: logger.debug('Encountered match %s already in database, exiting.' % match_id) exit(0) sleep(1.0) process_match_details(match_id) last_match_id = matches[-1]['match_id'] logger.debug('Match_id of last match of GMH query: %s' % last_match_id) # We don't want to record the last match twice, so subtract 1 start_match_id = last_match_id - 1 mode_start_id[mode] = start_match_id
def test_player_match_history(self): """ Get the latest matches for a particular player """ j = api.get_match_history(account_id=STEAM_ID) self.assertEquals(j["result"]["status"], 1) self.assertTrue("matches" in j["result"]) matches = j["result"]["matches"] # Check that this player is in each of the games steam_id_32 = data.get_steam_id_32(STEAM_ID) for match in matches: contained_player = False for player in match["players"]: if player["account_id"] == steam_id_32: contained_player = True break self.assertTrue(contained_player)
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 main(start_match_id): '''The main entry point of dotabot.''' global date_max while True: # Note: GetMatchHistory returns a list of matches in descending order, # going back in time. sleep(1.0) logger.debug('Doing GMH query for start_at_match_id=%s' % start_match_id) gmh = api.get_match_history(start_at_match_id=start_match_id, skill=3, date_min=DATE_MIN, date_max=date_max, game_mode=2, min_players=10)['result'] error_code = gmh['status'] matches = gmh['matches'] if error_code is not 1: msg = 'GetMatchHistory query starting at match_id %s returned error code %s. Retrying.' % (start_match_id, error_code) logger.debug(msg) send_email(msg, subject='GMH query failed (script still running)') continue if len(matches) is 0: msg = 'Zero matches for GMH query with start_at_match_id=%s: \n\n %s' % (start_match_id, gmh) logger.debug(msg) send_email(msg, subject='GMH query had zero matches (forced script to crash)') exit(-1) for match in matches: sleep(1.0) process_match_details(match['match_id']) tail_match = matches[-1] date_max = tail_match['start_time'] tail_match_id = tail_match['match_id'] logger.debug('Match_id of last match of GMH query: %s' % last_match_id) logger.debug('Date of last match of GMH query: %s' % date_max) # We don't want to record the tail match twice, so subtract 1 start_match_id = tail_match_id - 1
def findMatches(account_id): return api.get_match_history(account_id=account_id)["result"]["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: # 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!' )
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, )
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())
def findMatches(account_id): try: return api.get_match_history(account_id=account_id)["result"]["matches"] except: logging.error('no match history data found') return logging.error('no match history found')
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!')
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:
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""" 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 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 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
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 getLastMatchId(self, account_id): last_match = dota_api.get_match_history(account_id=account_id)["result"]["matches"][0] return last_match["match_id"]