Ejemplo n.º 1
1
def get_tilt(area, summoner_name):
    try:
        watcher = RiotWatcher(API_KEY, default_region=area)
        champions_dict = get_champions_data(watcher)
        # check if we have API calls remaining
        if watcher.can_make_request():
            current_app.logger.debug('Requests to API available')
        else:
            current_app.logger.error('Too many requests. '
                                     'Please try again later.')
            sys.exit(2)
        try:
            player = watcher.get_summoner(name=summoner_name, region=area)
        except LoLException:
            current_app.logger.debug('Summoner {0} not found.'.format(
                summoner_name))
            raise SummonerNotFound(
                'Summoner {0} not found in {1} server.'.format(
                    summoner_name, area.upper()))

        recent_games = watcher.get_recent_games(player['id'])['games']
        response = {"status": 200,
                    "wins": get_wins_number(recent_games),
                    "metadata": {
                        "background": get_random_background_url(
                            champions_dict),
                        "display": get_random_display()},
                    "stats": get_stats(recent_games, champions_dict),
                    "summoner_name": summoner_name,
                    "tilt_level": get_tilt_level(recent_games)}
        return response
    except:
        current_app.logger.error(traceback.format_exc())
        raise
Ejemplo n.º 2
0
def main():
    w = RiotWatcher(constants.riot_id)
    db = sqlite3.connect('matchdb')

    cursor = db.cursor()
    cursor.execute(
        '''SELECT DISTINCT match_id FROM match_by_tier ORDER BY match_id ASC'''
    )
    if not os.path.exists("matches_silver"):
        os.makedirs("matches_silver")
    os.chdir("matches_silver");
    for row in cursor:
        match_id = row[0]
        print(match_id)
        match_filename = get_match_filename(match_id)
        if (os.path.isfile(match_filename)):
            print("Skipping: {}".format(match_filename))
        else:
            try:
                match_json = w.get_match(match_id, include_timeline=True)
                with open(match_filename, 'w') as f:
                    f.write(json.dumps(match_json))
                print("Writing: {}".format(match_filename))
            except Exception as e:
                print("Failed: {0} with {1}".format(
                    match_filename,
                    e
                ))
            time.sleep(1.2)
def import_champs():
    w = RiotWatcher(os.environ.get('RIOT_API_KEY'))
    champs = w.static_get_champion_list()

    new_champs = {}
    for champ in champs['data'].itervalues():
        new_champs[champ['id']] = champ['name']

    return new_champs
def getMatch(matchList, server):
	key = readApiKey()
	w = RiotWatcher(key, server)
	try:
		match = w.get_match(matchList['matchId'], server)
	except Exception:
		pass
	
	return match
Ejemplo n.º 5
0
class LeagueGrind(object):
	
	def __init__(self, spreadSheetName):
		# Establish Google Drive Connection
		json_key = json.load(open('credentials.json'))
		scope = ['https://spreadsheets.google.com/feeds']
		credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
		gc = gspread.authorize(credentials)
		self.spreadsheet = gc.open("League Grinds")		
		
		#Establish Riot API Connection
		self.riotWatcher = RiotWatcher(getDevKey())		
		
	def update_player(self, playerName):
		
		# Get the current spread sheet for playerName
		# If it does not exist, create one for them
		try:		
			worksheet = self.spreadsheet.worksheet("API-"+playerName)
		except:		
			self.spreadsheet.add_worksheet("API-"+playerName,1,8)
			worksheet = self.spreadsheet.worksheet("API-"+playerName)
			self.init_player_spreadsheet(worksheet)
		
		# Determine Last Entered Match
		rows = worksheet.row_count
		if rows == 1:	lastTimeStamp = 0
		else: 			lastTimeStamp = worksheet.cell(rows,2).value
		
		# Get Summoner ID
		while self.riotWatcher.can_make_request() == False:
			continue
		player = self.riotWatcher.get_summoner(name=playerName)
		playerID = player['id']
		
		# Request Match Meta Data
		while self.riotWatcher.can_make_request() == False:
			continue
		match_list = self.riotWatcher.get_match_list(playerID,region='na',season='SEASON2016')
		
		# Send all new Matches to SpreadSheet
		for f in match_list['matches'][::-1]:
			if f['timestamp'] > int(lastTimeStamp):
				Match(playerID,self.riotWatcher,f).log(worksheet)
				
	def init_player_spreadsheet(self,worksheet):
		worksheet.update_cell(1,1,"MatchID")
		worksheet.update_cell(1,2,"Timestamp")
		worksheet.update_cell(1,3,"Champion")
		worksheet.update_cell(1,4,"Kills")
		worksheet.update_cell(1,5,"Deaths")
		worksheet.update_cell(1,6,"Assists")
		worksheet.update_cell(1,7,"KDA")
		worksheet.update_cell(1,8,"Outcome")		
def getSummonerMatchList(summonerId, server, queue, season):
	key = readApiKey()
	w = RiotWatcher(key, server)
	try:
		info = w.get_match_list(summonerId, server, champion_ids=None, #Aqui obtiene las partidas jugadasde un jugador (son muchas)
                          ranked_queues=queue,
                          season=season)
	except Exception:
		pass

	return info['matches']
def initChallengerTierList(server):
	key = readApiKey()
	if os.path.isfile('data.json') == False:
		with open('data.json', 'w') as f:
			w = RiotWatcher(key, server)
			challenger_tier = w.get_challenger(server)
			json.dump(challenger_tier, f)
			print 'CACHE NOT FOUND, CREATING JSON..'
			data = challenger_tier			
			return data
	else:
	    with open('data.json') as data_file:
	      print 'CACHE FOUND, LOADING...'
	      data = json.load(data_file)
	      return data	
