Giter VIP home page Giter VIP logo

srcomapi's Introduction

Inactive. Check the network graph to see if there are any active forks. Thanks for using srcomapi.

srcomapi (SpeedrunComAPI) travis-ci

A Python 3 implementation of the speedrun.com REST API. pip3 install srcomapi

Does not support Python 2. Sorry.

Usage

Start

>>> import srcomapi, srcomapi.datatypes as dt
>>> api = srcomapi.SpeedrunCom(); api.debug = 1

Searching for a game

# It's recommended to cache the game ID and use it for future requests.
# Data is cached for the current session by classname/id so future
# requests for the same game are instantaneous.
>>> api.search(srcomapi.datatypes.Game, {"name": "super mario sunshine"})
[<Game "Super Mario Sunshine">]
>>> game = _[0]

Getting the current world record for a game category

>>> game.categories
[<Category "Any%">, ...]
>>> _[0].records[0].runs
[{'run': <Run <Game "Super Mario Sunshine">/<Category "Any%">/9mr570dy 4498>, 'place': 1}, ...]
>>> _[0]["run"].times
{'primary_t': 4498, ...}
# primary_t is the time in seconds

Getting a dict containing all runs from a game

sms_runs = {}
for category in game.categories:
  if not category.name in sms_runs:
    sms_runs[category.name] = {}
  if category.type == 'per-level':
    for level in game.levels:
      sms_runs[category.name][level.name] = dt.Leaderboard(api, data=api.get("leaderboards/{}/level/{}/{}?embed=variables".format(game.id, level.id, category.id)))
  else:
    sms_runs[category.name] = dt.Leaderboard(api, data=api.get("leaderboards/{}/category/{}?embed=variables".format(game.id, category.id)))

srcomapi's People

Contributors

alyssadev avatar blha303 avatar cmnemoi avatar juliencoutault avatar lepelog avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

srcomapi's Issues

.version is not copied on setup.py

If you try to install this package, setup doesn't copy .version

To fix it just add package_data={'': ['.version']} to the setup method

Proposal: Add search methods for games and users

Currently there is only a way to get all games or a specific game by its id or abbreviation, but games should be searchable by name and a lot of other parameters listed in the Speedrun.com API-documentation. Same with users.

Publish to PyPI

I'm writing a tool that will use srcomapi and it would be really nice if it was part of PyPI so it could easily be installed as a dependency. Also, for future developers it would be nice if you could just pip install srcomapi to use this lib.

Get WR records

Hi! Thank you so much for writing this tool, I've found it very helpful.

I wanted to ask if there is a direct way of getting the data for WR progressions, as in the gamestat page of each game (example).

Concretely, I would like to end up with a list of dictionary entries, where each dictionary is of the form

{
'game' : 'Super Mario Sunshine', 
'category' : 'any%', 
'time' : <primary_t>,
'date'; <date>,
'runner' : '<player.id(s)>',
}

I tried downloading all runs with the intention of filtering them myself later to only include world record improvements, as this:

import srcomapi, srcomapi.datatypes as dt

api = srcomapi.SpeedrunCom(); api.debug = 1
search_results = api.search(srcomapi.datatypes.Game, {"name": "super mario sunshine"})
game = search_results[0]
category = game.categories[0]
leaderboard = dt.Leaderboard(api, data=api.get(f"leaderboards/{game.id}/category/{category.id}?embed=variables"))

data = []
for run in leaderboard.runs:
  run = run['run']
  row = {'date' : run.date,
         'time' : run.times['primary_t'],
         'runner' : ", ".join([player.name for player in run.players])}
  data.append(row)

But this method is very slow.

Extracting all runs from a game

Hello,

I am trying to gather data for a statistical modeling project. However, I can seem to figure out how to extract all the run times, dates, users and category (any% , etc) from one single game. Could you provide an examples how to do it?

Might be a very basic question but I am not that familiar with python syntax.

Thank you,

Tiago

requests.get() hits a stale cache without X-API-Key

I have an application which gets unverified runs every minute (SRC api appears to update every 5mins), but it appears that the current raw requests.get() hits a cache and continues to fetch stale data that eg. firefox does not retrieve for around 10 minutes.

Isolated to the PHPSESSID cookie - there may be some optimisation on SRC's end that forces new sessions to hit a cache but allows existing sessions to fetch fresh data. Manually inserting the cookie from my Firefox into the headers correctly fetches fresh data.

Bug with get_game

>>> import srcomapi
>>> api=srcomapi.SpeedrunCom()
>>> api.get_games()

results in an error, same with api.get_game

'-' is an invalid character in attributes

Executing the following code

api = srcomapi.SpeedrunCom()
g = api.get_game('sms')
dir(g)

shows that g has the attribute 'release-date'.

g.release-date

fails, because Python interpretes the '-' as an operator for g.release and date, which causes a AttributeError.
It's still possible to get it with g.__getattr__('release-date') but I don't think this is the way it should work.

Cannot access game attributes in a loop

So, given this code (for reproducibility) :

import srcomapi, srcomapi.datatypes as dt
import pandas as pd

api = srcomapi.SpeedrunCom(); api.debug = 1
test_df = pd.DataFrame(['Castlevania: Aria of Sorrow','Pokémon: Yellow'],columns=['Game'])
nb_games = len(test_df)

lb_per_game = []

#getting the game for each name
for i in range(nb_games):
    try: 
      test_df.loc[i,'SRC_game'] = api.search(srcomapi.datatypes.Game, {"name": test_df.loc[i]['Game']})[0]
    except IndexError:
      pass

#collecting leaderboards for each game
for i in range(nb_games):
    lb = {}
    for category in test_df.loc[i,'SRC_game'].categories:
      if not category.name in lb:
        lb[category.name] = {}
      if category.type == 'per-level':
        pass
      # if category.miscellaneous:
      #   pass
      else:
        lb[category.name] = dt.Leaderboard(api, data=api.get("leaderboards/{}/category/{}?embed=variables".format(test_df.loc[i,'SRC_game'].id, category.id)))
    lb_per_game.append(lb)

This piece of code works :

platform = lb_per_game[0]['Soma Any%'].game.__getattr__('platforms')[0]
 print(platform)

But this one does not :

for i in range(2):
  game = lb_per_game[0]['Soma Any%'].game
  platform = game.__getattr__('platforms')[0]
  print(platform)

It raises a Type Error at the second time you enter the loop on second line :

object of type 'Platform' has no len()
  File "C:\Users\charl\OneDrive\Documents\Projects\OWREstimator\srcdata.py", line 68, in <module>
    platform = game.__getattr__('platforms')[0]

By inspecting the debugger, it seems the game.platforms attribute equals to this at this moment :
'Traceback (most recent call last):\n File "c:\\Users\\charl\\.vscode\\extensions\\ms-python.python-2021.6.944021595\\pythonFiles\\lib\\python\\debugpy\\_vendored\\pydevd\\_pydevd_bundle\\pydevd_resolver.py", line 193, in _get_py_dictionary\n attr = getattr(var, name)\n File "C:\\Users\\charl\\miniconda3\\lib\\site-packages\\srcomapi\\datatypes.py", line 46, in __getattr__\n if type(self.data[attr]) is list and len(self.data[attr]) > 0 and len(self.data[attr][0]) == 8:\nTypeError: object of type \'Platform\' has no len()\n'
(same for all not null attributes)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.