コード例 #1
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)
コード例 #2
0
ファイル: league.py プロジェクト: sulbel/qtbot
    def __init__(self, bot):
        # Bot attrs
        self.bot = bot
        self.session = bot.aio_session
        self.redis_client = bot.redis_client
        self.db = PGDB(bot.pg_con)
        # self.rune_client = bot.rune_client

        # Champion data
        with open('data/champ_data.json') as f:
            self.champ_data = json.load(f)

        # Request information
        self.elo_api_uri = 'https://na.whatismymmr.com/api/v1/summoner?name={}'
        self.elo_headers = {'user-agent': 'qtbot/1.0'}
        self.browser_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                                              'like Gecko) Chrome/64.0.3257.0 Safari/537.36'}
        self.patch_url = 'https://na.leagueoflegends.com/en/news/game-updates/patch'

        # API deets
        with open('data/apikeys.json') as fp:
            api_keys = json.load(fp)

        self.champion_gg_api_key = api_keys['champion.gg']
        self.riot_api_key = api_keys['riot']
        self.riot_watcher = RiotWatcher(self.riot_api_key)
コード例 #3
0
async def on_ready():
    global watcher
    try:
        watcher = RiotWatcher(RIOT_API_KEY)
        return "APIキーを更新したよぉ~"
    except BaseException as _:
        return "APIキーの更新に失敗したよぉ~"
コード例 #4
0
    def __init__(self):

        self.record = None
        api_key, self.session, options = self.get_and_initialize_options()

        self.region = Region.__getattr__(options['region']).value['platform']
        if options['queue'] == 'RANKED_FLEX':
            self.queue = LeagueQueue.__getattr__(options['queue'] +
                                                 '_SR').value
        else:
            self.queue = LeagueQueue.__getattr__(options['queue']).value
        self.matchType = MatchQueue.__getattr__(options['queue'] +
                                                '_5V5').value
        self.tier = options['tier']
        if options['preseason'] == 'True':
            self.season = Season.__getattr__('PRESEASON_' +
                                             options['season']).value['id']
        else:
            self.season = Season.__getattr__('SEASON_' +
                                             options['season']).value['id']
        if options['by_patch'] == 'True':
            self.patch = "PATCH_" + options['patch']
        else:
            self.patch = None

        self.watcher = RiotWatcher(api_key)
        self.EZREAL_FACADE_EXTRACTION = EzrealFacadeExtraction()
        self.EZREAL_FACADE_MANAGEMENT = EzrealFacadeManagement(self.session)
コード例 #5
0
    def __init__(self, connection):

        auth = tweepy.OAuthHandler(
            '2XAQTR3zNwrBtD2i6AGxZDeP6',
            '7e9xsaOSvyyI0nY5ZDN1cYx0phndLtclhdxukaC1rSjztsH9Q2')
        auth.set_access_token(
            '3333417351-X483ie45LpKqy6vw3LEUa84LN1bG6aMuZXRUlF7',
            'FQnPzJbLjvODZXiph48eb5bK2UJRHhjdhBw5thKDFvZer')
        self.api = tweepy.API(auth)
        self.gen = gender.Detector()
        my_region = 'na1'
        watcher = RiotWatcher('RGAPI-11ab2328-9ef7-47f8-a4c5-e4afcf0baab0')
        static_champ_list = watcher.static_data.champions(my_region)
        static_item_list = watcher.static_data.items(my_region)
        champion_list = static_champ_list['data']
        item_list = static_item_list['data']
        item_names = []
        champion_names = []
        champion_key_list = list(champion_list.keys())
        item_key_list = list(item_list.keys())
        for i in item_key_list:
            item_names.append(item_list[i]['name'].encode('ascii', 'ignore'))

        for i in champion_key_list:
            champion_names.append(champion_list[i]['name'].encode(
                'ascii', 'ignore'))
        self.item_name = item_names
        self.champions_name = champion_names

        print(item_names)
        print(champion_names)
        #coordinates
        self.connection = connection
コード例 #6
0
    def setUp(self):
        if not os.path.isfile("api_key"):
            raise FileNotFoundError(
                'API Key not found (should be in file "api_key" in same directory tests run)'
            )

        with open("api_key", "r") as key_file:
            key = key_file.read()
            self._watcher = RiotWatcher(key.strip())

        self._region = "na1"

        self._test_accounts = ["pseudonym117", "fakename117"]

        self._versions = {
            "item": "8.16.1",
            "rune": "7.23.1",
            "mastery": "7.23.1",
            "summoner": "8.16.1",
            "champion": "8.16.1",
            "profileicon": "8.16.1",
            "map": "8.16.1",
            "language": "8.16.1",
            "sticker": "8.16.1",
        }
コード例 #7
0
 def run(self):
     watcher = RiotWatcher(settings.API_KEY)
     region = self.region
     i= 2585564750
     while not self.event.is_set():
         #logging.debug('Waiting for a lock')
         self.lock.acquire()
         #last object for platform id
         #obj = Match.objects.latest('gameId')
         #i = obj.gameId + 1
     
         try:
             response = watcher.match.by_id(region, i)
             #print(response)
             log = self.getName() + ' ' + self.objType + ' id: ' + str(i)
             print(log)
             data = {} 
             data['model'] = "main." + self.objType
             #data['pk'] = 
             data['fields'] = response
             data = [data]
             data = json.dumps(data, ensure_ascii=False)
             for deserialized_object in serializers.deserialize("json", data):
                 deserialized_object.save()
         except HTTPError as err:
             if err.response.status_code == 403:
                 print('API Key is invalid or has expired')
                 break
             else:
                 print(self.getName() + ' ' +str(err))
         finally:
             #logging.debug('Released a lock')
             self.lock.release()           
         i += 1
コード例 #8
0
def run_command(text, author):
    #Eventually will combine all the "startwith" stuff and move it to another file.
    if text.startswith('!hello'):
        return 'Hello {0.author.mention}'.format(text)
    elif text.startswith('!smite'):
        return "竜が我が敵を食らう!\nhttps://gph.is/2pMNtmz"
    elif text.startswith('!reflect'):
        return "竜神の剣をくらえ!\nhttps://gph.is/2J1G8Ze"
    elif text.startswith('!pewpew'):
        return "https://gph.is/2IZHG62"
    elif text.startswith('!roles'):
        ret_msg = ""
        for role in author.roles:
            ret_msg = ret_msg + " " + str(role)
        ret_msg = ret_msg.replace("@everyone", "")
        return ret_msg
    #Responds to !roll and captures the xdx after to roll a certain amount of dice limited by 20 dice and 100 max limit
    elif text.startswith('!roll'):
        #Remove command string
        user_msg = text.strip("!roll ")
        #Format <int>d<int>
        pattern = '(\d+)\s*d\s*(\d+)(\s*[+-]\s*\d+)?'
        try:
            #Pull the amount of dice and then the max roll
            dice_match = re.match(pattern, user_msg)
            times_to_roll = int(dice_match[1])
            die_limit = int(dice_match[2])
            modifier = dice_match[3]
            if modifier is None:
                modifier = "+0"
            if die_limit <= 100 and times_to_roll <= 20:
                dice_rolls = []
                for roll in range(times_to_roll):
                    dice_rolls.append(random.randint(1, die_limit))
                total_roll = str(eval(str(sum(dice_rolls)) + modifier))
                modifier = eval(modifier)
                if times_to_roll == 1:
                    return "Range [" + str(times_to_roll + modifier) + ":" + str(times_to_roll * die_limit + modifier) + "]\nRoll " + str(dice_rolls)
                else:
                    return "Range [" + str(times_to_roll + modifier) + ":" + str(times_to_roll * die_limit + modifier) + "]\nRolls " + str(dice_rolls) + "\nTotal " + total_roll
        except TypeError:
            if user_msg == "":
                return "Range [1:20]\nRoll " + str(random.randint(1, 20))
            return "Incorrect Format.  !roll <int>d<int> [+ int]"
    elif text.startswith('!riot'):
        #Input = !riot SUMMONER_NAME REGION
        with open("various_text/riot.txt") as f:
            content = f.readlines()
        #Pull secret from a hidden txt file.  Not best practice, but better than plain text.
        for line in content:
            KEY = re.search('Riot:(.*)', line).group(1)
        watcher = RiotWatcher(KEY)
        region = 'na1'
        user_msg = text.strip("!riot ")
        summoner = watcher.summoner.by_name(region, user_msg)
        ranked_stats = watcher.league.positions_by_summoner(region, summoner['id'])
        return str(summoner) + "\n\n" + str(ranked_stats)
    else:
        return "No correct command was given"
