I am writing an application that interacts with Lichess. However when I use the API to get game state, I must use
for event in client.bots.stream_game_state(game_id):
as provided by the documentation. In fact, this is exactly the code they use in their example. However, I get the following error:
HTTPError: 400 Client Error: Bad Request for url: https://lichess.org/api/bot/game/stream/8Kjolz4k
Here is my code:
# Type "!pip install berserk" in Console to get berserk module
import berserk
import time
import threading
# Initiate a session with my personal API token
token = "***************"
session = berserk.TokenSession(token)
client = berserk.Client(session)
# Stream whats happening and continue when we are challenged
in_game = False
while(not in_game):
time.sleep(0.5)
for event in client.bots.stream_incoming_events():
if event['type'] == 'gameStart':
game_id = event['game']['id']
in_game = True
break
elif event['type'] == 'challenge':
game_id = event['challenge']['id']
client.bots.accept_challenge(game_id)
in_game = True
print("The game has started!")
# Stream the events of the game and respond accordingly
playing = True
while(playing):
for event in client.bots.stream_game_state(game_id):
if event['type'] == 'gameFull':
if client.account.get()['username'] == event['white']['id']:
client.bots.post_message(game_id, "I got first, nerd!")
else:
client.bots.post_message(game_id, "You got first, nerd!")
I don't know why your code was failing at the time. The 400 response can be catched like this (example for an abort call):
Please find below a slightly modified version that works for me in the context of Play-Chess-With-A-WebCam (where I am a committer). You need a config.yaml file in ~/.pcwawc/config.yaml with your token:
The result of the test is:
test_lichess
test_stream()
lichess.py
excerpt of requirements.txt: