def __init__(self, args):
     self.api = None
     self.key = None
     self.homies_by_id = {}
     self.homie_names = set()
     self.custom_only = False
     self.classic_only = True
     self.threshold = 4
     self.gen_config = False
     self.monitor = args.monitor
     self.output_dir = args.output_dir
     if args.config:
         self.read_config(args.config)
     if args.key:
         self.key = args.key
     if args.summoner_list:
         self.read_summoners(args.summoner_list)
     if args.gen_config:
         self.gen_config = args.gen_config
     if not args.custom_only is None:
         self.custom_only = args.custom_only
     if not args.classic_only is None:
         self.classic_only = args.classic_only
     if not args.threshold is None:
         self.threshold = args.threshold
     if self.key:
         self.api = riotwatcher.RiotWatcher(self.key, enforce_limits=True)
def riot_context(mock_get: mock.MagicMock) -> MockContext:
    import riotwatcher

    api_key = "abcdefg"
    yield MockContext(
        api_key, mock_get, riotwatcher.RiotWatcher(api_key), None,
    )
def migrate_players(bkt):
    doc = bkt.get('players').value
    riot = riotwatcher.RiotWatcher(default_region=riotwatcher.EUROPE_WEST,
                                   key=os.environ.get('RIOT_API_KEY'))

    for player_id in doc.itervalues():
        summoner = riot.get_summoner(_id=player_id)
        new_key = 'Player::{}'.format(player_id)
        bkt.upsert(new_key, summoner)
        time.sleep(5)
def mock_context(mock_get, request):
    import riotwatcher

    api_key = "abcdefg"
    yield MockContext(
        api_key,
        mock_get,
        riotwatcher.RiotWatcher(api_key, kernel_url=request.param),
        request.param,
    )
def add_champions(bkt):
    riot = riotwatcher.RiotWatcher(default_region=riotwatcher.EUROPE_WEST,
                                   key=os.environ.get('RIOT_API_KEY'))
    champs = riot.static_get_champion_list()
    champ_dict = {}
    for champ in champs['data'].itervalues():
        champ_dict[int(champ['id'])] = {
            'key': champ['key'],
            'name': champ['name']
        }
    bkt.upsert('Champions', champ_dict)
