Giter VIP home page Giter VIP logo

berserk's Introduction

berserk

Available on PyPI

Continuous Integration

Code Coverage

Documentation Status

Python client for the Lichess API (modified).

Features

  • handles JSON and PGN formats at user's discretion
  • token auth session
  • easy integration with OAuth2
  • automatically converts time values to datetimes

Usage

You can use any requests.Session-like object as a session, including those from requests_oauth. A simple token session is included, as shown below:

import berserk

session = berserk.TokenSession(API_TOKEN)
client = berserk.Client(session=session)

Most if not all of the API is available:

client.account.get
client.account.get_email
client.account.get_preferences
client.account.get_kid_mode
client.account.set_kid_mode
client.account.upgrade_to_bot

client.users.get_puzzle_activity
client.users.get_realtime_statuses
client.users.get_all_top_10
client.users.get_leaderboard
client.users.get_public_data
client.users.get_activity_feed
client.users.get_by_id
client.users.get_by_team
client.users.get_live_streamers
client.users.get_users_followed
client.users.get_users_following
client.users.get_rating_history

client.teams.get_members
client.teams.join
client.teams.leave
client.teams.kick_member

client.games.export
client.games.export_by_player
client.games.export_multi
client.games.get_among_players
client.games.get_ongoing
client.games.get_tv_channels

client.challenges.create
client.challenges.create_ai
client.challenges.create_open
client.challenges.create_with_accept
client.challenges.accept
client.challenges.decline

client.board.stream_incoming_events
client.board.seek
client.board.stream_game_state
client.board.make_move
client.board.post_message
client.board.abort_game
client.board.resign_game
client.board.handle_draw_offer
client.board.offer_draw
client.board.accept_draw
client.board.decline_draw

client.bots.stream_incoming_events
client.bots.stream_game_state
client.bots.make_move
client.bots.post_message
client.bots.abort_game
client.bots.resign_game
client.bots.accept_challenge
client.bots.decline_challenge

client.tournaments.get
client.tournaments.create
client.tournaments.export_games
client.tournaments.stream_results
client.tournaments.stream_by_creator

client.broadcasts.create
client.broadcasts.get
client.broadcasts.update
client.broadcasts.push_pgn_update

client.simuls.get

client.studies.export_chapter
client.studies.export

Details for each function can be found in the full documentation.

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

berserk's People

Contributors

dependabot[bot] avatar haklein avatar jrwaine avatar kraktus avatar rhgrant10 avatar rpgraham84 avatar virinas-code 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

berserk's Issues

Use discord to launch lichess game and invite players to play, then be able to grab the game information after .

  • berserk version:
  • Python version:
  • Operating System:

Description

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?

What I Did

Took a look at the resource page.

Play against AI problem.

  • berserk version: 0.10.0
  • Python version: 3.9.2
  • Operating System: Manjaro Linux (last version)

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.

http.client.RemoteDisconnected: Remote end closed connection without response

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
```
`

error messages for 400 return codes

  • berserk version: 0.3.1
  • Python version: 3.7.4
  • Operating System: Mac OS

Description

According to https://lichess.org/api some calls will return error information with a 404 status code e.g. "Authorization header missing".

What I Did

   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.

Parameter of export_by_player since, end not working like documentation

  • berserk version: 0.10.0
  • Python version: Python 3.8.5
  • Operating System: Windows 10

Description

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 .

What I Did

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)

export_by_player incorrect work of a boolean argument rated

  • berserk version: 0.10.0
  • Python version: 3.9
  • Operating System: Windows

Description

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".

What I Did

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, ...}

Missing important method of the official "BOARD" Lichess API in Berserk

  • berserk version:8
  • Python version:
  • Operating System:

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

board seek function increment parameter in seconds, not minutes

  • berserk version: 0.10.0
  • Python version: 3.10
  • Operating System: Linux

Description

In the docs, the seek function is described to take time and increment in minutes.
image

