async def cdoRemoveCompetition(msg : Message,**kwargs): """ Removes a competition from the watchlist. :return: Answer message """ responseData = CDOInteralResponseData() if "parameter0" in kwargs.keys(): parameter = kwargs['parameter0'] else: return CDOInteralResponseData("You need to give me a competition, mate") watcher = CompetitionWatcher.objects.filter(competition__clear_name=parameter) if len(watcher) == 0: responseData.response = f"Competition {parameter} was not monitored" return responseData if len(watcher) > 1: if "parameter1" in kwargs.keys(): watcher = watcher.filter(competition__association=kwargs['parameter1']) else: nameCode = [f"{i.competition.clear_name},{i.competition.association}" for i in watcher] return CDOInteralResponseData(f"We have multiple competitions that match {parameter}, " f"naming " f"{nameCode}" f", please provide an association with a second parameter. For example: " f"**{kwargs['prefix']}removeCompetition Premier League,ENG**") logger.info(f"Deleting {watcher}") await Scheduler.removeCompetition(watcher.first()) watcher.delete() responseData.response = f"Removed {parameter} from monitoring" return responseData
async def cdoRemoveCompetition(**kwargs): """ Removes a competition from the watchlist. :return: Answer message """ responseData = CDOInteralResponseData() parameter = checkCompetitionParameter(kwargs['msg'].content) if isinstance(parameter, str): return parameter else: competition_string = parameter["competition"] association = parameter["association"] watcher = CompetitionWatcher.objects.filter(competition__clear_name=competition_string) if len(watcher) == 0: responseData.response = f"Competition {competition_string} was not monitored" return responseData if len(watcher) > 1: watcher = watcher.filter(competition__association=association) logger.info(f"Deleting {watcher}") await Scheduler.removeCompetition(watcher.first()) watcher.delete() responseData.response = f"Removed {competition_string} from monitoring" return responseData
async def cdoListCompetitionByCountry(**kwargs): """ Lists all competitions for a given country. Needs the name of the country of country code as a parameter. :return: """ responseData = CDOInteralResponseData() data = kwargs['msg'].content.split(" ") if len(data) == 0: responseData.response = "List competition needs the country or countrycode as parameter" return responseData association = "" for i in data[1:]: if association == "": association += i else: association += " " + i competition = Competition.objects.filter(association__clear_name=association) if len(competition) == 0: competition = Competition.objects.filter(association_id=association) if len(competition) == 0: responseData.response = f"No competitions were found for {association}" return responseData retString = "Competitions:\n\n" compList = [] for comp in competition: retString += comp.clear_name + "\n" compList.append(f"{comp.clear_name}#{comp.association.id}") retString += f"\n\nReact with according number emoji to add competitions. Only the first {len(emojiList())} can " \ f"be added this way" responseData.response = retString def check(reaction, user): if reaction.emoji in emojiList(): try: index = emojiList().index(reaction.emoji) except ValueError: logger.error(f"{reaction.emoji} not in list!") return False if index < len(compList): kwargs['msg'].content = f"!addCompetition {compList[index]}" client.loop.create_task(cmdHandler(kwargs['msg'])) return True return False responseData.reactionFunc = check return responseData
async def cdoAddCompetition(**kwargs): """ Adds a competition to be watched by soccerbot. It will be regularly checked for new games :return: Answer message """ responseData = CDOInteralResponseData() parameter = checkCompetitionParameter(kwargs['msg'].content) if isinstance(parameter, str): responseData.response = "Error within Commando!" logger.error("Parameter is not string instance, please check logic!") return responseData else: competition_string = parameter["competition"] association = parameter["association"] comp = Competition.objects.filter(clear_name=competition_string) logger.debug(f"Available competitions: {comp}") if len(comp) == 0: responseData.response = f"Can't find competition {competition_string}" return responseData if len(comp) != 1: if association == None: names = [existing_com.clear_name for existing_com in comp] countryCodes = [existing_com.association for existing_com in comp] name_code = list(zip(names, countryCodes)) responseData.response = f"Found competitions {name_code} with that name. Please be more specific (add #ENG for example)." return responseData else: comp = Competition.objects.filter(clear_name=competition_string, association=association) if len(comp) != 1: names = [existing_com.clear_name for existing_com in comp] countryCodes = [existing_com.association for existing_com in comp] name_code = list(zip(names, countryCodes)) responseData.response = f"Found competitions {name_code} with that name. Please be more specific (add #ENG for example)." return responseData watcher = CompetitionWatcher.objects.filter(competition=comp.first()) logger.debug(f"Watcher objects: {watcher}") if len(watcher) != 0: return CDOInteralResponseData(f"Allready watching {competition_string}") client.loop.create_task(watchCompetition(comp.first(), kwargs['msg'].server)) responseData.response = f"Start watching competition {competition_string}" return responseData
async def cdoListCompetitionByCountry(msg : Message,**kwargs): """ Lists all competitions for a given country. Needs the name of the country of country code as a parameter. :return: """ responseData = CDOInteralResponseData() if "parameter0" not in kwargs.keys(): return CDOInteralResponseData(f"Needs the country or countrycode as parameter") association = kwargs['parameter0'] competition = Competition.objects.filter(association__clear_name=association) if len(competition) == 0: competition = Competition.objects.filter(association_id=association) if len(competition) == 0: responseData.response = f"No competitions were found for {association}" return responseData retString = "Competitions:\n\n" compList = [] for comp in competition: retString += comp.clear_name + "\n" compList.append(f"{comp.clear_name},{comp.association.id}") retString += f"\n\nReact with according number emoji to add competitions. Only the first {len(emojiList())} can " \ f"be added this way" responseData.response = retString def check(reaction: Reaction, user): if reaction.emoji in emojiList(): try: index = emojiList().index(reaction.emoji) except ValueError: logger.error(f"{reaction.emoji} not in list!") return False if index < len(compList): msg.content = f"{kwargs['prefix']}addCompetition {compList[index]}" client.loop.create_task(cmdHandler(msg)) return True responseData.reactionFunc = check return responseData
async def cdoStopBot(msg : Message,**kwargs): """ Stops the execution of the bot :param kwargs: :return: """ responseData = CDOInteralResponseData() retString = f"To confirm the shutdown, please react with {emojiList()[0]} to this message." responseData.response = retString def check(reaction : Reaction, user): if reaction.emoji == emojiList()[0]: client.loop.create_task(msg.channel.send("Bot is shutting down in 10 seconds")) client.loop.create_task(shutdown()) return True responseData.reactionFunc = check return responseData
async def cdoAddCompetition(msg : Message,**kwargs): """ Adds a competition to be watched by soccerbot. It will be regularly checked for new games. Optional arguments: **channel**: Defines a default channel for all live output for a given competition **role**: Assigns a role for a competition. This applies to the channel. So only people with this role can see this channel. :return: Answer message """ responseData = CDOInteralResponseData() if "parameter0" in kwargs.keys(): parameter = kwargs['parameter0'] else: return CDOInteralResponseData("You need to give me a competition, mate") comp = Competition.objects.filter(clear_name=parameter) logger.debug(f"Available competitions: {comp}") if len(comp) == 0: return CDOInteralResponseData(f"Can't find competition {parameter}") if len(comp) != 1: if "parameter1" not in kwargs.keys(): name_code = [f"{existing_com.clear_name},{existing_com.association_id}" for existing_com in comp] responseData.response = f"Found competitions {name_code} with that name. Please add a second parameter " \ f"with the country code. For example: " \ f"**Premier League,ENG**" return responseData else: comp = comp.filter(association=kwargs['parameter1']) if len(comp) > 1: return CDOInteralResponseData(f"Sorry, we still couldn't find a unique competition. Found competitions " f"are {[(i.clear_name,i.association) for i in comp]}") elif len(comp) <1: return CDOInteralResponseData(f"Sorry no competition was found with {parameter},{kwargs['parameter1']}") watcher = CompetitionWatcher.objects.filter(competition=comp.first()) logger.debug(f"Watcher objects: {watcher}") if len(watcher) != 0: return CDOInteralResponseData(f"Allready watching {parameter}") responseData.response = f"Start watching competition {parameter}" channel = None if 'channel' not in kwargs.keys() else kwargs['channel'] category = None if 'category' not in kwargs.keys() else kwargs['category'] roleNames = [i.name for i in msg.guild.roles] role = None if 'role' in kwargs.keys(): fullRole = kwargs['role'].replace("+"," ") if fullRole not in roleNames: return CDOInteralResponseData(f"The role __{fullRole}__ is not available on this server!") else: for i in msg.guild.roles: if i.name == fullRole: role = i.id client.loop.create_task(watchCompetition(comp.first(), msg.guild, channel,role,category)) return responseData
async def cdoScores(msg : Message,**kwargs): """ Returns the scores for a given competition/matchday/team :param kwargs: :return: """ channel = msg.channel if "parameter0" not in kwargs.keys(): if not "live-" in channel.name: return CDOInteralResponseData(f"This command with no argument can only be called within matchday channels") comp,md = Scheduler.findCompetitionMatchdayByChannel(channel.name) matchList = Scheduler.getScores(comp,md) resp = CDOInteralResponseData("Current scores:") addInfo = InfoObj() for matchString,goalList in matchList.items(): addInfo[matchString] = "" for goals in goalList[0]: if goals != '': addInfo[matchString] += goals+"\n" if addInfo[matchString] == "": del addInfo[matchString] if addInfo == InfoObj(): addInfo[matchString] = f"{goalList[1]}: 0-0" if addInfo == InfoObj(): resp.response = "Currently no running matches" else: resp.response = "Current scores:" resp.additionalInfo = addInfo return resp else: searchString = kwargs['parameter0'] query = Competition.objects.filter(clear_name = searchString) if len(query) == 0: teamList = getTeamsSearchedByName(searchString) if len(teamList) == 0: return CDOInteralResponseData(f"Can't find team {searchString}") matchObj = teamList[0]['Name'][0]['Description'] matchList = getLiveMatches(teamID=int(teamList[0]["IdTeam"])) else: comp = query.first() matchObj = comp.clear_name matchList = getLiveMatches(competitionID=comp.id) if len(matchList) == 0: return CDOInteralResponseData(f"No current matches for {matchObj}") addInfo = InfoObj() for matchID in matchList: try: data = makeMiddlewareCall(DataCalls.liveData + f"/{matchID}") except JSONDecodeError: logger.error(f"Failed to do a middleware call for {matchID}") continue newEvents, _ = LiveMatch.parseEvents(data["match"]["events"], []) class Match: id = matchID for event in newEvents: title,_,goalListing = await LiveMatch.beautifyEvent(event,Match) if goalListing != "": try: addInfo[title]+=goalListing + "\n" except KeyError: addInfo[title] = goalListing + "\n" if addInfo == InfoObj(): return CDOInteralResponseData(f"No goals currently for {matchObj}") resp = CDOInteralResponseData(f"Current scores for {matchObj}") resp.additionalInfo = addInfo return resp