Exemplo n.º 1
0
async def cdoCurrentGames(msg : Message,**kwargs):
    """
    Lists all current games within a matchday channel
    :param kwargs:
    :return:
    """

    if "parameter0" in kwargs.keys():
        competition = Competition.objects.filter(clear_name=kwargs['parameter0'])
    else:
        competition = None

    matchList = Scheduler.startedMatches()
    addInfo = InfoObj()
    for match in matchList:
        if competition == None:
            addInfo[match.title] = f"{match.minute}"
        else:
            if match.match.competition == competition.first():
                addInfo[match.title] = f"{match.minute}"

    if addInfo == InfoObj():
        respStr = "No running matches"
    else:
        respStr = "Running matches:"

    resp = CDOInteralResponseData(respStr,addInfo)

    return resp
Exemplo n.º 2
0
async def getTopScorers(competition: Competition) -> InfoObj:
    """
    Returns the topScorers for a given league by its competition.
    :param competition: competition Object. Needs to be valid, no further check is done
    :return: InfoObj that can be directly fed into a CDOInternalResponse
    """
    season = Season.objects.filter(competition=competition)
    if season == None or len(season) == 0:
        getAndSaveData(getAllSeasons, idCompetitions=competition.id)
        season = Season.objects.filter(competition=competition)
        if season == None or len(season) == 0:
            raise ValueError(f"No season for {competition}")

    season = season.order_by('start_date').last()
    data = makeAPICall(ApiCalls.topScorer + f"/{season.id}/topscorers")

    addInfo = InfoObj()
    try:
        for i in data['PlayerStatsList']:
            goalStr = f"**Goals scored: __{i['GoalsScored']}__**\n"
            goalStr += f"_Headers: __{i['GoalsScoredByHead']}__ _\n"
            goalStr += f"_Penalties: __{i['GoalsScoredOnPenalty']}__ _\n"
            addInfo[f"{i['Rank']}.: " +
                    i['PlayerInfo']['PlayerName'][0]['Description']] = goalStr
            lastName = i['PlayerInfo']['PlayerName'][0]['Description'].split(
                " ")[-1].lower()
            firstName = i['PlayerInfo']['PlayerName'][0]['Description'].split(
                " ")[0].lower()
            imageList = Player.objects.filter(lastName=lastName)

            if len(imageList) != 0:
                if len(imageList) == 1:
                    addInfo[f"{i['Rank']}.: " + i['PlayerInfo']['PlayerName']
                            [0]['Description']].set_thumbnail(
                                url=imageList.first().imageLink)
                else:
                    imageList = imageList.filter(firstName=firstName)
                    if len(imageList) != 0:
                        addInfo[f"{i['Rank']}.: " +
                                i['PlayerInfo']['PlayerName'][0]
                                ['Description']].set_thumbnail(
                                    url=imageList.first().imageLink)
                    else:
                        imageList = Player.objects.filter(lastName=lastName)
                        addInfo[f"{i['Rank']}.: " +
                                i['PlayerInfo']['PlayerName'][0]
                                ['Description']].set_thumbnail(
                                    url=imageList.first().imageLink)

        return addInfo
    except (KeyError, TypeError) as e:
        return InfoObj()
Exemplo n.º 3
0
async def cdoGetHelp(msg : Message,**kwargs):
    """
    Returns all available Commandos and their documentation.
    :return:
    """
    retString = "Available Commandos:"
    addInfo = InfoObj()

    try:
        userQuery = DiscordUsers.objects.get(id=msg.author.id)
        authorUserLevel = userQuery.userLevel
    except ObjectDoesNotExist:
        authorUserLevel = 0

    for i in DiscordCommando.allCommandos():
        if i.userLevel <= authorUserLevel:
            doc = i.docstring
            doc = re.sub(':.+\n', "", doc)
            doc = re.sub('\n+', "", doc)
            if authorUserLevel >= 5:
                level = f" lvl:{i.userLevel}"
            else:
                level = ""
            addInfo[kwargs['prefix'] + i.commando + level] = doc

    responseData = CDOInteralResponseData(retString, addInfo)

    return responseData