コード例 #9
0
def getMatch(matchList, server):
    key = readApiKey()
    w = RiotWatcher(key, server)
    try:
        match = w.get_match(matchList['matchId'], server)
    except Exception:
        pass

    return match
コード例 #10
0
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
コード例 #11
0
def main():

    #key = input("Enter Riot API key:")
    key = "RGAPI-69e9cbd7-035f-465f-8cc1-d1826272e5dc"
    w = RiotWatcher(key)
    r = "na1"
    g = 3040961431
    #plotByGameId(w,  r, g, 0)
    plotBySummonerName(w, r, "dragonragers", 0)
コード例 #12
0
 def __init__(self, player_name, summoner_name, region, main_role, team, substitute, account_type):
     self.player_name = player_name
     self.summoner_name = summoner_name
     self.region = region
     self.main_role = main_role
     self.team = team
     self.substitute = substitute
     self.account_type = account_type
     self.rw = RiotWatcher(API_KEY)
コード例 #13
0
 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()
コード例 #14
0
def makeSearch(region, summonerName):

    watcher = RiotWatcher(apiKey())
    args = {}
    try:
        summoner = watcher.summoner.by_name(region, summonerName)

        id = summoner['id']
        account_id = summoner['accountId']
        stats = watcher.league.by_summoner(region, id)

        match_list_id = []
        matches = watcher.match.matchlist_by_account('na1', account_id)

        match_list = matches['matches']

        matches = []

        for match in match_list:
            match_list_id.append(match['gameId'])

        match = watcher.match.by_id('na1', match_list_id[0])

        print('*' * 50)
        print(match)
        print('*' * 50)

        args = {
            'summoner_name': summoner['name'],
            'profile_icon': summoner['profileIconId'],
            'solo_queue_tier': None,
            'solo_queue_rank': None,
            'solo_queue_lp': None,
            'flex_queue_tier': None,
            'flex_queue_rank': None,
            'flex_queue_lp': None
        }

        for queue in stats:
            if queue['queueType'] == 'RANKED_FLEX_SR':
                args['flex_queue_tier'] = queue['tier']
                args['flex_queue_rank'] = queue['rank']
                args['flex_queue_lp'] = queue['leaguePoints']

            if queue['queueType'] == 'RANKED_SOLO_5x5':
                args['solo_queue_tier'] = queue['tier']
                args['solo_queue_rank'] = queue['rank']
                args['solo_queue_lp'] = queue['leaguePoints']

        return args

    except ApiError as err:
        if err.response.status_code == 404:
            args['summoner_name'] = 'No summoner with this name found'
            return args
コード例 #15
0
def getSummonerRank(summonerName, region):
    server = regionDict[str(region).upper()]
    watcher = RiotWatcher(tokens.lolapikey)
    try:
        summoner = watcher.summoner.by_name(server, summonerName)
    except:
        return text_constants.NOT_FOUND
    my_ranked_stats = watcher.league.by_summoner(server, summoner['id'])
    for rank in my_ranked_stats:
        if rank['queueType'] == "RANKED_SOLO_5x5":
            return rank['tier']
コード例 #16
0
ファイル: riot_utility.py プロジェクト: Susannova/Discord_Bot
def create_summoners(summoner_names: list, config: GeneralConfig):
    riot_token = str(config.riot_token)
    watcher = RiotWatcher(riot_token)
    for player in summoner_names:
        with ThreadPoolExecutor() as executor:
            future = executor.submit(fetch_summoner, player, watcher)
            data = future.result()
            yield Summoner(player,
                           data_summoner=data[0],
                           data_mastery=data[1],
                           data_league=data[2])
