Skip to content

Instantly share code, notes, and snippets.

@NikolasTzimoulis
Last active January 17, 2017 17:46
Show Gist options
  • Save NikolasTzimoulis/fafd374843feae40cb46c2a00da70660 to your computer and use it in GitHub Desktop.
Save NikolasTzimoulis/fafd374843feae40cb46c2a00da70660 to your computer and use it in GitHub Desktop.
Background check your dota teammates and enemies to see if the trench is real.
import requests, json, time, pickle, re, os
myAccount = 68186278 #REPLACE THIS WITH YOUR STEAM ID
matchCountMe = 0 # how many of my latest matches to look for players in (set to 0 to fetch current live match)
matchCountOthers = 10 # how many matches from each other player to look at
matchExtra = 5 # buffer of extra matches to fetch for other players in case some need to be thrown out
steamKeyFileName = 'steamwebapikey.txt'
serverLogFile = 'C:\Program Files (x86)\Steam\steamapps\common\dota 2 beta\game\dota\server_log.txt'
logFileName = 'teammates.txt'
anonymous = 4294967295 #-1 in unsigned form
GetMatchHistory = r'https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v1/'
GetMatchDetails = r'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v1/'
def statFormat(stat):
if stat == 0:
return '-'
elif stat <= 1:
return str(round(100*stat,1))+'%'
elif stat < 100:
return str(round(stat,1))
else:
return str(int(round(stat,0)))
# get steam api key
try:
steamKeyFile = open(steamKeyFileName, 'rb')
steamKey = pickle.load(steamKeyFile)
steamKeyFile.close()
except:
print "Steam API Key:",
steamKey = raw_input()
steamKeyFile = open(steamKeyFileName, 'wb')
pickle.dump(steamKey, steamKeyFile)
steamKeyFile.close()
teammates = []
enemies = []
client = requests.session()
if matchCountMe > 0:
# get last matches for my account
print "Fetching your last " + str(matchCountMe) + " matches..."
parameters = {'key': steamKey, 'account_id': myAccount, 'matches_requested': matchCountMe}
r = client.get(GetMatchHistory, params=parameters)
page = json.loads(r.content)['result']['matches']
for match in page:
# for each of my matches find my enemeis and teammates
meInRadiant = True
radiant = []
dire = []
for p in match['players']:
account = p['account_id']
if len(radiant) < 5:
radiant.append(account)
else:
dire.append(account)
if account == myAccount:
meInRadiant = False
if meInRadiant:
teammates.extend(radiant)
enemies.extend(dire)
else:
teammates.extend(dire)
enemies.extend(radiant)
else:
for line in reversed(open(serverLogFile).readlines()):
meInRadiant = True
radiant = []
dire = []
if not line.split()[3] == 'loopback':
print "Reading server log from " + ''.join(line.split()[0:3])
for p in line.split()[7:17]:
account = int(re.findall(r"[\w']+", p)[3])
if len(radiant) < 5:
radiant.append(account)
else:
dire.append(account)
if account == myAccount:
meInRadiant = False
if meInRadiant:
teammates.extend(radiant)
enemies.extend(dire)
else:
teammates.extend(dire)
enemies.extend(radiant)
break
# trim useless data from list of teammates/enemies
anonTeam = teammates.count(anonymous)
anonEnem = enemies.count(anonymous)
teammates = set(teammates)
enemies = set(enemies)
teammates.remove(myAccount)
if anonymous in teammates: teammates.remove(anonymous)
if anonymous in enemies: enemies.remove(anonymous)
pickle.dump(teammates, open( "teammates.p", "wb" ))
pickle.dump(enemies, open( "enemies.p", "wb" ))
playerStats = {}
playerCounter = 0
# for each player I've been in a match with
print "Will look up", len(enemies.union(teammates)), "players."
for player in enemies.union(teammates):
time.sleep(1)
playerCounter += 1
print "Looking up player "+str(playerCounter) + ",", str(player)+ ",",
print ("teammate:" if player in teammates else "enemy:"),
parameters = {'key': steamKey, 'account_id': player, 'matches_requested': matchCountOthers+matchExtra}
thisPlayerMatches = 0
try:
r = client.get(GetMatchHistory, params=parameters)
page = json.loads(r.content)['result']['matches']
thisPlayerStats = {'wins':0, 'kills': 0, 'deaths': 0, 'assists': 0, 'last_hits': 0, 'gold_per_min': 0, 'xp_per_min':0, 'hero_damage': 0, 'tower_damage': 0, 'hero_healing': 0, 'level': 0}
# find his latest matches
for match in page:
# keep looking into matches until we run out of fetched matches or we reach our match quata
if thisPlayerMatches >= matchCountOthers:
break
matchID = str(match['match_id'])
parameters = {'key': steamKey, 'match_id': matchID}
r = client.get(GetMatchDetails, params=parameters)
details = json.loads(r.content)['result']
radiantWin = details['radiant_win']
pCount = 0
skipThisMatch = False
#skip match if I'm in it
for p in details['players']:
if p['account_id'] == myAccount:
skipThisMatch = True
if skipThisMatch:
continue
for p in details['players']:
# find him and his stats in the match details
pCount += 1
if p['account_id'] == player:
try:
if pCount<=5 and radiantWin:
thisPlayerStats['wins'] += 1
elif pCount>5 and not radiantWin:
thisPlayerStats['wins'] += 1
thisPlayerStats['kills'] += p['kills']
thisPlayerStats['deaths'] += p['deaths']
thisPlayerStats['assists'] += p['assists']
thisPlayerStats['last_hits'] += p['last_hits']
thisPlayerStats['gold_per_min'] += p['gold_per_min']
thisPlayerStats['xp_per_min'] += p['xp_per_min']
thisPlayerStats['hero_damage'] += p['hero_damage']
thisPlayerStats['tower_damage'] += p['tower_damage']
thisPlayerStats['hero_healing'] += p['hero_healing']
thisPlayerStats['level'] += p['level']
thisPlayerMatches += 1
print '.',
except:
print '!',
break
except:
pass
if thisPlayerMatches == matchCountOthers:
playerStats[player] = thisPlayerStats
print statFormat(thisPlayerStats['wins']/float(matchCountOthers))
else:
print " (player ignored)"
pickle.dump(playerStats, open( "playerStats.p", "wb" ))
# divide stats by teammates and enemies
sumTeammates = {'wins':0, 'kills': 0, 'deaths': 0, 'assists': 0, 'last_hits': 0, 'gold_per_min': 0, 'xp_per_min':0, 'hero_damage': 0, 'tower_damage': 0, 'hero_healing': 0, 'level': 0}
actualTeammateCount = 0
for p in teammates:
if p in playerStats:
actualTeammateCount +=1
for stat in playerStats[p]:
sumTeammates[stat] += playerStats[p][stat]
if actualTeammateCount > 0:
sumTeammates = {k: v/float(actualTeammateCount)/float(matchCountOthers) for k, v in sumTeammates.items()}
#print 'teammates:', actualTeammateCount, sumTeammates
sumEnemies = {'wins':0, 'kills': 0, 'deaths': 0, 'assists': 0, 'last_hits': 0, 'gold_per_min': 0, 'xp_per_min':0, 'hero_damage': 0, 'tower_damage': 0, 'hero_healing': 0, 'level': 0}
actualEnemyCount = 0
for p in enemies:
if p in playerStats:
actualEnemyCount += 1
for stat in playerStats[p]:
sumEnemies[stat] += playerStats[p][stat]
if actualEnemyCount > 0:
sumEnemies = {k: v/float(actualEnemyCount)/float(matchCountOthers) for k, v in sumEnemies.items()}
#print 'enemies:', actualEnemyCount, sumEnemies
# all stats as a sanity check
sumAll = {'wins':0, 'kills': 0, 'deaths': 0, 'assists': 0, 'last_hits': 0, 'gold_per_min': 0, 'xp_per_min':0, 'hero_damage': 0, 'tower_damage': 0, 'hero_healing': 0, 'level': 0}
for p in playerStats:
for stat in playerStats[p]:
sumAll[stat] += playerStats[p][stat]
if len(playerStats) > 0:
sumAll = {k: v/float(len(playerStats))/float(matchCountOthers) for k, v in sumAll.items()}
#print 'all:', len(playerStats), sumAll
logFile = open(logFileName, 'w')
printOutput = "teammates: " + str(actualTeammateCount) + " (+" + str(anonTeam+len(teammates)-actualTeammateCount) + ")"
logFile.write(printOutput+'\n')
printOutput = "enemies: " + str(actualEnemyCount) + " (+" + str(anonEnem+len(enemies)-actualEnemyCount) + ")"
logFile.write(printOutput+'\n')
printOutput = "union: " +str(len(playerStats)) + " (+" + str(len(enemies.union(teammates))-len(playerStats)) + ")"
logFile.write(printOutput+'\n')
printOutput = "intersection: " + str(len(enemies.intersection(teammates)))
logFile.write(printOutput+'\n\n')
for stat in sumAll:
logFile.write(stat+'\n')
logFile.write('\t' + statFormat(sumTeammates[stat]) + '\t\t' + statFormat(sumEnemies[stat]) + '\t\t' + statFormat(sumAll[stat]) + '\n')
logFile.write("\n\nI see " +str(actualTeammateCount) + " teammates and they have an average recent game winrate of " + statFormat(sumTeammates['wins']) + ". I see " + str(actualEnemyCount) + " enemies and they have " + statFormat(sumEnemies['wins']) + ". ")
logFile.close()
os.startfile(logFileName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment