minor code refactoring

This commit is contained in:
s-prechtl 2022-03-17 14:34:30 +01:00
parent 36a8795245
commit 169599dff5
6 changed files with 56 additions and 54 deletions

View file

@ -4,6 +4,7 @@ import discord
import riotwatcher import riotwatcher
import APICommands.Command import APICommands.Command
from APICommands.Command import getSummonerNameFromMessage, getChampionsJSON, championIdToName
class ChampionMastery(APICommands.Command.Command, ABC): class ChampionMastery(APICommands.Command.Command, ABC):
@ -15,10 +16,37 @@ class ChampionMastery(APICommands.Command.Command, ABC):
super().__init__(pref, api, region, additionalKeywords) super().__init__(pref, api, region, additionalKeywords)
async def execute(self, message: discord.Message): async def execute(self, message: discord.Message):
pass sumname = ""
try:
sumname = getSummonerNameFromMessage(message, 2)
except:
await self.usage(message)
if sumname != "":
if not await self.checkSumname(sumname, message):
return
response = self.api.champion_mastery.by_summoner(self.region,
self.api.summoner.by_name(self.region,
sumname)["id"])
championsJSON = getChampionsJSON()
for i in response:
champname = championIdToName(i["championId"], championsJSON)
if champname == message.content.split(" ")[1]:
mpoints = i["championPoints"]
mastery = i["championLevel"]
out = "**" + sumname + "** --> **" + champname + "**" + " Points: " + str(
mpoints) + " Level: " + str(
mastery) + "\n"
await message.channel.send(out)
return
await message.channel.send("No matching champion was found.")
async def info(self, message: discord.Message): async def info(self, message: discord.Message):
pass pass
async def usage(self, message: discord.Message): async def usage(self, message: discord.Message):
pass await message.channel.send("Wrong usage of " + self.commandName + "!\nUsage: " + self.pref + "cm [champion] ["
"Summoner]")

View file

@ -1,3 +1,4 @@
import json
from abc import abstractmethod, ABCMeta from abc import abstractmethod, ABCMeta
from datetime import datetime from datetime import datetime
@ -6,6 +7,25 @@ import requests
import riotwatcher import riotwatcher
def championIdToName(id, championsText):
champions = json.loads(championsText)['data']
for j in dict(champions):
if id == int(champions[j]["key"]):
return j
def getChampionsJSON():
return requests.get("http://ddragon.leagueoflegends.com/cdn/11.19.1/data/en_US/champion.json").text
def intTryParse(value):
try:
return int(value), True
except ValueError:
return value, False
def getSummonerNameFromMessage(message: discord.Message, argumentstart=1): def getSummonerNameFromMessage(message: discord.Message, argumentstart=1):
ret = "" ret = ""
inp = message.content.split(" ") inp = message.content.split(" ")

View file

@ -4,7 +4,7 @@ import discord
import riotwatcher import riotwatcher
import APICommands.Command import APICommands.Command
from iLeague import intTryParse, championIdToName, getChampionsJSON from APICommands.Command import intTryParse, championIdToName, getChampionsJSON, getSummonerNameFromMessage
class HighestMastery(APICommands.Command.Command, ABC): class HighestMastery(APICommands.Command.Command, ABC):
@ -20,7 +20,7 @@ class HighestMastery(APICommands.Command.Command, ABC):
firstIsInt = intTryParse(message.content.split(" ")[1])[1] firstIsInt = intTryParse(message.content.split(" ")[1])[1]
try: try:
sumname = APICommands.Command.getSummonerNameFromMessage(message, 2) sumname = getSummonerNameFromMessage(message, 2)
except: except:
await self.usage(message) await self.usage(message)
if sumname != "": if sumname != "":

View file

@ -4,6 +4,7 @@ import discord
import riotwatcher import riotwatcher
import APICommands.Command import APICommands.Command
from APICommands.Command import getSummonerNameFromMessage
class SummonerLevel(APICommands.Command.Command, ABC): class SummonerLevel(APICommands.Command.Command, ABC):
@ -17,7 +18,7 @@ class SummonerLevel(APICommands.Command.Command, ABC):
async def execute(self, message: discord.Message): async def execute(self, message: discord.Message):
sumname = "" sumname = ""
try: try:
sumname = APICommands.Command.getSummonerNameFromMessage(message) sumname = getSummonerNameFromMessage(message)
except: except:
await self.usage(message) await self.usage(message)
if sumname != "": if sumname != "":

View file

@ -4,6 +4,7 @@ import discord
import riotwatcher import riotwatcher
import APICommands.Command import APICommands.Command
from APICommands.Command import getSummonerNameFromMessage
def truncate(f, n): def truncate(f, n):
@ -26,7 +27,7 @@ class SummonerRank(APICommands.Command.Command, ABC):
async def execute(self, message: discord.Message): async def execute(self, message: discord.Message):
sumname = "" sumname = ""
try: try:
sumname = APICommands.Command.getSummonerNameFromMessage(message) sumname = getSummonerNameFromMessage(message)
except: except:
await self.usage(message) await self.usage(message)

View file

@ -9,12 +9,7 @@ from riotwatcher import LolWatcher
from APICommands import ChampionMasteryCommand, HighestMasteryCommand, SummonerLevelCommand, PrefixCommand, SummonerRankCommand from APICommands import ChampionMasteryCommand, HighestMasteryCommand, SummonerLevelCommand, PrefixCommand, SummonerRankCommand
def championIdToName(id, championsText):
champions = json.loads(championsText)['data']
for j in dict(champions):
if id == int(champions[j]["key"]):
return j
class MyClient(discord.Client): class MyClient(discord.Client):
@ -75,47 +70,11 @@ class MyClient(discord.Client):
if True: if True:
return return
elif self.getContentFromMessageWithPrefixCommand(message, ["cm", "CM", "Championmastery",
"championmastery"]): # get Mastery from Champion
self.log("Summoner champion mastery", message)
await self.requestChampionMastery(message)
# FREE CHAMPS # FREE CHAMPS
elif self.getContentFromMessageWithPrefixCommand(message, ["f2p", "rotation", "F2P", "ROTATION"]): elif self.getContentFromMessageWithPrefixCommand(message, ["f2p", "rotation", "F2P", "ROTATION"]):
self.log("F2P rotation", message) self.log("F2P rotation", message)
await self.requestFreeChampRot(message) await self.requestFreeChampRot(message)
async def requestChampionMastery(self, message: discord.Message):
err = "Something went wrong.\nUsage: " + self.pref + "cm [Championname] [Summonername]"
sumname = ""
try:
sumname = self.getSummonerNameFromMessage(message, 2)
except Exception as e:
await message.channel.send(err)
if sumname != "":
if not await self.checkSumname(sumname, message):
return
response = self.api.champion_mastery.by_summoner(self.region,
self.api.summoner.by_name(self.region,
sumname)["id"])
championsJSON = getChampionsJSON()
for i in response:
champname = championIdToName(i["championId"], championsJSON)
if champname == message.content.split(" ")[1]:
mpoints = i["championPoints"]
mastery = i["championLevel"]
out = "**" + sumname + "** --> **" + champname + "**" + " Points: " + str(
mpoints) + " Level: " + str(
mastery) + "\n"
await message.channel.send(out)
return
await message.channel.send("No matching champion was found.")
async def requestFreeChampRot(self, message: discord.Message): async def requestFreeChampRot(self, message: discord.Message):
err = "Something went wrong.\nUsage: " + self.pref + "f2p [Summonername]" err = "Something went wrong.\nUsage: " + self.pref + "f2p [Summonername]"
sumname = "" sumname = ""
@ -150,14 +109,7 @@ class MyClient(discord.Client):
if len(output.split("\n")) <= 2: if len(output.split("\n")) <= 2:
await message.channel.send("\t- **Keine**") await message.channel.send("\t- **Keine**")
def getChampionsJSON():
return requests.get("http://ddragon.leagueoflegends.com/cdn/11.19.1/data/en_US/champion.json").text
def intTryParse(value):
try:
return int(value), True
except ValueError:
return value, False
if __name__ == '__main__': if __name__ == '__main__':