Exemple #6
0
 def __init__(self,
              riot=None,
              report_callback=default_report_callback,
              report_freq=default_report_freq):
     if riot is None:
         riot = riotwatcher.RiotWatcher()
     self.riot = riot
     if report_callback is None:
         report_callback = default_report_callback
     self.report_callback = report_callback
     self.report_freq = report_freq
 def __init__(self):
     self.watcher = riotwatcher.RiotWatcher(
         default_region=riotwatcher.EUROPE_WEST,
         key='4f973eb3-7400-4eaf-9e6b-05b9ca56068c')
     self.bkt = Bucket()
     self.player_dict = self.get_players()
     self.bkt.upsert('Champions', self.watcher.static_get_champion_list())
     while True:
         for _, v in self.player_dict.iteritems():
             self.update_recent_games(v)
             time.sleep(SLEEP_TIME)
    def __init__(self):
        self.riot = riotwatcher.RiotWatcher(
            default_region=riotwatcher.EUROPE_WEST,
            key=os.environ.get('RIOT_API_KEY'))
        self.storage_manager = CouchbaseManager(
            os.environ.get('MATCH_HISTORY_BUCKET'))

        self.player_dict = self.storage_manager.get('players')
        logger_datapop.info('Setup complete')
        while True:
            for _, player_id in self.player_dict.iteritems():
                self.update_recent_games(player_id)
                time.sleep(SLEEP_TIME)
            self.player_dict = self.get_players()
    def __init__(self):
        self.riot = riotwatcher.RiotWatcher(
            default_region=riotwatcher.EUROPE_WEST,
            key=os.environ.get('RIOT_API_KEY'))
        self.bucket = Bucket('couchbase://{}/{}'.format(
            os.environ.get('DB_HOST', 'localhost'),
            os.environ.get('DB_BUCKET_MATCH_HISTORY', 'match_history')))

        self.players = self.get_players()
        logger_datapop.info('Setup complete')
        while True:
            for player in self.players:
                self.update_recent_games(player['id'])
                time.sleep(SLEEP_TIME)
            self.players = self.get_players()
    def __init__(self):
        # read info.txt file
        info = {}
        with open("info.txt", "r") as f:
            for line in f:
                (key,value) = line.split()
                info[key] = value
        # setup bot
        updater = Updater(token=info['token'], use_context=True)
        self.dispatcher = updater.dispatcher
        updater.start_polling()
        # setup Neo4j driver
        self.neo4j_uri = "bolt://localhost:7687"
        self.neo4j_driver = GraphDatabase.driver(self.neo4j_uri, auth=("neo4j", "password"))
        # setup logging
        logging.basicConfig(format='%(asctime)s - %(message)s',
                             level=logging.INFO)
        self.logger = logging.getLogger()

        # create handlers
        help_handler = CommandHandler('help', self.help)
        subscribe_to_summoner_handler = CommandHandler('subscribe_to', self.subscribe_to_summoner)
        list_subscriptions_handler = CommandHandler('subscriptions', self.list_subscriptions)
        unsubscribe_from_handler = CommandHandler('unsubscribe_from', self.unsubscribe_from_summoner)
        clear_subs_handler = CommandHandler('clear_subs', self.clear_subs)

        # add handlers to dispatcher
        self.dispatcher.add_handler(subscribe_to_summoner_handler)
        self.dispatcher.add_handler(list_subscriptions_handler)
        self.dispatcher.add_handler(unsubscribe_from_handler)
        self.dispatcher.add_handler(clear_subs_handler)
        self.dispatcher.add_handler(help_handler)

        #setup all we need in order to scrape
        self.summoner_list = []
        self.dict_summ_last_status = {}
        # riotwatcher
        self.region = 'euw1'
        self.watcher = rw.RiotWatcher(info['riot_developer_key'])
        while True:
            with self.neo4j_driver.session() as sess:
                l  = sess.read_transaction(get_all_summoners)
                self.logger.info(f"Summoners: {l}")
            for s in l:
                self.check_summoner_activity(s)
            time.sleep(POLL_SECONDS)