コード例 #17
0
ファイル: Riot.py プロジェクト: Psychless/league-auto-stats
 def __init__(self):
     print('Starting up Riot API')
     self.watcher = RiotWatcher(API_KEY)
     self.dd_champ_version = self.watcher.data_dragon.versions_for_region(
         REGION_DATA_DRAGON)['n']['champion']
     self.champion_json = self.watcher.data_dragon.champions(
         self.dd_champ_version)
     self.queue_json = json.loads(
         urllib.request.urlopen(
             "http://static.developer.riotgames.com/docs/lol/queues.json").
         read())
     print('Riot API - RUNNING')
コード例 #18
0
ファイル: riot_utility.py プロジェクト: Susannova/Discord_Bot
def create_summoner(summoner_name: str, config: GeneralConfig,
                    guild_config: GuildConfig):
    riot_token = config.riot_token
    watcher = RiotWatcher(riot_token)
    with ThreadPoolExecutor() as executor:
        future = executor.submit(fetch_summoner, summoner_name, watcher,
                                 guild_config)
        data = future.result()
        return Summoner(summoner_name,
                        data_summoner=data[0],
                        data_mastery=data[1],
                        data_league=data[2])
コード例 #19
0
ファイル: RiotCrawler.py プロジェクト: DavidCorn/LeagueRank
 def __init__(self, key):
     self.key = key
     self.w = RiotWatcher(key)
     self.tiers = {
         'bronze': [],
         'silver': [],
         'gold': [],
         'platinum': [],
         'diamond': [],
         'challenger': [],
         'master': [],
     }
コード例 #20
0
def handle_api_setup():
    global WATCHER, STATICDATA
    WATCHER = RiotWatcher(CONFIG['API']['KEY'])
    STATICDATA['VERSION'] = WATCHER.data_dragon.versions_for_region(CONFIG['API']['DATA-DRAGON-GATEWAY'])
    STATICDATA = {
        "CHAMPIONS":WATCHER.data_dragon.champions(STATICDATA['VERSION']['v']),
        "ITEMS":WATCHER.data_dragon.items(STATICDATA['VERSION']['v']),
    }
    extra_data = {}
    for champName, champData in STATICDATA['CHAMPIONS']['data'].items():
        extra_data[int(champData['key'])] = champData
    STATICDATA['CHAMPIONS']['data'].update(extra_data)
コード例 #21
0
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()
コード例 #22
0
def init():
    kernel = os.getenv('KERNEL_URL')

    watcher = RiotWatcher(kernel_url=kernel)

    from . import views

    riotapi.add_url_rule('/graphql',
                         view_func=GraphQLView.as_view(
                             'graphql',
                             schema=schema,
                             get_context=lambda: watcher,
                             graphiql=True))
コード例 #23
0
def fill_spells(c, api_key):
	api = RiotWatcher(api_key)
	try:
		all_spells = api.static_get_summoner_spell_list(None, None, None, None, "image")
	except:
		print("Error getting all spells:", sys.exc_info()[0])
		return

	for _, spell in all_spells["data"].iteritems():
		c.execute('''
			INSERT INTO Spell (Id, Name, Image)
			VALUES (?, ?, ?)
		''', (spell["id"], spell["name"], spell["image"]["full"]))
コード例 #24
0
 def __init__(self, region, league):
     self.rw = RiotWatcher(API_KEY)
     self.region = region
     self.league = league
     self.mongo_cnx = MongoClient(MONGODB_CONN)
     self.mongo_soloq_m_col = self.mongo_cnx.slds.soloq_m
     self.mongo_soloq_tl_col = self.mongo_cnx.slds.soloq_tl
     self.mongo_slo_m_col = self.mongo_cnx.slds.slo_m
     self.mongo_slo_tl_col = self.mongo_cnx.slds.slo_tl
     self.mongo_static_data = self.mongo_cnx.slds.static_data
     self.mongo_players = self.mongo_cnx.slds.players
     self.mongo_teams = self.mongo_cnx.slds.teams
     self.mongo_competitions = self.mongo_cnx.slds.competitions
     self.mongo_slo = self.mongo_cnx.slds.slo