def main():
    p_ids = []
    with open("player_tiers.csv") as csvfile:
        reader = csv.DictReader(csvfile)
        p_ids = [row["user_id"] for row in reader if row["tier"] == "SILVER"]

    db = sqlite3.connect("matchdb")
    cursor = db.cursor()
    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS match_by_tier(
            user_id INTEGER KEY,
            match_id INTEGER KEY,
            tier VARCHAR(255),
            UNIQUE (user_id, match_id) ON CONFLICT REPLACE);
    """
    )
    db.commit()
    db.close()

    w = RiotWatcher(constants.riot_id)
    db = sqlite3.connect("matchdb")
    cursor = db.cursor()

    curTime = long(time.time() * 1000)

    for user_id in p_ids:
        cursor.execute("""SELECT DISTINCT user_id FROM match_by_tier WHERE user_id=?""", (user_id,))
        if cursor.fetchone() is None:
            match_list = []
            try:
                match_list = w.get_match_list(
                    str(user_id), region=NORTH_AMERICA, begin_time=curTime - 1000 * 60 * 60 * 24 * 30, end_time=curTime
                )["matches"]
            except Exception as e:
                print(e)
            filtered_matches = [m for m in match_list if m["queue"] == "RANKED_SOLO_5x5"]
            retVal = filtered_matches[:10]
            time.sleep(2)
            user_matches = [(user_id, m["matchId"], "SILVER") for m in retVal]
            cursor.executemany("""INSERT INTO match_by_tier (user_id, match_id, tier) VALUES (?,?, ?)""", user_matches)
            db.commit()
            print("Dealt with {0}".format(user_id))
        else:
            print("Skipped {0}".format(user_id))
    db.close()
Ejemplo n.º 9
0
    def __init__(self):
        """Set up the initial values for the class and read from the config file"""
        jsonConfig = open("./config.json").read()
        self.config = json.loads(jsonConfig)

        self.api = RiotWatcher(self.config["api-key"], default_region=self.config["region"])
        self.canMakeRequest = True
        self.callCount = 10
Ejemplo n.º 10
0
	def __init__(self, spreadSheetName):
		# Establish Google Drive Connection
		json_key = json.load(open('credentials.json'))
		scope = ['https://spreadsheets.google.com/feeds']
		credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
		gc = gspread.authorize(credentials)
		self.spreadsheet = gc.open("League Grinds")		
		
		#Establish Riot API Connection
		self.riotWatcher = RiotWatcher(getDevKey())		
Ejemplo n.º 11
0
class LeagueGrind(object):
	
	def __init__(self, spreadSheetName):
		# Establish Google Drive Connection
		json_key = json.load(open('credentials.json'))
		scope = ['https://spreadsheets.google.com/feeds']
		credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
		gc = gspread.authorize(credentials)
		self.spreadsheet = gc.open("League Grinds")
		
		#Establish Riot API Connection
		self.riotWatcher = RiotWatcher(getDevKey())		
		
	def update_player(self, playerName):
		player = self.riotWatcher.get_summoner(name=playerName)
		playerID = player['id']
		match_list = self.riotWatcher.get_match_list(playerID,region='na',season='SEASON2016')
		
		if raw_input("Get Match Data? yes/no\n") == "yes":
			matches = [Match(playerID,self.riotWatcher,f) for f in match_list['matches']]
Ejemplo n.º 12
0
	def on_button_click(self):
		self.error_label.configure(text='validating...')

		w = RiotWatcher(self.apikey.get())
		#validate summoner name and api key
		try:
			me = w.get_summoner(name=self.summoner.get(), region=self.region_var.get())
			print me
			#save new settings
			self.settings['summonerName'] = self.summoner.get()
			self.settings['region'] = self.region_var.get()
			self.settings['apikey'] = self.apikey.get()
			with open('settings.json', 'w') as f:
				json.dump(self.settings, f)
			self.error_label.configure(text='settings saved!')

		except Exception as error:
			if error.error == "Unauthorized":
				self.error_label.configure(text='API Key is invalid!')
			else:
				self.error_label.configure(text='Summoner does not exist!')
Ejemplo n.º 13
0
class CallCounter:
    """Class to control the rate of requests"""

    def __init__(self):
        """Set up the initial values for the class and read from the config file"""
        jsonConfig = open("./config.json").read()
        self.config = json.loads(jsonConfig)

        self.api = RiotWatcher(self.config["api-key"], default_region=self.config["region"])
        self.canMakeRequest = True
        self.callCount = 10

    def get_call_count(self):
        return self.callCount

    def decrease_call_count(self):
        self.callCount -= 1
        if self.callCount == 0:
            self.canMakeRequest = False

    def reset_call_count(self):
        self.callCount = 10
        self.canMakeRequest = True

    def get_match_details_from_id(self, match_id):
        """Gets match details for the given match_id. Returns a list of match details"""
        if self.canMakeRequest:
            time.sleep(1)
            print("Getting match details for game id: " + str(match_id))
            md = self.api.get_match(match_id, include_timeline=True)
            print(md)
            return md

    def get_match_ids_for_team(self):
        """Gets the latest games for the team. Returns a list of strings with the game ids"""
        if self.canMakeRequest:
            time.sleep(1)
            print("Getting match history for team id " + self.config["team-id"])
            return self.api.get_team(self.config["team-id"])
Ejemplo n.º 14
0
class Request:
    def __init__(self):
        self.riot = RiotWatcher(LoL.API_KEY)
        self.champions = self._getChampions()

    def _getChampions(self):
        champion_list = {}
        champions = self.riot.static_get_champion_list()
        for champion in champions["data"]:
            champion_list[champions["data"][champion]["id"]] = champion
        return champion_list

    def _checkRequestStatus(self):
        return self.riot.can_make_request()

    def retrievePlayerData(self, playerId):
        while not self._checkRequestStatus():
            sleep(2.6)
        else:
            player = {}
            player["id"] = playerId
            player["summoner"] = self.riot.get_summoner(name=playerId)
            player["match_history"] = self.riot.get_match_history(player["summoner"]["id"])
            return player
Ejemplo n.º 15
0
def home(request):
    summoner_name = request.GET.get('summoner_name')
    region = request.GET.get("region")

    # Get Api key
    cur_path = os.getcwd()
    file = open(os.path.join(cur_path, '_info', 'api.txt'),
                "r")  #path to api key
    APIKey = file.read()

    watcher = RiotWatcher(APIKey)
    try:
        summoner_data = watcher.summoner.by_name(region, summoner_name)
    except ApiError as e:
        status_code = e.response.status_code
        return render(request, "summoner/error.html", {
            "summonerData": {
                "name": summoner_name
            },
            "status": status_code
        })

    # if summoner not found
    if "status" in summoner_data:
        return render(request, "summoner/error.html",
                      {"summonerData": {
                          "name": summoner_name
                      }})

    match_list = watcher.match.matchlist_by_account(region,
                                                    summoner_data["accountId"],
                                                    end_index=25)['matches']
    matches = {}
    champion_ids = {}
    for match in match_list[:min(25, len(match_list))]:
        match_by_id = watcher.match.by_id(region, match["gameId"])

        # 0th index = blue team, 1st index = red team
        for ban in zip(match_by_id['teams'][0]['bans'],
                       match_by_id['teams'][1]['bans']):
            for i in range(len(ban)):
                id = str(ban[i]['championId'])
                if id not in champion_ids:
                    champion_json = riot.getStaticChampionInfo(id)
                    champion_ids[id] = champion_json

    league_data = watcher.league.by_summoner(region, summoner_data["id"])

    #Static content
    version = watcher.data_dragon.versions_for_region(region)['v']
    champions = watcher.data_dragon.champions(version)['data']
    items = watcher.data_dragon.items(version)['data']
    profile_icons = watcher.data_dragon.profile_icons(version)['data']
    summoner_spells = watcher.data_dragon.summoner_spells(version)['data']

    # runes = watcher.data_dragon.runes(version) not working??

    context = {
        "summonerData": summoner_data,
        "matches": match_list,
        "leagues": league_data,
        "champions": champions,
        "items": items,
        "profile_icons": profile_icons,
        "summoner_spells": summoner_spells,
        "champion_ids": Champion_Id.objects.in_bulk()
    }

    return render(request, 'summoner/home.html', context)
Ejemplo n.º 16
0
 def __init__(self, key, default_region=EUROPE_WEST):
     self.lol_watcher = RiotWatcher(key, default_region=default_region)
     self.wait()
     self.champion_list = self.lol_watcher.static_get_champion_list(
     )['data']
Ejemplo n.º 17
0
        for ind in range(20):
            try:
                last_match = watcher.match.by_id(
                    my_region, recent_matches['matches'][ind]['gameId'])

                print_match_info(last_match, champion, enemy_champion)
            except ChampNotFoundException:
                print(".")
                continue
            break

    # print(json.dumps(last_match, indent=4, sort_keys=True))


try:
    watcher = RiotWatcher(open('riot-api-key.txt', 'r').read())

    my_region = 'na1'

    me = watcher.summoner.by_name(my_region, 'iqiq')

    champ_data = watcher.static_data.champions(my_region)['data'].items()

    champion_name_to_id_map = {key: value['id'] for key, value in champ_data}

    champion = sys.argv[1]
    enemy_champion = sys.argv[2]
    if len(sys.argv) > 3:
        game_index = int(sys.argv[3])
    else:
        game_index = -1
Ejemplo n.º 18
0
# these tests are pretty bad, mostly to make sure no exceptions are thrown

import time
from riotwatcher import RiotWatcher, NORTH_AMERICA

key = '<YOUR KEY HERE>'
# if summoner doesnt have ranked teams, teams tests will fail
# if summoner doesnt have ranked stats, stats tests will fail
# these are not graceful failures, so try to use a summoner that has them
summoner_name = 'YOUR NAME HERE'

w = RiotWatcher(key)


def wait():
    while not w.can_make_request():
        time.sleep(1)


def champion_tests():
    wait()
    temp = w.get_all_champions()
    wait()
    w.get_champion(temp['champions'][0]['id'])


def game_tests(summoner):
    wait()
    w.get_recent_games(summoner['id'])

Ejemplo n.º 19
0
import requests
import logging
import configparser



from io import BytesIO
from PIL import Image
from riotwatcher import RiotWatcher
from riotwatcher import EUROPE_WEST
from riotwatcher import NORTH_AMERICA
from riotwatcher import LoLException, error_404, error_429

logger = logging.getLogger("scuript_logger.league")

w = RiotWatcher('b6e57fc8-b03e-40ce-8c84-55d616941248')
#static_champ_list = w.static_get_champion_list()
#logger.debug(static_champ_list)

#CONSTANTS
UNKNOWN = 'unknown'

config = configparser.ConfigParser()
config.read('../cfg/regions.txt')

queue_types = {
    0  : 'CUSTOM',  # Custom games
    2  : 'NORMAL 5x5 BLIND',  # Normal 5v5 blind pick
    8  : 'NORMAL 3x3',  # Normal 3v3 games
    14 : 'NORMAL 5x5 DRAFT',  # Normal 5v5 Draft Pick games
    16 : 'ODIN 5x5 BLIND',  # Dominion 5v5 Blind Pick games
Ejemplo n.º 20
0
import cassiopeia as cass
from riotwatcher import RiotWatcher

import settings
from requests import HTTPError

from utils.regions import get_region

watcher = RiotWatcher(settings.RIOT_API_KEY)

summoner = watcher.summoner.by_name(region=get_region('eune'),
                                    summoner_name='xerrion')
league = watcher.league.positions_by_summoner(get_region('eune'),
                                              summoner['id'])

print(summoner)
print(league[0])
Ejemplo n.º 21
0
 def __init__(self, bot):
     self.bot = bot
     self.watcher = RiotWatcher('RIOT API')
Ejemplo n.º 22
0
from decimal import *
import sys
import datetime

from riotwatcher import RiotWatcher

from libraries.perms import *
from libraries.library import *

from urllib import request
import linecache
import ast

ApiKey = getApiKey()

w = RiotWatcher(ApiKey)

#####################################################################################################################################################

def getSummonerInfo(summoner):
	"""Récupère les données d'un invocateur"""
	try:
		user = w.get_summoner(name=summoner)
		return user
	except LoLException as e:
		if e == error_429:
			error = '```py\nWe should retry in {} seconds.\n```'.format(e.headers['Retry-After'])
			return error
		elif e == error_404:
			error = '```py\nSummoner not found.\n```'
			return error
Ejemplo n.º 23
0
    def league_rank(self, **options):
        try:
            from riotwatcher import RiotWatcher, LoLException
        except ImportError:
            log.error('Missing required module for League Rank module: riotwatcher')
            return False

        source = options['source']
        message = options['message']
        bot = options['bot']

        riot_api_key = self.settings['riot_api_key']
        summoner_name = self.settings['default_summoner']
        def_region = self.settings['default_region']
        region_list = ['br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr']

        if message:
            summoner_name = message.split()[0]
            try:
                region = message.split()[1].lower()
            except IndexError:
                region = def_region.lower()

            if region not in region_list:
                bot.whisper(source.username, 'Region is not valid. Please enter a valid region, region is optional and the default region is {}'.format(def_region.upper()))
                return False
            else:
                pass
        else:
            region = def_region.lower()

        error_404 = "Game data not found"
        error_429 = "Too many requests"

        try:
            rw = RiotWatcher(riot_api_key, default_region=region)

            summoner = rw.get_summoner(name=summoner_name)
            summoner_id = str(summoner['id'])
            summoner_name = summoner['name']

        except LoLException as e:
            if e == error_429:
                bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After']))
                return False
            elif e == error_404:
                bot.say('The summoner not found. Use a valid summoner name (remove spaces) and region FailFish')
                return False

        try:
            summoner_league = rw.get_league_entry(summoner_ids=(summoner_id, ))

            tier = summoner_league[summoner_id][0]['tier']
            division = summoner_league[summoner_id][0]['entries'][0]['division']
            league_points = summoner_league[summoner_id][0]['entries'][0]['leaguePoints']

            bot.say('The Summoner {} on region {} is currently in {} {} with {} LP 4Head'.format(summoner_name, region.upper(), tier, division, league_points))
        except LoLException as e:
            if e == error_429:
                bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After']))
                return False
            elif e == error_404:
                bot.say('The Summoner {} on region {} is currently UNRANKED.. FeelsBadMan'.format(summoner_name, region.upper()))
                return False
            else:
                bot.say('Trouble fetching summoner rank.. Kappa Try again later!')
                return False
Ejemplo n.º 24
0
# Generated by Django 2.0.2 on 2018-04-08 16:49
#from .models import *
from django.db import migrations
from riotwatcher import RiotWatcher

from ..static.python import APIKey

Key = APIKey.riot_key()
watcher = RiotWatcher(Key)
region = 'na1'


def genChampions(apps, schema_editor):
	static_champ_list = watcher.static_data.champions(region, tags = 'all')
	champion_keys = static_champ_list['keys']
	data = static_champ_list['data']
	Champion = apps.get_model('league','Champion')
	champ_objects = []
	for key,name in champion_keys.items():
		champ = data[name]
		img = 'http://stelar7.no/cdragon/latest/champion-icons/' + str(champ['id']) +'.png'
		passive = champ['passive']
		passiveImg = 'http://ddragon.leagueoflegends.com/cdn/6.24.1/img/passive/' + passive['image']['full']
		Champion.objects.create(champion_id=int(key),name=champ['name'],image=img,title=champ['title'],
			passiveName=passive['name'],passiveDescription=passive['sanitizedDescription'],passiveImage=passiveImg).save()


def genSpells(apps, schema_editor):
	static_spell_list = watcher.static_data.summoner_spells(region, tags = 'all')
	spell_objects = []
	data = static_spell_list['data']
Ejemplo n.º 25
0
import time
import pymysql
from cassiopeia import Summoner, Match, Patch, Champion
from cassiopeia.core import MatchHistory
from cassiopeia import Queue
from discord.ext import commands
from riotwatcher import RiotWatcher
from requests import HTTPError

bot = commands.Bot(
    command_prefix=("!", "@LeagueBot"),
    description='Bot for League of Legends')

champion_gg_api_key = config.championGGAPI
kass.set_riot_api_key(config.riotAPI)
watcher = RiotWatcher(config.riotAPI)

all_champions = kass.Champions(region="NA")

latestLeaguePatch = kass.get_versions(region="NA")


#StoreMatches.populateTables()

# Shows when bot is ready
@bot.event
async def on_ready():
    print('Logged in as ' + bot.user.name)

# Simple hello command
@bot.command()
Ejemplo n.º 26
0
    def league_rank(self, **options):
        try:
            from riotwatcher import RiotWatcher, LoLException
        except ImportError:
            log.error('Missing required module for League Rank module: riotwatcher')
            return False

        source = options['source']
        message = options['message']
        bot = options['bot']

        riot_api_key = self.settings['riot_api_key']
        summoner_name = self.settings['default_summoner']
        def_region = self.settings['default_region']

        if len(riot_api_key) == 0:
            log.error('Missing riot API key in settings.')
            return False

        region_list = ['br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr']

        if message:
            summoner_name = message.split()[0]
            try:
                region = message.split()[1].lower()
            except IndexError:
                region = def_region.lower()

            if region not in region_list:
                bot.whisper(source.username, 'Region is not valid. Please enter a valid region, region is optional and the default region is {}'.format(def_region.upper()))
                return False
            else:
                pass
        else:
            region = def_region.lower()

        if len(summoner_name) == 0 or len(region) == 0:
            return False

        error_404 = 'Game data not found'
        error_429 = 'Too many requests'

        try:
            rw = RiotWatcher(riot_api_key, default_region=region)

            summoner = rw.get_summoner(name=summoner_name)
            summoner_id = str(summoner['id'])
            summoner_name = summoner['name']

        except LoLException as e:
            if e == error_429:
                bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After']))
                return False
            elif e == error_404:
                bot.say('The summoner not found. Use a valid summoner name (remove spaces) and region FailFish')
                return False
            else:
                log.info('Something unknown went wrong: {}'.format(e))
                return False

        try:
            summoner_league = rw.get_league_entry(summoner_ids=(summoner_id, ))

            tier = summoner_league[summoner_id][0]['tier']
            division = summoner_league[summoner_id][0]['entries'][0]['division']
            league_points = summoner_league[summoner_id][0]['entries'][0]['leaguePoints']

            bot.say('The Summoner {} on region {} is currently in {} {} with {} LP 4Head'.format(summoner_name, region.upper(), tier, division, league_points))
        except LoLException as e:
            if e == error_429:
                bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After']))
                return False
            elif e == error_404:
                bot.say('The Summoner {} on region {} is currently UNRANKED.. FeelsBadMan'.format(summoner_name, region.upper()))
                return False
            else:
                bot.say('Trouble fetching summoner rank.. Kappa Try again later!')
                return False
Ejemplo n.º 27
0
import sys
from riotwatcher import RiotWatcher
import mysql.connector as sql
from mysql.connector import Error

watcher = RiotWatcher("RGAPI-a15d5a32-06e3-475d-a59b-a2880f1ca49f")


def connect(query, status):
    conn = None
    cursor = None
    records = None

    try:
        conn = sql.connect(host='localhost',
                           database='league_api',
                           user='******',
                           port=3306,
                           password='******')

        cursor = conn.cursor()
        cursor.execute(query)

        if status == "insert":
            conn.commit()
        elif status == "select":
            records = cursor.fetchall()

    except Error as e:
        print(e)
Ejemplo n.º 28
0
async def on_ready(bot):

    # Obtain all static data required
    watcher = RiotWatcher(bot.configurations['discrank.py']['token'])
    if not watcher.can_make_request():
        raise BotException(ErrorTypes.STARTUP, EXCEPTION,
            "The given Riot API token cannot get requests.")

    # Add champions by ID and name, and skills by ID
    champions = watcher.static_get_champion_list(data_by_id=True)['data']
    champions_named = watcher.static_get_champion_list()['data']
    champions_named = dict(
            (key.lower(), value) for key, value in champions_named.items())
    champions.update(champions_named)
    spells = watcher.static_get_summoner_spell_list(data_by_id=True)['data']

    # Add game modes by queue type and name
    modes = {
        "0": "Custom",
        "8": "Normal 3v3",
        "2": "Normal",
        "14": "Normal Draft",
        "4": "Dynamic Queue",
        "6": "Dynamic Queue",
        "9": "Ranked 3v3",
        "41": "Ranked 3v3",
        "42": "Ranked 5v5",
        "16": "This Gamemode doesn't even exist anymore",
        "17": "Same with this one",
        "7": "Co-op vs AI",
        "25": "Co-op vs AI",
        "31": "Co-op vs AI",
        "32": "Co-op vs AI",
        "33": "Co-op vs AI",
        "52": "Co-op vs AI (3v3)",
        "61": "Team Builder",
        "65": "ARAM",
        "70": "One For All",
        "72": "Magma Chamber 1v1",
        "73": "Magma Chamber 2v2",
        "75": "Hexakill",
        "76": "URF",
        "83": "Co-op vs AI (URF)",
        "91": "Doom Bots Lv 1",
        "92": "Doom Bots Lv 2",
        "93": "Doom Bots Lv 3",
        "96": "Ascension",
        "98": "Hexakill",
        "100": "Bilgewater",
        "300": "Legend of the Poro King",
        "313": "Bilgewater ARAM",
        "400": "Team Builder",
        "410": "Dynamic Queue",
        "CUSTOM": "0",
        "NORMAL_3x3": "8",
        "NORMAL_5x5_BLIND": "2",
        "NORMAL_5x5_DRAFT": "14",
        "RANKED_SOLO_5x5": "4",
        "RANKED_PREMADE_5x5*": "6",
        "RANKED_PREMADE_3x3*": "9",
        "RANKED_TEAM_3x3": "41",
        "RANKED_TEAM_5x5": "42",
        "ODIN_5x5_BLIND": "16",
        "ODIN_5x5_DRAFT": "17",
        "BOT_5x5*": "7",
        "BOT_ODIN_5x5": "25",
        "BOT_5x5_INTRO": "31",
        "BOT_5x5_BEGINNER": "32",
        "BOT_5x5_INTERMEDIATE": "33",
        "BOT_TT_3x3": "52",
        "GROUP_FINDER_5x5": "61",
        "ARAM_5x5": "65",
        "ONEFORALL_5x5": "70",
        "FIRSTBLOOD_1x1": "72",
        "FIRSTBLOOD_2x2": "73",
        "SR_6x6": "75",
        "URF_5x5": "76",
        "BOT_URF_5x5": "83",
        "NIGHTMARE_BOT_5x5_RANK1": "91",
        "NIGHTMARE_BOT_5x5_RANK2": "92",
        "NIGHTMARE_BOT_5x5_RANK5": "93",
        "ASCENSION_5x5": "96",
        "HEXAKILL": "98",
        "BILGEWATER_ARAM_5x5": "100",
        "KING_PORO_5x5": "300",
        "COUNTER_PICK": "310",
        "BILGEWATER_5x5": "313",
        "TEAM_BUILDER_DRAFT_UNRANKED_5x5": "400",
        "TEAM_BUILDER_DRAFT_RANKED_5x5": "410"
    }

    bot.data['discrank.py'] = [watcher, champions, spells, modes]
Ejemplo n.º 29
0
from riotwatcher import RiotWatcher
from pprint import pprint
from riotwatcher import KOREA
from riotwatcher import EUROPE_WEST

w = RiotWatcher('API KEY')


def outFile(aFile, write):
    f = open(aFile, 'w')
    f.write(write)
    f.close()


#NORTH_AMERICA
challenger = w.get_challenger()
#pprint(challenger)
#KOREA
challengerKR = w.get_challenger(region=KOREA)
#pprint(challengerKR)
#EUROPE_WEST
challengerEUW = w.get_challenger(region=EUROPE_WEST)
#pprint(challengerEUW)
Ejemplo n.º 30
0
from riotwatcher import RiotWatcher
from riotwatcher import EUROPE_WEST
import operator
#Your API key here
w = RiotWatcher('')

if w.can_make_request():
	dict = {}
	num_players = input('How many players are we comparing?\n')
	for x in range(0, num_players):
		player_name = raw_input('Enter player name\n')
		player = w.get_summoner(name = player_name, region = EUROPE_WEST)
		#Hihgly complex algorithm designed to predict a players ability to play legaue
		dict[player['name']] = player['id']/player['profileIconId'] + player['revisionDate']/player['id']
	sortDic = sorted(dict.items(), key=operator.itemgetter(1))
	print "The best player is:\n"
	print dict.keys()[0]
else:
	print "You aren't allowed to"
Ejemplo n.º 31
0
async def league(summonername: str):
    watcher = RiotWatcher('League Of Legends API required')
    my_region = 'na1'

    try:
        me = watcher.summoner.by_name(my_region, summonername)

        my_ranked_stats = watcher.league.positions_by_summoner(
            my_region, me['id'])
        print(my_ranked_stats)
        solo_tier = None
        solo_rank = None
        solo_win = None
        solo_lose = None
        flex_tier = None
        flex_rank = None
        flex_win = None
        flex_lose = None

        if len(my_ranked_stats) == 0:
            await bot.say('You currently aren\'t placed in rank.')
        else:
            for x in range(0, len(my_ranked_stats)):
                if my_ranked_stats[x]['queueType'] == 'RANKED_FLEX_SR':
                    flex_tier = my_ranked_stats[x]['tier']
                    flex_rank = my_ranked_stats[x]['rank']
                    flex_win = my_ranked_stats[x]['wins']
                    flex_lose = my_ranked_stats[x]['losses']
                    winpercentflex = round(
                        (flex_win / (flex_win + flex_lose)) * 100, 1)
                elif my_ranked_stats[x]['queueType'] == 'RANKED_SOLO_5x5':
                    solo_tier = my_ranked_stats[x]['tier']
                    solo_rank = my_ranked_stats[x]['rank']
                    solo_win = my_ranked_stats[x]['wins']
                    solo_lose = my_ranked_stats[x]['losses']
                    winpercentsolo = round(
                        (solo_win / (solo_win + solo_lose)) * 100, 1)

            if flex_rank == None and solo_rank != None:
                await bot.say('Your Solo rank is: ' + str(solo_tier) + ' ' +
                              str(solo_rank) +
                              ' and your Flex rank is: Unranked.')
                await bot.say('Your Solo winrate is: ' + str(winpercentsolo) +
                              '%.')
            elif flex_rank != None and solo_rank == None:
                await bot.say('Your Solo rank is: Unranked' +
                              ' and your Flex rank is: ' + str(flex_tier) +
                              ' ' + str(flex_rank) + '.')
                await bot.say('Your Flex winrate is: ' + str(winpercentflex) +
                              '%.')
            elif flex_rank != None and solo_rank != None:
                await bot.say('Your Solo rank is: ' + str(solo_tier) + ' ' +
                              str(solo_rank) + ' and your Flex rank is: ' +
                              str(flex_tier) + ' ' + str(flex_rank) + '.')
                await bot.say('Your Solo winrate is: ' + str(winpercentsolo) +
                              '% and your Flex winrate is: ' +
                              str(winpercentflex) + '%.')

    except HTTPError as err:
        if err.response.status_code == 429:
            await bot.say('We should retry in {} seconds.'.format(
                e.headers['Retry-After']))
            await bot.say(
                'this retry-after is handled by default by the RiotWatcher library'
            )
            await bot.say(
                'future requests wait until the retry-after time passes')
        elif err.response.status_code == 404:
            await bot.say('Summoner with that ridiculous name not found.')
        else:
            raise
Ejemplo n.º 32
0
import json
from riotwatcher import RiotWatcher

jsonConfig = open("./config.json").read()
config = json.loads(jsonConfig)

api = RiotWatcher(config["api-key"], default_region=config["region"])
match_id = 2483005284


details = api.get_match(match_id, include_timeline=True)

# def split_match_details(details):

participantIdentities = details["participantIdentities"]
participants = details["participants"]

del details["participantIdentities"]
del details["participants"]


print(details)
print(participantIdentities)
print(participants)
import os.path
from urllib2 import HTTPError

error_400 = "Bad request"
error_401 = "Unauthorized"
error_403 = "Blacklisted key"
error_404 = "Game data not found"
error_429 = "Too many requests"
error_500 = "Internal server error"
error_503 = "Service unavailable"
error_504 = 'Gateway timeout'

startup = time.time()


w = RiotWatcher(apikey)

challenger = w.get_challenger()
masters = w.get_master()

tier_dict = {x:i for i, x in enumerate(['CHALLENGER', 'MASTER', 'DIAMOND', 'PLATINUM', 'GOLD', 'SILVER', 'BRONZE'])}

player_tiers = {x['playerOrTeamId']:0 for x in challenger['entries']}
#player_tiers.update({x['playerOrTeamId']:1 for x in masters['entries']})

players = Queue.PriorityQueue()

a = [players.put((player_tiers[x['playerOrTeamId']],x['playerOrTeamId'])) for x in challenger['entries']]# + masters['entries']]

epoch = datetime.datetime.utcfromtimestamp(0)
Ejemplo n.º 34
0
import datetime
import json
from modules.champions import Champions
from objects.player import Player
from requests import HTTPError
from riotwatcher import RiotWatcher

# Load the config file
with open('config.json') as json_data_file:
    data = json.load(json_data_file)

# Store config details
key = data['key']

watcher = RiotWatcher(key)
default_region = 'na1'


class Match:
    def __init__(self, match_id: int):
        self.match_id = match_id
        self.raw_match = watcher.match.by_id(default_region, self.match_id)

        # Information on the match
        self.season = self.raw_match['seasonId']
        self.queue = self.raw_match['queueId']
        self.game_duration = self.raw_match['gameDuration']
        self.game_creation = datetime.datetime.fromtimestamp(
            self.raw_match['gameCreation'] /
            1000.0).strftime('%m-%d-%Y %H:%M:%S')
Ejemplo n.º 35
0
def lol_connect():
    file_json = get_json_secret()
    return RiotWatcher(file_json['riot_key'])
