Beispiel #1
0
 def setUp(self):
     if not self.api_key:
         with open(os.path.join(os.path.dirname(__file__), '../../api-key'),'rt') as f:
             self.api_key = f.read()[:36]
     baseriotapi.print_calls(False)
     baseriotapi.set_region('euw')
     baseriotapi.set_api_key(self.api_key)
Beispiel #2
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-key",
                        type=str,
                        required=True,
                        help="API key to use for scraping")
    parser.add_argument("-region",
                        type=str,
                        required=True,
                        help="API region to use for scraping")
    parser.add_argument("-db",
                        type=str,
                        required=False,
                        help="Path to DB folder (default \"matches\")")
    parser.add_argument(
        "-chunk",
        type=int,
        required=False,
        help="Max number of matches per chunk file (default 50)")
    parser.add_argument("-ids",
                        type=str,
                        required=True,
                        help="Path to match id file")
    args = parser.parse_args()

    baseriotapi.set_region(args.region)
    baseriotapi.set_api_key(args.key)
    baseriotapi.set_rate_limit(1000, 10)
    baseriotapi.print_calls(True)
    baseriotapi.get_match = auto_retry(baseriotapi.get_match)

    db = args.db if args.db else "matches"
    chunk = args.chunk if args.chunk else 50

    scrape_matches(db, args.ids, chunk)
Beispiel #3
0
 def setUp(self):
     if not self.api_key:
         with open(os.path.join(os.path.dirname(__file__), '../../api-key'),
                   'rt') as f:
             self.api_key = f.read()[:36]
     baseriotapi.print_calls(False)
     baseriotapi.set_region('euw')
     baseriotapi.set_api_key(self.api_key)
Beispiel #4
0
def setup_riot_api(conf):
    cassioepia = conf['cassiopeia']
    baseriotapi.set_api_key(cassioepia['api_key'])
    baseriotapi.set_region(cassioepia['region'])

    limits = cassioepia.get('rate_limits', None)
    if limits is not None:
        if isinstance(limits[0], (list, tuple)):
            baseriotapi.set_rate_limits(*limits)
        else:
            baseriotapi.set_rate_limit(limits[0], limits[1])

    baseriotapi.print_calls(cassioepia.get('print_calls', False))
def setup_riot_api(conf):
    cassioepia = conf['cassiopeia']
    baseriotapi.set_api_key(cassioepia['api_key'])
    baseriotapi.set_region(cassioepia['region'])

    limits = cassioepia.get('rate_limits', None)
    if limits is not None:
        if isinstance(limits[0], (list, tuple)):
            baseriotapi.set_rate_limits(*limits)
        else:
            baseriotapi.set_rate_limit(limits[0], limits[1])

    baseriotapi.print_calls(cassioepia.get('print_calls', False))
def predict(summ_region, summ_name):
    # Set up libraries, load saved x
    x = np.load(open('tmp/trainedX_avg.npy', 'rb'))
    api.set_api_key(keys.riotapikey)
    api.set_region(summ_region)

    # TODO: Handle unicode characters in summoner names
    # Retrieve summoner
    summ_name_key = summ_name.lower().replace(' ', '')
    summ = api.get_summoners_by_name(summ_name)[summ_name_key]

    # Create template summoner w/ empty ratings
    db = Session()
    champ_dict = {}
    for champ in db.query(Champion):
        champ_dict[champ.champion_id] = 0

    # Fill in template summoner w/ specified summoner champion points
    masteries = api.get_champion_masteries(summ.id)
    for m in masteries:
        champ_dict[m.championId] = m.championPoints
    y_raw = [champ_dict[champ_id] for champ_id in sorted(champ_dict.keys())]

    # Normalize summoner champion points
    y_raw = np.asarray(y_raw)
    y_std = np.std(y_raw)
    y = y_raw / y_std

    # Train theta for user
    lamb = .1
    alpha = .0001
    iterations = 2000
    feature_count = len(x[0])
    init_theta = np.random.random_sample((1, feature_count))
    theta = train_theta(x, y, init_theta, lamb, alpha, iterations)

    # Create champ_id: champ_name dictionary
    champ_dict = []
    for champ in db.query(Champion):
        champ_dict.append((champ.champion_id, champ.champion_name))
    champ_dict = sorted(champ_dict, key=lambda x: x[0])

    # Make predictions and print formatted results
    h = np.dot(theta, x.T)
    champ_ids, champ_names = zip(*champ_dict)
    predictions = zip(champ_names, h[0])
    predictions = sorted(predictions, key=lambda x: x[1])
    return predictions
