From 8e04859091154279c433ea7b13bb93295708c1e9 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 12 Aug 2016 22:53:12 +0200 Subject: [PATCH] Added league of legends integration --- .gitignore | 3 ++- league.py | 39 +++++++++++++++++++++++++++++++++++++++ main.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++---- strings.py | 14 +++++++++++++- 4 files changed, 101 insertions(+), 6 deletions(-) create mode 100644 league.py diff --git a/.gitignore b/.gitignore index 887bf779..430ccab2 100644 --- a/.gitignore +++ b/.gitignore @@ -139,4 +139,5 @@ $RECYCLE.BIN/ *.lnk .idea/ discordtoken.txt -db.json \ No newline at end of file +db.json +leaguetoken.txt diff --git a/league.py b/league.py new file mode 100644 index 00000000..4f96a082 --- /dev/null +++ b/league.py @@ -0,0 +1,39 @@ +import asyncio +import requests + + +class NotFoundException(Exception): + pass + + +class NoRankedGamesCompletedException(Exception): + pass + + +loop = asyncio.get_event_loop() + +# Load League of Legends API key from the leaguetoken.txt file +file = open("leaguetoken.txt", "r") +token = file.read() +file.close() + +ranklist = ['BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'DIAMOND', 'MASTER', 'CHALLENGER'] +roman = ['I', 'II', 'III', 'IV', 'V'] + + +# Get player rank info +async def get_player_rank(region: str, summonerid: int, **kwargs): + # GET the json unofficial API response + r = await loop.run_in_executor(None, requests.get, + 'https://{region}.api.pvp.net/api/lol/{region}/v2.5/league/by-summoner/{summonerid}' + '/entry?api_key={token}'.format(region=region, summonerid=summonerid, token=token)) + # Ensure the request is successful + if r.status_code == 200: + if len(r.json()[str(summonerid)]) > 0: + return r.json()[str(summonerid)][0] + else: + raise NoRankedGamesCompletedException("This player hasn't completed any ranked games.") + elif r.status_code == 404: + raise NotFoundException("Player not found.") + else: + raise Exception("Unhandled API response.") diff --git a/main.py b/main.py index 8ee204ad..af78a0a5 100644 --- a/main.py +++ b/main.py @@ -2,6 +2,7 @@ import asyncio import discord import json import overwatch +import league import strings as s loop = asyncio.get_event_loop() @@ -17,12 +18,14 @@ file = open("discordtoken.txt", "r") token = file.read() file.close() -# Every 300 seconds, update player status and check for levelups +# Every timeout seconds, update player status and check for levelups async def overwatch_level_up(timeout): while True: + # Wait for the timeout + await asyncio.sleep(timeout) # Update data for every player in list for player in db: - if db[player]["overwatch"] is not None: + if "overwatch" in db[player]: r = await overwatch.get_player_data(**db[player]["overwatch"]) if r["data"]["level"] > db[player]["overwatch"]["level"]: # Convert user ID into a mention @@ -31,13 +34,53 @@ async def overwatch_level_up(timeout): msg = s.overwatch_level_up.format(player=user, level=r["data"]["level"]) # Send the message to the discord channel loop.create_task(d_client.send_message(d_client.get_channel("213655027842154508"), msg)) - db[player]["overwatch"]["level"] = r["data"]["level"] # Update database + db[player]["overwatch"]["level"] = r["data"]["level"] f = open("db.json", "w") json.dump(db, f) f.close() + +# Every timeout seconds, update player league and check for rank changes +async def league_rank_change(timeout): + while True: # Wait for the timeout await asyncio.sleep(timeout) + # Update data for every player in list + for player in db: + if "league" in db[player]: + try: + r = await league.get_player_rank(**db[player]["league"]) + except league.NoRankedGamesCompletedException: + # If the player has no ranked games completed, skip him + continue + else: + # Convert tier into a number + tier_number = league.ranklist.index(r["tier"]) + roman_number = league.roman.index(r["entries"][0]["division"]) + # Check for tier changes + if tier_number != db[player]["league"]["tier"] or roman_number < db[player]["league"]["division"]: + # Convert user ID into a mention + user = "<@" + player + ">" + # Prepare the message to send + msg = s.league_rank_up.format(player=user, + tier=s.league_tier_list[tier_number], + division=r["entries"][0]["division"]) + # Send the message to the discord channel + loop.create_task(d_client.send_message(d_client.get_channel("213655027842154508"), msg)) + # Update database + db[player]["league"]["tier"] = tier_number + db[player]["league"]["division"] = roman_number + f = open("db.json", "w") + json.dump(db, f) + f.close() loop.create_task(overwatch_level_up(900)) -d_client.run(token) +loop.create_task(league_rank_change(120)) + +try: + loop.run_until_complete(d_client.start(token)) +except KeyboardInterrupt: + loop.run_until_complete(d_client.logout()) + # cancel all tasks lingering +finally: + loop.close() diff --git a/strings.py b/strings.py index 2e959bab..4bd26c7a 100644 --- a/strings.py +++ b/strings.py @@ -1,4 +1,16 @@ # Overwatch: Level up! # {player} = player # {level} = new level -overwatch_level_up = "{player} è salito al livello **{level}** su Overwatch!" +overwatch_level_up = "{player} è salito al livello **{level}** su _Overwatch_!" + +# League of Legends: Rank up! +league_rank_up = "{player} è salito alla divisione **{tier} {division}** su _League of Legends_!" + +# League of Legends: Tier list +league_tier_list = ["Bronzo", + "Argento", + "Oro", + "Platino", + "Diamante", + "Master", + "Challenger"]