Ejemplo n.º 36
0
class Lol:
    def __init__(self, key, default_region=EUROPE_WEST):
        self.lol_watcher = RiotWatcher(key, default_region=default_region)
        self.wait()
        self.champion_list = self.lol_watcher.static_get_champion_list(
        )['data']

    def wait(self):
        while not self.lol_watcher.can_make_request():
            time.sleep(1)

    def test_map(self, _id):
        if _id == 1:
            return "Summoner's Rift"
        elif _id == 2:
            return "Summoner's Rift"
        elif _id == 3:
            return "The Proving Grounds (tuto)"
        elif _id == 4:
            return "Twisted Treeline"
        elif _id == 8:
            return "The Crystal Scar"
        elif _id == 10:
            return "Twisted Treeline"
        elif _id == 11:
            return "Summoner's Rift"
        elif _id == 12:
            return "Howling Abyss"
        elif _id == 14:
            return "Butcher's Bridge"

    def test_queue(self, _id):
        if _id == 0:
            return "Custom"
        elif _id == 2:
            return "Normal 5v5 blind"
        elif _id == 4:
            return "Ranked Solo 5v5"
        elif _id == 6:
            return "Ranked Premade 5v5"
        elif _id == 7:
            return "Coop vs ia 5v5"
        elif _id == 8:
            return "Normal 3v3"
        elif _id == 9:
            return "Ranked flex"
        elif _id == 14:
            return "Normal Draft 5v5"
        elif _id == 16:
            return "Odin 5v5 Blind"
        elif _id == 17:
            return "Odin 5v5 Draft"
        elif _id == 25:
            return "Coop vs ia 5v5"
        elif _id == 31:
            return "Coop vs ia (intro)"
        elif _id == 32:
            return "Coop vs ia (beginner)"
        elif _id == 33:
            return "Coop vs ia (Intermediate)"
        elif _id == 41:
            return "Ranked Team 3v3"
        elif _id == 52:
            return "Ranked Team 5v5"
        elif _id == 61:
            return "GROUP_FINDER_5v5"
        elif _id == 65:
            return "Aram"
        elif _id == 70:
            return "One For All"
        elif _id == 72:
            return "FIRSTBLOOD_1v1"
        elif _id == 73:
            return "FIRSTBLOOD_2v2"
        elif _id == 75:
            return "Hexakill"
        elif _id == 76:
            return "URF"
        elif _id == 78:
            return "One For All"
        elif _id == 83:
            return "Bot URF"
        elif _id == 91:
            return "DOOM Bot (rank 1)"
        elif _id == 92:
            return "DOOM Bot (rank 2)"
        elif _id == 93:
            return "DOOM Bot (rank 5)"
        elif _id == 96:
            return "Ascension"
        elif _id == 98:
            return "Hexakill"
        elif _id == 100:
            return "BILGEWATER_ARAM_5v5"
        elif _id == 300:
            return "Poro King"
        elif _id == 310:
            return "COUNTER_PICK"
        elif _id == 313:
            return "BILGEWATER_5v5"
        elif _id == 315:
            return "Siege"
        elif _id == 317:
            return "Definitly Not Dominion"
        elif _id == 318:
            return "Aram URF"
        elif _id == 400:
            return "Normal Draft"
        elif _id == 410:
            return "Ranked"
        elif _id == 420:
            return "Ranked Solo/Duo"
        elif _id == 440:
            return "Ranked Flex"

    def test_champ(self, _id):
        temp = []
        for k in self.champion_list:
            temp.append(self.champion_list[k])
        temp = [nb for nb in temp if nb['id'] == _id]
        return temp[0]['name']

    def test_ranked_stats(self, stats, key):

        stats = stats['champions']
        stats = [nb for nb in stats if nb['id'] == 0]
        stats = stats[0]['stats']
        return stats[key]

    def test_team(self, _id):
        if _id == 100:
            return ":large_blue_circle:"
        else:
            return ":red_circle:"

    def check_lol(self, player, region):
        try:
            self.wait()
            return self.lol_watcher.get_summoner(name=player, region=region)
        except LoLException as e:
            if e == error_429:
                return ":x: Resseye dans {} secondes.".format(
                    e.headers['Retry-After'])
            elif e == error_404:
                return ":x: Summoner inconnu : {}".format(player)

    def message_lol(self, summoner):
        message = ":information_source: {} :video_game:\n\n".format(
            summoner['name'])
        message += " :information_source: Général Stats\n"
        message += " **ID**: {}\n".format(summoner['id'])
        message += " **Level**: {}\n".format(summoner['summonerLevel'])
        self.wait()
        temp = self.lol_watcher.get_league(summoner_ids=[summoner['id']])
        rank = []
        for i in temp[str(summoner['id'])]:
            rank.append(i['queue'] + " " + i['tier'])
        message += " **Rank**: {}\n".format(rank)
        #message += " **Mastery Levels**: {}\n".format()
        #message += " **Mastery Points**: {}\n".format()
        #message += " **Mastery Tokens**: {}\n".format()
        self.wait()
        player_stats = self.lol_watcher.get_stat_summary(
            summoner['id'])['playerStatSummaries']
        player_stats = [
            nb for nb in player_stats
            if nb['playerStatSummaryType'] == 'Unranked'
        ]
        player_stats = player_stats[0]
        message += " **Wins**: {}\n".format(player_stats['wins'])
        message += " **Kills**: {}\n".format(
            player_stats['aggregatedStats']['totalChampionKills'])
        message += " **Assistances**: {}\n".format(
            player_stats['aggregatedStats']['totalAssists'])
        message += " **Creeps tués**: {}\n".format(
            player_stats['aggregatedStats']['totalMinionKills'])
        message += " **Tourelles détruite**: {}\n\n".format(
            player_stats['aggregatedStats']['totalTurretsKilled'])
        #message += " **Dernière connexion**: {}\n\n".format()
        message += ":information_source: Ranked Stats :\n"
        try:
            self.wait()
            ranked_stats = self.lol_watcher.get_ranked_stats(summoner['id'])
            message += " **Win:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalSessionsWon'))
            message += " **Loose:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalSessionsLost'))
            message += " **Kill:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalChampionKills'))
            message += " **Assistance:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalAssists'))
            message += " **Damages infligés:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalDamageDealt'))
            message += " **Damages Reçus:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalDamageTaken'))
            message += " **Argent gagné:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalGoldEarned'))
            message += " **Creeps tués:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalMinionKills'))
            message += " **Tourelles détruites:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalTurretsKilled'))
            message += " **Double kills:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalDoubleKills'))
            message += " **Triple kills:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalTripleKills'))
            message += " **Quadra kills:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalQuadraKills'))
            message += " **Penta kills:** {}\n".format(
                self.test_ranked_stats(ranked_stats, 'totalPentaKills'))
            message += " **Total Killing Spree:** {}\n\n".format(
                self.test_ranked_stats(ranked_stats, 'killingSpree'))

        except:
            message += "**Aucune Stats de Ranked n'a été trouvée !**\n\n"

        message += ":information_source: Game en cours :\n"

        try:
            self.wait()
            temp = self.lol_watcher.get_current_game(summoner['id'])
            message += " **ID Partie:** {}\n".format(temp['gameId'])
            message += " **GameMode:** {}\n".format(temp['gameMode'])
            message += " **GameType:** {}\n".format(temp['gameType'])
            message += " **ID Queue:** {}\n".format(
                self.test_queue(temp['gameQueueConfigId']))
            message += " **ID Platform:** {}\n".format(temp['platformId'])
            message += " **ID Map:** {}\n".format(self.test_map(temp['mapId']))

            for i in temp['participants']:
                message += "  " + i['summonerName'] + " (" + self.test_champ(
                    i['championId']) + ") Team: " + self.test_team(
                        i['teamId']) + "\n"

        except:
            message += "**Aucune game en cours...**"

        return message
Ejemplo n.º 37
0
import json
# Library for ease of Riot Game API use.
# https://riot-watcher.readthedocs.io/en/latest/
from riotwatcher import RiotWatcher, ApiError
import RequestMatchlist.requestMatchlists as RequestMatchlists
# print(json.load(open("keys.json", encoding="UTF-8"))['apiKey'])
api = RiotWatcher(json.load(open("keys.json", encoding="UTF-8"))['apiKey'])
'''
PlayerInfo object defines all the information that makes up a summoner information
search window.

Error Handling:
if error == 'init' then either the league API is down, the API key is out of date, or the player name doesn't exist
if wins == 'none then there was no information in last week search
'''


class PlayerInfo():

    # Iterates through JSON return of API request to return JSON object of current season RANKED SOLO 5x5 information.
    def summonerSearch(self, id, region):
        stats = api.league.by_summoner(region, id)
        for stat in stats:
            if stat['queueType'] == "RANKED_SOLO_5x5":
                return stat

    # Iterates though a game and searches for the JSON array with the given player name to retrieve information.
    def gameWinLoss(self, game):
        for player in game['participantIdentities']:
            if player['player']['summonerName'].lower() == "mccloudi":
                return game['participants'][player['participantId'] -
Ejemplo n.º 38
0
from riotwatcher import RiotWatcher
import time
import json
watcher = RiotWatcher('RGAPI-b17a8469-7cf1-4f9d-bbd7-e244a4225b92')

my_region = 'jp1'
'''
me = watcher.summoner.by_name(my_region, 'test')
print(me)

# all objects are returned (by default) as a dict
# get my 1 mastery page i keep changing
my_mastery_pages = watcher.masteries.by_summoner(my_region, me['id'])
print(my_mastery_pages)

# lets see if i got diamond yet (i probably didnt)
my_ranked_stats = watcher.league.leagues_by_summoner(my_region, me['id'])
print(my_ranked_stats)

# Lets some champions
static_champ_list = watcher.static_data.champions(my_region)
print(static_champ_list)

# Error checking requires importing HTTPError from requests
'''
from requests import HTTPError

# For Riot's API, the 404 status code indicates that the requested data wasn't found and
# should be expected to occur in normal operation, as in the case of a an
# invalid summoner name, match ID, etc.
#
Ejemplo n.º 39
0
from riotwatcher import RiotWatcher
import csv
api_key = input(
    'Enter your Riot Games API Key. (https://developer.riotgames.com/)\n')
watcher = RiotWatcher(api_key)
my_region = 'na1'
version = watcher.data_dragon.versions_for_region(my_region)['v']
dragon = watcher.data_dragon.champions(version)
champ_data = dragon['data']
begin = 0
end = 100
champs_played = []
game_ids = []
champion_ids = {}
champion_wins = {}
champion_losses = {}
champion_kills = {}
champion_deaths = {}
champion_assists = {}
win_counter = 0
loss_counter = 0
kill_counter = 0
death_counter = 0
assist_counter = 0
double_counter = 0
triple_counter = 0
quadra_counter = 0
penta_counter = 0
damage_dealt = 0
#************** End Initial Setup ******************************************************
Ejemplo n.º 40
0
import sys
import time
from riotwatcher import RiotWatcher, NORTH_AMERICA, LoLException
from tools import save_obj

def secondsToStr(t):
    rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:]
    return "%d:%02d:%02d.%03d" % tuple(reduce(rediv,[[t*1000,],1000,60,60]))

