def test_correct_api_key(self): key = 'abcdxyz' tmp_api = d2api.APIWrapper(key) with self.assertRaises( d2errors.APIAuthenticationError, msg= 'Request with API key \'{0}\' should raise authentication error' .format(key)): tmp_api.get_match_details('4176987886')
def addPlayer(steamId): try: conn = psycopg2.connect(dbname='sammy1', password='******', user='******', host='localhost') except: print("i am unable to connect to the database") api = d2api.APIWrapper(steamApi) cursor = conn.cursor() #create list var for parse playerId #api = d2api.APIWrapper(steamApi) #variables playerId = steamId playerInfo = [] playerIds = [] playerIds.append(playerId) playersInfo = api.get_player_summaries(account_ids=playerIds) playerInfo.append(playersInfo['players'][0]['avatarmedium']) playerInfo.append(playersInfo['players'][0]['lastlogoff']) playerInfo.append(playersInfo['players'][0]['personaname']) playerInfo.append(playersInfo['players'][0]['personastate']) playerInfo.append(playersInfo['players'][0]['profileurl']) playerInfo.append(playersInfo['players'][0]['steam_account']['id32']) playerInfo.append(playersInfo['players'][0]['steam_account']['id64']) playerInfo.append(playersInfo['players'][0]['steamid']) playerInfo.append(playersInfo['players'][0]['timecreated']) try: cursor.execute( "INSERT INTO test2 (avatar, lastlogoff, personaname, personastate, profileurl, steamaccount32, steamaccount64, steamid, timecreated) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s);", (playerInfo[0], playerInfo[1], playerInfo[2], playerInfo[3], playerInfo[4], playerInfo[5], playerInfo[6], playerInfo[7], playerInfo[8])) except: print(cursor.fetchall()) print("Insert into been failed ;c") conn.commit() conn.close() cursor.close() playerInfo.clear() userMenu()
def add_single_replay(session, match_id: int): dota2_webapi = d2api.APIWrapper() @DecoratorUsageCheck(session, get_api_usage, WEB_API_LIMIT) def _get_replay_details(web_query): return dota2_webapi.get_match_details(**web_query) match_query = _get_replay_details({'match_id': match_id}) sleep(1) new_replay = make_replay(match_query) try: session.add(new_replay) session.commit() except SQLAlchemyError as e: print("Failed to add new match {}".format(match_id)) print(e) session.rollback()
def setUp(self): api = d2api.APIWrapper() self.get_broadcaster_info = api.get_broadcaster_info
def setUp(self): api = d2api.APIWrapper() self.get_live_league_games = api.get_live_league_games
def update_league_replays(session, league_id): api_usage = get_api_usage(session) if api_usage.api_calls > WEB_API_LIMIT: print("Update aborted due to exceeding API limit!") return None league = session.query(League).filter(League.league_id == league_id).one() if league.status == LeagueStatus.FINISHED: print("League {} considered finished.".format(league_id)) return None last_replay = league.last_replay if last_replay == 0 or last_replay is None: web_query = {'league_id': league_id} else: web_query = {'league_id': league_id, 'start_at_match_id': last_replay} @DecoratorUsageCheck(session, get_api_usage, WEB_API_LIMIT) def _get_replays(web_query): return dota2_webapi.get_match_history(**web_query) def _query_replays(web_query): try: request = _get_replays(web_query) except (APIAuthenticationError, APITimeoutError) as e: print("Failed to update league listing.") print(e) return None, None, None except APIOverLimit as e: print(e) return None, None, None finally: sleep(1) total = request['total_results'] replays = request['matches'] processed = len(replays) if processed == 0: last_replay = 0 return total, processed, last_replay else: last_replay = replays[-1]['match_id'] for r in replays: replay_id = r['match_id'] if session.query( exists().where(Replay.replay_id == replay_id)).scalar(): continue new_replay = make_replay(r) new_replay.league_id = league_id try: session.add(new_replay) #session.commit() except SQLAlchemyError as e: print("Failed to add new match {}".format(replay_id)) print(e) session.rollback() return total, processed, last_replay processed = 0 total = 1 with requests_Session() as r_session: # dota2_webapi = Initialise(executor=r_session.get) dota2_webapi = d2api.APIWrapper() while total > processed: total, p_in, last_replay = _query_replays(web_query) if total is None: break processed += p_in web_query = { 'league_id': league_id, 'start_at_match_id': last_replay - 1 } replay, time = get_most_recent(session, league_id) league.last_replay = replay league.last_replay_time = time league.last_update = datetime.now() try: session.merge(league) session.commit() except SQLAlchemyError as e: print(e) session.rollback() check_league_expiry(session, league_id)
def weekReport(cursor, conn): today = datetime.datetime.today() monday = today - datetime.timedelta(datetime.datetime.weekday(today)) sunday = today + datetime.timedelta(6 - datetime.datetime.weekday(today)) lastMonday = monday - datetime.timedelta(days=7) lastSunday = sunday - datetime.timedelta(days=7) print('') print('*Отчётик!*') time2 = time.mktime(monday.timetuple()) time3 = time2 - 604800 api = d2api.APIWrapper(SteamApi) sql = """ SELECT steamId FROM users WHERE user = ? """ cursor.execute(sql, [(getpass.getuser())]) temp = cursor.fetchall()[0][0] steamId32 = temp sql = """ SELECT * FROM match""" + str(temp) + """ ORDER BY start_time DESC """ cursor.execute(sql) fetch = cursor.fetchall() time1 = fetch[0][7] # print(fetch['num_results']) tempMatches = [] for row in cursor.execute(""" SELECT rowid, * FROM match""" + str(temp) + """ ORDER BY start_time DESC """): if ((row[8] < time2) & (row[8] > time3)): tempMatches.append(row) matchDetails = api.get_match_details(tempMatches[0][3]) print('На прошлой неделе: ' + str(datetime.date.today().isocalendar()[1] - 1) + '. ' + str(lastMonday.day) + ' ' + str(lastMonday.strftime("%B")) + ' - ' + str(lastSunday.day) + ' ' + str(lastSunday.strftime("%B")) + '.') win = 0 for match in tempMatches: # print(match) matchDetails = api.get_match_details(match[4]) wonside = matchDetails['winner'] for player in range(10): if (matchDetails['players'][player]['steam_account']['id32'] == steamId32): if (wonside == matchDetails['players'][player]['side']): win = win + 1 if (win == 0): temp = 0 else: temp = win / (len(tempMatches) / 100) print('Количество игр: ' + str(len(tempMatches)) + '. ' + 'Win: ' + str(win) + ' Lose: ' + str(len(tempMatches) - win) + ' . WR: ' + str(temp)) mytopkda = [] tempList = [] tempList1 = [] for i in range(len(tempMatches)): tempList1.append([None] * 11) i = 0 for match in tempMatches: matchDetails = api.get_match_details(match[4]) #ищем лучшее кда topkda = [] temp = matchDetails['players'][player]['hero']['hero_name'] temp = re.sub(r"npc_dota_hero_", "", temp) topkda.insert(0, temp) topkda.insert(1, matchDetails['players'][0]['kills']) topkda.insert(2, matchDetails['players'][0]['deaths']) topkda.insert(3, matchDetails['players'][0]['assists']) temp = (matchDetails['players'][0]['kills'] + matchDetails['players'][0]['assists'] ) / matchDetails['players'][0]['deaths'] topkda.insert(4, temp) temp1 = '' for num in matchDetails['players'][0]['inventory']: if (num['item_name'] != 'unknown_item'): temp = num['item_name'] temp = re.sub(r"item_", "", temp) temp1 = temp1 + temp + '; ' if (num['item_id'] == 271): temp1 = temp1 + 'aghanim_blessing;' if (num['item_name'] == 'unknown_item'): temp1 = temp1 + 'Empty_slot; ' topkda.insert(5, temp1) topkda.insert(6, matchDetails['duration']) topkda.insert(7, matchDetails['start_time']) topkda.insert(8, matchDetails['match_id']) topkda.insert(9, matchDetails['players'][player]['side']) topkda.insert(10, matchDetails['winner']) for player in range(10): kda = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists'] ) / matchDetails['players'][player]['deaths'] if (matchDetails['players'][player]['steam_account']['id32'] == steamId32): temp = matchDetails['players'][player]['hero']['hero_name'] temp = re.sub(r"npc_dota_hero_", "", temp) tempList1[i][0] = temp tempList1[i][1] = matchDetails['players'][player]['kills'] tempList1[i][2] = matchDetails['players'][player]['deaths'] tempList1[i][3] = matchDetails['players'][player]['assists'] temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists'] ) / matchDetails['players'][player]['deaths'] tempList1[i][4] = temp temp1 = '' for num in matchDetails['players'][player]['inventory']: if (num['item_name'] != 'unknown_item'): temp = num['item_name'] temp = re.sub(r"item_", "", temp) temp1 = temp1 + temp + '; ' if (num['item_id'] == '271'): temp1 = temp1 + 'aghanim_blessing;' if (num['item_name'] == 'unknown_item'): temp1 = temp1 + 'Empty_slot; ' tempList1[i][5] = temp1 tempList1[i][6] = matchDetails['duration'] tempList1[i][7] = matchDetails['start_time'] tempList1[i][8] = matchDetails['match_id'] tempList1[i][9] = matchDetails['players'][player]['side'] tempList1[i][10] = matchDetails['winner'] print(kda) if (mytopkda != []): print(mytopkda[4]) print(mytopkda) print(kda) if (mytopkda == []): temp = matchDetails['players'][player]['hero']['hero_name'] temp = re.sub(r"npc_dota_hero_", "", temp) mytopkda.insert(0, temp) mytopkda.insert(1, matchDetails['players'][player]['kills']) mytopkda.insert(2, matchDetails['players'][player]['deaths']) mytopkda.insert(3, matchDetails['players'][player]['assists']) temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists'] ) / matchDetails['players'][player]['deaths'] mytopkda.insert(4, temp) temp1 = '' for num in matchDetails['players'][player]['inventory']: if (num['item_name'] != 'unknown_item'): temp = num['item_name'] temp = re.sub(r"item_", "", temp) temp1 = temp1 + temp + '; ' if (num['item_id'] == '271'): temp1 = temp1 + 'aghanim_blessing;' if (num['item_name'] == 'unknown_item'): temp1 = temp1 + 'Empty_slot; ' mytopkda.insert(5, temp1) mytopkda.insert(6, matchDetails['duration']) mytopkda.insert(7, matchDetails['start_time']) mytopkda.insert(8, matchDetails['match_id']) mytopkda.insert(9, matchDetails['players'][player]['side']) mytopkda.insert(10, matchDetails['winner']) print(mytopkda) print(mytopkda[4]) elif (kda > mytopkda[4]): mytopkda.clear() temp = matchDetails['players'][player]['hero']['hero_name'] temp = re.sub(r"npc_dota_hero_", "", temp) mytopkda.insert(0, temp) mytopkda.insert(1, matchDetails['players'][player]['kills']) mytopkda.insert(2, matchDetails['players'][player]['deaths']) mytopkda.insert(3, matchDetails['players'][player]['assists']) temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists'] ) / matchDetails['players'][player]['deaths'] mytopkda.insert(4, temp) temp1 = '' for num in matchDetails['players'][player]['inventory']: if (num['item_name'] != 'unknown_item'): temp = num['item_name'] temp = re.sub(r"item_", "", temp) temp1 = temp1 + temp + '; ' if (num['item_id'] == '271'): temp1 = temp1 + 'aghanim_blessing;' if (num['item_name'] == 'unknown_item'): temp1 = temp1 + 'Empty_slot; ' mytopkda.insert(5, temp1) mytopkda.insert(6, matchDetails['duration']) mytopkda.insert(7, matchDetails['start_time']) mytopkda.insert(8, matchDetails['match_id']) mytopkda.insert(9, matchDetails['players'][player]['side']) mytopkda.insert(10, matchDetails['winner']) print(mytopkda[4]) kd if (kda > topkda[4]): topkda.clear() temp = matchDetails['players'][player]['hero']['hero_name'] temp = re.sub(r"npc_dota_hero_", "", temp) topkda.insert(0, temp) topkda.insert(1, matchDetails['players'][player]['kills']) topkda.insert(2, matchDetails['players'][player]['deaths']) topkda.insert(3, matchDetails['players'][player]['assists']) temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists'] ) / matchDetails['players'][player]['deaths'] topkda.insert(4, temp) temp = '' temp1 = '' for num in matchDetails['players'][player]['inventory']: if (num['item_name'] != 'unknown_item'): temp = num['item_name'] temp = re.sub(r"item_", "", temp) temp1 = temp1 + temp + '; ' if (num['item_id'] == '271'): temp1 = temp1 + 'aghanim_blessing; ' if (num['item_name'] == 'unknown_item'): temp1 = temp1 + 'Empty_slot;' topkda.insert(5, temp1) topkda.insert(6, matchDetails['duration']) topkda.insert(7, matchDetails['start_time']) topkda.insert(8, matchDetails['match_id']) topkda.insert(9, matchDetails['players'][player]['side']) topkda.insert(10, matchDetails['winner']) tempList.clear i = i + 1 # print(tempList1) # print(tempList1[0][0]) tableName = 'week' + str(datetime.date.today().isocalendar()[1] - 1) + 'matches' + str(steamId32) sql = """ CREATE TABLE if not exists """ + tableName + """ ( id INTEGER PRIMARY KEY NOT NULL, hero INTEGER, kills INTEGER, deaths INTEGER UNIQUE, assists INTEGER, kda REAL, inventory TEXT, duration INTEGER, start_time INTEGER, match_id INTEGER, side TEXT, winner TEXT ); """ # print(sql) cursor.execute(sql) # print(tempList1[1][0]) for number in range(len(tempList1)): sql = """ INSERT OR IGNORE INTO """ + tableName + """(hero, kills, deaths, assists, kda, inventory, duration, start_time, match_id, side, winner) VALUES ('""" + str(tempList1[number][0]) + """',""" + str( tempList1[number][1] ) + """,""" + str(tempList1[number][2]) + """,""" + str( tempList1[number][3]) + """,""" + str( tempList1[number][4]) + """,'""" + str( tempList1[number][5]) + """',""" + str( tempList1[number][6]) + """,""" + str( tempList1[number][7]) + """,""" + str( tempList1[number][8]) + """,'""" + str( tempList1[number][9]) + """','""" + str( tempList1[number][10]) + """'); """ # print(sql) cursor.execute(sql) # вывод в убывании матчей с прошлой недели. sql = """ SELECT * FROM """ + tableName + """ ORDER BY kda DESC """ cursor.execute(sql) temp = cursor.fetchall() # print(temp) # print(len(temp)) report = PrettyTable() report.field_names = [ "Result", "Hero", "Kills", "Deaths", "Assists", "KDA", "Inventory", "Duration", "Date" ] for number in range(len(temp)): if (temp[number][10] == temp[number][11]): result = 'W' else: result = 'L' duration = str(int(temp[number][7] / 60)) + ':' + str( temp[number][7] % 60) start_time = time.strftime("%d %b %H:%M", time.localtime(temp[number][8])) report.add_row([ result, str(temp[number][1]), str(temp[number][2]), str(temp[number][3]), str(temp[number][4]), str(temp[number][5]), str(temp[number][6]), str(duration), str(start_time) ]) print(report) # temp1 = '[' + result + '][' + str(temp[number][1]) + '][' + str(temp[number][2]) + '-' + str(temp[number][3]) + '-' + str(temp[number][4]) + '][' + str(temp[number][5]) + '][' + temp[number][6] + '][' + duration + '][' + start_time + ']'; # print(temp1) # print(len(tempList1)) print(topkda) print(mytopkda) print('') print('Данная неделя ' + str(datetime.date.today().isocalendar()[1]) + '. ' + str(monday.day) + ' ' + str(monday.strftime("%B")) + ' - ' + str(sunday.day) + ' ' + str(sunday.strftime("%B")) + '.') if (time1 > time2): print('На этой неделе были игры') else: print('на данной неделе вы не играли никаких игр.') print('') sql = """ SELECT players FROM users WHERE user = ? """ cursor.execute(sql, [(getpass.getuser())]) temp = cursor.fetchall()[0][0] tempStr = '{}{}'.format('match', temp) sql = """ CREATE TABLE if not exists """ + tempStr + """ ( id INTEGER PRIMARY KEY NOT NULL, dire_team_id INTEGER, lobby_type INTEGER, match_id INTEGER UNIQUE, match_seq_num INTEGER, players TEXT, radiant_team_id INTEGER, start_time INTEGER ); """ cursor.execute(sql) playerHistory = api.get_match_history(account_id=temp) # matchDetails = api.get_match_details() for number1 in range(playerHistory['num_results']): tempStr2 = "" for number2 in range(10): tempStr2 += "(" + str( playerHistory['matches'][number1]['players'][number2]['hero'] ) + ", " + str(playerHistory['matches'][number1]['players'] [number2]['side']) + ", " + str( playerHistory['matches'][number1]['players'] [number2]['steam_account']) + ");\n " sql = """ INSERT OR IGNORE INTO """ + tempStr + """ (dire_team_id, lobby_type, match_id, match_seq_num, players, radiant_team_id, start_time) VALUES (""" + str( playerHistory['matches'][number1]['dire_team_id']) + """,""" + str( playerHistory['matches'][number1]['lobby_type'] ) + """,""" + str( playerHistory['matches'][number1]['match_id']) + """,""" + str( playerHistory['matches'][number1]['match_seq_num'] ) + """, '""" + tempStr2 + """',""" + str( playerHistory['matches'][number1]['radiant_team_id'] ) + """,""" + str( playerHistory['matches'][number1]['start_time']) + """);""" cursor.execute(sql) sql = """ SELECT * FROM match""" + str(temp) + """ ORDER BY start_time DESC """ cursor.execute(sql) fetch = cursor.fetchall() playerIds = [] playerIds.append(temp) playersInfo = api.get_player_summaries(account_ids=playerIds) print(playersInfo['players'][0]['personaname']) if (fetch[0][7] > time2): # print(fetch[0]) print('На этой неделе у игрока не было') # for number in range(playerHistory['num_results'] - 1): # print(fetch[number][7]) conn.commit()
# nachalo raboti import d2api import psycopg2 from myData import SteamApi #connect to api, and player api = d2api.APIWrapper(SteamApi) #variables playerId = 78312288 playerInfo = [] playerIds = [] playerIds.append(playerId) playersInfo = api.get_player_summaries(account_ids = playerIds) def checkPlayerInDb(SteamId): #проверить есть ли этот персонаж уже вбазе 1, если нету то создать ему новую базу для матчей #проверить дату последней игры в бд и спарсить последнюю игру(проверка актуальности базы) -> если она оказывается не последней то добавлять игры до момента пока первоначально *последняя* айди матча не совпадёт def playerGamesInfo1(SteamId): #алгоритм который выводит информацию из бд, по всем матчам которые были сыграны на данной неделе. вывод информации в виде вывода табличных данных. пока что. def playerGamesInfo2(SteamId): #алгоритм который выводит информацию из бд, по всем матчам которые были сыграны на данной неделе. вывод информации в виде вывода табличных данных. пока что. ''' def createTest2():
def setUp(self): api = d2api.APIWrapper() self.get_match_details = api.get_match_details
def setUp(self): api = d2api.APIWrapper() self.get_match_history = api.get_match_history
def setUp(self): api = d2api.APIWrapper() self.get_heroes = api.get_heroes
def test_unparsed_results_dtype(self): api = d2api.APIWrapper(parse_response=False) self.assertIsInstance( api.get_match_history(), str, msg='Setting parse_response = False should return a dict.')
def test_api_method_unavailable(self): method_url = 'http://api.steampowered.com/IDOTA2Match_570/RANDOMMETHOD/v0001/' with self.assertRaises( d2errors.APIMethodUnavailable, msg="{0} is an unavailable method.".format(method_url)): d2api.APIWrapper()._api_call(method_url)
def test_insufficient_params(self): with self.assertRaises( d2errors.APIInsufficientArguments, msg="match_id is a required argument for get_match_details"): d2api.APIWrapper().get_match_details(match_id=None)
def setUp(self): api = d2api.APIWrapper() self.get_player_summaries = api.get_player_summaries
def setUp(self): api = d2api.APIWrapper() self.get_game_items = api.get_game_items
def setUp(self): api = d2api.APIWrapper() self.get_match_history_by_sequence_num = api.get_match_history_by_sequence_num
def setUp(self): api = d2api.APIWrapper() self.get_tournament_prize_pool = api.get_tournament_prize_pool
def get_instance(): if TestAPI._api_instance == None: TestAPI._api_instance = d2api.APIWrapper() return TestAPI._api_instance
def setUp(self): api = d2api.APIWrapper() self.get_top_live_game = api.get_top_live_game
def weekReport(cursor, conn): today = datetime.datetime.today() monday = today - datetime.timedelta(datetime.datetime.weekday(today)) sunday = today + datetime.timedelta(6 - datetime.datetime.weekday(today)) lastMonday = monday - datetime.timedelta(days=7) lastSunday = sunday - datetime.timedelta(days=7) print('Неделя ' + str(datetime.date.today().isocalendar()[1]) +'. ' + str(monday.day) + ' ' + str(monday.strftime("%B")) + ' - ' + str(sunday.day) + ' ' + str(sunday.strftime("%B")) + '.') time2 = time.mktime(monday.timetuple()) time3 = time2 - 604800 api = d2api.APIWrapper(SteamApi) sql = """ SELECT steamId FROM users WHERE user = ? """ cursor.execute(sql,[(getpass.getuser())]) temp = cursor.fetchall()[0][0] steamId32 = temp sql = """ SELECT * FROM match"""+str(temp)+""" ORDER BY start_time DESC """ cursor.execute(sql) fetch = cursor.fetchall() time1 = fetch[0][7] # print(fetch['num_results']) tempMatches = [] for row in cursor.execute(""" SELECT rowid, * FROM match"""+str(temp)+""" ORDER BY start_time DESC """): if((row[8] < time2) & (row[8] > time3)): tempMatches.append(row) matchDetails = api.get_match_details(tempMatches[0][3]) print('На прошлой неделе: ' + str(datetime.date.today().isocalendar()[1] - 1) + '. ' + str(lastMonday.day) + ' ' + str(lastMonday.strftime("%B")) + ' - ' + str(lastSunday.day) + ' ' + str(lastSunday.strftime("%B")) + '.') # print('Неделя ' + str(datetime.date.today().isocalendar()[1]) +'. ' + str(monday.day) + ' ' + str(monday.strftime("%B")) + ' - ' + str(sunday.day) + ' ' + str(sunday.strftime("%B")) + '.') win = 0; for match in tempMatches: # print(match) matchDetails = api.get_match_details(match[4]) wonside = matchDetails['winner'] for player in range(10): if(matchDetails['players'][player]['steam_account']['id32'] == steamId32): if(wonside == matchDetails['players'][player]['side']): win = win + 1 if(win == 0): temp = 0 else: temp = win/(len(tempMatches)/100) print('Количество игр: ' + str(len(tempMatches)) + '. ' + 'Win: ' + str(win) + ' Lose: ' + str(len(tempMatches) - win) + ' . WR: ' + str(temp)) for match in tempMatches: matchDetails = api.get_match_details(match[4]) #ищем лучшее кда topkda = [] topkda.insert(0, matchDetails['players'][0]['hero']['hero_name']) topkda.insert(1, matchDetails['players'][0]['kills']) topkda.insert(2, matchDetails['players'][0]['deaths']) topkda.insert(3, matchDetails['players'][0]['assists']) temp = (matchDetails['players'][0]['kills'] + matchDetails['players'][0]['assists']) / matchDetails['players'][0]['deaths'] topkda.insert(4, temp) temp = '' for num in matchDetails['players'][0]['inventory']: # print(num['item_name']) temp = temp + num['item_name'] + ';' topkda.insert(5, temp) topkda.insert(6, matchDetails['duration']) topkda.insert(7, matchDetails['start_time']) topkda.insert(8, matchDetails['match_id']) topkda.insert(9, matchDetails['winner']) mytopkda = [] for player in range(10): kda = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists']) / matchDetails['players'][player]['deaths'] if (matchDetails['players'][player]['steam_account']['id32'] == steamId32): if (mytopkda == []): mytopkda.insert(1, matchDetails['players'][player]['kills']) mytopkda.insert(0, matchDetails['players'][player]['hero']['hero_name']) mytopkda.insert(2, matchDetails['players'][player]['deaths']) mytopkda.insert(3, matchDetails['players'][player]['assists']) temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists']) / matchDetails['players'][player]['deaths'] mytopkda.insert(4, temp) temp = '' for num in matchDetails['players'][player]['inventory']: temp = temp + num['item_name'] + ';' mytopkda.insert(5, temp) mytopkda.insert(6, matchDetails['duration']) mytopkda.insert(7, matchDetails['start_time']) mytopkda.insert(8, matchDetails['match_id']) mytopkda.insert(9, matchDetails['winner']) elif(kda > mytopkda[5]): mytopkda.clear() mytopkda.insert(1, matchDetails['players'][player]['kills']) mytopkda.insert(0, matchDetails['players'][player]['hero']['hero_name']) mytopkda.insert(2, matchDetails['players'][player]['deaths']) mytopkda.insert(3, matchDetails['players'][player]['assists']) temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists']) / matchDetails['players'][player]['deaths'] mytopkda.insert(4, temp) temp = '' for num in matchDetails['players'][player]['inventory']: temp = temp + num['item_name'] + ';' mytopkda.insert(5, temp) mytopkda.insert(6, matchDetails['duration']) mytopkda.insert(7, matchDetails['start_time']) mytopkda.insert(8, matchDetails['match_id']) mytopkda.insert(9, matchDetails['winner']) if (kda > topkda[4]): topkda.clear() topkda.insert(0, matchDetails['players'][player]['hero']['hero_name']) topkda.insert(1, matchDetails['players'][player]['kills']) topkda.insert(2, matchDetails['players'][player]['deaths']) topkda.insert(3, matchDetails['players'][player]['assists']) temp = (matchDetails['players'][player]['kills'] + matchDetails['players'][player]['assists']) / matchDetails['players'][player]['deaths'] topkda.insert(4, temp) temp = '' for num in matchDetails['players'][player]['inventory']: temp = temp + num['item_name'] + ';' topkda.insert(5, temp) topkda.insert(6, matchDetails['duration']) topkda.insert(7, matchDetails['start_time']) topkda.insert(8, matchDetails['match_id']) topkda.insert(9, matchDetails['winner']) print(topkda) print(mytopkda) print('Количество побед') if(time1 > time2): print('На этой неделе были игры') else: print('на данной неделе вы не играли никаких игр.') sql = """ SELECT players FROM users WHERE user = ? """ cursor.execute(sql,[(getpass.getuser())]) temp = cursor.fetchall()[0][0] print(temp) tempStr = '{}{}'.format('match', temp) sql=""" CREATE TABLE if not exists """ + tempStr + """ ( id INTEGER PRIMARY KEY NOT NULL, dire_team_id INTEGER, lobby_type INTEGER, match_id INTEGER UNIQUE, match_seq_num INTEGER, players TEXT, radiant_team_id INTEGER, start_time INTEGER ); """ cursor.execute(sql) playerHistory = api.get_match_history(account_id = temp) # matchDetails = api.get_match_details() for number1 in range(playerHistory['num_results']): tempStr2 = "" for number2 in range(10): tempStr2 += "(" + str(playerHistory['matches'][number1]['players'][number2]['hero']) + ", " + str(playerHistory['matches'][number1]['players'][number2]['side']) + ", " + str(playerHistory['matches'][number1]['players'][number2]['steam_account']) + ");\n " sql=""" INSERT OR IGNORE INTO """ + tempStr + """ (dire_team_id, lobby_type, match_id, match_seq_num, players, radiant_team_id, start_time) VALUES (""" + str(playerHistory['matches'][number1]['dire_team_id']) +""",""" + str(playerHistory['matches'][number1]['lobby_type']) +""",""" + str(playerHistory['matches'][number1]['match_id']) +""",""" + str(playerHistory['matches'][number1]['match_seq_num']) +""", '""" + tempStr2 +"""',""" + str(playerHistory['matches'][number1]['radiant_team_id']) +""",""" + str(playerHistory['matches'][number1]['start_time']) + """);""" cursor.execute(sql) sql = """ SELECT * FROM match"""+str(temp)+""" ORDER BY start_time DESC """ cursor.execute(sql) fetch = cursor.fetchall() playerIds = [] playerIds.append(temp) playersInfo = api.get_player_summaries(account_ids = playerIds) print(playersInfo['players'][0]['personaname']) if(fetch[0][7]>time2): # print(fetch[0]) print('На этой неделе у игрока не было') # for number in range(playerHistory['num_results'] - 1): # print(fetch[number][7]) conn.commit()
def setUp(self): api = d2api.APIWrapper() self.api = api
def userMenu(user, cursor, conn): sql = """ SELECT steamId FROM users WHERE user = ? """ cursor.execute(sql, [(user)]) temp = cursor.fetchall()[0][0] if (temp == None): temp1 = input('Введите пожалуйста ваш steamId.') sql = """ UPDATE users SET steamId = ? WHERE user = ?; """ cursor.execute(sql, [(temp1), (user)]) print(cursor.fetchall()) api = d2api.APIWrapper(SteamApi) playerHistory = api.get_match_history(account_id=temp) tempStr = '{}{}'.format('match', temp) sql = """ CREATE TABLE if not exists """ + tempStr + """ ( id INTEGER PRIMARY KEY NOT NULL, dire_team_id INTEGER, lobby_type INTEGER, match_id INTEGER UNIQUE, match_seq_num INTEGER, players TEXT, radiant_team_id INTEGER, start_time INTEGER ); """ cursor.execute(sql) tempStr2 = '' for number1 in range(playerHistory['num_results']): tempStr2 = "" for number2 in range(10): tempStr2 += "(" + str( playerHistory['matches'][number1]['players'][number2]['hero'] ) + ", " + str(playerHistory['matches'][number1]['players'] [number2]['side']) + ", " + str( playerHistory['matches'][number1]['players'] [number2]['steam_account']) + ");\n " sql = """ INSERT OR IGNORE INTO """ + tempStr + """ (dire_team_id, lobby_type, match_id, match_seq_num, players, radiant_team_id, start_time) VALUES (""" + str( playerHistory['matches'][number1]['dire_team_id']) + """,""" + str( playerHistory['matches'][number1]['lobby_type'] ) + """,""" + str( playerHistory['matches'][number1]['match_id']) + """,""" + str( playerHistory['matches'][number1]['match_seq_num'] ) + """, '""" + tempStr2 + """',""" + str( playerHistory['matches'][number1]['radiant_team_id'] ) + """,""" + str( playerHistory['matches'][number1]['start_time']) + """);""" cursor.execute(sql) sql = """ SELECT players FROM users WHERE user = """ + getpass.getuser() + """ """ sql = """ SELECT players FROM users WHERE user = ? """ cursor.execute(sql, [(getpass.getuser())]) temp = cursor.fetchall() if (temp[0][0] == None): print('Ваш список Players пуст') ans = input('Хотите добавить игрока?(Y/N)') if (ans == 'y' or 'Y'): temp = input('Введите SteamId игрока: ') sql = """ UPDATE users SET players = ? WHERE user = ?; """ cursor.execute(sql, [(temp), getpass.getuser()]) print(cursor.fetchall()) conn.commit() weekReport(cursor, conn)
def setUp(self): api = d2api.APIWrapper() self.get_team_info_by_team_id = api.get_team_info_by_team_id
# import dota2api import d2api import requests import time from dotenv import load_dotenv from json import dump from pathlib import Path output_dir = Path('./heroes') load_dotenv(dotenv_path="setup.env") #api = dota2api.Initialise() api = d2api.APIWrapper() heroes = api.get_heroes() dota2_heroimage_url = "http://cdn.dota2.com/apps/dota2/images/heroes/" hero_map = {} redownload = False download = "url_full_portrait" download_abrev = "_full.png" for h in heroes['heroes']: full_name = h['name'] print("Processing {}".format(h['name'])) path: Path = output_dir / (full_name + download_abrev) if path.exists() and not redownload: print("{} exists and redownload is False".format(path)) hero_map[full_name] = full_name + download_abrev continue try:
def _update_league(): dota2_webapi = d2api.APIWrapper() return dota2_webapi.get_league_listing()