diff --git a/chatbot/botfunctions.py b/chatbot/botfunctions.py index 4640cd2..114f345 100644 --- a/chatbot/botfunctions.py +++ b/chatbot/botfunctions.py @@ -1,11 +1,9 @@ import secretkeys from xmlrpc.client import Boolean import requests -import time -import matplotlib.pyplot as plt -import numpy as np + ## gets summoner id or puuid by name -def get_summoner_id(summoner, puuid=Boolean): +def get_summoner_id(summoner, puuid=Boolean): ## takes 2 arguments, summoner name and a bool, returns either the puuid or id which we need to other API calls url = f'https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/{summoner}?api_key={secretkeys.riot_api_key}' response = requests.get(url).json() @@ -14,6 +12,22 @@ def get_summoner_id(summoner, puuid=Boolean): elif puuid == True: return response['puuid'] +def get_champion_id_by_name(champion_name): + url = f'http://ddragon.leagueoflegends.com/cdn/12.20.1/data/en_US/champion.json' + get_champion_info = requests.get(url) + data = get_champion_info.json()["data"] + champion_id = data[champion_name]["key"] + wrong_name_error = "Wrong name" + if champion_id == 0: + return wrong_name_error + else: + return champion_id + + + + + + ## gets champion name by id def get_champion_name_by_id(id): ## takes in an id as argument and returns the champion's name @@ -36,7 +50,7 @@ def get_top5(summoner): return most_played -## gets last 10 games can adjust for up to last 100 games +## gets last 10 games can adjust for up to last 100 games def get_match_history(summoner): puuid = get_summoner_id(summoner,True) url = f'https://europe.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?start=0&count=20&api_key={secretkeys.riot_api_key}' @@ -57,150 +71,94 @@ def get_winrate(summoner): break if champion in champ_wr: champ_wr[champion][0] += 1 - else: + else: champ_wr[champion] = [1,0,0] if game_won: champ_wr[champion][1] += 1 else: champ_wr[champion][2] += 1 return champ_wr +get_winrate('tibijczykzvesti') -#PLAYER DATA (temp to test) - -name = 'TILTPROOF XD' -region = 'euw1' -massRegion = 'EUROPE' - -#takes a player name and returns puuid -def get_player_puuid(name,region): - api_url = ("https://" + region +".api.riotgames.com/lol/summoner/v4/summoners/by-name/" + name + "?api_key=" + secretkeys.riot_api_key) - data = requests.get(api_url) - player_info = data.json() - puuid = player_info['puuid'] - return puuid - - -puuid = get_player_puuid(name,region) - - -#takes puuid and region and returns match ids of recent matches - used for accessing match data later -def get_match_ids(puuid, massRegion): - api_url = ("https://" + massRegion +".api.riotgames.com/lol/match/v5/matches/by-puuid/" +puuid + "/ids?start=0&count=20" + "&api_key=" + secretkeys.riot_api_key) - data = requests.get(api_url) - match_ids = data.json() - return match_ids - -match_ids = get_match_ids(puuid, massRegion) - -#function to get all match data (a very long unreadable file, but useful for picking out individual bits of data) -def get_match_data(matchId,massRegion): - api_url = ("https://" + massRegion + ".api.riotgames.com/lol/match/v5/matches/" +matchId + "?api_key=" + secretkeys.riot_api_key) - data = requests.get(api_url) - match_data = data.json() - return match_data - -match_id = match_ids[0] -match_data = get_match_data(match_id, massRegion) - -#gets data of a single player for a given match. again a very long file -def get_player_data(matchData,puuid): - players = matchData['metadata']['participants'] - player_index = players.index(puuid) - player_data = matchData['info']['participants'][player_index] - return player_data - -get_player_data(match_data,puuid) - -#creating a dictionary to hold player stats. The index of the value in each list in the dictionary represents the given key stat for that game -data = { - 'champion': [], - 'kills': [], - 'deaths': [], - 'assists': [], - 'damage' : [], - 'KDA' : [], - 'win': [] -} - -for match_id in match_ids: - - - # gets the match data and player data for each match - match_data = get_match_data(match_id, massRegion) - player_data = get_player_data(match_data, puuid) - - # assign the variables we're interested in - playerName = player_data['summonerName'] - playerLevel = player_data['summonerLevel'] - champion = player_data['championName'] - k = player_data['kills'] - d = player_data['deaths'] - a = player_data['assists'] - win = player_data['win'] - - # add them to our dictionary - data['champion'].append(champion) - data['kills'].append(k) - data['deaths'].append(d) - - data['assists'].append(a) - data['win'].append(win) - - -#displays the important stats for a game for a given player -def display_match_stats(game): - champion =data.get('champion')[game] - kills =data.get('kills')[game] - deaths = data.get('deaths')[game] - assists = data.get('assists')[game] - win = data.get('win')[game] - - return (f'champion: {champion} \nkills: {kills} \ndeaths: {deaths} \nassists: {assists} \nwin: {win}') - -#displays a graph of kills over the past 20 games -def displayKills(): - - kills = data.get('kills') - numArray = [] - for i in range(len(kills)): - numArray.append(f'game{i}') - plt.bar(numArray[i],kills[i],1) - plt.title(f'Graph of {name} kills on {champion}') - plt.ylabel('Kills') - plt.savefig(fname='kills') - #plt.show() - -#displays a graph of deaths over the past 20 games -def displayDeaths(): - - deaths = data.get('deaths') - numArray = [] - for i in range(len(deaths)): - numArray.append(f'game{i}') - plt.bar(numArray[i],deaths[i],1) - plt.title(f'Graph of {name} deaths on {champion}') - plt.ylabel('Deaths') - plt.savefig(fname='deaths') - #plt.show() - -#displays a graph of assists over the past 20 games -def displayAssists(): - - assists = data.get('assists') - numArray = [] - for i in range(len(assists)): - numArray.append(f'game{i}') - plt.bar(numArray[i],assists[i],1) - plt.title(f'Graph of {name} assists on {champion}') - plt.ylabel('assists') - plt.savefig(fname='assists') - #plt.show() - -#master function (not in use) -def displayAll(): - displayKills() - displayDeaths() - displayAssists() + +## gets ranked stats +def get_summoner_stats(summoner): + summoner = get_summoner_id(summoner,False) + url =f'https://euw1.api.riotgames.com/lol/league/v4/entries/by-summoner/{summoner}?api_key={secretkeys.riot_api_key}' + response = requests.get(url).json() + data = response[0] + tier = data['tier'] + rank = data['rank'] + league_points = str(data['leaguePoints']) + 'LP' + winrate = str(round(data['wins']/(data['wins']+data['losses'])*100,2))+'%' + streak = data['hotStreak'] + ranked_stats = [tier,rank,league_points,winrate] + if streak == True: + ranked_stats.append(streak) + return (ranked_stats) + +def getMatchListByAccountId(accountId): + print("Running Service: getMatchListByAccountId...") + url = 'https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/%s?api_key=%s' % (accountId, secretkeys.riot_api_key) + response = requests.get(url) + return response.json() + + + +def getMatchByGameId(gameId): + print("Running Service: getMatchByGameId...") + url = 'https://na1.api.riotgames.com/lol/match/v3/matches/%s?api_key=%s' % (gameId, secretkeys.riot_api_key) + response = requests.get(url) + return response.json() + + +def getParticipantStats(participantId, game): + print("Getting Participant Stats...") + return game['participants'][participantId] + +def sortStats(participantStats): + try: + stats = {'championId':participantStats['championId'],'participantId':participantStats['participantId'],'win':participantStats['stats']['win'],'item0':participantStats['stats']['item0'],'item1':participantStats['stats']['item1'],'item2':participantStats['stats']['item2'],'item3':participantStats['stats']['item3'], + 'item4':participantStats['stats']['item4'],'item5':participantStats['stats']['item5'],'item6':participantStats['stats']['item6'],'kills':participantStats['stats']['kills'], 'deaths':participantStats['stats']['deaths'], + 'assists':participantStats['stats']['assists'],'longestTimeSpentLiving':participantStats['stats']['longestTimeSpentLiving'],'totalDamageDealt':participantStats['stats']['longestTimeSpentLiving'], + 'magicDamageDealt':participantStats['stats']['magicDamageDealt'],'physicalDamageDealt':participantStats['stats']['physicalDamageDealt'],'trueDamageDealt':participantStats['stats']['trueDamageDealt'], + 'totalDamageDealtToChampions':participantStats['stats']['totalDamageDealtToChampions'],'magicDamageDealtToChampions':participantStats['stats']['magicDamageDealtToChampions'],'physicalDamageDealtToChampions':participantStats['stats']['physicalDamageDealtToChampions'], + 'trueDamageDealtToChampions':participantStats['stats']['trueDamageDealtToChampions'],'totalHeal':participantStats['stats']['totalHeal'],'damageSelfMitigated':participantStats['stats']['damageSelfMitigated'], + 'damageDealtToObjectives':participantStats['stats']['damageDealtToObjectives'],'damageDealtToTurrets':participantStats['stats']['damageDealtToTurrets'],'visionScore':participantStats['stats']['visionScore'], + 'timeCCingOthers':participantStats['stats']['timeCCingOthers'],'totalDamageTaken':participantStats['stats']['totalDamageTaken'],'magicalDamageTaken':participantStats['stats']['magicalDamageTaken'], + 'physicalDamageTaken':participantStats['stats']['physicalDamageTaken'],'goldEarned':participantStats['stats']['goldEarned'],'goldSpent':participantStats['stats']['goldSpent'],'totalMinionsKilled':participantStats['stats']['totalMinionsKilled'], + 'neutralMinionsKilled':participantStats['stats']['neutralMinionsKilled'],'visionWardsBoughtInGame':participantStats['stats']['visionWardsBoughtInGame'],'wardsPlaced':participantStats['stats']['wardsPlaced'],'wardsKilled':participantStats['stats']['wardsKilled']} + + return stats; + + + #Error handling for assumed non-summoner's rift game mode + except KeyError as error: + print('KeyError has occured because - ', str(error), ' was not found in the JSON to be sorted.') + print('Trying new parse for assumed non-summoner\'s rift game mode') + stats = {'championId':participantStats['championId'],'participantId':participantStats['participantId'],'win':participantStats['stats']['win'],'item0':participantStats['stats']['item0'],'item1':participantStats['stats']['item1'],'item2':participantStats['stats']['item2'],'item3':participantStats['stats']['item3'], + 'item4':participantStats['stats']['item4'],'item5':participantStats['stats']['item5'],'item6':participantStats['stats']['item6'],'kills':participantStats['stats']['kills'], 'deaths':participantStats['stats']['deaths'], + 'assists':participantStats['stats']['assists'],'longestTimeSpentLiving':participantStats['stats']['longestTimeSpentLiving'],'totalDamageDealt':participantStats['stats']['longestTimeSpentLiving'], + 'magicDamageDealt':participantStats['stats']['magicDamageDealt'],'physicalDamageDealt':participantStats['stats']['physicalDamageDealt'],'trueDamageDealt':participantStats['stats']['trueDamageDealt'], + 'totalDamageDealtToChampions':participantStats['stats']['totalDamageDealtToChampions'],'magicDamageDealtToChampions':participantStats['stats']['magicDamageDealtToChampions'],'physicalDamageDealtToChampions':participantStats['stats']['physicalDamageDealtToChampions'], + 'trueDamageDealtToChampions':participantStats['stats']['trueDamageDealtToChampions'],'totalHeal':participantStats['stats']['totalHeal'],'damageSelfMitigated':participantStats['stats']['damageSelfMitigated'], + 'damageDealtToObjectives':participantStats['stats']['damageDealtToObjectives'],'damageDealtToTurrets':participantStats['stats']['damageDealtToTurrets'],'visionScore':participantStats['stats']['visionScore'], + 'timeCCingOthers':participantStats['stats']['timeCCingOthers'],'totalDamageTaken':participantStats['stats']['totalDamageTaken'],'magicalDamageTaken':participantStats['stats']['magicalDamageTaken'], + 'physicalDamageTaken':participantStats['stats']['physicalDamageTaken'],'goldEarned':participantStats['stats']['goldEarned'],'goldSpent':participantStats['stats']['goldSpent'],'totalMinionsKilled':participantStats['stats']['totalMinionsKilled'], + 'neutralMinionsKilled':participantStats['stats']['neutralMinionsKilled'],'visionWardsBoughtInGame':participantStats['stats']['visionWardsBoughtInGame']} + + return stats + + +def getChampionMastery(summoner_id,champion_name): + print('Running service: getChampionMastery...') + champion_id = champion_name + url = f'https://euw1.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/{summoner_id}/by-champion/{champion_id}?api_key={secretkeys.riot_api_key}' + response = requests.get(url) + data = response.json() + print(data) + + return data \ No newline at end of file diff --git a/chatbot/discordbot.py b/chatbot/discordbot.py index 162ebd3..e3eb0fb 100644 --- a/chatbot/discordbot.py +++ b/chatbot/discordbot.py @@ -6,9 +6,9 @@ import random import secretkeys ## for API keys import botfunctions as idk ## for botfunctions.py functions import asyncio -import matplotlib as plt +##import matplotlib as plt import os -import numpy as np +##import numpy as np greetings = ['hello','hi','whats up','sup','yo','hey'] ## setting intents for discord bot# @@ -95,6 +95,57 @@ async def on_message(message): await asyncio.sleep(1) await channel.send(embed = stats) + + + + if 'champion mastery' in message.content: + channel = message.channel + async with channel.typing(): + await asyncio.sleep(1) + await channel.send('Whats your summoner name?') + def check(m): + return message.content + message = await bot.wait_for('message',check = check) + summoner_name = message.content + print(summoner_name) + await channel.send('What champion do you want to find the mastery for?') + def check(m): + return message.content + message = await bot.wait_for('message', check = check) + champion_name = message.content + print(champion_name) + + summoner_id = idk.get_summoner_id(summoner_name, False) + champion_id = idk.get_champion_id_by_name(champion_name) + + if champion_id == "Wrong name": + await channel.send("This champion name is incorrect. Please make sure you capitalize the first letter and try again.") + + else: + + mastery_stats = idk.getChampionMastery(summoner_id, champion_id) + + print("working") + + stats = discord.Embed(title=f'{summoner_name}\'s mastery information for {champion_name}') + + championLevel = mastery_stats['championLevel'] + championPoints = mastery_stats['championPoints'] + championPointsSinceLastLevel = mastery_stats['championPointsSinceLastLevel'] + championPointsUntilNextLevel = mastery_stats['championPointsUntilNextLevel'] + + + stats.add_field(name=f'**Champion Level**', value=f'{championLevel}') + stats.add_field(name=f'**Champion Points**', value=f'{championPoints}') + stats.add_field(name=f'**Champion Points Since Last Level**', value=f'{championPointsSinceLastLevel}') + stats.add_field(name=f'**Champion Points Until Next Level**', value=f'{championPointsUntilNextLevel}') + + + async with channel.typing(): + await asyncio.sleep(1) + await channel.send(embed = stats) + + if 'match history' in message.content: channel = message.channel async with channel.typing():