#key = #PUT YOUR API KEY HERE
w = RiotWatcher(key)

def get_participants_for_further_pulls(match):
    """ This function takes a riot api 'match' and returns only selected
        participant information. You may add to the returned information
        if you want.
        The return value is a list of dictionaries, one for each
        participant in the match. """
    participants = [ {} for i in range(len(match['participants'])) ]
    for i,p in enumerate(match['participants']):
        participants[i]['highestAchievedSeasonTier'] = p['highestAchievedSeasonTier']
        participants[i]['summonerId'] = match['participantIdentities'][p['participantId']-1]['player']['summonerId']
    return participants

def get_match_information_to_save(match):
    """ This function takes a riot api 'match' and parses
        through it to save only the information you want. You can
        choose to save everything, or only specific things.
        The return value is a dictionary containing only the
        information you want to save for the match. """
    # Uncomment the following line to save all the data
Ejemplo n.º 41
0
    def league_rank(self, bot, source, message, **rest):
        try:
            from riotwatcher import RiotWatcher, LoLException
        except ImportError:
            log.error(
                "Missing required module for League Rank module: riotwatcher")
            return False

        riot_api_key = self.settings["riot_api_key"]
        summoner_name = self.settings["default_summoner"]
        def_region = self.settings["default_region"]

        if len(riot_api_key) == 0:
            log.error("Missing riot API key in settings.")
            return False

        region_list = [
            "br", "eune", "euw", "kr", "lan", "las", "na", "oce", "ru", "tr"
        ]

        if message:
            summoner_name = message.split()[0]
            try:
                region = message.split()[1].lower()
            except IndexError:
                region = def_region.lower()

            if region not in region_list:
                bot.whisper(
                    source,
                    f"Region is not valid. Please enter a valid region, region is optional and the default region is {def_region.upper()}",
                )
                return False
            else:
                pass
        else:
            region = def_region.lower()

        if len(summoner_name) == 0 or len(region) == 0:
            return False

        error_404 = "Game data not found"
        error_429 = "Too many requests"

        try:
            rw = RiotWatcher(riot_api_key, default_region=region)

            summoner = rw.get_summoner(name=summoner_name)
            summoner_id = str(summoner["id"])
            summoner_name = summoner["name"]

        except LoLException as e:
            if e == error_429:
                bot.say(
                    f"Too many requests. Try again in {e.headers['Retry-After']} seconds"
                )
                return False
            elif e == error_404:
                bot.say(
                    "The summoner not found. Use a valid summoner name (remove spaces) and region FailFish"
                )
                return False
            else:
                log.info(f"Something unknown went wrong: {e}")
                return False

        try:
            summoner_league = rw.get_league_entry(summoner_ids=(summoner_id, ))

            tier = summoner_league[summoner_id][0]["tier"]
            division = summoner_league[summoner_id][0]["entries"][0][
                "division"]
            league_points = summoner_league[summoner_id][0]["entries"][0][
                "leaguePoints"]

            bot.say(
                f"The Summoner {summoner_name} on region {region.upper()} is currently in {tier} {division} with {league_points} LP 4Head"
            )
        except LoLException as e:
            if e == error_429:
                bot.say(
                    f"Too many requests. Try again in {e.headers['Retry-After']} seconds"
                )
                return False
            elif e == error_404:
                bot.say(
                    f"The Summoner {summoner_name} on region {region.upper()} is currently UNRANKED.. FeelsBadMan"
                )
                return False
            else:
                bot.say(
                    "Trouble fetching summoner rank.. Kappa Try again later!")
                return False
Ejemplo n.º 42
0
def main():
	# gets key from file
	api_key = get_file("api.key")

	## init RiotWatcher
	rw = RiotWatcher(api_key.strip())

	# location of the matchIDs if you want AP_ITEM_DATASET change to
	# the appropriate directory
	dir_location = "../info/BILGEWATER_DATASET/BILGEWATER"
	files_dir = os.listdir(dir_location)

	for file in files_dir:
		# For every file that doesn't end in _info.json loop through it
		# expecting a list of MatchIDs and then preform API calls to get the match info
		# and then write to a file with ending "_info.json"
		if "_info.json" not in file:
			

			new_file_name = file.replace(".json","_info.json")

			print "Generating %s"%(new_file_name)
			print_file = open(dir_location + "/" + new_file_name ,"w+")

			# opens the file and reads contents
			file_info = get_file(dir_location + "/" + file)

			# turns the string representation of a list of MatchIDs
			# into an actual list of MatchIDs
			match_list = ast.literal_eval(file_info)

			# variables to display progress in processing MatchIDs
			count = 1
			match_len = len(match_list)

			# Begins writing the output file with beginning of the list
			print_file.write("[")

			# For every MatchId in the MatchList
			for matchID in match_list:

				# Sets default value for match_info
				match_info = {}

				# used to gauge 429 responses later on
				gotitbool = False

				# Loops until gotitbool is found
				while not gotitbool:
					try:
						# checks if queue is clear if not waits until it is
						wait(rw)

						# attempts to get the match information given MatchID
						match_info = rw.get_match(matchID, region=file.replace(".json","").lower(), include_timeline=True)

						# if it got this far it successful and gotitbool is set to True
						gotitbool = True

					except LoLException as e:
						# This trips if an LoLException is raised from RiotWatcher

						print e.error

						# If this is not a 429 error then it can't wait a time span
						# to find a solution to it

						if e.error not in [error_429, error_503, error_500]:
							# a 400, 401, 404 error
							print "error from server: %s"%(e.error)
							return

						# Prints out all the applicable headers used for debugging
						for header in e.response.headers:
							if header not in ['access-control-allow-headers','content-encoding','transfer-encoding','x-newrelic-app-data','server','connection','cache-control','date','access-control-allow-origin','access-control-allow-methods','content-type','content-length']:
								print "headers: %s"%(header)

						if 'Retry-After' in e.response.headers:
							# If the client receives a Rate Limit Exceeded response the client 
							# should process this response and halt future API calls for the duration, 
							# in seconds, indicated by the Retry-After header
							time.sleep(int(e.response.headers['Retry-After']))
						else:
							# Else if no Retry-After header wait a reasonable time (1sec)
							# and then try agian

							if e.error in [error_500,error_503]:
								time.sleep(30)
							else:
								time.sleep(1)
							
					except Exception as e:
						# An error occured that was not anticipated
						print str(e)
						return 

				# Dumps the json information into the output file
				print_file.write(str(json.dumps(match_info)))

				# If not the end of the file adds a ",\n" which is 
				# needed to properly process the file later
				if count != match_len:
					print_file.write(",\n")

				# Prints progress in processing the file
				print "%s: %s/%s"%(str(file), count, match_len)

				# Moves counter up by 1
				count += 1

			# closing off the list of matches
			print_file.write("]")
			print_file.close()
Ejemplo n.º 43
0
__author__ = 'Vixus'
from riotwatcher import RiotWatcher

w = RiotWatcher('eda1ed56-6ae8-41bf-97b7-acaa970537dc')

# check if we have API calls remaining
print(w.can_make_request())

me = w.get_summoner(name='vixus360')
print(me)

# championList = w.static_get_champion_list()
# print championList
# print w.get_champion(championList['data']['Lux']['id'])

def print_tabs(count):
    for i in range(count):
        print '\t',

def print_data(obj,tabCount=-1):
    if type(obj) == dict:
        for key, value in obj.items():
            print_tabs(tabCount)

            if hasattr(value, '__iter__'):
                print key,":"
                print_data(value,tabCount+1)
            else:
                print '%s : %s' % (key, value)
    elif type(obj) == list:
        for value in obj:
Ejemplo n.º 44
0
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      James
#
# Created:     28/01/2015
# Copyright:   (c) James 2015
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

from riotwatcher import RiotWatcher
import pygametools as pt

w = RiotWatcher('e4a0c61e-4a2b-41b2-9b98-5f95f745b1b7')

# check if we have API calls remaining
#print(w.can_make_request())

me = w.get_summoner(name='salvsis')

print(me)

a = pt.Linesoftext([str(me['name'])],(300,50),True)
a.test((600,300))

#print(w.get_stat_summary(me['id']))
Ejemplo n.º 45
0
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)

sys.setrecursionlimit(100000)

patchMillSecs = 1548316800000  #game version 9.2
path = 'F:/lolMatchData/data/matches/'

count = 0

matchIDsDownloaded = []
matchIDsDownloading = []
summonerIDsDownloaded = []
summonerIDsDownloading = []

watcher = RiotWatcher('RGAPI-753fa9d9-7ec6-4b63-bd92-9428824c4484')


#将match中的summonerId判断后,放入指定缓存容器
def appendSummonerId(match):
    SummonerIdInThisMatch = []
    playerNum = len(match['participantIdentities'])
    for i in range(0, playerNum):
        SummonerIdInThisMatch.append(
            match['participantIdentities'][i]['player']['accountId'])
    for SummonerId in SummonerIdInThisMatch:
        if SummonerId not in summonerIDsDownloaded and SummonerId not in summonerIDsDownloading:
            summonerIDsDownloading.append(SummonerId)
    return

