pseudonym117 / riot-watcher Goto Github PK
View Code? Open in Web Editor NEWSimple Python wrapper for the Riot Games API for League of Legends
License: MIT License
Simple Python wrapper for the Riot Games API for League of Legends
License: MIT License
There are some methodes not updated like championmastery
Are you going to update it? ^^
Your default rate limit code is correct; 10/10s, 500/600s, but your README is written as 500 req / 6 min.
how get a league?
league = w.get_league(summoner['id'], region=LATIN_AMERICA_NORTH)
print (league)
I have this error:
TypeError: 'int' object is not iterable
When you receive a 429 response from the servers they send Retry-After in the header. The user is suppose to back off from the api for that amount of time, but because there is no current way of retrieving this information from your lib it can't be done.
Info about it can be found here: https://developer.riotgames.com/docs/rate-limiting
The riot API endpoint /api/lol/{region}/v2.5/league/master
allows for directly querying the master league, and isn't available in RW currently. I may add it and submit a pull request, but just opening an issue first as per github guidelines.
Any plans on adding tournament API endpoints/methods?
I may end up adding this as I need it, but just in case I missed something. Please stop me before I add it.
Thanks
Riot's API team just announced that positional ranking endpoints have been deprecated and will be removed on Monday, June 17th, meaning there are changes to the league-v4
API.
These endpoints are being removed:
/lol/league/v4/positional-rank-queues
/lol/league/v4/positions/by-summoner/{encryptedSummonerId}
/lol/league/v4/positions/{positionalQueue}/{tier}/{division}/{position}/{page}
And these are being added:
/lol/league/v4/entries/by-summoner/{encryptedSummonerId}
/lol/league/v4/entries/{queue}/{tier}/{division}
Unfortunately, I don't currently have the bandwidth to make a PR for this myself, but I hope that by posting this early on, someone will be able to pick up this issue! 😓
Not sure what it takes to download 1.3.1 from pypi.
I already upgrade pip using pip install --upgrade pip
and even triedpip install riotwatcher==1.3
but no luck.
As of October 30, 2015, it's not getting 1.3.1 nor 1.3; it is showing patch notes for 1.3, though.
Here's the link https://pypi.python.org/pypi/riotwatcher/1.3
So on July 24, this API will be outdated, does anyone know how to change the version?
recently timeout problems often occur due to my bad network. Could you consider add timeout config as a property of the Watcher Class so that i can handle timeout problem within the exception return?
e.g. support optional forAccountId / forPlatformId keyword argument when calling match.by_id()
-- see https://developer.riotgames.com/api-methods/#match-v3/GET_getMatch
We should be able to call something like
watcher.match.by_id(region, match_id, forAccountId=None, forPlatformId=None)
Not sure if this is my fault but I got this error when I was trying to grab match data recursively given a list of matchIds. It was run in a simple for loop and included a self rate limit by sleeping after 100 requests. I got this error 2x both around the 10000th recursive call. However running it my third time everything went smoothly.
Traceback (most recent call last):
File "getMatchDataStats.py", line 42, in
match = recentMatches(game)
File "getMatchDataStats.py", line 13, in recentMatches
return watcher.match.by_id(region, id)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/_apis/MatchApiV3.py", line 31, in by_id
'/lol/match/v3/matches/{matchId}'.format(matchId=match_id)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/_apis/NamedEndpoint.py", line 28, in _request
return self._base_api.request(self._endpoint_name, method_name, region, url_ext, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/_apis/BaseApi.py", line 34, in request
mod = handler.after_request(region, endpoint_name, method_name, url, response)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/Handlers/RateLimit/RateLimitHandler.py", line 63, in after_request
limiter.update_limiter(region, endpoint_name, method_name, response)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/Handlers/RateLimit/HeaderBasedLimiter.py", line 49, in update_limiter
scoped_limit.update_limits(raw_limits)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/Handlers/RateLimit/Limits.py", line 33, in update_limits
self._limits[raw_limit.time].set_raw_limit(raw_limit)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/riotwatcher/Handlers/RateLimit/Limits.py", line 100, in set_raw_limit
raw_limit.count = self._raw_limit.count
AttributeError: can't set attribute
Looks like Riot sneaked in their Match and MatchHistory endpoints. I didn't see this announced anywhere, but the discussions on them make it look like they're a few days old.
how can defined ranked_queues?
summoner = w.get_summoner(name=test, region=LATIN_AMERICA_NORTH)
match = w.get_match_history(summoner['id'],region=LATIN_AMERICA_NORTH,ranked_queues=RANKED_SOLO_5x5)
print (match)
i get this error: NameError: name 'RANKED_SOLO_5x5' is not defined
Querying for free to play champions seem to return all champions because the url is wrongly formatted:
riotwatcher.get_all_champions(settings.STATIC_DATA_REGION, free_to_play=True)
print(len(response['champions'])) # => 134
The reason is that the parsed url looks like this:
/api/lol/NA/v1.2/champion/?api_key=SECRET&freeToPlay=True
but should actually look like this for additional arguments being accepted by riot (remove / before params):
/api/lol/NA/v1.2/champion?api_key=SECRET&freeToPlay=True
Riot API has been updated, causing some of your calls to break.
https://developer.riotgames.com/change-history
TIA!
>>> me
{'id': 50156526, 'accountId': 212758343, 'name': 'l am Anjo', 'profileIconId': 973, 'revisionDate': 1502660431000, 'summonerLevel': 30}
>>> my_region = 'na1'
>>> my_ranked_stats = watcher.league.leagues_by_summoner(my_region, me['id'])
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
my_ranked_stats = watcher.league.leagues_by_summoner(my_region, me['id'])
AttributeError: 'LeagueApiV3' object has no attribute 'leagues_by_summoner'
>>>
Get a summoner with special char results a Key Error...
from riotwatcher import RiotWatcher, BRAZIL
w = RiotWatcher(key='<key>', default_region=BRAZIL)
me = w.get_summoner(name='faucheurdecrân')
# KeyError: 'faucheurdecr\xc3\xa2n'
So, I recommend to use this strategy in RiotWatcher#get_summoner method:
return self.get_summoners(names=[name, ], region=region).itervalues().next()
instead of
return self.get_summoners(names=[name, ], region=region)[name]
Final method:
def get_summoner(self, name=None, _id=None, region=None):
if (name is None) != (_id is None):
if name is not None:
# name = self.sanitized_name(name) redundant statement ... it is called in RiotWatcher#get_summoners method
return self.get_summoners(names=[name, ], region=region).itervalues().next()
else:
return self.get_summoners(ids=[_id, ], region=region)[str(_id)]
return None
Have only tested w/EUW, but it looks like you are constructing an URL that looks like:
https://prod.api.pvp.net/api/lol/euw/...
...which returns a 401 error.
Querying EUW via the Riot API reference page uses the following domain (which works):
euw.api.pvp.net
No idea when they changed this but I wouldn't be surprised if other regions had different hosts, too.
When querying, by summoner ID, the teams endpoint, a 404 is returned when the summoner is not on a team. This caught me off guard, but I guess it makes sense to pass that through via riotwatcher's representing a 404. TBH I'm in no position to advise on how this should be handled.
However, I was wondering if you had any recommendations how users of your wrapper should handle it? I tried this in my module:
from riotwatcher.riotwatcher import error_404
...
# Riot API returns HTTP 404 if summoner is not on any teams.
try:
teams_dto = riot_api.get_teams_for_summoner(summoner_id, region)
got_teams = True
except error_404:
got_teams = False
But this still causes program halt on the 404 being received. Is there some way to make the exception propagate to a level where I can catch it or something?
In tests.py you set key = '5cf65626-43f1-4919-aade-47bba8c847b9' which is your League of Legends API Key. You should probably change it like in your README.rst to 'your-api-key' and also reset your actual key.
Reasons why you should not give out your key listed here: https://developer.riotgames.com/docs/credentials-security
when can you put the current game info?
https://developer.riotgames.com/api/methods#!/956
https://developer.riotgames.com/discussion/riot-games-api/show/ji66sYEN
When I try to call a summoner's league entry using their ID it's returning information for the completely wrong player.
https://developer.riotgames.com/discussion/announcements/show/GzTxcP8A
not yet an issue, but keep in mind.
I have a django server with an endpoint that calls upon riot-watcher a single time. In a script, I spawned 13 threads each with a request to my server and ran them all at once and hit a "cant set attribute" error. The problem is with the line below:
Limits.py :
RawLimit = namedtuple('RawLimit', ['count', 'limit', 'time'])
namedtuples are NOT mutable, so Line 100 of Limits.py will not work:
raw_limit.counts = self._raw_limit.counts
theres a mutable list implementation called namedlist
which does the job, but has a default attribute called 'count' so just rename that to whatever.
I'm testing this with a production key so im definitely not hitting any limit, but this gets logged:
'overwriting time limit, previously %s, now %s. ' + 'This may cause rate limitting issues.'
Can you elaborate how the limiter works and any edge cases you may be aware of, especially with these comments in the code:
double check that we arent assigning a lower, non-1 value to
our count. This may be screwy if a bunch of requests are sent
as the rate limit is getting reset, but I dont think There
is a more elegant solution.
In addition, I tested it with a dev key (20calls/sec) with 25 threads and as expected 5 error429's were logged.
You describe a means of checking status codes here #5 (comment) that doesn't work:
try:
teams = riot_api.get_teams_for_summoner(summoner_id)
except LoLException as e:
if e == error_404:
...
else:
...
Sticking w/your example code, what I've found works is comparing the error
attribute of the e
object to the error_
strings defined by riotwatcher, like so:
try:
teams = riot_api.get_teams_for_summoner(summoner_id)
except LoLException as e:
if e.error == error_404:
...
else:
...
Can't speak to whether you intend for this kind of operation, but I thought it should be documented somewhere. If you are cool w/this method of determining error codes, I will submit a pull request w/an updated README as this is quite useful to know, especially in conjunction w/429 errors and the associated Retry-After
header.
Please add to the requirements
pip install requests[security]
would be nice if RateLimit.request_available have a "wait" parameter to sleep till next request can be made
How do you feel about being able to do:
rw = RiotWatcher('api-key')
rw.get_match_list(summoner_id=123456,
region='na',
ranked_queues=('RANKED_SOLO_5x5', 'TEAM_BUILDER_DRAFT_RANKED_5x5'))
# returns match list dict containing both solo queue and dynamic queue matches
vs what is now done by:
rw = RiotWatcher('api-key')
rw.get_match_list(summoner_id=123456,
region='na',
ranked_queues='RANKED_SOLO_5x5,TEAM_BUILDER_DRAFT_RANKED_5x5')
Right now, using the former, unsupported, syntax results in just the first value being used, which is a bit misleading.
This could break some users' code, and would warrant changing how multiple values are worked with in more of riotwatcher's API than just get_match_list
, but I think it'd be a good change. Support could be added to preserve the old functionality while enabling the new and then we emit some deprecation warning if, e.g. a comma is detected in a param for an arg that accepts multiple values.
Hi. This is not an issue per se, but I'm trying to figure out how your rate limiting works.
I might be reading the code wrong, but it seems like the can_make_request method in RiotWatcher doesn't get used, is that right? Are you just using the LoLException/raise_status bit to catch too many requests?
I also don't understand how the __reload method works; since all requests prior to the method being used would have self.made_requests[0] < t, wouldn't that just basically make the queue size 1 again? Which makes sense since you need to make a "new" queue every time a request is sent...but how does that manage the initial queue (r1 at t1 - r10 at t10...what if r10 occurred at t9?)?
Anyhow, I'm new to this, and working on my own stats app, and your repository has been quite helpful in getting some of the API logic. Thanks!
Cheers,
Mahen
matchlist = _match_list_request('XXX')
I am getting this error
Traceback (most recent call last):
File "C:\Python27\Newer Folder\lolwatcher.py", line 11, in
matchlist = match_list_request('mufasakim')
NameError: name '_match_list_request' is not defined
Missing Grandmaster league endpoint
/lol/league/v3/grandmasterleagues/by-queue/{queue}
or
/lol/league/v4/grandmasterleagues/by-queue/{queue} when migrating to v4
Note that Riot will change their api at the 24th of july 2017!
V1/V2 deprecation. quick overview:
This is a great package. You should take 10 minutes and turn this into a proper package, get it on PyPi so that it can be installed by pip.
Syntax error when try to execute following (Readme):
my_mastery_pages = w.get_mastery_pages([me['id', ])[str(me['id'])]
Use this:
my_mastery_pages = w.get_mastery_pages([me['id']])[str(me['id'])]
The URL given for this is lol/league/v3/leagues/by-summoner/`, it should be lol/league/v3/positions/by-summoner/
So I'm trying to extract the JSON values of champion and item data using DataDragonApi and I try assign the value to a variable like so
pChampdata = DataDragonApi(BaseApi).champions(gameVersion, full=True)
I get the following error
Python\Python36\lib\site-packages\riotwatcher\_apis\DataDragonApi.py, line 48, in _request return self._base_api.raw_request_static(url, query) TypeError: raw_request_static() missing 1 required positional argument: 'query_params'
Am I doing this wrong? Does DataDragonApi return dictionaries of the champion and item data? Thanks!
Would it be possible to update it? It is still impossible to install this library on Python 3.
EDIT: Actual pip command: pip3.5 install --user riotwatcher
Relevant source: https://github.com/pseudonym117/Riot-Watcher/blob/master/riotwatcher/riotwatcher.py#L179-L188
The biggest problem w/this for me -- although I imagine it could apply to a lot of other users -- is illustrated by the following example:
import logging
from riorwatcher.riotwatcher import RiotWatcher, LoLException
logger = logging.getLogger(__name__)
rw = RiotWatcher(api_key)
try:
result = rw.get_summoner(name='foo', region='bar')
except LoLException as e:
logger.exception('something happen')
# --- Logging error ---
# *** TypeError: unhashable type: 'LoLException'
The exception
method of python logger objects automatically includes the raised exception in output.
However, LoLException is unhashable, which causes a Logging error
to occur.
I have never run into an issue like this before, but a cursory googling reveals the following solution:
http://stackoverflow.com/questions/1608842/types-that-define-eq-are-unhashable-in-python-3-x
Sure enough, removing the __eq__
and __ne__
methods from LoLException makes the exception loggable via logger.exception
. To paraphrase the SO answer, if you wish to keep __eq__
the solution seems like simply defining __hash__
.
Official docs on __hash__
: https://docs.python.org/3/reference/datamodel.html#object.__hash__
As an aside, this is also problematic for task queues like celery
that must work w/raised exceptions during the processing of jobs, e.g. to retry a task that failed due to a rate limit exceeded error, etc.
In this page of the documentation:
StaticDataApiV3
In the function champions(region, locale=None, version=None, tags=None, data_by_id=None)
, the parameter data_by_id
is documented as having the type bool
. I tested and by using data_by_id=True
I got a Bad Request error. Changed it to data_by_id="true"
and it worked. This means that the wrapper is not converting from True to "true" and instead it's using the value directly into the URL. So in the URL it's becoming dataById=True
.
Is RiotWatcher using the values directly in the URL instead of converting from Python types to JSON types?
Hi! It's me again. I was wondering if Japan is going to be addded plus the unadded methodes like the one here
Thanks!
I'm getting an error that seemed to have been solved in issue #46 when I want to return "N/A" for summoners with no rank.
import riotwatcher
from riotwatcher import LoLException
w = RiotWatcher(self.config.lol_api_key)
for league in w.get_league_entry(args)[str(w.get_summoner(name=theName, region=theRegion))]:
try:
if league["queue"] == "RANKED_SOLO_5x5":
return league["entries"][0]["leaguePoints"])
else:
return "N/A"
except LoLException as e:
return "N/A"
yields me:
# --- Logging error ---
# *** TypeError: unhashable type: 'LoLException'
I can't figure out your code enough to add one myself. I keep getting simple python errors too.
The first one I've discovered is TEAM_BUILDER_DRAFT_RANKED_5x5
as a possible value for queue types. This is a valid value for the rankedQueues
param of Riot's API. It also appears as a value in Match and MatchList responses.
There is also TEAM_BUILDER_DRAFT_UNRANKED_5x5
. See https://developer.riotgames.com/docs/game-constants
As a side note, it appears that sending rankedQueues=TEAM_BUILDER_DRAFT_RANKED_5x5 to the matchlist endpoint results in a response containing ranked solo, 5s and dynamic queue matches.
I don't use the constants from riotwatcher, but if I feel I've found all the changes (these 2 may very well be it) I will submit a PR.
Hi,
the "watcher.match.matchlist_by_account_recent" api is broken; it seems Riot has changed its API URL routing. You can reproduce this by running the "full_test_RiotWatcher.py" unittest.
Just wanted to let you know that the matchhistory-v2.2 API endpoint will deprecated on 09/22/15, in case you did not know yet. Not sure if they will remove it completely on this date. There is just an innocent note saying "This API will be deprecated on 09/22/15." in https://developer.riotgames.com/api/methods#!/1025/3479
Hello,
I can't seem to get this package to import correctly.
Whenever I try from riotwatcher import RiotWatcher
I get an "Cannot import name RiotWatcher" error.
I tried installing the package via pip as well as manually via setup.py.
Do you have any ideas?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.