chesssnake docs

Python client

pip install 'chesssnake[client]' lets your code play games on a chesssnake server. The server checks every move, so your program and its opponent always agree on the game.

from chesssnake import Game, connect

client = connect("https://chess.example", username="alice", password="...")
state = client.current_games()[0]         # a game in progress
game = Game.remote(state, client=client)
game.move("e4")

Connecting

connect(api_url) returns a logged-in client. It takes the first of these it finds:

  1. username= and password=
  2. token=, an api token: the right choice for a script
  3. the CHESSSNAKE__CLIENT__TOKEN environment variable
  4. the login chesssnake login stored for that server

api_url can be left out when CHESSSNAKE__CLIENT__API_URL is set. If no login is found, it raises AuthError.

Async

For an asyncio program (most chat bots, web servers), ask for the async client. It has every method of the blocking one, with the same names and arguments; you await them:

client = connect("https://chess.example", token="css_...", asynchronous=True)

async with client:
    state = await client.get_game(41)
    result = await client.move(state, "e4")

It cannot log in with a password inside connect, which is not async: pass a token, or make AsyncApiClient(url) and await client.login(username, password). Game.remote is blocking only; with the async client, work with the game state the methods return.

Starting a game

Games start with a challenge that the other player accepts:

challenge = alice.challenge("bob", color="white")     # or "black", "random"

# as bob:
bob.challenges(direction="incoming")
state = bob.accept_challenge(challenge.id)            # the game starts
# or bob.decline_challenge(challenge.id); alice can withdraw_challenge(...)

Players are given by username or id. Two players can have one game in progress at a time.

Playing

Game.remote(game_id_or_state, client=client) is a Game whose moves go to the server. Everything on the Python library page works on it: move, legal_moves, render, save, fen, pgn, the state properties.

game = Game.remote(41, client=client)

game.move("e4")          # raises the same errors as a local game
game.refresh()           # fetch the latest state, e.g. the opponent's move
game.to_move, game.is_over, game.winner

game.offer_draw()        # you act as yourself: no player id needed
game.resign()

Besides chess errors, a move can raise NotYourTurnError, and VersionConflictError when the game changed since you last looked: call refresh() and decide again. These are in chesssnake.db.errors.

A finished game keeps its id and stays readable. A rematch is a new challenge.

Game state

Methods that return a game give a GameState. Besides its fields (the REST API’s data), it answers the usual questions with the library’s enums, so you never read the FEN yourself:

state = client.get_game(41)
state.to_move            # Color.WHITE or Color.BLACK
state.is_over, state.result, state.winner, state.ending   # GameStatus, Color, Termination
state.draw_offered_by    # Color, or None
state.last_move          # {"from": "e2", "to": "e4", "san": "e4", "promotion": None}
state.color_of(user_id), state.player_id(Color.WHITE), state.player_name("black")

Waiting for the opponent

Either poll:

import time

while game.to_move != my_color and not game.is_over:
    time.sleep(5)
    game.refresh()

or, when the server has live updates on, be told:

import select

with client.events(games=[game.id]) as stream:    # RealtimeUnavailable if they are off
    while not game.is_over:
        select.select([stream.fileno()], [], [])
        for event in stream.drain():
            if event["type"] == "game":
                game.refresh()

With the async client the stream is an async iterator:

async with client.events(games=[41]) as stream:
    async for event in stream:
        if event["type"] == "game":
            print(event["state"]["last_move"])

The stream reconnects by itself. The events are described in Websocket API; the stream adds disconnected, reconnected, ended and auth_error of its own.

An administrator can stream.follow(all=True) to hear every game on the server, and a group admin can stream.follow(group=7) for their group, instead of subscribing to games one by one (with the async stream, await both).

Everything else

The client has a method for everything the server can do.

  Methods
The server info() (needs no login)
You me(), change_password(current, new), settings(), update_settings(...), link_code(), logout()
Tokens create_token(name, current_password, expires_in_days=None), tokens(), revoke_token(id)
Challenges challenge(opponent, group_id=0, color="random"), challenges(direction="all"), get_challenge(id), accept_challenge(id), decline_challenge(id), withdraw_challenge(id)
Finding games current_games(), get_game(id), live_games(limit=50, group_id=None), finished_games(player=None, limit=50, before=None, group_id=None), games_between(a, b), record(a, b)
One game move(id, move), resign(id), offer_draw(id), accept_draw(id), decline_draw(id), legal_moves(id), history(id), pgn(id), fen(id), image(id, perspective=None)
Users get_user(name_or_id), search_users(query="", limit=20, offset=0)
Group admins create_game(white, black, group_id), delete_game(id), and acting for players in their group (see Bots)
Administrators create_user(username, password=None, role="user"), update_user(id, username=, role=, disabled=, password=), group_admins(group), add_group_admin(group, user), remove_group_admin(group, user), and the identity methods in Bots

They return small objects with the same fields as the REST API’s data: GameState, MoveResult, User, Challenge.

client.record("alice", "bob")
# {"player1": 1, "player2": 2, "player1_wins": 3, "player2_wins": 1, "draws": 2}

open("board.png", "wb").write(client.image(41, perspective="white"))

To test code that uses the client against a real server, see Testing.