import random
from riotwatcher import RiotWatcher, EUROPE_WEST, LoLException
from tools import save_obj, load_obj
unpulled_summoners = [52333251,72343187,22403890] #Insert some starting summoner ids here
pulled_summoners = list()
#matchId : file number
pulled_matches = list()
pulled_matches_count = 0
#saved_files = 0
#match_data_to_save = []
data_file = open("data_composition.tab","a")

BLUE = 100
RED = 200

w = RiotWatcher("YOUR-API-KEY", default_region=EUROPE_WEST)

def wait_for_request_availability(w):
    while not w.can_make_request():
        time.sleep(0.2)

champions = w.get_all_champions()
if not os.path.isfile('pulled_matches.txt'):
    data_file.write("matchId\tcreateDate\t")
    for champion in champions['champions']:
        data_file.write("b chmp " + str(champion['id']) + "\t")
    for champion in champions['champions']:
        data_file.write("r chmp " + str(champion['id']) + "\t")
    data_file.write("winner\n")

    data_file.write("c\t"*2)
Ejemplo n.º 47
0
 def __init__(self, region, api_key):
     self._region = region
     self._watcher = RiotWatcher(api_key)
Ejemplo n.º 48
0
import os
import os.path
import time
import zipfile
import random
from riotwatcher import RiotWatcher, EUROPE_WEST, LoLException
from tools import save_obj, load_obj
unpulled_summoners = [35076397, 41527671, 80239244, 78377150] #Insert some starting summoner ids here
pulled_summoners = list()
#matchId : file number
pulled_matches = dict()
pulled_matches_count = 0
saved_files = 0
match_data_to_save = []

w = RiotWatcher("YOUR-API-KEY", default_region=EUROPE_WEST)

def wait_for_request_availability(w):
    while not w.can_make_request():
        time.sleep(0.2)

#alt_list is for further prevention of requestion same match_ids multiple times
def get_match_details_from_history(match_history, match_created, num_old_matches=10, alt_list = []):
    if 'matches' not in match_history:
        #history is empty
        return []
    newer_match_ids = [match['matchId'] for match in match_history['matches'] if match['timestamp'] > match_created]
    older_match_ids = [match['matchId'] for match in match_history['matches'] if match['timestamp'] < match_created]
    #this is to avoid queries that take way too long
    if len(newer_match_ids)>40:
        #-1 means skip this summoner - too many matches to get - time consuming
Ejemplo n.º 49
0
from pymongo import MongoClient
import pymongo
import riotwatcher as rw
from riotwatcher import RiotWatcher
from riotwatcher import LoLException
import time
from optparse import OptionParser
import json

#frodo621 key
key = "45fbe47f-84f1-43b6-9394-9f433a23d522"

watcher = RiotWatcher(key)

print watcher.static_get_versions(region = 'na')
Ejemplo n.º 50
0
import urllib2, json, sys, os
from riotwatcher import RiotWatcher
from datetime import datetime
today = datetime.now()
if len(sys.argv) != 3:
    print "Usage: python summonerids.py [max_summoners] [API_KEY]"
    sys.exit(0)
max_summoners = int(sys.argv[1])
# input
q = []
API_KEY = sys.argv[2]
w = RiotWatcher(API_KEY)
startid = '20120281'
q.append(int(startid))
# opening a json gamehistory file
if w.can_make_request() == True:
    readfile = urllib2.urlopen('https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/' + startid + '/recent?api_key=' + API_KEY)
    data = json.load(readfile)
    for game in data["games"]:
        if game["subType"] == "RANKED_SOLO_5x5":
            for player in game["fellowPlayers"]:
                if player["summonerId"] not in q:
                    q.append(player["summonerId"])
# print q
i = 1
while len(q) < max_summoners:
    if w.can_make_request() == True:
        if i >= len(q):
            print "only scraped " + str(i) + " summoners"
            max_summoners = len(q)
Ejemplo n.º 51
0
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .models import Tutorial
from .forms import SummonerForm
from django.views.generic import TemplateView
from riotwatcher import RiotWatcher, ApiError

watcher = RiotWatcher('RGAPI-5c43a0af-efb8-48c0-8225-d8c4ff2eef73')
my_region = 'na1'
name = 'ellls'

sum_spell_json = {
    4:
    "http://ddragon.leagueoflegends.com/cdn/10.2.1/img/spell/SummonerFlash.png",
    21:
    "http://ddragon.leagueoflegends.com/cdn/10.2.1/img/spell/SummonerBarrier.png",
    7:
    "http://ddragon.leagueoflegends.com/cdn/10.2.1/img/spell/SummonerHeal.png",
    14:
    "http://ddragon.leagueoflegends.com/cdn/10.2.1/img/spell/SummonerIgnite.png"
}


def summonerSpellKey(dict, key):
    if key in dict.keys():
        return dict[key]
    else:
        return key

Ejemplo n.º 52
0
from riotwatcher import RiotWatcher
import time

leagueApi = RiotWatcher('04328930-7ab0-4e23-8c83-af1bbc4147ea')

#Get Summoner ID and Stats
summoner = raw_input("Enter your summoner name: ")
opponent = raw_input("Enter your opponent's summoner name:")

if leagueApi.can_make_request():
    summonerId = leagueApi.get_summoner(name=summoner)
    opponentId = leagueApi.get_summoner(name=opponent)
    print
    print "Welcome Summoner!"
    bet = raw_input("Enter the amount of $ you would like to bet: ")
    print
    print "You've bet", bet, "dollars"

    lastPlayedGame = leagueApi.get_recent_games(summonerId['id'])['games'][0]['createDate']
    currentDate = lastPlayedGame

    print "Waiting for you to play a game!"
    while lastPlayedGame == currentDate:
        #Checks every 10 seconds for new game
        time.sleep(10)
        currentDate = leagueApi.get_recent_games(summonerId['id'])['games'][0]['createDate']

    #Need to also make a check to see if the other player was playing
    summonerGameId = leagueApi.get_recent_games(summonerId['id'])['games'][0]['gameId']
    opponentGameId = leagueApi.get_recent_games(opponentId['id'])['games'][0]['gameId']
    
Ejemplo n.º 53
0
# these tests are pretty bad, mostly to make sure no exceptions are thrown

import time
from riotwatcher import RiotWatcher, NORTH_AMERICA

key = '9213b085-ed48-4bf0-af91-d8fa519e3b35'
# if summoner doesnt have ranked teams, teams tests will fail
# if summoner doesnt have ranked stats, stats tests will fail
# these are not graceful failures, so try to use a summoner that has them
summoner_name = 'rias'

w = RiotWatcher(key)


def wait():
    while not w.can_make_request():
        time.sleep(1)


def champion_tests():
    wait()
    temp = w.get_all_champions()
    wait()
    w.get_champion(temp['champions'][0]['id'])


def game_tests(summoner):
    wait()
    w.get_recent_games(summoner['id'])

Ejemplo n.º 54
0
 def __init__(self):
     self.riot = RiotWatcher(LoL.API_KEY)
     self.champions = self._getChampions()
Ejemplo n.º 55
0
titleFont = wx.Font(55, wx.ROMAN, wx.ITALIC, wx.BOLD)
miniFont = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)
miniBoldFont = wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD)

textColor = constants['colors']['text_color']
titleColor = constants['colors']['title_color']
lighterTextColor = constants['colors']['lighter_text_color']
lighterBlue = constants['colors']['lighter_blue']
lightBlue = constants['colors']['light_blue']
lighterRed = constants['colors']['lighter_red']
lightRed = constants['colors']['light_red']

#Three API keys = thrice the calls before rate limit
order = []
if len(config['api_key_1']) > 0:
    watcher1 = RiotWatcher(config['api_key_1'], default_region=NORTH_AMERICA)
    order.append(watcher1)
if len(config['api_key_2']) > 0:
    watcher2 = RiotWatcher(config['api_key_2'], default_region=NORTH_AMERICA)
    order.append(watcher2)
if len(config['api_key_3']) > 0:
    watcher3 = RiotWatcher(config['api_key_3'], default_region=NORTH_AMERICA)
    order.append(watcher3)


#Finds out which API key is usable
def getWatcher():
    temp = order.pop(0)
    order.append(temp)
    try:
        temp.get_summoner(name)
Ejemplo n.º 56
0
import discord
from riotwatcher import RiotWatcher, ApiError
import time
import random
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
import keys

watcher = RiotWatcher(keys.riotAPI)
champData = watcher.data_dragon.champions('9.6.1')

#Creating id dictionaries to reference
champion_key_dic = {}

for champ in champData['data']:
    champion_key_dic[champData['data'][champ]
                     ['key']] = champData['data'][champ]['name']


def simple_get(url):

    try:
        with closing(get(url, stream=True)) as resp:
            if is_good_response(resp):
                return resp.content
            else:
                return None

    except:
Ejemplo n.º 57
0
async def on_message(msg):
    if msg.author.id != client.user.id:  # ignore our own commands
        if msg.content.startswith(conf['invoker']):
            command = msg.content[len(conf['invoker']):]
            print(command)
            if command == 'help':
                g_4 = '\n' + conf['invoker']
                g_3 = '{0}{1}'.format(conf['invoker'],
                                      g_4.join(os.listdir('audio/')))
                g_3 = g_3.lower().replace(conf['fileformat'], '')
                g_2 = 'Comandos para o ' + conf['bot'] + ':\n' + \
                    g_3 + '\n'
                if not msg.channel.is_private:
                    await client.send_message(msg.channel, g_2)
            elif command.startswith('lol'):
                player_name = command.lstrip('lol ')
                watcher = RiotWatcher(lol_token)
                region = 'br1'
                player = watcher.summoner.by_name(region, player_name)
                ranked = watcher.league.positions_by_summoner(
                    region, player['id'])
                for lists in ranked:
                    for items in ranked:
                        name = items['playerOrTeamName']
                        tier = items['tier'].lower()
                        rank = items['rank']
                        wins = str(items['wins'])
                        loss = str(items['losses'])
                        if items['queueType'] == 'RANKED_FLEX_TT':
                            fila = 'Twisted Treeline'
                        elif items['queueType'] == 'RANKED_SOLO_5x5':
                            fila = 'Summoners Rift Solo/Duo'
                        elif items['queueType'] == 'RANKED_FLEX_SR':
                            fila = 'Summoners Rift Flex'
                if player['summonerLevel'] < 30:
                    await client.send_message(
                        msg.channel, player['name'] + ' is currently level ' +
                        str(player['summonerLevel']))
                elif ranked == []:
                    await client.send_message(
                        msg.channel, player['name'] + ' is not ranked.')
                else:
                    em = discord.Embed(title=fila)
                    em.add_field(name="Rank",
                                 value=tier.capitalize() + ' ' + rank,
                                 inline=True)
                    em.add_field(name="Wins", value=wins, inline=True)
                    em.add_field(name="Loss", value=loss, inline=True)
                    em.set_author(name=name,
                                  icon_url=client.user.default_avatar_url)
                    await client.send_message(msg.channel, embed=em)
                print(player)
                print(ranked)

            elif command.startswith('ow'):
                battletag = command.lstrip('ow ')
                owclient = AsyncOWAPI()
                owdata = {}
                async with aiohttp.ClientSession(
                        connector=aiohttp.TCPConnector(
                            verify_ssl=False)) as session:
                    owdata[PC] = await owclient.get_stats(
                        battletag.capitalize(), session=session, platform=PC)
                    d = owdata[PC]['us']['competitive']['overall_stats']
                    em = discord.Embed(title='Overwatch Stats: ')
                    for k, v in d.items():
                        # if k == 'comprank':
                        em.add_field(name=k, value=v, inline=True)
                        print(k, v)
                    #await client.send_message(msg.channel, str(k) + str(v))

                    # em.set_author(name=battletag, icon_url=client.user.default_avatar_url)
                    await client.send_message(msg.channel, embed=em)

            else:
                if msg.author.voice_channel:
                    try:
                        message = msg.author.voice_channel
                        voice = await client.join_voice_channel(message)
                        player = voice.create_ffmpeg_player(
                            'audio/' + command + conf['fileformat'],
                            use_avconv=True)
                        player.volume = 0.3
                        player.start()
                        print("sound played!")
                    except:
                        pass
                else:
                    await client.send_message(
                        msg.channel, 'voce nao esta em um canal de voz!')
                while True:
                    try:
                        if player.is_done():
                            await voice.disconnect()
                            break
                    except:
                        break
Ejemplo n.º 58
0
	def __init__(self, keys):
		RiotWatcher.__init__(self, keys[0])
		self.keys = keys[1:]
Ejemplo n.º 59
0
class LeagueBot(DiscordBot):
    def __init__(self, client):
        super(LeagueBot, self).__init__(client, 'leaguebot')
        self.storage_manager = CouchbaseManager(
            os.environ.get('MATCH_HISTORY_BUCKET'))
        self.riot = RiotWatcher(os.environ.get('RIOT_API_KEY'),
                                default_region=EUROPE_WEST)
        self.players = self.load_player_list()
        self.champions = self.load_champions()
        self.memes = self.load_memes()
        self.cleverbot = cleverbot.Cleverbot()

    def load_player_list(self):
        try:
            players = self.storage_manager.get('players')
        except FileNotFoundError:
            players = {}

        return players

    def load_champions(self):
        try:
            champs = self.storage_manager.get('champions')
        except FileNotFoundError:
            champs = import_champs()
            self.storage_manager.set('champions', champs)

        return champs

    def load_memes(self):
        try:
            memes = self.storage_manager.get('memes')
        except FileNotFoundError:
            memes = []
        return memes

    @DiscordBot.add_command('add')
    def add_player(self, *args):
        """Adds a player to be tracked"""
        player = ''.join(args)
        if player.lower() not in self.players:
            try:
                summoner = self.riot.get_summoner(name=player)
            except LoLException as e:
                if e == error_404:
                    self.send_message(
                        'Error - Player {} does not exist'.format(player))
                else:
                    self.send_message(
                        'An unknown error occurred, let Matt know!')
                    league_bot_logger.warning(e)
                return
            self.players[summoner['name'].lower()] = summoner['id']
            self.send_message('Added {} to list of players'.format(player))
            self.storage_manager.set('players', self.players)
        else:
            self.send_message(
                '{} already in the list of players'.format(player))

    @DiscordBot.add_command('list')
    def print_players(self, *_):
        """Prints out the list of players"""
        if self.players:
            player_list = '\n'
            for player, player_id in self.players.iteritems():
                try:
                    number_of_games = len(
                        self.storage_manager.get(
                            'matches-{}'.format(player_id))['games'])
                except FileNotFoundError:
                    number_of_games = 0

                player_list += '{} - {} games\n'.format(
                    player, number_of_games)

            self.send_message(player_list)
        else:
            self.send_message('Player list empty')

    @DiscordBot.add_command('current-games')
    def get_current_games(self, *_):
        for player in self.players:
            self.get_current_game(player)

    @DiscordBot.add_command('current-game')
    def get_current_game(self, *args):
        """Gets current-game information for the provided player"""
        player = ''.join(args).lower()
        if player not in self.players.keys():
            try:
                summoner = self.riot.get_summoner(name=player)
            except LoLException as e:
                if e == error_404:
                    self.send_message(
                        'Error - Player {} does not exist'.format(player))
                else:
                    self.send_message(
                        'An unknown error occurred, let Matt know!')
                    league_bot_logger.warning(e)
                return
            else:
                player_id = summoner['id']
        else:
            player_id = self.players[player]

        try:
            curr_game = self.riot.get_current_game(player_id)
        except LoLException as e:
            if e == error_404:
                self.send_message('{} is not in a game'.format(player))
            else:
                league_bot_logger.warning(e)
        else:
            game_length = (int(curr_game['gameLength']) / 60) + 3
            for participant in curr_game['participants']:
                if participant['summonerName'].lower() == player.lower():
                    champion = self.champions[str(participant['championId'])]
                    lolnexus_url = (
                        'http://www.lolnexus.com/EUW/search?name={}&region=EUW'
                        .format(player))

                    self.send_message(
                        '{} has been in a game for {} minutes - Playing {}\n'
                        'Link to game: {}'.format(player, game_length,
                                                  champion, lolnexus_url))
                    break

    @DiscordBot.add_command('stats')
    def summarise_stats(self, *args):
        """Prints out average stats for the given player"""
        player = ' '.join(args).lower()
        if player not in self.players:
            self.send_message(
                '{} not in list of players, no stats found'.format(player))
        matches = self.storage_manager.get('matches-{}'.format(
            self.players[player]))
        stat_averages = defaultdict(list)
        match_counter = 0
        for match in matches['games']:
            if match['subType'] in WANTED_SUB_TYPES:
                match_counter += 1
                for stat, value in match['stats'].iteritems():
                    stat_averages[stat].append(value)

        output = ''
        for stat, value in OrderedDict(sorted(
                stat_averages.items())).iteritems():
            try:
                output += '{} - {:.3f}\n'.format(
                    stat,
                    float(sum(value)) / match_counter)
            except TypeError:
                pass
        output += 'Games - {}'.format(match_counter)
        self.send_message(output)

    @DiscordBot.add_command('is Neku eloboosted?')
    def dank_meme(self, *args):
        """'Nuff said"""
        self.send_message(
            "It's not boosting, it's just elo rushing, he is entitled to be there"
        )

    @DiscordBot.add_command('help')
    def list_commands(self, *args):
        """Lists all commands and their purpose"""
        command_str = 'List of commands:'
        for command in sorted(self.__class__.commands):
            command_str += '\n{} - {}'.format(command,
                                              self.commands[command].__doc__)
        self.send_message(command_str)

    @DiscordBot.add_command('meme add')
    def add_meme(self, *args):
        """Adds a new meme"""
        meme = ' '.join(args)
        if meme not in self.memes:
            self.memes.append(meme)
            self.storage_manager.set('memes', self.memes)
            self.send_message("Added '{}' to list of memes".format(meme))
        else:
            self.send_message('No reposts pls')

    @DiscordBot.add_command('meme me')
    def random_meme(self, *args):
        """Prints a random meme"""
        self.send_message(random.choice(self.memes))

    @DiscordBot.add_command('chat')
    def ask_cleverbot(self, *args):
        """Have a conversation with leaguebot"""
        response = self.cleverbot.ask(' '.join(args))
        self.send_message(response)