Beispiel #7
0
import json
import string
from boto.sqs.connection import SQSConnection
from boto.sqs.message import RawMessage
from cassiopeia import baseriotapi
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from portal.errors import INVALID_REQUEST_FORMAT
from portal.keys import AWS_ACCESS_KEY_ID
from portal.keys import AWS_SECRET_ACCESS_KEY
from portal.keys import RIOT_API_KEY

QUEUE = "TEAM_BUILDER_DRAFT_RANKED_5x5"
SEASON = "SEASON2016"
baseriotapi.set_api_key(RIOT_API_KEY)
baseriotapi.set_rate_limits((270, 10), (16200, 600))


def format_key(key):
    # filter to remove punctuation
    translator = str.maketrans({key: None for key in string.punctuation})

    # also remove white spaces and make lowercase
    return key.translate(translator).replace(" ", "").lower()


def riot_request(region, args):
    # set region
    baseriotapi.set_region(region)

    # extract arguments
Beispiel #8
0
)



# Set API key
# Lets cassi handle riot api rate limits. But does this work per instance of this app (if many ppl are using website at same time) or globally? is this the best place
# for this, or should this be under the relevant url routes?
riotapi.set_region('na')
riotapi.print_calls(True)
riotapi.set_api_key(API_KEY)
riotapi.set_rate_limits((9, 10), (480, 600))
riotapi.set_load_policy(LoadPolicy.lazy)

baseriotapi.set_region('na')
baseriotapi.print_calls(True)
baseriotapi.set_api_key(API_KEY)
baseriotapi.set_rate_limits((9, 10), (480, 600))


def auto_retry(api_call_method):
    """ A decorator to automatically retry 500s (Service Unavailable) and skip 400s (Bad Request) or 404 (Not Found). """
    def call_wrapper(*args, **kwargs):
        try:
            return api_call_method(*args, **kwargs)
        except APIError as error:
            # Try Again Once
            if error.error_code in [500]:
                try:
                    print("Got a 500, trying again...")
                    return api_call_method(*args, **kwargs)
                except APIError as another_error:
        newLosses = losses - lastLosses
        timestamp = datetime.utcnow()

        elastic.index(index='lol_challenger_solo_weekly', doc_type='weekly_played', body={"region": region, "wins": newWins,
                                                                                          "most_wins": mostWins, "user_most_wins": userMostWins,
                                                                                          "avg_wins": avgWins, "losses": newLosses,
                                                                                          "most_losses": mostLosses,
                                                                                          "user_most_losses": userMostLosses,
                                                                                          "avg_losses": avgLosses,
                                                                                          "timestamp": timestamp})

    except:
        traceback.print_exc()



def process_challenger_data():
    regions=['BR', 'EUNE', 'EUW', 'KR', 'LAN', 'LAS', 'NA', 'OCE', 'RU', 'TR']
    for i in regions:
        process_region(i)
    with open('conf/lol_api_challenger.conf', 'w') as configfile:
        config.write(configfile)

if __name__ == '__main__':
    config = configparser.RawConfigParser()
    config.read('conf/lol_api_challenger.conf')
    baseriotapi.set_api_key(config.get('General', 'api_key'))


    process_challenger_data()