Exemplo n.º 4
0
async def cdoShowMonitoredCompetitions(msg : Message,**kwargs):
    """
    Lists all watched competitions by soccerbot.
    :return: Answer message
    """
    retString = f"React with number emojis to remove.Only the first {len(emojiList())} can " \
                f"be added this way):\n\n"
    addInfo = InfoObj()
    compList = []
    for watchers in CompetitionWatcher.objects.all():
        compList.append(watchers.competition)
        try:
            addInfo[watchers.competition.association.clear_name].description +=(f"\n{watchers.competition.clear_name}")
        except KeyError:
            addInfo[watchers.competition.association.clear_name] = watchers.competition.clear_name

    def check(reaction : Reaction, user):
        if reaction.emoji in emojiList():
            index = emojiList().index(reaction.emoji)
            if index < len(compList):
                msg.content = f"{kwargs['prefix']}removeCompetition {compList[index].clear_name},{compList[index].association_id}"
                client.loop.create_task(cmdHandler(msg))
                return True

    return CDOInteralResponseData(retString, addInfo, check)
Exemplo n.º 5
0
async def cdoUpcomingGames(msg : Message,**kwargs):
    """
    Lists all upcoming games
    :param kwargs:
    :return:
    """
    if "parameter0" in kwargs.keys():
        competition = Competition.objects.filter(clear_name=kwargs['parameter0'])
        watchers = CompetitionWatcher.objects.filter(competition=competition)
    else:
        competition = None
        watchers = []

    if len(watchers) == 0 and competition is not None:
        return CDOInteralResponseData(f"Sorry {competition.clear_name} is not watched by Soccerbot.")


    matchList = Scheduler.upcomingMatches()

    if len(matchList) == 0:
        return CDOInteralResponseData("No upcoming matches.")

    addInfo = InfoObj()
    for match in matchList:
        if competition == None:
            addInfo[match.title] = match.match.date
        else:
            if match.match.competition == competition.first():
                addInfo[match.title] = match.match.date
                
    tmpAddInfo =  dict([(k, addInfo[k]) for k in sorted(addInfo, key=addInfo.get, reverse=False)])


    addInfo = InfoObj()

    for key,value in tmpAddInfo.items():
        addInfo[key] = f"{tmpAddInfo[key].description.strftime('%d %b %Y, %H:%M')} (UTC)"

    respStr = "Upcoming matches:"



    resp = CDOInteralResponseData(respStr,addInfo)
    return resp
Exemplo n.º 6
0
async def cdoGetUserPermissions(msg : Message,**kwargs):
    """
    Gets the userlevel of a mentioned user
    :param kwargs:
    :return:
    """
    addInfo = InfoObj()
    for user in msg.mentions:
        try:
            user = DiscordUsers.objects.get(id=user.id)
            addInfo[user.name] = f"User level: {user.userLevel}"
        except ObjectDoesNotExist:
            addInfo[user.name] = f"User level: 0"

    if addInfo == InfoObj():
        return CDOInteralResponseData("You need to mention a user to get its permission status!")

    retObj = CDOInteralResponseData("UserLevels:")
    retObj.additionalInfo = addInfo
    return retObj
Exemplo n.º 7
0
async def cdoShowRunningTasks(msg : Message,**kwargs):
    """
    Shows all currently running tasks on the server
    :return:
    """
    tasks = Task.getAllTaks()
    responseString = "Running tasks:"
    addInfo = InfoObj()

    for i in tasks:
        args = str(i.args).replace("<", "").replace(">", "").replace(",)", ")")
        addInfo[f"{i.name}{args}"] = f"Started at {i.time}"

    return CDOInteralResponseData(responseString, addInfo)
Exemplo n.º 8
0
async def cdoGoals(msg : Message,**kwargs):
    """
    Lists the goals stored in the database
    :param msg:
    :param kwargs:
    :return:
    """
    if "parameter0" in kwargs.keys():
        teams = Team.objects.filter(clear_name=kwargs['parameter0'])
        if len(teams) != 0:
            goalListHome = Goal.objects.filter(match_home_Team__clear_name=kwargs['parameter0']).order_by(
                'match__date')
            goalListAway = Goal.objects.filter(match_away_Team__clear_name=kwargs['parameter0']).order_by(
                'match__date')
            goalist = goalListHome | goalListAway
        else:
            goalList = Goal.objects.filter(player=kwargs['parameter0']).order_by('match__date')
            if len(goalList) == 0:
                return CDOInteralResponseData(f"Sorry, nothing found for {kwargs['parameter0']}")
    else:
        goalList = Goal.objects.all().order_by('match__date')

    retDict = InfoObj()

    for i in reversed(goalList):
        keyStr = f"{i.match.home_team.clear_name} : {i.match.home_team.clear_name}"
        try:
            retDict[keyStr].description += f"{i.minute}: {i.player} {i.link}\n"
        except KeyError:
            retDict[keyStr] = f"{i.minute}: {i.player} {i.link}\n"


    if retDict == InfoObj():
        return CDOInteralResponseData("No goals found")
    else:
        return CDOInteralResponseData("Goallinks:",additionalInfo=retDict)