コード例 #25
0
ファイル: MyUeno.py プロジェクト: Masuku/Ueno
async def lol(summn_name: str):
    """サモナーネームを入力してstatusを取得"""
    API_KEY = "RGAPI-76bb5df1-c89e-4c7f-8eea-2de77a6a1fb5"
    watcher = RiotWatcher(API_KEY)
    region = "jp1"
    try:
        me = watcher.summoner.by_name(region, summn_name)
        await bot.say(me)
        #ranked_stats = watcher.league.by_summoner(region, me["id"])
        #print(ranked_stats)
    except HTTPError as err:
        if err.response.status_code == 429:
            print("We should retry in {} seconds.".format(
                e.headers["Retry-After"]))
            print(
                "this retry-after is handled by default by the RiotWatcher library"
            )
            print("future requests wait until the retry-after time passes")
        elif err.response.status_code == 400:
            await bot.say("BAD REQUEST")
        elif err.response.status_code == 403:
            await bot.say("API key is expired")
        elif err.response.status_code == 404:
            await bot.say("Summoner with that ridiculous name not found.")
        else:
            raise

    try:
        curr_game_stats = watcher.spectator.by_summoner(region, me["id"])
        mini = str(int(curr_game_stats["gameLength"] / 60))
        sec = str(curr_game_stats["gameLength"] % 60)
        await bot.say("GameMode:" + curr_game_stats["gameMode"] + ", " + mini +
                      "min." + sec + "sec.")
        parti = curr_game_stats["participants"]
        player_list = [parti[i]["summonerName"] for i in range(len(parti))]
        await bot.say(player_list)
    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 is currently not in game.")
        else:
            raise bot.sa
コード例 #26
0
ファイル: lol_api.py プロジェクト: njw1204/hot-play
def start_convert(api_key, region, match_id):
    print("변환을 시작합니다. 잠시 기다려주세요...")
    watcher = RiotWatcher(api_key)
    output_file = "lol_output.json"
    match = watcher.match.by_id(region, match_id)
    timeline = watcher.match.timeline_by_match(region, match_id)
    replay = {
        "info": parseBasicGameInfo(match),
        "timeline": parseTimeline(timeline, match["mapId"])
    }
    result = json.dumps(replay, cls=GameEventJSONEncoder)
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(result)
    print("===========================================")
    print("Complete!", os.path.abspath(output_file), "에 저장되었습니다.")
コード例 #27
0
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']
コード例 #28
0
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
コード例 #29
0
def fill_items(c, api_key):
	api = RiotWatcher(api_key)
	try:
		all_items = api.static_get_item_list(None, None, None, "image")
	except:
		print("Error getting all items:", sys.exc_info()[0])
		return

	for _, item in all_items["data"].iteritems():
		wiki_url = "http://leagueoflegends.wikia.com/wiki/" + item["name"]

		c.execute('''
			INSERT INTO Item (Id, Name, Description, WikiLink, Image)
			VALUES (?, ?, ?, ?, ?)
		''', (item["id"], item["name"], item["description"],
			wiki_url, item["image"]["full"]))
コード例 #30
0
ファイル: championSave.py プロジェクト: Keerran/Badeli
def genChampions():
    key = APIKey.APIKey()
    watcher = RiotWatcher(key)
    region = 'euw1'
    static_champ_list = watcher.static_data.champions(region, tags='all')
    champion_keys = static_champ_list['keys']
    data = static_champ_list['data']
    champ_objects = []
    for key, name in champion_keys.items():
        champ = data[name]
        img = 'http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/' + champ[
            'image']['full']
        passive = champ['passive']
        passive_img = 'http://ddragon.leagueoflegends.com/cdn/6.24.1/img/passive/' + passive[
            'image']['full']
        print(passive_img
              )  # ),name=champ['name'],image=img,title=champ['title'],