While the Lichess API says that increment is taken in seconds, which makes sense.
image

What I Did

N/A

Timestamp inconsistency between the services

  • berserk version:0.1.2
  • Python version:3.6.4
  • Operating System:MacOs Mojave Version 10.14

Description

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'

What I Did

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.

Lichess improving berserk UX

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!

using API from Alexa skill to play unlimited engine game

  • berserk version:
  • Python version:
  • Operating System:

Description

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.

Challenge result does not reflect color

  • berserk version: master
  • Python version: 3.6.12
  • Operating System: OpenSuSE Leap

Description

Challenge result does not indicate color correctly.

What I Did

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.

error on fresh install with simplejson

  • berserk version: 0.10.0
  • Python version: 3.8.5
  • Operating System: Mac OS 10.13

Description

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 module not found

  • berserk version:
  • Python version:3.6 and 2.7
  • Operating System:ubuntu 16.04

Description

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?

What I Did

prod@PROD-512mb-lon1-01:/workspace/lichess$ pyhton Berserk.py
-bash: pyhton: command not found
prod@PROD-512mb-lon1-01:
/workspace/lichess$ python Berserk.py
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
Traceback (most recent call last):
File "Berserk.py", line 2, in
import berserk
ModuleNotFoundError: No module named 'berserk'
prod@PROD-512mb-lon1-01:
/workspace/lichess$ pip

prod@PROD-512mb-lon1-01:/workspace/lichess$ pip 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:
/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:~/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.

Challenges not customizable

  • berserk version:0.3.1
  • Python version:3.7
  • Operating System: Ubuntu 19.04

Description

trying to create a customized challenge.

What I Did

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.

Cannot create future dated tournament

  • berserk version:
  • Python version: 3.8
  • Operating System: Windows

Description

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 ...

What I Did

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']}}

ChunkedEncodingError While extracting the data

  • berserk version: 0.10.0
  • Python version: 3.9.13
  • Operating System: MacOS

Description

I am extracting my chess games with this code for over a year, but just 2 hours ago I got this error.

What I Did

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))

JSONDecodeError in get_rating_history

  • berserk version: 0.8.0
  • Python version: 3.8
  • Operating System: Linux

Description

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.

What I Did

    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)

Can't call get_activity_feed

  • berserk version: berserk-downstream:0.11.6
  • Python version: Python 3.9.5
  • Operating System: Windows 10

Description

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 )

What I Did

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

Games exported via `export_by_player` have no opening info

  • berserk version: 0.3.1

Description

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 ?

Get tournament bug

  • berserk version: 0.11.8
  • Python version: 3.8
  • Operating System: macOS monterrey 12.1

Description

trying to get tournament data

What I Did

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

inconsistent usage of session headers/authentication?

  • berserk version: 0.3.1
  • Python version: 3.7.4
  • Operating System: Mac OS

Description

The session header for authentication seems not to be used consequently.

What I Did

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.

[Feature request] Trigger an analysis

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.

got an unexpected keyword argument 'encoding'

  • berserk version: 0.10.0
  • Python version: python 3.7.3
  • Operating System:Raspbian

Description

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!

get_rating_hist returns raw json string instead of list

  • berserk version: 0.10.0
  • Python version: 3.7.1
  • Operating System: Windows

Description

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.

What I Did

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

client.users.get_by_team(⟨teamName⟩) does not work

  • berserk version: 0.10.0
  • Python version: 3.8.2
  • Operating System: Win 10

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

Berserk `since` and `until` should be integers

  • berserk version: berserk-downstream 0.11.6
  • Python version: Python 3.9.5
  • Operating System: Mac

Description

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.

What I Did

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

TypeError using create_open meathod on raspian with Python 3.9 and lastest bersek version

  • berserk version: latest
  • Python version: 3.9
  • Operating System: raspian

Description

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'

How know the type of color on a challenge Random Color?

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'}}}

Two users at the same time?

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.

Oauth2

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.

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.