コード例 #1
0
def reloadData(flag=None):
    if flag == "s":
        data_updater.reloadSummonerData(refresh=False)
        discord_bot.SendMessage("Reloaded Summoner Data")
    elif flag == "c":
        data_updater.reloadChampionData()
        discord_bot.SendMessage("Reloaded Champion Data")
    else:
        data_updater.reloadSummonerData(refresh=False)
        data_updater.reloadChampionData()
        discord_bot.SendMessage("Reloaded Data")
コード例 #2
0
ファイル: run.py プロジェクト: SarhadSalam/LeagueGameNotify
def notifyGameStart(summoner, gameInfo):
    participants = gameInfo["participants"]
    participant = None
    for p in participants:
        summonerId = p["summonerId"]
        if summonerId == summoner.SummonerDTO["id"]:
            participant = p
            break
    if participant != None:
        champion = data.getChampionName(participant["championId"])
        msg = "GAME START: " + \
            summoner.SummonerDTO["name"] + \
            " has started a ranked game as " + champion + "!"
        data.loadNotifyData()
        notifyList = data.getNotifyListForSummoner(
            summoner.SummonerDTO["name"])
        postMsg = None
        if notifyList and len(notifyList) > 0:
            postMsg = "Notifying Simps:"
            for user in notifyList:
                postMsg += " " + helper.mentionUser(user)
        discord_bot.SendMessage(msg, utils.ColorCodes.YELLOW, postMsg)
    else:
        logging.info(
            f"Could not obtain participant for current game of {summoner.SummonerDTO['name']}"
        )
コード例 #3
0
ファイル: run.py プロジェクト: SarhadSalam/LeagueGameNotify
def updateSummonerCurrentRank(summoner, response):
    if response and response.status_code == 200:
        leagueEntrySet = response.json()
        rank = {}
        for entry in leagueEntrySet:
            if (entry["queueType"] != consts.RANKED_SOLO_QUEUE_TYPE):
                continue
            rank["tier"] = entry["tier"]
            rank["division"] = entry["rank"]
            rank["lp"] = entry["leaguePoints"]
            if "miniSeries" in entry:
                rank["miniSeries"] = entry["miniSeries"]
            break
        change = summoner.updateCurrentRank(rank)
        if change == 2:
            # Promoted to new Tier!
            discord_bot.SendMessage(
                "PROMOTION: " + summoner.SummonerDTO["name"] +
                " has promoted to " + rank["tier"] + " " + rank["division"] +
                " !!! <3", utils.ColorCodes.GREEN)
        elif change == 1:
            # Promoted to new Division
            discord_bot.SendMessage(
                "PROMOTION: " + summoner.SummonerDTO["name"] +
                " has promoted to " + rank["tier"] + " " + rank["division"] +
                " <3", utils.ColorCodes.GREEN)
        elif change == -1:
            # Demoted to new Division
            discord_bot.SendMessage(
                "DEMOTION: " + summoner.SummonerDTO["name"] +
                " has demoted to " + rank["tier"] + " " + rank["division"] +
                " :(", utils.ColorCodes.RED)
        elif change == -2:
            # Demoted to new Tier
            discord_bot.SendMessage(
                "DEMOTION: " + summoner.SummonerDTO["name"] +
                " has demoted to " + rank["tier"] + " " + rank["division"] +
                " :( :(\nCan we get an F in the chat", utils.ColorCodes.RED)
        if change != 0:
            # Newly assigned rank
            requestDataSave()
コード例 #4
0
def run_health_check():
    global already_reported
    all_threads = []
    for t in threading.enumerate():
        all_threads.append(t.getName())

    if consts.GAME_CHECK_THREAD_NAME not in all_threads:
        if not already_reported:
            msg = f"{consts.GAME_CHECK_THREAD_NAME} has stopped running. Games are not being reported."
            logging.error(msg)
            discord_bot.SendMessage(
                f"{msg} {helper.mentionUser(data.getDiscordIdFromSummonerName('sardaddy'))} {helper.mentionUser(data.getDiscordIdFromSummonerName('Nashweed'))}",
                utils.ColorCodes().RED)
            already_reported = True
