rhgrant10 / berserk Goto Github PK
View Code? Open in Web Editor NEWPython client for the lichess API
Home Page: https://berserk.readthedocs.io
License: Other
Python client for the lichess API
Home Page: https://berserk.readthedocs.io
License: Other
Follow the docs on the part of exporting games by player but is seems that since
and end
parameters is not working properly. I expected a subset of games filter by timestamp, instead got the max
of recent games .
start = berserk.utils.to_millis(datetime(2018, 12, 8))
end = berserk.utils.to_millis(datetime(2018, 12, 9))
games = list(client.games.export_by_player('LeelaChess', as_pgn=False, since=start, until=end,max=300))
print(len(games))
Output:
300
If I check the dates of the list I got:
print(games[0]['createdAt'], games[-1]['createdAt'])
Output:
2020-04-14 02:57:30.645000+00:00 2020-04-01 04:02:40.694000+00:00
Reading the docs the function berserk.utils.to_millis
look since
and until
as an int
value, start
and end
are float
. So I convert start
and until
to int
games = list(client.games.export_by_player('LeelaChess', as_pgn=False, since=int(start), until=int(end),max=300))
print(len(games))
Output:
291
And checking the dates
print(games[0]['createdAt'], games[-1]['createdAt'])
Output:
2018-12-09 03:43:47.412000+00:00 2018-12-08 08:00:12.072000+00:00
It's work now. I can try to fix it make a PR if you can guide me (this my first issue)
Description
Hello,
first of all thanks for this great Python API wrapper for the Lichess API - I really enjoy using it.
Some weeks ago lichess introduced the "board client" which I use to integrate it with my DGT Board.
I was happy to see that you already support this client but I am missing one method/command of the official lichess BOARD API: the seek command for creating an automatic challenge, see
https://lichess.org/api/board/seek
Is it possible that you include this method?
Thanks
Dirk
Berserk.py is my client to communicate with lichess.org. It works pretty well on my macbookpro but some how it doesn't work on ubuntu due to berserk package error. I tried with python 2.7 and python 3.6 and none worked. it throws ' berserk module not found' for python 3.6 whilst there is an exception on line 144 in clients.py of berserk module for python 2.7. error traces are below.
Can you support?
prod@PROD-512mb-lon1-01:/workspace/lichess$ pyhton Berserk.py/workspace/lichess$ python Berserk.py
-bash: pyhton: command not found
prod@PROD-512mb-lon1-01:
Traceback (most recent call last):
File "Berserk.py", line 2, in
import berserk
File "/home/prod/.local/lib/python2.7/site-packages/berserk/init.py", line 10, in
from .clients import Client # noqa: F401
File "/home/prod/.local/lib/python2.7/site-packages/berserk/clients.py", line 144
path = f'player/top/{count}/{perf_type}'
^
SyntaxError: invalid syntax
prod@PROD-512mb-lon1-01:/workspace/lichess$ python3.6 Berserk.py/workspace/lichess$ pip
Traceback (most recent call last):
File "Berserk.py", line 2, in
import berserk
ModuleNotFoundError: No module named 'berserk'
prod@PROD-512mb-lon1-01:
prod@PROD-512mb-lon1-01:/workspace/lichess$ pip install berserk/workspace/lichess$ pip3 install berserk
Requirement already satisfied: berserk in /home/prod/.local/lib/python2.7/site-packages (0.1.2)
Requirement already satisfied: ndjson==0.1.0 in /home/prod/.local/lib/python2.7/site-packages (from berserk) (0.1.0)
Requirement already satisfied: requests==2.18.4 in /home/prod/.local/lib/python2.7/site-packages (from berserk) (2.18.4)
Requirement already satisfied: certifi>=2017.4.17 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (2018.10.15)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (3.0.4)
Requirement already satisfied: idna<2.7,>=2.5 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (2.6)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (1.22)
prod@PROD-512mb-lon1-01:
Requirement already satisfied: berserk in /home/prod/.local/lib/python2.7/site-packages (0.1.2)
Requirement already satisfied: ndjson==0.1.0 in /home/prod/.local/lib/python2.7/site-packages (from berserk) (0.1.0)
Requirement already satisfied: requests==2.18.4 in /home/prod/.local/lib/python2.7/site-packages (from berserk) (2.18.4)
Requirement already satisfied: certifi>=2017.4.17 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (2018.10.15)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (3.0.4)
Requirement already satisfied: idna<2.7,>=2.5 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (2.6)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /home/prod/.local/lib/python2.7/site-packages (from requests==2.18.4->berserk) (1.22)
prod@PROD-512mb-lon1-01:~/workspace/lichess$ python3.6 Berserk.py
Traceback (most recent call last):
File "Berserk.py", line 2, in
import berserk
ModuleNotFoundError: No module named 'berserk'
Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
I am extracting my chess games with this code for over a year, but just 2 hours ago I got this error.
token = os.environ.get('TOKEN')
session = berserk.TokenSession(token)
client = berserk.Client(session=session)
extract = client.games.export_by_player('YourKingIsInDanger',
as_pgn=False, since=None, until=None, max=None, vs=None, rated=True,
perf_type=None, color=None, analysed=None, moves=True, tags=True,
evals=False, opening=True)
data = list(extract)
ValueError: invalid literal for int() with base 16: b''
During handling of the above exception, another exception occurred:InvalidChunkLength: InvalidChunkLength(got length b'', 0 bytes read)
During handling of the above exception, another exception occurred:ProtocolError: ("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))
During handling of the above exception, another exception occurred:ChunkedEncodingError: ("Connection broken: InvalidChunkLength(got length b'', 0 bytes read)", InvalidChunkLength(got length b'', 0 bytes read))
Trying yo to run this simple code on RPI4, but this error shows up:
code:
import berserk
session = berserk.TokenSession("my key lol")
client = berserk.Client(session=session)
challenge = client.challenges.create_open(900, 10, "standard")
print(challenge)
error
File "/home/blackbeard/Python/lichess.py", line 5, in <module>
challenge = client.challenges.create_open(900, 10, "standard")
File "/usr/local/lib/python3.9/dist-packages/berserk-0.10.0-py3.9.egg/berserk/clients.py", line 957, in create_open
File "/usr/local/lib/python3.9/dist-packages/berserk-0.10.0-py3.9.egg/berserk/session.py", line 72, in post
File "/usr/local/lib/python3.9/dist-packages/berserk-0.10.0-py3.9.egg/berserk/session.py", line 64, in request
File "/usr/local/lib/python3.9/dist-packages/berserk-0.10.0-py3.9.egg/berserk/formats.py", line 35, in handle
File "/usr/local/lib/python3.9/dist-packages/berserk-0.10.0-py3.9.egg/berserk/formats.py", line 76, in parse
File "/usr/lib/python3/dist-packages/requests/models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 542, in loads
return cls(encoding=encoding, **kw).decode(s)
TypeError: __init__() got an unexpected keyword argument 'encoding'
Hi,
Was wondering if I can trigger an analysis of a game using the API. This would help analyse all my games and see how I am improving by doing less mistakes. I may be able to do a little app even if that can work.
thanks.
HI.
I'm doing a physical chess board. I already use berserk for play in lichess. But i want to add the posibility to "save" the game, that maybe i play with a friend (face to face) on the physical board.
So. it is possible to do that?
i can log in with both players? (i dont know if this is a good aproach or possible because why make the game face to face, also a "online game", instead of just "upload/send" the moves without the lichess intervention?).
Thanks for your time.
I'm trying to get de recent activity of my account on lichess, but receive an error when looking for activity if user exists.
If user doesn't exists on Lichess, then I receive an empty response ( which seems OK for me )
def get_activity():
API_TOKEN = 'abcdef1234'
session = berserk.TokenSession(API_TOKEN)
client = berserk.Client(session=session)
print(client.users.get_activity_feed('username'))
if name == 'main':
get_activity()
C:\Users\user\Lichess\venv\Scripts\python.exe C:/Users/user/PycharmProjects/LichessGifDiscorder/main.py
Traceback (most recent call last):
File "C:\Users\user\Lichess\main.py", line 32, in <module>
get_activity()
File "C:\Users\user\Lichess\main.py", line 28, in get_activity
print(client.users.get_activity_feed('Pimy_1234'))
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\clients.py", line 235, in get_activity_feed
return self._r.get(path, converter=models.Activity.convert)
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\session.py", line 60, in get
return self.request('GET', *args, **kwargs)
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\session.py", line 56, in request
return fmt.handle(response, is_stream=is_stream, converter=converter)
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\formats.py", line 35, in handle
return converter(self.parse(response))
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\models.py", line 15, in convert
return [cls.convert_one(v) for v in data]
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\models.py", line 15, in <listcomp>
return [cls.convert_one(v) for v in data]
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\models.py", line 21, in convert_one
data[k] = cls.conversions[k](data[k])
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\utils.py", line 63, in convert
data[k] = func(data[k])
File "C:\Users\user\Lichess\venv\lib\site-packages\berserk\utils.py", line 25, in datetime_from_seconds
return datetime.fromtimestamp(ts, timezone.utc)
OSError: [Errno 22] Invalid argument
Process finished with exit code 1
installed berserk a few minutes ago
Describe what you were trying to get done.
import berserk
client = berserk.Client(berserk.SessionToken('...'))
client.account.get()
Tell us what happened, what went wrong, and what you expected to happen.
Traceback (most recent call last):
File "<input>", line 1, in <module>
client.account.get()
File "/usr/local/lib/python3.8/site-packages/berserk/clients.py", line 115, in get
return self._r.get(path, converter=models.Account.convert)
File "/usr/local/lib/python3.8/site-packages/berserk/session.py", line 60, in get
return self.request('GET', *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/berserk/session.py", line 56, in request
return fmt.handle(response, is_stream=is_stream, converter=converter)
File "/usr/local/lib/python3.8/site-packages/berserk/formats.py", line 35, in handle
return converter(self.parse(response))
File "/usr/local/lib/python3.8/site-packages/berserk/formats.py", line 76, in parse
return response.json(cls=self.decoder)
File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 889, in json
return complexjson.loads(
File "/usr/local/lib/python3.8/site-packages/simplejson/__init__.py", line 542, in loads
TypeError: __init__() got an unexpected keyword argument 'encoding'
error is happening somewhere deep in the simplejson code. uninstalling simplejson makes the function work, but I shouldn't need to do this - I use simplejson in many other places (and other libraries depend on it) and so this is a bug for me. I tried to debug it myself for a but but could not understand why this error was appearing - the parameters look fine.
berserk-downstream 0.11.6
3.9.5
Lichess API has sort
param: https://lichess.org/api#operation/apiUserCurrentGame
But berserk is throwing TypeError: export_by_player() got an unexpected keyword argument 'sort'
Tried to call:
games = client.games.export_by_player(
user_a,
vs=user_b,
since=start,
rated='true',
sort='dateAsc',
)
When using client.users.get_rating_hist() return value is a string with the list of the dict inside instead of the expected list.
This happened suddenly and thus it might be a lichess api change or bug.
import berserk
token = 'SUPER-SECRET-TOKEN'
session = berserk.TokenSession(token)
client = berserk.Client(session=session)
rating_hist = client.users.get_rating_history(username='someUserId')
type(rating_hist)
>>> <class str>
It seems that this issue is only impacting get_rating_history
other commands like get_live_streamers
are returning a list as expected
The mismatch between documentation and the code, namely https://berserk.readthedocs.io/en/master/api.html#berserk.clients.Games.export_by_player
The documentation states that it should accept the clocks
argument, but the method, actually, does not accept it.
Tried to get all members of a team with client.users.get_by_team(⟨teamName⟩)
Input:
client.users.get_by_team(⟨teamName⟩)
Outpurt:
berserk.exceptions.ResponseError: 404 Client Error: Not Found for url: https://lichess.org/team/⟨teamName⟩/users
In the official Lichess API documentation there is a paragraph about the openingExplorerLichess.
These features of the opening explorer for master and lichess games seem pretty useful so it would be great if these endpoints get added:
Hello.
I'm trying to make a match against the lichess AI.
like this:
reto = berserk.clients.Challenges(session)
(...)
reto.create_ai(level=6, clock_limit=None, clock_increment=None, days=None, color="black", variant=None, position=None)
but I have a problem ...
If I play with white against the AI everything works great. But, if the AI plays with white "my code" (actually is the code of "lichs") is broken ... this happens because the AI has neither "user" nor "id".
if player_id != client.games.export(event['game']['id'])['players']['white']['user']['id']:
Therefore, I thought about eliminating those fields (just to test ...), the error is not generated there but the AI move does not reach me. The AI moves for example e2e4 ... and it never reaches me. In fact, the AI movement only comes when I enter the website and cancel the game.
Thanks for your time.
I ask you if it occurs to you what could be happening. Maybe it's something related to Berserk ... maybe not.
Thanks a lot.
trying to get tournament data
Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
class LichessDataLoadService:
def init(self):
session = berserk.TokenSession(settings.BNL_TOKEN)
self.client = berserk.Client(session=session)
def get_tournament_data(self, tournament_id):
data = self.client.tournaments.get_tournament(tournament_id)
return data
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
File "/Users/givanov/PycharmProjects/bnl_landing/bnl_league/bnl_league/common/services/lichess_api_service.py", line 11, in get_tournament_data
data = self.client.tournaments.get_tournament(tournament_id)
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/clients.py", line 995, in get_tournament
return self._r.get(path, converter=models.Tournaments.convert_values)
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/session.py", line 60, in get
return self.request('GET', *args, **kwargs)
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/session.py", line 56, in request
return fmt.handle(response, is_stream=is_stream, converter=converter)
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/formats.py", line 35, in handle
return converter(self.parse(response))
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/models.py", line 27, in convert_values
data[k] = cls.convert(data[k])
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/models.py", line 16, in convert
return cls.convert_one(data)
File "/Users/givanov/PycharmProjects/bnl_landing/venv/lib/python3.8/site-packages/berserk/models.py", line 20, in convert_one
for k in set(data) & set(cls.conversions):
TypeError: 'int' object is not iterable
berserk version: 0.10.0
Python version: 3.9.2
Operating System: Manjaro Linux (last version)
Hello.
How do I know what kind of color is going to play in this kind of situation.
I mean a "challenge" with a random color.
I accept the challenge, and in the indications of the "challenge" I only see that it is random.
How can I find out what kind of color I got after accepting the challenge?
board = berserk.clients.Board(session)
reto = berserk.clients.Challenges(session)
for event in board.stream_incoming_events():
print (event)
if event['type'] == "challenge":
reto.accept(event['challenge']['id'])
{'type': 'challenge', 'challenge': {'id': 'bbbbbbb', 'url': 'https://lichess.org/bbbbbbbb', 'status': 'created', 'challenger': {'id': 'xxxxxxxx', 'name': 'xxxxxx', 'title': None, 'rating': 1500, 'provisional': True, 'online': True}, 'destUser': {'id': 'bbbbbbbb', 'name': 'bbbbbbb', 'title': None, 'rating': 1404, 'provisional': True, 'online': True}, 'variant': {'key': 'standard', 'name': 'Standard', 'short': 'Std'}, 'rated': False, 'speed': 'correspondence', 'timeControl': {'type': 'unlimited'}, 'color': 'random', 'perf': {'icon': ';', 'name': 'Correspondence'}}}
consider that code that performs two exports on same game :
for game in LICHESS.games.export_by_player(user, max=1):
print(game)
print(LICHESS.games.export(game['id']))
in the second print we have the info 'opening': {'eco': 'D30', 'name': "Queen's Gambit Declined", 'ply': 4},
, not available in the other.
Is that expected that information returned by export using id is more complete than the export_by_player
?
Challenge result does not indicate color correctly.
In [5]: chall.create_ai(level=2, clock_limit=None, color=berserk.Color.WHITE)
Out[5]:
{'id': 'UMpK5lST',
'variant': {'key': 'standard', 'name': 'Standard', 'short': 'Std'},
'speed': 'correspondence',
'perf': 'correspondence',
'rated': False,
'fen': 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
'player': 'white',
'turns': 0,
'startedAtTurn': 0,
'source': 'ai',
'status': {'id': 20, 'name': 'started'},
'createdAt': 1639302816645}
In [6]: chall.create_ai(level=2, clock_limit=None, color=berserk.Color.BLACK)
Out[6]:
{'id': '3VdaeZQb',
'variant': {'key': 'standard', 'name': 'Standard', 'short': 'Std'},
'speed': 'correspondence',
'perf': 'correspondence',
'rated': False,
'fen': 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
'player': 'white',
'turns': 0,
'startedAtTurn': 0,
'source': 'ai',
'status': {'id': 20, 'name': 'started'},
'createdAt': 1639302860353}
Two AI games were challenged, one with white one with black. As you can see the returned "player" slot is always white.
Games export API expects integer timestamps, but berserk sends floats.
If you go here: https://lichess.org/api#operation/apiGamesUser
You see that since
and until
expect integers.
utils.to_millis(dt)
does not return integer seconds, it returns floats, per https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp
As is, the berserk timestamps are completely ignored.
Try running the example from the docs, but I changed to a 10 minute window:
start = berserk.utils.to_millis(dt.datetime(2018, 12, 8, 1, 10))
end = berserk.utils.to_millis(dt.datetime(2018, 12, 8, 1, 20))
print(f'Query from {start} to {end}')
games = lichess.games.export_by_player('LeelaChess', since=start, until=end, max=300)
print(f'Found {len(list(games))} Leela games')
start, end = int(start), int(end) # Convert to ints
print(f'Query from {start} to {end}')
games = lichess.games.export_by_player('LeelaChess', since=start, until=end, max=300)
print(f'Found {len(list(games))} Leela games')
Output:
Query from 1544260200000.0 to 1544260800000.0
Found 300 Leela games # Hit max!
Query from 1544260200000 to 1544260800000
Found 3 Leela games # Presumably correct
I don't know if this is the best place to post this:
A discord group we have called 'the vat' would like to create a discord bot that can automatically launch games from Lichess and send links to players for them to play game as a way to settle arguments. We looked over the api and it didn't seem that there was a way to make this happen. There is a way to play against a bot on one side?
Took a look at the resource page.
The session header for authentication seems not to be used consequently.
Trying to let two bots play against each other. Some requests for the other bot are denied (so I assume see #6 ) due to invalid session handling.
There is a new API
https://lichess.org/api#tag/Broadcasts
Asked for broadcast api support and
I am trying to create a future dated tournament. I am having trouble passing a date. I have created a future date using date_time, converted it to timestamp, then cast to integer and string. The call fails saying the date is not in the future.
Love the work being done here with Berserk BTW and I am also new to Python so apologies if i have missed something obvious ...
this was run on 31/1/21
relevant code fragments as follows
tourney_date = datetime(2021, 2, 1, 8, 00, 00)
datetime.fromtimestamp(int(tourney_date.timestamp())))
td_int = int(tourney_date.timestamp())
td_int_as_str = str(td_int)
tournament = client.tournaments.create(clock_time=2, clock_increment=3, minutes=30,
berserkable = "true",
start_date = td_int_as_str ,
password="mdntest",
conditions=myconditions)
Traceback (most recent call last):
File "d:\users\nigel\appdata\local\programs\python\python38-32\lib\site-packages\berserk\exceptions.py", line 63, in _catch_exception
response.raise_for_status()
File "d:\users\nigel\appdata\local\programs\python\python38-32\lib\site-packages\requests\models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://lichess.org/api/tournament
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\Users\Nigel\AppData\Local\Programs\Python\Python38-32\Requests.py", line 117, in <module>
tournament = client.tournaments.create(clock_time=2, clock_increment=3, minutes=30,
File "d:\users\nigel\appdata\local\programs\python\python38-32\lib\site-packages\berserk\clients.py", line 933, in create
return self._r.post(path, json=payload,
File "d:\users\nigel\appdata\local\programs\python\python38-32\lib\site-packages\berserk\session.py", line 64, in post
return self.request('POST', *args, **kwargs)
File "d:\users\nigel\appdata\local\programs\python\python38-32\lib\site-packages\berserk\session.py", line 54, in request
raise exceptions.ResponseError(response)
berserk.exceptions.ResponseError: HTTP 400: Bad Request: {'startDate': ['**The date must be set in the future'**], 'error': {'startDate': ['The date must be set in the future']}}
The timestamp types are not consistent between the services. While 'get_activity_feed(username)' returns timestamp in the format of python, 'export_by_player' returns Javascript timestamp.
Describe what you were trying to get done.
1- The ''export_by_player' API returns the timestamp value of milliseconds for 'createAt' parameter , e.g. '1541551788049' whereas the 'get_activity_feed(username)' API returns timestamp without milliseconds which compliance with python datetime parsers, e.g. '1541548800'
I had to divide the timestamp values with '1000' if they have milliseconds as explained below.
JavaScript timestamp to Python datetime conversion: https://stackoverflow.com/questions/10286224/javascript-timestamp-to-python-datetime-conversion
Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
Im using lichs (https://github.com/Cqsi/lichs).
On windows works perfect, also on Archlinux.
On my raspberry pi with raspbian (after put the token from lichess) i get this, what can i do?:
pi@chess:~/.local/bin $ python3 lichs
Traceback (most recent call last):
File "lichs", line 10, in <module>
sys.exit(main())
File "/home/pi/.local/lib/python3.7/site-packages/lichs/__main__.py", line 34, in main
account_data = client.account.get()
File "/home/pi/.local/lib/python3.7/site-packages/berserk/clients.py", line 115, in get
return self._r.get(path, converter=models.Account.convert)
File "/home/pi/.local/lib/python3.7/site-packages/berserk/session.py", line 60, in get
return self.request('GET', *args, **kwargs)
File "/home/pi/.local/lib/python3.7/site-packages/berserk/session.py", line 56, in request
return fmt.handle(response, is_stream=is_stream, converter=converter)
File "/home/pi/.local/lib/python3.7/site-packages/berserk/formats.py", line 35, in handle
return converter(self.parse(response))
File "/home/pi/.local/lib/python3.7/site-packages/berserk/formats.py", line 76, in parse
return response.json(cls=self.decoder)
File "/usr/lib/python3/dist-packages/requests/models.py", line 889, in json
self.content.decode(encoding), **kwargs
File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 535, in loads
return cls(encoding=encoding, **kw).decode(s)
TypeError: __init__() got an unexpected keyword argument 'encoding'
Thanks!
Hey rhgrant10, lichess dev here,
We’re currently trying to improve Lichess API support for Python and specifically your berserk library since it's currently the most widely used and feature-complete Lichess API Python library. As you may or may not know, there is a fork of your work with patches for the latest updates: https://github.com/ZackClements/berserk, named berserk-downstream on pypi. However, users frequently download berserk instead which leads to confusion and a subpar experience. We'd like to improve this situation and ensure that berserk will continue to be maintained well in the future.
Therefore we'd like to ask whether you'd be willing to hand off the berserk pypi namespace to lichess.org? That way we would ensure it’s kept up to date.
You can also contact us at [email protected] or on the official Lichess Discord or contact a dev (preferably Solal35: https://lichess.org/@/Solal35 or benwerner: https://lichess.org/@/benwerner) on lichess.org.
Thank you again for your work!
Why i'm getting this errors sometimes, what could be that is generating this:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.7/http/client.py", line 1336, in getresponse
response.begin()
File "/usr/lib/python3.7/http/client.py", line 306, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.7/http/client.py", line 275, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response
```
`
trying to create a customized challenge.
client.challenges.create(username="tschmoderer", rated=False, clock_limit=300, clock_increment=1)
no crash but the options were not taken into account. i got a correspondence unlimited challenge.
When retrieving the rating history for a user, which works for many users, hit the following error. You can reproduce with user IDs A23012011 and AboodSalah.
history = client.users.get_rating_history(user)
File "/home/mike/.local/lib/python3.8/site-packages/berserk/clients.py", line 298, in get_rating_history
return self._r.get(path, converter=models.RatingHistory.convert)
File "/home/mike/.local/lib/python3.8/site-packages/berserk/session.py", line 60, in get
return self.request('GET', *args, **kwargs)
File "/home/mike/.local/lib/python3.8/site-packages/berserk/session.py", line 56, in request
return fmt.handle(response, is_stream=is_stream, converter=converter)
File "/home/mike/.local/lib/python3.8/site-packages/berserk/formats.py", line 35, in handle
return converter(self.parse(response))
File "/home/mike/.local/lib/python3.8/site-packages/berserk/formats.py", line 76, in parse
return response.json(cls=self.decoder)
File "/home/mike/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 370, in loads
return cls(**kw).decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
According to https://lichess.org/api some calls will return error information with a 404 status code e.g. "Authorization header missing".
def abort(self):
try:
self.client.bots.abort_game(self.game_id)
return True
except requests.exceptions.HTTPError as httpError:
return self.handle(httpError)
def handle(self,httpError):
if self.debug:
print (httpError)
return False
The httpError does not seem to carry any detail information which might be necessary for a proper control flow.
This is probably my own stupidity rather than an issue, but when trying to use berserk with Oauth2 authentication, I can't seem to get it working as it's unable to work with the code_challenge required for lichess. The documentation states that this is outside the scope of the project, but adding a simple example for how this should be done would be very helpful.
The function rated contains the boolean parameter rated, which takes the values True for rated games and False for casual games. But if you pass this argument as True/False, as the documentation says, then only casual games will be obtained. This parameter will work correctly only if you pass the string value "true"/"false".
import berserk
token = 'TOKEN'
session = berserk.TokenSession(token)
client = berserk.Client(session=session)
client.games.export_by_player(username='USERNAME', max=1, rated=True) # {..., 'rated': False, ...}
client.games.export_by_player(username='USERNAME', max=1, rated='true') # {..., 'rated': True, ...}
This is kind of checking if the idea is possible. Alexa skills are code (e.g. Python) hosted in the cloud, and are invoked by Alexa speech recognition. Provided someone has given their Lichess login credentials to the skill, do you think it possible they can play a game against the engine, unlimited time control? Do you see fundamental problems invoking the API from the cloud to do this? I'm a bit wobbly with this as I'm more of a desktop dev, less a web dev.
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.