Exemple #11
0
def main():
    w = rw.RiotWatcher(constants.riot_id)

    cur_data = {}
    with open('player_tiers.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            cur_data[row['user_id']] = row

    ids_to_crawl = {row['user_id'] for row in cur_data.viewvalues()
                    if row['tier'] in ["SILVER"] and row['crawled'] == '0'}
    total_ids = set(cur_data.viewkeys())

    new_data = copy.deepcopy(cur_data)

    for x in range(100):
        cur_id = ids_to_crawl.pop()
        print("Crawling: {0}".format(cur_id))
        neighbor_ids = get_neighbors(w, cur_id)
        neighbor_ids -= total_ids
        neighbor_ids = list(neighbor_ids)[:40]
        neighbor_tiers = get_tiers(w, neighbor_ids)

        for n_id, n_tier in neighbor_tiers.viewitems():
            new_data[n_id] = {
                'user_id': n_id,
                'tier': n_tier,
                'crawled': 0,
            }
            ids_to_crawl.add(n_id)
        total_ids |= set(neighbor_tiers.keys())
        new_data[cur_id]['crawled'] = 1

    sorted_rows = new_data.values()
    sorted_rows.sort(key=lambda row: (1-int(row['crawled']), row['user_id']))

    with open('player_tiers.csv', 'w') as csvout:
        writer = csv.DictWriter(csvout, fieldnames=['user_id', 'tier', 'crawled'])
        writer.writeheader()
        writer.writerows(sorted_rows)
Exemple #12
0
 def __init__(self, interface: CommandInterface):
     super().__init__(interface)
     self._riotwatcher = riotwatcher.RiotWatcher(
         api_key=self.config["Lol"]["token"])
     if self.interface.name == "telegram":
         self.loop.create_task(self._updater(900))
Exemple #13
0
def mock_context(mock_get):
    import riotwatcher

    api_key = "abcdefg"
    return MockContext(api_key, mock_get, riotwatcher.RiotWatcher(api_key))
Exemple #14
0
def main():
    id_to_name = get_id_to_name(riotwatcher.RiotWatcher())
    make_columns_to_id(id_to_name)
Exemple #15
0
import os

import riotwatcher

try:
    token = os.environ['LEAGUE_TOKEN']
except KeyError:
    raise Exception('No LEAGUE_TOKEN found. See developer.riotgames.com')
riot = riotwatcher.RiotWatcher(token)


def get_champ(champ_filter=None):
    champs = []
    for champ in riot.static_get_champion_list()['data'].values():
        champs.append(
            dict(id=champ['id'], key=champ['key'], name=champ['name']))
        if not champ_filter:
            continue

        if champ_filter == champ['name'].lower():
            return champs[-1:]

    if champ_filter:
        raise Exception('Could not find champion {}', champ_filter)

    return champs


def get_item(item_filter=None):
    items = []
    for item in riot.static_get_item_list()['data'].values():
Exemple #16
0
import json
from time import sleep

import mysql.connector
import cassiopeia as cass
import riotwatcher as rw

cass.set_riot_api_key("RIOT-API-KEY")
cass.set_default_region("NA")

matchmm = 3154904286  # 3152058384

watcher = rw.RiotWatcher('RIOT-API-KEY')
my_region = 'na1'

mydb = mysql.connector.connect(host="localhost",
                               user="******",
                               passwd="",
                               database="lol_database")

mycursor = mydb.cursor()


def getRedSideByMatch(id):
    return cass.get_match(id).red_team.to_json()


def getBlueSideByMatch(id):
    return cass.get_match(id).blue_team.to_json()

def setup_test_data():
    import riotwatcher, collect_summoner_ids, data_path
    riot = riotwatcher.RiotWatcher()
    with open(data_path.test_store_champions_usage_data, 'w') as f:
        collect_summoner_ids.store_summoner_ids(f, riot, 1, 30890339)
Exemple #18
0
# -*- coding: utf-8 -*-
__author__ = 'Vance'
import riotwatcher as rw
import json
import time
import os
w = rw.RiotWatcher('a66b170f-ecc4-4173-84cc-9371cb61ab24')
player_list = []
all_match_ids = []
player_offset = 0
def get_match_from_summoner_name(summoner_name):
    global player_list
    global all_match_ids

    ret = 0
    print 'Player:', summoner_name
    me = w.get_summoner(name=summoner_name)
    #print me
    my_id = me['id']
    #print my_id
    #print w.get_ranked_stats(my_id)
    try:
        my_match_list = w.get_match_list(summoner_id=my_id, begin_time=1441065600000, ranked_queues='RANKED_SOLO_5x5') #patch 5.16
    except:
        print 'Error in API'
        my_match_list = []
    #print my_match_list

    if 'matches' in my_match_list:
        for match in my_match_list['matches']:
            #print match
Exemple #19
0
def scrape(store, api_key, region, summoner_name, empty_weeks_to_stop=10,
           with_timeline=False, progress_callback=NotImplemented):
  """
  Scrape the matchlist and save all matches in *store*.

  progress_callback (function): See #scrape_default_progress_callback().
  """

  watcher = riotwatcher.RiotWatcher(api_key)
  summoner = watcher.summoner.by_name(region, summoner_name)

  if progress_callback is NotImplemented:
    progress_callback = scrape_default_progress_callback

  # The Riot API only allows a time interval of one week, thus we
  # have to find the matches in chunks of one week.
  one_week = 1000 * 3600 * 24 * 7

  user_abort = False
  for interval in store.suggest_search_intervals(summoner['accountId']):
    if user_abort: break
    if interval[1] is None:
      interval = (interval[0], int(time.time() * 1000))                         # TODO: that region's current time
    empty_weeks_passed = 0
    while empty_weeks_passed < empty_weeks_to_stop:
      begin_time = interval[1] - one_week
      if interval[0] and begin_time < interval[0]:
        begin_time = interval[0]
      try:
        matches = watcher.match.matchlist_by_account(
          region, summoner['accountId'], begin_time=begin_time,
          end_time=interval[1])['matches']
      except requests.HTTPError as e:
        if e.response.status_code == 400:  # request too far in the past?
          break
        if e.response.status_code == 404:  # no matches found
          continue
        raise
      interval = (interval[0], begin_time)  # shrink the interval
      if not matches:
        empty_weeks_passed += 1
        continue
      # Sort by newest first, for consistency with lookback order and the
      # FileStore --continuous option.
      matches.sort(key=lambda x: -x['timestamp'])
      matches = [m for m in matches if not store.has_match(m['gameId'], m['timestamp'])]
      if progress_callback:
        event_data = {'beginTime': begin_time, 'matchCount': len(matches)}
        if progress_callback('matchlist', event_data) is False:
          user_abort = True
          break
      empty_weeks_passed = 0
      for index, match_info in enumerate(matches):
        if progress_callback:
          event_data = {'matchIndex': index, 'matchCount': len(matches)}
          if progress_callback('match', event_data) is False:
            user_abort = True
            break
        match_data = watcher.match.by_id(region, match_info['gameId'])
        timeline = None
        if with_timeline:
          try:
            timeline = watcher.match.timeline_by_match(region, match_info['gameId'])
          except requests.HTTPError as e:
            if e.response.status_code != 404:  # no timeline data
              raise
            timeline = {}  # indicate that no timeline data is present
        store.store_match(
          match_info['gameId'],
          match_info['timestamp'],
          match_data,
          timeline
        )

  return not user_abort
Exemple #20
0
import riotwatcher

watcher = riotwatcher.RiotWatcher("LOLOL")

print(watcher.champion.rotations("TRLH4"))

watcher.summoner.by_name("TRLH4", "Cobular")
    linha = {}
    linha[fields[0]] = IdSummoner
    linha[fields[1]] = IdAccount
    linha[fields[2]] = tier
    linha[fields[3]] = rank
    if testarPlayer(IdAccount):
        print("salvando player")
        print(linha)
        csv_writer.writerow(linha)


arq = open("key.txt")

key = arq.readline()
watcher = riotwatcher.RiotWatcher(key)
## criar uma lista com os jogadores que vai comecar
players = open("playersStart.txt")
## parametros
partidasPorPlayer = 5
regiao = "br1"

for nome in players.readlines():
    nome = nome.strip()
    playerDados = watcher.summoner.by_name(region=regiao, summoner_name=nome)
    print(playerDados)
    idSum = playerDados["accountId"]
    try:
        partidas = watcher.match.matchlist_by_account(region=regiao,
                                                      account_id=idSum,
                                                      queue=420)
Exemple #22
0
import json, riotwatcher, collect_summoner_ids, collect_champions_usage




riot = riotwatcher.RiotWatcher()


#store_summoner_ids('summoner_ids_plat', riot, 10000, 30890339)

#store_champions_usage('summoner_ids', 'champions_usage', riot)

# for i in reversed(range(10)):
#     print('i = '+str(i))
#     store_champions_usage('data/summoner_ids_plat_'+str(i), 'data/champions_usage_plat_'+str(i), riot)



#collect_summoner_ids.collect_master_summoner_ids()

from data_path import summoner_ids_master, champions_usage_master
collect_champions_usage.store_champions_usage(summoner_ids_master, champions_usage_master, riot)