コード例 #5
0
ファイル: run.py プロジェクト: SarhadSalam/LeagueGameNotify
def notifyGameEnd(summoner, gameId, previouslyFailedCount=0):
    if gameId is None:
        return

    gameId = str(gameId)  # api v5 fix
    url = api_calls.BASE_API_URL_V5 + \
        api_calls.MATCH_API_URL.format(matchId=f"NA1_{gameId}")
    response = call_api(url)
    if response and response.status_code == 200:
        json_data = response.json()
        participants = json_data["info"]["participants"]
        participantID = None
        participant = None
        totalKills = 0
        totalDamage = 0
        damageRank = 1
        team = None

        for p in participants:
            if p["summonerId"] == summoner.SummonerDTO["id"]:
                summonerId = p["summonerId"]
                participantID = p["participantId"]
                participant = p
                team = p["teamId"]
                break
        if participantID is None:
            logging.info(
                f"Could not find {summoner.SummonerDTO['name']} in participant list"
            )

        # participant now has the summoner stats for the game

        # personal stats
        champion = data.getChampionName(participant["championId"])
        kills = int(participant["kills"])
        deaths = int(participant["deaths"])
        assists = int(participant["assists"])
        damage = int(participant["totalDamageDealtToChampions"])

        # cumulative team stats
        for p in participants:
            if p["teamId"] == team:
                totalKills += int(p["kills"])
                p_dmg = int(p["totalDamageDealtToChampions"])
                totalDamage += p_dmg
                if p["participantId"] != participantID and p_dmg > damage:
                    damageRank += 1

        # kp
        if totalKills > 0:
            kp = str((100 * (kills + assists)) // totalKills)
        else:
            kp = "0"

        # damage share
        if totalDamage > 0:
            damageShare = str((100 * damage) // totalDamage)
        else:
            damageShare = 0
            damageRank = 5

        # Game End Stats Message
        win = participant["win"]
        result = "won" if win else "lost"
        dmg_text = ""
        if damageRank == 1:
            dmg_text = "highest in the team"
        elif damageRank == 5:
            dmg_text = "lowest in the team"
        else:
            pos = "2nd" if damageRank == 2 else "3rd" if damageRank == 3 else "4th" if damageRank == 4 else "NaN"
            dmg_text = pos + " highest in the team"
        msg = "GAME END: {} {} a game as {}. He went {}/{}/{} with a kp of {}% and dealt {:,} damage ({}% damage share, {})"
        msg = msg.format(summoner.getName(), result, champion, kills, deaths,
                         assists, kp, damage, damageShare, dmg_text)

        # Rank Change
        if summoner.CurrentRank != None:
            promos = None
            url = api_calls.BASE_API_URL + \
                api_calls.LEAGUE_API_URL.format(
                    encryptedSummonerId=summoner.SummonerDTO["id"])
            response = call_api(url)
            if response and response.status_code == 200:
                leagueEntrySet = response.json()
                rank = {}
                for entry in leagueEntrySet:
                    if (entry["queueType"] != consts.RANKED_SOLO_QUEUE_TYPE):
                        continue
                    rank["tier"] = entry["tier"]
                    rank["division"] = entry["rank"]
                    rank["lp"] = entry["leaguePoints"]
                    if "miniSeries" in entry:
                        promos = entry["miniSeries"]
                    break
                if rank["tier"] == summoner.CurrentRank["tier"] and rank[
                        "division"] == summoner.CurrentRank["division"]:
                    prevLp = int(summoner.CurrentRank["lp"])
                    newLp = int(rank["lp"])
                    lpDiff = 0
                    if win:
                        lpDiff = newLp - prevLp
                    else:
                        lpDiff = prevLp - newLp
                    result = "gained" if win else "lost"
                    if promos is None or lpDiff != 0:
                        msg += "\n" + summoner.SummonerDTO[
                            "name"] + " " + result + " " + str(
                                lpDiff
                            ) + "lp for this game. He is currently " + str(
                                rank["tier"]) + " " + str(
                                    rank["division"]) + " " + str(
                                        rank["lp"]) + "lp."
                    if promos is not None:
                        wins = str(promos["wins"])
                        losses = str(promos["losses"])
                        nextRankIndex = consts.TIERS.index(
                            summoner.CurrentRank["tier"]) + 1
                        nextRank = consts.TIERS[nextRankIndex]
                        msg += "\n" + summoner.SummonerDTO["name"] + " is currently " + \
                            wins + "-" + losses + " in promos to " + nextRank + "."

        # Match History Uri:
        postMsg = None

        matchUrls = [
            ("Mobalytics",
             api_calls.MOBALYTICS_MATCH_URL.format(
                 summonerName=urllib.parse.quote(summoner.SummonerDTO["name"]),
                 gameId=gameId)),
            ("LeagueOfGraphs", api_calls.LOG_MATCH_URL.format(gameId=gameId))
        ]
        urlListText = " | ".join([
            "[{text}](<{url}>)".format(text=item[0], url=item[1])
            for item in matchUrls
        ])
        postMsg = "View Game Details Here: " + urlListText

        color = utils.ColorCodes.GREEN if win else utils.ColorCodes.RED

        image_handler.get_image(gameId)
        image_handler.crop_image_post_game(gameId)

        discord_bot.SendMessage(msg,
                                color,
                                postMsg,
                                file=discord.File(f"cropped_{gameId}.png"))

        image_handler.remove_images(gameId)

        # Special Naeem section xD
        if summoner.getName(
        ) == "NaeemP" and not win and champion != "Nocturne":
            discord_bot.SendMessage("SADGE: No Nocturne no LP. ",
                                    file=discord.File("naeem_lose.jpg"))

    else:
        msg = "Try #" + str(previouslyFailedCount + 1) + ": Error Obtaining Game Info for match# " + \
            str(gameId) + " (Game by " + summoner.SummonerDTO["name"] + ")"

        if previouslyFailedCount > 3:
            msg += " Stopping trying, match query failed. Look into it."
        else:
            failed_game_end_ids.add(
                (gameId, summoner, previouslyFailedCount + 1))

        logging.info(response)  # print response to see what is going on
        logging.info(msg)

        discord_bot.SendMessage(msg)
コード例 #6
0
ファイル: run.py プロジェクト: SarhadSalam/LeagueGameNotify
def sysExit(signal, frame):
    discord_bot.SendMessage("```Bot is going to sleep.```")
    bot_process.terminate()
    sys.exit(0)
コード例 #7
0
ファイル: run.py プロジェクト: SarhadSalam/LeagueGameNotify
if __name__ == "__main__":
    signal.signal(signal.SIGINT, sysExit)
    configure_logger()

    options = (["--refresh", "--r"])

    args = sys.argv[1:]

    bot_process = Process(target=discord_bot.start_bot,
                          args=(BOT_COMM_QUEUE, ))
    bot_process.start()

    if len(args) > 0:
        if args[0] in options[0]:
            # Run with Refresh
            discord_bot.SendMessage(
                "```Starting Up Bot With Refreshed Data```")
            data.refreshSummonerData()
        else:
            # Invalid args
            print("Invalid arguments")
            printHelp()
            sys.exit()
    summonerData = data.loadSummonerData()
    if summonerData is None:
        logging.info(
            "No summoner data file found. Refreshing summoner data to generate data"
        )
        summonerData = data.refreshSummonerData()
    data.loadChampionData()
    data.loadNotifyData()
    FIVE_MINUTES = 5 * 60
コード例 #8
0
def updateData():
    _, status = data_updater.updateDDVersionFiles(True)
    discord_bot.SendMessage(status)