Exemplo n.º 9
0
async def basicStatsFun(msg,fun,onlyText,**kwargs):
    """
    Shows the topscorer for a given competition
    :param kwargs:
    :return:
    """
    if 'parameter0' not in kwargs.keys():
        return CDOInteralResponseData("You need to tell me the competition, mate!")

    searchString = kwargs['parameter0']

    competition = Competition.objects.filter(clear_name=searchString)
    if len(competition) == 0:
        return CDOInteralResponseData(f"Sorry, can't find {searchString}")

    if len(competition) > 1:
        if 'parameter1' not in kwargs.keys():
            compStr = ""
            for i in competition:
                compStr +=f"**{i.clear_name} , {i.association.clear_name}**\n"

            retString = f"Multiple competitions found with name {searchString}.\n\n{compStr}\n" \
                        f"React with emojis to choose"

            def check(reaction : Reaction, user):
                if reaction.emoji in emojiList():
                    index = emojiList().index(reaction.emoji)
                    if index < len(competition):
                        msg.content = f"{kwargs['prefix']}{kwargs['cdo']} " \
                                                f"{competition[index].clear_name},{competition[index].association_id}"
                        client.loop.create_task(cmdHandler(msg))
                        return True
                return False

            return CDOInteralResponseData(retString,reactionFunc=check)
        else:
            competition = competition.filter(association_id=kwargs['parameter1'])

    addInfo = await fun(competition.first())
    if addInfo == InfoObj():
        return CDOInteralResponseData(f"Sorry no data available for {searchString}")
    else:
        if onlyText:
            return CDOInteralResponseData(addInfo, onlyText=True)
        else:
            return CDOInteralResponseData(f"Result for {searchString}",addInfo,paging=1)
Exemplo n.º 10
0
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
Exemplo n.º 11
0
def getPlayerInfo(playerName: str) -> Tuple[str, InfoObj]:
    apiPlayer = playerName.replace(" ", "+")
    try:
        params = {"name": apiPlayer}
        data = makeAPICall(ApiCalls.playerSearch, payload=params)
    except JSONDecodeError:
        return None

    if not isinstance(data, list):
        return None

    if len(data) == 0:
        return None

    data = data[0]
    if len(data) == 0:
        return (playerName, InfoObj())

    id = data['IdPlayer']
    name = data['Name'][0]['Description']
    lastName = name.split(" ")[-1].lower()
    firstName = name.split(" ")[0].lower()

    imageList = Player.objects.filter(lastName=lastName)
    image = None

    if len(imageList) != 0:
        if len(imageList) == 1:
            image = imageList.first().imageLink
        else:
            imageList = imageList.filter(firstName=firstName)
            if len(imageList) != 0:
                image = imageList.first().imageLink
            else:
                imageList = Player.objects.filter(lastName=lastName)
                image = imageList.first().imageLink

    try:
        data = makeAPICall(ApiCalls.playerInfo + f"/{id}/teams")
    except JSONDecodeError:
        return None

    addData = InfoObj()

    for i in reversed(data):
        retString = f"Position: {PositionMatcher.pos[i['Position']]}\n"

        if "JerseyNum" in i.keys():
            retString += f"Jersey Number: {i['JerseyNum']}\n"

        if len(i['PositionLocalized']) != 0:
            retString += f"Position: {i['PositionLocalized'][0]['Description']}\n"

        statList = {
            "Goals": "Goals",
            "RedCards": "Red cards",
            "YellowCards": "Yellow cards",
            "MatchesPlayed": "Matches played",
        }

        for key, val in statList.items():
            if i[key] != None:
                retString += f"{val}: {i[key]}\n"
            else:
                retString += f"{val}: 0\n"
        retString += f"Joined at {parser.parse(i['JoinDate']).strftime('%d %b %Y')}\n"
        if parser.parse(
                i['LeaveDate']) > datetime.utcnow().replace(tzinfo=UTC):
            retString += f"Contract running until {parser.parse(i['LeaveDate']).strftime('%d %b %Y')}\n"
        else:
            retString += f"Contract ran out at {parser.parse(i['LeaveDate']).strftime('%d %b %Y')}\n"

        try:
            teamData = makeAPICall(ApiCalls.specificTeam + f"/{i['IdTeam']}")
        except JSONDecodeError:
            return None

        addData[teamData['Name'][0]['Description']] = retString
        if image is not None:
            addData[teamData['Name'][0]['Description']].set_thumbnail(
                url=image)
    return name, addData