Developer Interface

Clients

class berserk.clients.Account(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for account-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

get() AccountInformation[source]

Get your public information.

Returns:

public information about the authenticated user

Return type:

AccountInformation

get_email() str[source]

Get your email address.

Returns:

email address of the authenticated user

Return type:

str

get_kid_mode() bool[source]

Get your kid mode status.

Returns:

current kid mode status

Return type:

bool

get_preferences() Preferences[source]

Get your account preferences.

Returns:

preferences of the authenticated user

Return type:

Preferences

set_kid_mode(value: bool) None[source]

Set your kid mode status.

Parameters:

value (bool) – whether to enable or disable kid mode

Return type:

None

upgrade_to_bot()[source]

Upgrade your account to a bot account.

Requires bot:play oauth scope. User cannot have any previously played games.

class berserk.clients.Analysis(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for analysis-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

get_cloud_evaluation(fen: str, num_variations: int = 1, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] = 'standard') PositionEvaluation[source]

Get the cached evaluation of a position, if available.

Opening positions have more chances of being available. There are about 15 million positions in the database. Up to 5 variations may be available. Variants are supported.

Parameters:
  • fen (str) – FEN of a position

  • num_variations (int) – number of variations

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard']) – game variant to use

Returns:

cloud evaluation of a position

Return type:

PositionEvaluation

class berserk.clients.Board(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for physical board or external application endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

abort_game(game_id: str) None[source]

Abort a board game.

Parameters:

game_id (str) – ID of a game

Return type:

None

accept_draw(game_id: str) None[source]

Accept an already offered draw in the given game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

accept_takeback(game_id: str) None[source]

Accept an already offered takeback in the given game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

claim_victory(game_id: str) None[source]

Claim victory when the opponent has left the game for a while.

Generally, this should only be called once the opponentGone event is received in the board game state stream and the claimWinInSeconds time has elapsed.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

decline_draw(game_id: str) None[source]

Decline an already offered draw in the given game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

decline_takeback(game_id: str) None[source]

Decline an already offered takeback in the given game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

get_game_chat(game_id: str) List[Dict[str, str]][source]

Get the messages posted in the game chat.

Parameters:

game_id (str) – ID of a game

Returns:

list of game chat events

Return type:

List[Dict[str, str]]

go_berserk(game_id: str) None[source]

Go berserk on an arena tournament game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

handle_draw_offer(game_id: str, accept: bool) None[source]

Create, accept, or decline a draw offer.

To offer a draw, pass accept=True and a game ID of an in-progress game. To response to a draw offer, pass either accept=True or accept=False and the ID of a game in which you have received a draw offer.

Often, it’s easier to call offer_draw(), accept_draw(), or decline_draw().

Parameters:
  • game_id (str) – ID of an in-progress game

  • accept (bool) – whether to accept

Return type:

None

handle_takeback_offer(game_id: str, accept: bool) None[source]

Create, accept, or decline a takeback offer.

To offer a takeback, pass accept=True and a game ID of an in-progress game. To response to a takeback offer, pass either accept=True or accept=False and the ID of a game in which you have received a takeback offer.

Often, it’s easier to call offer_takeback(), accept_takeback(), or decline_takeback().

Parameters:
  • game_id (str) – ID of an in-progress game

  • accept (bool) – whether to accept

Return type:

None

make_move(game_id: str, move: str) None[source]

Make a move in a board game.

Parameters:
  • game_id (str) – ID of a game

  • move (str) – move to make

Return type:

None

offer_draw(game_id: str) None[source]

Offer a draw in the given game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

offer_takeback(game_id: str) None[source]

Offer a takeback in the given game.

Parameters:

game_id (str) – ID of an in-progress game

Return type:

None

post_message(game_id: str, text: str, spectator: bool = False) None[source]

Post a message in a board game.

Parameters:
  • game_id (str) – ID of a game

  • text (str) – text of the message

  • spectator (bool) – post to spectator room (else player room)

Return type:

None

resign_game(game_id: str) None[source]

Resign a board game.

Parameters:

game_id (str) – ID of a game

Return type:

None

seek(time: int, increment: int, rated: bool = False, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] = 'standard', color: Literal['white', 'black'] | Literal['random'] = 'random', rating_range: str | Tuple[int, int] | List[int] | None = None) float[source]

Create a public seek to start a game with a random opponent.

Parameters:
  • time (int) – initial clock time in minutes

  • increment (int) – clock increment in minutes

  • rated (bool) – whether the game is rated (impacts ratings)

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard']) – game variant to use

  • color (Literal['white', 'black'] | ~typing.Literal['random']) – color to play

  • rating_range (str | Tuple[int, int] | List[int] | None) – range of opponent ratings

Returns:

duration of the seek

Return type:

float

stream_game_state(game_id: str) Iterator[Dict[str, Any]][source]

Get the stream of events for a board game.

Parameters:

game_id (str) – ID of a game

Returns:

iterator over game states

Return type:

Iterator[Dict[str, Any]]

stream_incoming_events() Iterator[Dict[str, Any]][source]

Get your realtime stream of incoming events.

Returns:

stream of incoming events

Return type:

Iterator[Dict[str, Any]]

class berserk.clients.Bots(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for bot-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

abort_game(game_id: str) None[source]

Abort a bot game.

Parameters:

game_id (str) – ID of a game

Return type:

None

accept_challenge(challenge_id: str) None[source]

Accept an incoming challenge.

Parameters:

challenge_id (str) – ID of a challenge

Return type:

None

decline_challenge(challenge_id: str, reason: Literal['generic', 'later', 'tooFast', 'tooSlow', 'timeControl', 'rated', 'casual', 'standard', 'variant', 'noBot', 'onlyBot'] = 'generic') None[source]

Decline an incoming challenge.

Parameters:
  • challenge_id (str) – ID of a challenge

  • reason (Literal['generic', 'later', 'tooFast', 'tooSlow', 'timeControl', 'rated', 'casual', 'standard', 'variant', 'noBot', 'onlyBot']) – reason for declining challenge

Return type:

None

get_online_bots(limit: int | None = None) Iterator[Dict[str, Any]][source]

Stream the online bot users.

Parameters:

limit (int | None) – Maximum number of bot users to fetch

Returns:

iterator over online bots

Return type:

Iterator[Dict[str, Any]]

make_move(game_id: str, move: str) None[source]

Make a move in a bot game.

Parameters:
  • game_id (str) – ID of a game

  • move (str) – move to make

Return type:

None

post_message(game_id: str, text: str, spectator: bool = False)[source]

Post a message in a bot game.

Parameters:
  • game_id (str) – ID of a game

  • text (str) – text of the message

  • spectator (bool) – post to spectator room (else player room)

resign_game(game_id: str) None[source]

Resign a bot game.

Parameters:

game_id (str) – ID of a game

Return type:

None

stream_game_state(game_id: str) Iterator[Dict[str, Any]][source]

Get the stream of events for a bot game.

Parameters:

game_id (str) – ID of a game

Returns:

iterator over game states

Return type:

Iterator[Dict[str, Any]]

stream_incoming_events() Iterator[Dict[str, Any]][source]

Get your realtime stream of incoming events.

Returns:

stream of incoming events

Return type:

Iterator[Dict[str, Any]]

class berserk.clients.Broadcasts(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Broadcast of one or more games.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

create(name: str, description: str, auto_leaderboard: bool, markdown: str | None = None, tier: int | None = None, players: List[BroadcastPlayer] | None = None) Dict[str, Any][source]

Create a new broadcast.

Parameters:
  • name (str) – name of the broadcast

  • description (str) – short description

  • auto_leaderboard (bool) – simple leaderboard based on game results

  • markdown (str | None) – long description

  • tier (int | None) – can only be used by Lichess staff accounts: 3 for normal, 4 for high, 5 for best

  • players (List[BroadcastPlayer] | None) – replace player names, ratings and titles. One line per player, formatted as such: Original name; Replacement name; Optional rating; Optional title

Returns:

created tournament info

Return type:

Dict[str, Any]

create_round(broadcast_id: str, name: str, syncUrl: str | None = None, syncUrlRound: str | None = None, startsAt: int | None = None, delay: int | None = None, period: int | None = None, finished: bool | None = None) Dict[str, Any][source]

Create a new broadcast round to relay external games.

Parameters:
  • broadcast_id (str) – broadcast tournament ID

  • name (str) – Name of the broadcast round

  • syncUrl (str | None) – URL that Lichess will poll to get updates about the games

  • syncUrlRound (str | None) – required if syncUrl contains a LiveChessCloud link

  • startsAt (int | None) – Timestamp in milliseconds of broadcast round start

  • delay (int | None) – how long to delay moves coming from the source in seconds

  • period (int | None) – how long to wait between source requests in seconds

  • finished (bool | None) – set whether the round is completed

Returns:

broadcast round info

Return type:

Dict[str, Any]

get(broadcast_id: str) Dict[str, Any][source]

Get a broadcast by ID.

Parameters:
  • broadcast_id (str) – ID of a broadcast

  • slug – slug for SEO

Returns:

broadcast information

Return type:

Dict[str, Any]

get_official(nb: int | None = None, leaderboard: bool | None = None) Iterator[Dict[str, Any]][source]

Get the list of incoming, ongoing, and finished official broadcasts. Sorted by start date, most recent first.

Parameters:
  • nb (int | None) – maximum number of broadcasts to fetch, default is 20

  • leaderboard (bool | None) – include the leaderboards, if available

Returns:

iterator over broadcast objects

Return type:

Iterator[Dict[str, Any]]

get_pgns(broadcast_id: str) Iterator[str][source]

Get all games of all rounds of a broadcast in PGN format.

Parameters:

broadcast_id (str) – the broadcast ID

Returns:

iterator over all games of the broadcast in PGN format

Return type:

Iterator[str]

get_round(broadcast_id: str) Dict[str, Any][source]

Get information about a broadcast round.

Parameters:

broadcast_id (str) – broadcast round ID (8 characters)

Returns:

broadcast round info

Return type:

Dict[str, Any]

get_round_pgns(broadcast_round_id: str) Iterator[str][source]

Get all games of a single round of a broadcast in PGN format.

Parameters:

broadcast_round_id (str) – broadcast round ID

Returns:

iterator over all games of the broadcast round in PGN format

Return type:

Iterator[str]

push_pgn_update(broadcast_round_id: str, pgn_games: List[str]) None[source]

Manually update an existing broadcast by ID.

Parameters:
  • broadcast_round_id (str) – ID of a broadcast round

  • pgn_games (List[str]) – one or more games in PGN format

Return type:

None

stream_my_rounds(nb: int | None = None) Iterator[Dict[str, Any]][source]

Stream all broadcast rounds you are a member of.

Also includes broadcasts rounds where you’re a non-writing member. See the writeable flag in the response.

Rounds are ordered by rank, which is roughly chronological, most recent first, slightly pondered with popularity.

Parameters:

nb (int | None) – how many rounds to get

Returns:

iterator over broadcast objects with rounds you’re a member of and a study.writeable flag

Return type:

Iterator[Dict[str, Any]]

stream_round(broadcast_round_id: str) Iterator[str][source]

Stream an ongoing broadcast tournament in PGN format.

This streaming endpoint first sends all games of a broadcast tournament in PGN format.

Then, it waits for new moves to be played. As soon as it happens, the entire PGN of the game is sent to the stream.

The stream will also send PGNs when games are added to the tournament.

Parameters:

broadcast_round_id (str) – broadcast round ID

Returns:

stream of games of the broadcast round in PGN format

Return type:

Iterator[str]

update(broadcast_id: str, name: str, description: str, auto_leaderboard: bool, markdown: str | None = None, tier: int | None = None, players: List[BroadcastPlayer] | None = None) Dict[str, Any][source]

Update an existing broadcast by ID.

Note

Provide all fields. Values in missing fields will be erased.

Parameters:
  • broadcast_id (str) – ID of a broadcast

  • name (str) – name of the broadcast

  • description (str) – short description

  • auto_leaderboard (bool) – simple leaderboard based on game results

  • markdown (str | None) – long description

  • tier (int | None) – can only be used by Lichess staff accounts: 3 for normal, 4 for high, 5 for best

  • players (List[BroadcastPlayer] | None) – replace player names, ratings and titles. One line per player, formatted as such: Original name; Replacement name; Optional rating; Optional title

Returns:

updated broadcast information

Return type:

Dict[str, Any]

update_round(broadcast_id: str, name: str, syncUrl: str | None = None, syncUrlRound: str | None = None, startsAt: int | None = None, delay: int | None = None, period: int | None = None, finished: bool | None = None) Dict[str, Any][source]

Update information about a broadcast round that you created.

Parameters:
  • broadcast_id (str) – broadcast round ID

  • name (str) – Name of the broadcast round

  • syncUrl (str | None) – URL that Lichess will poll to get updates about the games

  • syncUrlRound (str | None) – required if syncUrl contains a LiveChessCloud link

  • startsAt (int | None) – Timestamp in milliseconds of broadcast round start

  • delay (int | None) – how long to delay moves coming from the source in seconds

  • period (int | None) – how long to wait between source requests in seconds

  • finished (bool | None) – set whether the round is completed

Returns:

updated broadcast information

Return type:

Dict[str, Any]

class berserk.clients.BulkPairings(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for bulk pairing related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

cancel(bulk_pairing_id: str) None[source]

Cancel and delete a bulk pairing that is scheduled in the future.

If the games have already been created, then this does nothing.

Parameters:

bulk_pairing_id (str) – id of the bulk pairing to cancel

Return type:

None

create(token_pairings: list[tuple[str, str]], clock_limit: int | None = None, clock_increment: int | None = None, days: int | None = None, pair_at: int | None = None, start_clocks_at: int | None = None, rated: bool = False, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] | None = None, fen: str | None = None, message: str | None = None, rules: list[str] | None = None) BulkPairing[source]

Create a bulk pairing.

Parameters:
  • players_tokens – players OAuth tokens

  • clock_limit (int | None) – clock initial time

  • clock_increment (int | None) – clock increment

  • days (int | None) – days per turn (for correspondence)

  • pair_at (int | None) – date at which the games will be created as a milliseconds unix timestamp. Up to 7 days in the future. Defaults to now.

  • start_clocks_at (int | None) – date at which the clocks will be automatically started as a Unix timestamp in milliseconds. Up to 7 days in the future. Note that the clocks can start earlier than specified, if players start making moves in the game. If omitted, the clocks will not start automatically.

  • rated (bool) – set to true to make the games rated. defaults to false.

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard'] | None) – variant of the games

  • fen (str | None) – custom initial position (in FEN). Only allowed if variant is standard, fromPosition, or chess960 (if a valid 960 starting position), and the games cannot be rated.

  • message (str | None) – message sent to players when their game is created

  • rules (list[str] | None) – extra game rules

  • token_pairings (list[tuple[str, str]]) –

Returns:

the newly created bulk pairing

Return type:

BulkPairing

get_upcoming() list[berserk.types.bulk_pairings.BulkPairing][source]

Get a list of upcoming bulk pairings you created.

Only bulk pairings that are scheduled in the future, or that have a clock start scheduled in the future, are listed.

Bulk pairings are deleted from the server after the pairings are done and the clocks have started.

Returns:

list of your upcoming bulk pairings.

Return type:

list[berserk.types.bulk_pairings.BulkPairing]

start_clocks(bulk_pairing_id: str) None[source]

Immediately start all clocks of the games of the given bulk pairing.

This overrides the startClocksAt value of an existing bulk pairing.

If the games have not yet been created (pairAt is in the future) or the clocks have already started (startClocksAt is in the past), then this does nothing.

Parameters:

bulk_pairing_id (str) – id of the bulk pairing to start clocks of

Return type:

None

class berserk.clients.Challenges(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

accept(challenge_id: str) None[source]

Accept an incoming challenge.

Parameters:

challenge_id (str) – id of the challenge to accept

Return type:

None

add_time_to_opponent_clock(game_id: str, seconds: int) None[source]

Add seconds to the opponent’s clock. Can be used to create games with time odds.

Requires OAuth2 authorization with challenge:write scope.

Parameters:
  • game_id (str) – game ID

  • seconds (int) – number of seconds to add to opponent’s clock

Return type:

None

cancel(challenge_id: str, opponent_token: str | None = None) None[source]

Cancel an outgoing challenge, or abort the game if challenge was accepted but the game was not yet played.

Requires OAuth2 authorization with challenge:write, bot:play and board:play scopes.

Parameters:
  • challenge_id (str) – ID of a challenge

  • opponent_token (str | None) – if set to the challenge:write token of the opponent, allows game to be cancelled even if both players have moved

Return type:

None

create(username: str, rated: bool, clock_limit: int | None = None, clock_increment: int | None = None, days: int | None = None, color: Literal['white', 'black'] | None = None, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] | None = None, position: str | None = None) Dict[str, Any][source]

Challenge another player to a game.

Parameters:
  • username (str) – username of the player to challenge

  • rated (bool) – whether or not the game will be rated

  • clock_limit (int | None) – clock initial time (in seconds)

  • clock_increment (int | None) – clock increment (in seconds)

  • days (int | None) – days per move (for correspondence games; omit clock)

  • color (Literal['white', 'black'] | None) – color of the accepting player

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard'] | None) – game variant to use

  • position (str | None) – custom initial position in FEN (variant must be standard and the game cannot be rated)

Returns:

challenge data

Return type:

Dict[str, Any]

create_ai(level: int = 8, clock_limit: int | None = None, clock_increment: int | None = None, days: int | None = None, color: Literal['white', 'black'] | None = None, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] | None = None, position: str | None = None) Dict[str, Any][source]

Challenge AI to a game.

Parameters:
  • level (int) – level of the AI (1 to 8)

  • clock_limit (int | None) – clock initial time (in seconds)

  • clock_increment (int | None) – clock increment (in seconds)

  • days (int | None) – days per move (for correspondence games; omit clock)

  • color (Literal['white', 'black'] | None) – color of the accepting player

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard'] | None) – game variant to use

  • position (str | None) – use one of the custom initial positions (variant must be standard and cannot be rated)

Returns:

information about the created game

Return type:

Dict[str, Any]

create_open(clock_limit: int | None = None, clock_increment: int | None = None, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] | None = None, position: str | None = None, rated: bool | None = None, name: str | None = None) Dict[str, Any][source]

Create a challenge that any two players can join.

Parameters:
  • clock_limit (int | None) – clock initial time (in seconds)

  • clock_increment (int | None) – clock increment (in seconds)

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard'] | None) – game variant to use

  • position (str | None) – custom initial position in FEN (variant must be standard and the game cannot be rated)

  • rated (bool | None) – Game is rated and impacts players ratings

  • name (str | None) – Optional name for the challenge, that players will see on the challenge page.

Returns:

challenge data

Return type:

Dict[str, Any]

create_tokens_for_multiple_users(usernames: List[str], description: str) Dict[str, str][source]

This endpoint can only be used by Lichess admins.

Create and obtain challenge:write tokens for multiple users.

If a similar token already exists for a user, it is reused. This endpoint is idempotent.

Parameters:
  • usernames (List[str]) – List of usernames

  • description (str) – user-visible token description

Returns:

challenge:write tokens of each user

Return type:

Dict[str, str]

create_with_accept(username: str, rated: bool, token: str, clock_limit: int | None = None, clock_increment: int | None = None, days: int | None = None, color: Literal['white', 'black'] | None = None, variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] | None = None, position: str | None = None) Dict[str, Any][source]

Start a game with another player.

This is just like the regular challenge create except it forces the opponent to accept. You must provide the OAuth token of the opponent and it must have the challenge:write scope.

Parameters:
  • username (str) – username of the opponent

  • rated (bool) – whether or not the game will be rated

  • token (str) – opponent’s OAuth token

  • clock_limit (int | None) – clock initial time (in seconds)

  • clock_increment (int | None) – clock increment (in seconds)

  • days (int | None) – days per move (for correspondence games; omit clock)

  • color (Literal['white', 'black'] | None) – color of the accepting player

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard'] | None) – game variant to use

  • position (str | None) – custom initial position in FEN (variant must be standard and the game cannot be rated)

Returns:

game data

Return type:

Dict[str, Any]

decline(challenge_id: str, reason: Literal['generic', 'later', 'tooFast', 'tooSlow', 'timeControl', 'rated', 'casual', 'standard', 'variant', 'noBot', 'onlyBot'] = 'generic') None[source]

Decline an incoming challenge.

Parameters:
  • challenge_id (str) – ID of a challenge

  • reason (Literal['generic', 'later', 'tooFast', 'tooSlow', 'timeControl', 'rated', 'casual', 'standard', 'variant', 'noBot', 'onlyBot']) – reason for declining challenge

Return type:

None

get_mine() Dict[str, List[Challenge]][source]

Get all outgoing challenges (created by me) and incoming challenges (targeted at me).

Requires OAuth2 authorization with challenge:read scope.

Returns:

all my outgoing and incoming challenges

Return type:

Dict[str, List[Challenge]]

start_clocks(game_id: str, token_player_1: str, token_player_2: str) None[source]

Starts the clocks of a game immediately, even if a player has not yet made a move.

Requires the OAuth tokens of both players with challenge:write scope. The tokens can be in any order.

If the clocks have already started, the call will have no effect.

Parameters:
  • game_id (str) – game ID

  • token_player_1 (str) – OAuth token of player 1 with challenge:write scope

  • token_player_2 (str) – OAuth token of player 2 with challenge:write scope

Return type:

None

class berserk.clients.Client(session: Session | None = None, base_url: str | None = None, pgn_as_default: bool = False, *, tablebase_url: str | None = None, explorer_url: str | None = None)[source]

Bases: BaseClient

Main touchpoint for the API.

All endpoints are namespaced into the clients below:

  • account - managing account information

  • account - getting information about position analysis

  • bots - performing bot operations

  • broadcasts - getting and creating broadcasts

  • challenges - using challenges

  • games - getting and exporting games

  • simuls - getting simultaneous exhibition games

  • studies - exporting studies

  • teams - getting information about teams

  • tournaments - getting and creating

    tournaments

  • users - getting information about users

  • board - play games using a normal account

  • messaging - private message other players

  • tv - get information on tv channels and games

  • tablebase - lookup endgame tablebase

  • bulk_pairings - manage bulk pairings

  • class:

    external_engine <berserk.clients.ExternalEngine> - manage external engines

Parameters:
  • session (requests.Session | None) – request session, authenticated as needed

  • base_url (str | None) – base API URL to use (if other than the default)

  • pgn_as_default (bool) – True if PGN should be the default format for game exports when possible. This defaults to False and is used as a fallback when as_pgn is left as None for methods that support it.

  • tablebase_url (str | None) – URL for tablebase lookups

  • explorer_url (str | None) –

class berserk.clients.ExternalEngine(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for external engine related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

create(name: str, max_threads: int, max_hash_table_size: int, default_depth: int, provider_secret: str, variants: List[str] | None = None, provider_data: str | None = None) ExternalEngine[source]

Registers a new external engine for the user.

Requires OAuth2 authorization.

Parameters:
  • name (str) – engine display name

  • max_threads (int) – maximum number of available threads

  • max_hash_table_size (int) – maximum available hash table size, in MiB

  • default_depth (int) – estimated depth of normal search

  • provider_secret (str) – random token that used to wait for analysis requests and provide analysis

  • variants (List[str] | None) – list of supported chess variants

  • provider_data (str | None) – arbitrary data that engine provider can use for identification or bookkeeping

Returns:

info about the external engine

Return type:

ExternalEngine

delete(engine_id: str) None[source]

Unregisters an external engine.

Requires OAuth2 authorization.

Parameters:

engine_id (str) – engine ID

Return type:

None

get() List[ExternalEngine][source]

Lists all external engines that have been registered for the user, and the credentials required to use them.

Requires OAuth2 authorization.

Returns:

info about the external engines

Return type:

List[ExternalEngine]

get_by_id(engine_id: str) ExternalEngine[source]

Get properties and credentials of an external engine.

Requires OAuth2 authorization.

Parameters:

engine_id (str) – external engine ID

Returns:

info about the external engine

Return type:

ExternalEngine

update(engine_id: str, name: str, max_threads: int, max_hash_table_size: int, default_depth: int, provider_secret: str, variants: List[str] | None = None, provider_data: str | None = None) ExternalEngine[source]

Updates the properties of an external engine.

Requires OAuth2 authorization.

Parameters:
  • engine_id (str) – engine ID

  • name (str) – engine display name

  • max_threads (int) – maximum number of available threads

  • max_hash_table_size (int) – maximum available hash table size, in MiB

  • default_depth (int) – estimated depth of normal search

  • provider_secret (str) – random token that used to wait for analysis requests and provide analysis

  • variants (List[str] | None) – list of supported chess variants

  • provider_data (str | None) – arbitrary data that engine provider can use for identification or bookkeeping

Returns:

info about the external engine

Return type:

ExternalEngine

class berserk.clients.Games(session: Session, base_url: str | None = None, pgn_as_default: bool = False)[source]

Bases: FmtClient

Client for games-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

  • pgn_as_default (bool) –

add_game_ids_to_stream(*game_ids: str, stream_id: str) None[source]

Add new game IDs to an existing stream.

Parameters:
  • stream_id (str) – the stream ID you used to create the existing stream

  • game_ids (str) – one or more game IDs to stream

Return type:

None

export(game_id: str, as_pgn: bool | None = None, moves: bool | None = None, tags: bool | None = None, clocks: bool | None = None, evals: bool | None = None, opening: bool | None = None, literate: bool | None = None) str | Dict[str, Any][source]

Get one finished game as PGN or JSON.

Parameters:
  • game_id (str) – the ID of the game to export

  • as_pgn (bool | None) – whether to return the game in PGN format

  • moves (bool | None) – whether to include the PGN moves

  • tags (bool | None) – whether to include the PGN tags

  • clocks (bool | None) – whether to include clock comments in the PGN moves

  • evals (bool | None) – whether to include analysis evaluation comments in the PGN moves when available

  • opening (bool | None) – whether to include the opening name

  • literate (bool | None) – whether to include literate the PGN

Returns:

exported game, as JSON or PGN

Return type:

str | Dict[str, Any]

export_by_player(username: str, as_pgn: bool | None = None, since: int | None = None, until: int | None = None, max: int | None = None, vs: str | None = None, rated: bool | None = None, perf_type: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['bullet', 'blitz', 'rapid', 'classical', 'ultraBullet'] | None = None, color: Literal['white', 'black'] | None = None, analysed: bool | None = None, moves: bool | None = None, pgn_in_json: bool | None = None, tags: bool | None = None, clocks: bool | None = None, evals: bool | None = None, opening: bool | None = None, ongoing: bool | None = None, finished: bool | None = None, players: str | None = None, sort: str | None = None, literate: bool | None = None) Iterator[str] | Iterator[Dict[str, Any]][source]

Get games by player.

Parameters:
  • username (str) – which player’s games to return

  • as_pgn (bool | None) – whether to return the game in PGN format

  • since (int | None) – lower bound on the game timestamp

  • until (int | None) – upperbound on the game timestamp

  • max (int | None) – limit the number of games returned

  • vs (str | None) – filter by username of the opponent

  • rated (bool | None) – filter by game mode (True for rated, False for casual)

  • perf_type (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['bullet', 'blitz', 'rapid', 'classical', 'ultraBullet'] | None) – filter by speed or variant

  • color (Literal['white', 'black'] | None) – filter by the color of the player

  • analysed (bool | None) – filter by analysis availability

  • moves (bool | None) – whether to include the PGN moves

  • pgn_in_json (bool | None) – Include the full PGN within JSON response

  • tags (bool | None) – whether to include the PGN tags

  • clocks (bool | None) – whether to include clock comments in the PGN moves

  • evals (bool | None) – whether to include analysis evaluation comments in the PGN moves when available

  • opening (bool | None) – whether to include the opening name

  • ongoing (bool | None) – Include ongoing games, last 3 moves omitted

  • finished (bool | None) – Include finished games

  • players (str | None) – URL of text file containing real names and ratings for PGN

  • sort (str | None) – Sort the order of games

  • literate (bool | None) – whether to include literate the PGN

Returns:

iterator over the exported games, as JSON or PGN

Return type:

Iterator[str] | Iterator[Dict[str, Any]]

export_multi(*game_ids: str, as_pgn: bool | None = None, moves: bool | None = None, tags: bool | None = None, clocks: bool | None = None, evals: bool | None = None, opening: bool | None = None) Iterator[str] | Iterator[Dict[str, Any]][source]

Get multiple games by ID.

Parameters:
  • game_ids (str) – one or more game IDs to export

  • as_pgn (bool | None) – whether to return the game in PGN format

  • moves (bool | None) – whether to include the PGN moves

  • tags (bool | None) – whether to include the PGN tags

  • clocks (bool | None) – whether to include clock comments in the PGN moves

  • evals (bool | None) – whether to include analysis evaluation comments in the PGN moves when available

  • opening (bool | None) – whether to include the opening name

Returns:

iterator over the exported games, as JSON or PGN

Return type:

Iterator[str] | Iterator[Dict[str, Any]]

export_ongoing_by_player(username: str, as_pgn: bool | None = None, moves: bool | None = None, pgn_in_json: bool | None = None, tags: bool | None = None, clocks: bool | None = None, evals: bool | None = None, opening: bool | None = None, literate: bool | None = None, players: str | None = None) Iterator[str] | Iterator[Dict[str, Any]][source]

Export the ongoing game, or the last game played, of a user.

Parameters:
  • username (str) – the player’s username

  • as_pgn (bool | None) – whether to return the game in PGN format

  • moves (bool | None) – whether to include the PGN moves

  • pgn_in_json (bool | None) – include the full PGN within JSON response

  • tags (bool | None) – whether to include the PGN tags

  • clocks (bool | None) – whether to include clock comments in the PGN moves

  • evals (bool | None) – whether to include analysis evaluation comments in the PGN moves when available

  • opening (bool | None) – whether to include the opening name

  • literate (bool | None) – whether to include literate the PGN

  • players (str | None) – URL of text file containing real names and ratings for PGN

Returns:

iterator over the exported games, as JSON or PGN

Return type:

Iterator[str] | Iterator[Dict[str, Any]]

get_among_players(*usernames: str, with_current_games: bool = False) Iterator[Dict[str, Any]][source]

Stream the games currently being played among players.

Note this will not include games where only one player is in the given list of usernames. The stream will emit an event each time a game is started or finished.

Parameters:
  • usernames (str) – two or more usernames

  • with_current_games (bool) – include all current ongoing games at the beginning of the stream

Returns:

iterator over all games played among the given players

Return type:

Iterator[Dict[str, Any]]

get_ongoing(count: int = 10) List[Dict[str, Any]][source]

Get your currently ongoing games.

Parameters:

count (int) – number of games to get

Returns:

some number of currently ongoing games

Return type:

List[Dict[str, Any]]

import_game(pgn: str) Dict[str, Any][source]

Import a single game from PGN.

Parameters:

pgn (str) – the PGN of the game

Returns:

the game ID and URL of the import

Return type:

Dict[str, Any]

stream_game_moves(game_id: str) Iterator[Dict[str, Any]][source]

Stream positions and moves of any ongoing game.

Parameters:

game_id (str) – ID of a game

Returns:

iterator over game states

Return type:

Iterator[Dict[str, Any]]

stream_games_by_ids(*game_ids: str, stream_id: str) Iterator[Dict[str, Any]][source]

Stream multiple games by ID.

Parameters:
  • game_ids (str) – one or more game IDs to stream

  • stream_id (str) – arbitrary stream ID that can be used later to add game IDs to this stream

Returns:

iterator over the stream of results

Return type:

Iterator[Dict[str, Any]]

class berserk.clients.Messaging(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

send(username: str, text: str) None[source]

Send a private message to another player.

Parameters:
  • username (str) – the user to send the message to

  • text (str) – the text to send

Return type:

None

class berserk.clients.OAuth(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

test_tokens(*tokens: str) Dict[str, Any][source]

Test the validity of up to 1000 OAuth tokens.

Valid OAuth tokens will be returned with their associated user ID and scopes. Invalid tokens will be returned as null.

Parameters:

tokens (str) – one or more OAuth tokens

Returns:

info about the tokens

Return type:

Dict[str, Any]

class berserk.clients.Puzzles(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for puzzle-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

create_race() PuzzleRace[source]

Create a new private puzzle race. The Lichess user who creates the race must join the race page, and manually start the race when enough players have joined.

Returns:

puzzle race ID and URL

Return type:

PuzzleRace

get(id: str) Dict[str, Any][source]

Get a puzzle by its id.

Parameters:

id (str) – the id of the puzzle to retrieve

Returns:

the puzzle

Return type:

Dict[str, Any]

get_daily() Dict[str, Any][source]

Get the current daily Lichess puzzle.

Returns:

current daily puzzle

Return type:

Dict[str, Any]

get_puzzle_activity(max: int | None = None, before: int | None = None) Iterator[Dict[str, Any]][source]

Stream puzzle activity history of the authenticated user, starting with the most recent activity.

Parameters:
  • max (int | None) – maximum number of entries to stream. defaults to all activity

  • before (int | None) – timestamp in milliseconds. only stream activity before this time. defaults to now. use together with max for pagination

Returns:

iterator over puzzle activity history

Return type:

Iterator[Dict[str, Any]]

get_puzzle_dashboard(days: int = 30) Dict[str, Any][source]

Get the puzzle dashboard of the authenticated user.

Parameters:

days (int) – how many days to look back when aggregating puzzle results

Returns:

the puzzle dashboard

Return type:

Dict[str, Any]

get_storm_dashboard(username: str, days: int = 30) Dict[str, Any][source]

Get storm dashboard of a player. Set days to 0 if you’re only interested in the high score.

Parameters:
  • username (str) – the username of the player to download the dashboard for

  • days (int) – how many days of history to return

Returns:

the storm dashboard

Return type:

Dict[str, Any]

class berserk.clients.Relations(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

follow(username: str)[source]

Follow a player.

Parameters:

username (str) – user to follow

get_users_followed() Iterator[Dict[str, Any]][source]

Stream users you are following.

Returns:

iterator over the users the given user follows

Return type:

Iterator[Dict[str, Any]]

unfollow(username: str)[source]

Unfollow a player.

Parameters:

username (str) – user to unfollow

class berserk.clients.Simuls(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Simultaneous exhibitions - one vs many.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

get() Dict[str, Any][source]

Get recently finished, ongoing, and upcoming simuls.

Returns:

current simuls

Return type:

Dict[str, Any]

class berserk.clients.Studies(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Study chess the Lichess way.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

export(study_id: str) Iterator[str][source]

Export all chapters of a study.

Returns:

iterator over all chapters as PGN

Parameters:

study_id (str) –

Return type:

Iterator[str]

export_by_username(username: str) Iterator[str][source]

Export all chapters of all studies of a user in PGN format.

If authenticated, then all public, unlisted, and private studies are included.

If not, only public (non-unlisted) studies are included.

return:iterator over all chapters as PGN

Parameters:

username (str) –

Return type:

Iterator[str]

export_chapter(study_id: str, chapter_id: str) str[source]

Export one chapter of a study.

Returns:

chapter PGN

Parameters:
  • study_id (str) –

  • chapter_id (str) –

Return type:

str

import_pgn(study_id: str, chapter_name: str, pgn: str, orientation: Literal['white', 'black'] = 'white', variant: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['standard'] = 'standard') List[ChapterIdName][source]

Imports arbitrary PGN into an existing study. Creates a new chapter in the study.

If the PGN contains multiple games (separated by 2 or more newlines) then multiple chapters will be created within the study.

Note that a study can contain at most 64 chapters.

return: List of the chapters {id, name}

Parameters:
  • study_id (str) –

  • chapter_name (str) –

  • pgn (str) –

  • orientation (Literal['white', 'black']) –

  • variant (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['standard']) –

Return type:

List[ChapterIdName]

class berserk.clients.TV(session: Session, base_url: str | None = None, pgn_as_default: bool = False)[source]

Bases: FmtClient

Client for TV related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

  • pgn_as_default (bool) –

get_best_ongoing(channel: str, as_pgn: bool | None = None, count: int | None = None, moves: bool = True, pgnInJson: bool = False, tags: bool = True, clocks: bool = False, opening: bool = False) str | List[Dict[str, Any]][source]

Get a list of ongoing games for a given TV channel in PGN or NDJSON.

Parameters:
  • channel (str) – the name of the TV channel in camel case

  • as_pgn (bool | None) – whether to return the game in PGN format

  • count (int | None) – the number of games to fetch [1..30]

  • moves (bool) – whether to include the PGN moves

  • pgnInJson (bool) – include the full PGN within JSON response

  • tags (bool) – whether to include the PGN tags

  • clocks (bool) – whether to include clock comments in the PGN moves

  • opening (bool) – whether to include the opening name

Returns:

the ongoing games of the given TV channel in PGN or NDJSON

Return type:

str | List[Dict[str, Any]]

get_current_games() Dict[str, Any][source]

Get basic information about the current TV games being played.

Returns:

best ongoing games in each speed and variant

Return type:

Dict[str, Any]

stream_current_game() Iterator[Dict[str, Any]][source]

Streams the current TV game.

Returns:

positions and moves of the current TV game

Return type:

Iterator[Dict[str, Any]]

class berserk.clients.Tablebase(session: Session, tablebase_url: str | None = None)[source]

Bases: BaseClient

Client for tablebase related endpoints.

Parameters:
  • session (requests.Session) –

  • tablebase_url (str | None) –

antichess(position: str) Dict[str, Any][source]

Look up the tablebase result for an antichess position.

Parameters:

position (str) – FEN of the position to lookup

Returns:

tablebase information about this position

Return type:

Dict[str, Any]

atomic(position: str) Dict[str, Any][source]

Look up the tablebase result for an atomic chess position.

Parameters:

position (str) – FEN of the position to lookup

Returns:

tablebase information about this position

Return type:

Dict[str, Any]

look_up(position: str, variant: Literal['standard'] | Literal['atomic'] | Literal['antichess'] = 'standard') Dict[str, Any][source]

Look up the tablebase result for a position.

Parameters:
  • position (str) – FEN of the position to look up

  • variant (Literal['standard'] | ~typing.Literal['atomic'] | ~typing.Literal['antichess']) – the variant of the position to look up (supported are standard, atomic, and antichess)

Returns:

tablebase information about this position

Return type:

Dict[str, Any]

standard(position: str) Dict[str, Any][source]

Look up the tablebase result for a standard chess position.

Parameters:

position (str) – FEN of the position to lookup

Returns:

tablebase information about this position

Return type:

Dict[str, Any]

class berserk.clients.Teams(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

accept_join_request(team_id: str, user_id: str) None[source]

Accept someone’s request to join one of your teams

Parameters:
  • team_id (str) – ID of the team to accept the request for

  • user_id (str) – ID of the user requesting to join

Return type:

None

decline_join_request(team_id: str, user_id: str) None[source]

Decline someone’s request to join one of your teams

Parameters:
  • team_id (str) – ID of the team to decline the request for

  • user_id (str) – ID of the user requesting to join

Return type:

None

get_join_requests(team_id: str, declined: bool = False) List[Dict[str, Any]][source]

Get pending join requests of your team

Parameters:
  • team_id (str) – ID of the team to request the join requests from

  • declined (bool) – whether to show declined requests instead of pending ones

Returns:

list of join requests

Return type:

List[Dict[str, Any]]

get_members(team_id: str) Iterator[Dict[str, Any]][source]

Get members of a team.

Parameters:

team_id (str) – ID of the team to get members from

Returns:

users on the given team

Return type:

Iterator[Dict[str, Any]]

Get the most popular teams

Parameters:

page (int) – the page number that needs to be returned (Optional)

Returns:

A paginated list of the most popular teams.

Return type:

PaginatedTeams

get_team(team_id: str) Team[source]

Get the information about the team

Returns:

the information about the team

Parameters:

team_id (str) –

Return type:

Team

join(team_id: str, message: str | None = None, password: str | None = None) None[source]

Join a team.

Parameters:
  • team_id (str) – ID of the team to join

  • message (str | None) – optional request message, if the team requires one

  • password (str | None) – optional password, if the team requires one

Return type:

None

kick_member(team_id: str, user_id: str) None[source]

Kick a member out of your team.

Parameters:
  • team_id (str) – ID of the team to kick from

  • user_id (str) – ID of the user to kick from the team

Return type:

None

leave(team_id: str) None[source]

Leave a team.

Parameters:

team_id (str) – ID of the team to leave

Return type:

None

message_all_members(team_id: str, message: str) None[source]

Send a private message to all members of a team. You must be the team leader with the “Messages” permission.

Parameters:
  • team_id (str) – team ID

  • message (str) – message to send all team members

Return type:

None

search(text: str, page: int = 1) PaginatedTeams[source]

Search for teams

Parameters:
  • text (str) – the query text to search for

  • page (int) – the page number that needs to be returned (Optional)

Returns:

The paginated list of teams.

Return type:

PaginatedTeams

teams_of_player(username: str) List[Team][source]

Get all the teams a player is a member of

Returns:

list of teams the user is a member of

Parameters:

username (str) –

Return type:

List[Team]

class berserk.clients.Tournaments(session: Session, base_url: str | None = None, pgn_as_default: bool = False)[source]

Bases: FmtClient

Client for tournament-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

  • pgn_as_default (bool) –

arenas_by_team(teamId: str, maxT: int | None = None) List[Dict[str, Any]][source]

Get arenas created for a team.

Parameters:
  • teamId (str) – team ID

  • maxT (int | None) – how many tournaments to download

Returns:

arena tournaments

Return type:

List[Dict[str, Any]]

create_arena(clockTime: int, clockIncrement: int, minutes: int, name: str | None = None, wait_minutes: int | None = None, startDate: int | None = None, variant: str | None = None, rated: bool | None = None, position: str | None = None, berserkable: bool | None = None, streakable: bool | None = None, hasChat: bool | None = None, description: str | None = None, password: str | None = None, teamBattleByTeam: str | None = None, teamId: str | None = None, minRating: int | None = None, maxRating: int | None = None, nbRatedGame: int | None = None) Dict[str, Any][source]

Create a new arena tournament.

Note

wait_minutes is always relative to now and is overridden by start_time.

Note

If name is left blank then one is automatically created.

Parameters:
  • clockTime (int) – initial clock time in minutes

  • clockIncrement (int) – clock increment in seconds

  • minutes (int) – length of the tournament in minutes

  • name (str | None) – tournament name

  • wait_minutes (int | None) – future start time in minutes

  • startDate (int | None) – when to start the tournament (timestamp in milliseconds)

  • variant (str | None) – variant to use if other than standard

  • rated (bool | None) – whether the game affects player ratings

  • position (str | None) – custom initial position in FEN

  • berserkable (bool | None) – whether players can use berserk

  • streakable (bool | None) – whether players get streaks

  • hasChat (bool | None) – whether players can discuss in a chat

  • description (str | None) – anything you want to tell players about the tournament

  • password (str | None) – password

  • teamBattleByTeam (str | None) – ID of a team you lead to create a team battle

  • teamId (str | None) – Restrict entry to members of team

  • minRating (int | None) – Minimum rating to join

  • maxRating (int | None) – Maximum rating to join

  • nbRatedGame (int | None) – Min number of rated games required

Returns:

created arena info

Return type:

Dict[str, Any]

create_swiss(teamId: str, clockLimit: int, clockIncrement: int, nbRounds: int, name: str | None = None, startsAt: int | None = None, roundInterval: int | None = None, variant: str | None = None, description: str | None = None, rated: bool | None = None, chatFor: int | None = None) Dict[str, Any][source]

Create a new swiss tournament.

Note

If name is left blank then one is automatically created.

Note

If startsAt is left blank then the tournament begins 10 minutes after creation

Parameters:
  • teamId (str) – team ID, required for swiss tournaments

  • clockLimit (int) – initial clock time in seconds

  • clockIncrement (int) – clock increment in seconds

  • nbRounds (int) – maximum number of rounds to play

  • name (str | None) – tournament name

  • startsAt (int | None) – when to start tournament (timestamp in milliseconds)

  • roundInterval (int | None) – interval between rounds in seconds

  • variant (str | None) – variant to use if other than standard

  • description (str | None) – tournament description

  • rated (bool | None) – whether the game affects player ratings

  • chatFor (int | None) – who can read and write in the chat

Returns:

created swiss info

Return type:

Dict[str, Any]

edit_swiss(tournamentId: str, clockLimit: int, clockIncrement: int, nbRounds: int, startsAt: int | None = None, roundInterval: int | None = None, variant: str | None = None, description: str | None = None, name: str | None = None, rated: bool | None = True, password: str | None = None, forbiddenPairings: str | None = None, manualPairings: str | None = None, chatFor: int | None = 20, minRating: int | None = None, maxRating: int | None = None, nbRatedGame: int | None = None, allowList: str | None = None) Dict[str, SwissInfo][source]

Update a swiss tournament.

:param tournamentId : The unique identifier of the tournament to be updated. :param clockLimit : The time limit for each player’s clock. :param clockIncrement : The time increment added to a player’s clock after each move. :param nbRounds : The number of rounds in the tournament. :param startsAt : The start time of the tournament in Unix timestamp format. :param roundInterval :The time interval between rounds in minutes. :param variant :The chess variant of the tournament. :param description : A description of the tournament. :param name : The name of the tournament. :param rated : Whether the tournament is rated. :param password : A password to access the tournament. :param forbiddenPairings : Specify forbidden pairings in the tournament. :param manualPairings : Specify manual pairings for the tournament. :param chatFor :The duration for which the chat is available in minutes. :param minRating : The minimum rating required to participate in the tournament. :param maxRating : The maximum rating allowed to participate in the tournament. :param nbRatedGame : The number of rated games required for participation. :param allowList : Specify an allow list for the tournament. :return A dictionary containing information about the updated Swiss tournament.

Parameters:
  • tournamentId (str) –

  • clockLimit (int) –

  • clockIncrement (int) –

  • nbRounds (int) –

  • startsAt (int | None) –

  • roundInterval (int | None) –

  • variant (str | None) –

  • description (str | None) –

  • name (str | None) –

  • rated (bool | None) –

  • password (str | None) –

  • forbiddenPairings (str | None) –

  • manualPairings (str | None) –

  • chatFor (int | None) –

  • minRating (int | None) –

  • maxRating (int | None) –

  • nbRatedGame (int | None) –

  • allowList (str | None) –

Return type:

Dict[str, SwissInfo]

export_arena_games(id: str, as_pgn: bool | None = None, moves: bool = True, tags: bool = True, clocks: bool = False, evals: bool = True, opening: bool = False) Iterator[str] | Iterator[Dict[str, Any]][source]

Export games from an arena tournament.

Parameters:
  • id (str) – tournament ID

  • as_pgn (bool | None) – whether to return PGN instead of JSON

  • moves (bool) – include moves

  • tags (bool) – include tags

  • clocks (bool) – include clock comments in the PGN moves, when available

  • evals (bool) – include analysis evaluation comments in the PGN moves, when available

  • opening (bool) – include the opening name

Returns:

iterator over the exported games, as JSON or PGN

Return type:

Iterator[str] | Iterator[Dict[str, Any]]

export_swiss_games(id: str, as_pgn: bool | None = None, moves: bool = True, pgnInJson: bool = False, tags: bool = True, clocks: bool = False, evals: bool = True, opening: bool = False) Iterator[str] | Iterator[Dict[str, Any]][source]

Export games from a swiss tournament.

Parameters:
  • id (str) – tournament id

  • as_pgn (bool | None) – whether to return pgn instead of JSON

  • moves (bool) – include moves

  • pgnInJson (bool) – include the full PGN within the JSON response, in a pgn field

  • tags (bool) – include tags

  • clocks (bool) – include clock comments

  • evals (bool) – include analysis evaluation comments in the PGN, when available

  • opening (bool) – include the opening name

Returns:

iterator over the exported games, as JSON or PGN

Return type:

Iterator[str] | Iterator[Dict[str, Any]]

export_swiss_trf(tournament_id: str) str[source]

Download a tournament in the Tournament Report File format, the FIDE standard.

Parameters:

tournament_id (str) – tournament ID

Returns:

tournament information in the TRF format

Return type:

str

get() CurrentTournaments[source]

Get recently finished, ongoing, and upcoming arenas.

Returns:

current arenas

Return type:

CurrentTournaments

get_swiss(tournament_id: str) SwissInfo[source]

Get detailed info about a Swiss tournament.

Parameters:

tournament_id (str) – the Swiss tournament ID.

Returns:

detailed info about a Swiss tournament

Return type:

SwissInfo

get_team_standings(tournament_id: str) TeamBattleResult[source]

Get team standing of a team battle tournament, with their respective top players.

Parameters:

tournament_id (str) – tournament ID

Returns:

information about teams in the team battle tournament

Return type:

TeamBattleResult

get_tournament(tournament_id: str, page: int = 1) Dict[str, Any][source]

Get information about an arena.

Parameters:
  • tournament_id (str) – tournament ID

  • page (int) – the page number of the player standings to view

Returns:

tournament information

Return type:

Dict[str, Any]

join_arena(tournament_id: str, password: str | None = None, team: str | None = None, should_pair_immediately: bool = False) None[source]

Join an Arena tournament. Also, unpauses if you had previously paused the tournament.

Requires OAuth2 authorization with tournament:write scope.

Parameters:
  • tournament_id (str) – tournament ID

  • password (str | None) – tournament password or user-specific entry code generated and shared by the organizer

  • team (str | None) – team with which to join the team battle Arena tournament

  • should_pair_immediately (bool) – if the tournament is started, attempt to pair the user, even if they are not connected to the tournament page. This expires after one minute, to avoid pairing a user who is long gone. You may call “join” again to extend the waiting.

Return type:

None

join_swiss(tournament_id: str, password: str | None = None) None[source]

Join a Swiss tournament, possibly with a password.

Parameters:
  • tournament_id (str) – the Swiss tournament ID.

  • password (str | None) – the Swiss tournament password, if one is required.

Return type:

None

schedule_swiss_next_round(tournament_id: str, schedule_time: int) None[source]

Manually schedule the next round date and time of a Swiss tournament.

Parameters:
  • tournament_id (str) – the Swiss tournament ID.

  • schedule_time (int) – Timestamp in milliseconds to start the next round at a given date and time.

Return type:

None

stream_by_creator(username: str) Iterator[Dict[str, Any]][source]

Stream the tournaments created by a player.

Parameters:

username (str) – username of the player

Returns:

iterator over the tournaments

Return type:

Iterator[Dict[str, Any]]

stream_results(id: str, limit: int | None = None, sheet: bool = False) Iterator[Dict[str, ArenaResult]][source]

Stream the results of a tournament.

Results are the players of a tournament with their scores and performance in rank order. Note that results for ongoing tournaments can be inconsistent due to ranking changes.

Parameters:
  • id (str) – tournament ID

  • limit (int | None) – maximum number of results to stream

  • sheet (bool) – add a sheet field to player containing their concatenated results. Expensive server computation that slows the stream.

Returns:

iterator over the results

Return type:

Iterator[Dict[str, ArenaResult]]

stream_swiss_results(tournament_id: str, limit: int | None = None) Iterator[Dict[str, SwissResult]][source]

Results are the players of a swiss tournament with their scores and performance in rank order. Note that results for ongoing tournaments can be inconsistent due to ranking changes.

Parameters:
  • tournament_id (str) – the Swiss tournament ID.

  • limit (int | None) – Max number of players to fetch

Returns:

iterator of the SwissResult or an empty iterator if no result

Return type:

Iterator[Dict[str, SwissResult]]

swiss_by_team(teamId: str, maxT: int | None = None) List[Dict[str, Any]][source]

Get swiss tournaments created for a team.

Parameters:
  • teamId (str) – team ID

  • maxT (int | None) – how many tournaments to download

Returns:

swiss tournaments

Return type:

List[Dict[str, Any]]

terminate_arena(tournament_id: str) None[source]

Terminate an Arena tournament.

Parameters:

tournament_id (str) – tournament ID

Return type:

None

terminate_swiss(tournament_id: str) None[source]

Terminate a Swiss tournament.

Parameters:

tournament_id (str) – the Swiss tournament ID.

Return type:

None

tournaments_by_user(username: str, nb: int | None = None) List[Dict[str, Any]][source]

Get arena tournaments created by a user.

Parameters:
  • username (str) – username

  • nb (int | None) – max number of tournaments to fetch

Returns:

arena tournaments info

Return type:

List[Dict[str, Any]]

update_team_battle(tournament_id: str, team_ids: str | None = None, team_leader_count_per_team: int | None = None) Dict[str, Any][source]

Set the teams and number of leaders of a team battle tournament.

Parameters:
  • tournament_id (str) – tournament ID

  • team_ids (str | None) – all team IDs of the team battle, separated by commas

  • team_leader_count_per_team (int | None) – number of team leaders per team

Returns:

updated team battle information

Return type:

Dict[str, Any]

withdraw_arena(tournament_id: str) None[source]

Leave an upcoming Arena tournament, or take a break on an ongoing Arena tournament.

Parameters:

tournament_id (str) – tournament ID

Return type:

None

withdraw_swiss(tournament_id: str) None[source]

Withdraw a Swiss tournament.

Parameters:

tournament_id (str) – the Swiss tournament ID.

Return type:

None

class berserk.clients.Users(session: Session, base_url: str | None = None)[source]

Bases: BaseClient

Client for user-related endpoints.

Parameters:
  • session (requests.Session) –

  • base_url (str | None) –

get_activity_feed(username: str) List[Dict[str, Any]][source]

Get the activity feed of a user.

Returns:

activity feed of the given user

Parameters:

username (str) –

Return type:

List[Dict[str, Any]]

get_all_top_10() Dict[str, Any][source]

Get the top 10 players for each speed and variant.

Returns:

top 10 players in each speed and variant

Return type:

Dict[str, Any]

get_by_autocomplete(partial_username: str, only_followed_players: bool = False, as_object: bool = False) List[str] | List[OnlineLightUser][source]

Provides autocompletion options for an incomplete username.

Parameters:
  • partial_username (str) – the beginning of a username, must provide >= 3 characters

  • only_followed_players (bool) – whether to return matching followed players only, if any exist

  • as_object (bool) – if false, returns an array of usernames else, returns an object with matching users

Returns:

followed players matching term if any, else returns other players. Requires OAuth.

Return type:

List[str] | List[OnlineLightUser]

get_by_id(*usernames: str) List[Dict[str, Any]][source]

Get multiple users by their IDs.

Parameters:

usernames (str) – one or more usernames

Returns:

user data for the given usernames

Return type:

List[Dict[str, Any]]

get_crosstable(user1: str, user2: str, matchup: bool = False) List[Dict[str, Any]][source]

Get total number of games, and current score, of any two users.

Parameters:
  • user1 (str) – first user to compare

  • user2 (str) – second user to compare

  • matchup (bool) – Whether to get the current match data, if any

Return type:

List[Dict[str, Any]]

get_leaderboard(perf_type: Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | Literal['bullet', 'blitz', 'rapid', 'classical', 'ultraBullet'], count: int = 10)[source]

Get the leaderboard for one speed or variant.

Parameters:
  • perf_type (Literal['chess960', 'kingOfTheHill', 'threeCheck', 'antichess', 'atomic', 'horde', 'racingKings', 'crazyhouse', 'fromPosition'] | ~typing.Literal['bullet', 'blitz', 'rapid', 'classical', 'ultraBullet']) – speed or variant

  • count (int) – number of players to get

Returns:

top players for one speed or variant

get_live_streamers() List[Dict[str, Any]][source]

Get basic information about currently streaming users.

Returns:

users currently streaming a game

Return type:

List[Dict[str, Any]]

get_public_data(username: str) Dict[str, Any][source]

Get the public data for a user.

Returns:

public data available for the given user

Parameters:

username (str) –

Return type:

Dict[str, Any]

get_puzzle_activity(max: int | None = None) Iterator[Dict[str, Any]][source]

Stream puzzle activity history of the authenticated user, starting with the most recent activity.

Parameters:

max (int | None) – maximum number of entries to stream. defaults to all activity

Returns:

stream of puzzle activity history

Return type:

Iterator[Dict[str, Any]]

get_rating_history(username: str) List[Dict[str, Any]][source]

Get the rating history of a user.

Returns:

rating history for all game types

Parameters:

username (str) –

Return type:

List[Dict[str, Any]]

get_realtime_statuses(*user_ids: str, with_game_ids: bool = False) List[Dict[str, Any]][source]

Get the online, playing, and streaming statuses of players.

Only id and name fields are returned for offline users.

Parameters:
  • user_ids (str) – one or more user IDs (names)

  • with_game_ids (bool) – whether or not to return IDs of the games being played

Returns:

statuses of given players

Return type:

List[Dict[str, Any]]

get_user_performance(username: str, perf: str) List[Dict[str, Any]][source]

Read performance statistics of a user, for a single performance.

Similar to the performance pages on the website

Parameters:
  • username (str) –

  • perf (str) –

Return type:

List[Dict[str, Any]]

Session

class berserk.session.Requestor(session: Session, base_url: str, default_fmt: FormatHandler[T])[source]

Bases: Generic[T]

Encapsulates the logic for making a request.

Parameters:
  • session (requests.Session) – the authenticated session object

  • base_url (str) – the base URL for requests

  • default_fmt (FormatHandler[T]) – default format handler to use

get(path: str, *, stream: Literal[False] = False, params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: FormatHandler[U], converter: Callable[[U], U] = utils.noop, **kwargs: Any) U[source]
get(path: str, *, stream: Literal[True], params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: FormatHandler[U], converter: Callable[[U], U] = utils.noop, **kwargs: Any) Iterator[U]
get(path: str, *, stream: Literal[False] = False, params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: None = None, converter: Callable[[T], T] = utils.noop, **kwargs: Any) T
get(path: str, *, stream: Literal[True], params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: None = None, converter: Callable[[T], T] = utils.noop, **kwargs: Any) Iterator[T]

Convenience method to make a GET request.

post(path: str, *, stream: Literal[False] = False, params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: FormatHandler[U], converter: Callable[[U], U] = utils.noop, **kwargs: Any) U[source]
post(path: str, *, stream: Literal[True], params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: FormatHandler[U], converter: Callable[[U], U] = utils.noop, **kwargs: Any) Iterator[U]
post(path: str, *, stream: Literal[False] = False, params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: None = None, converter: Callable[[T], T] = utils.noop, **kwargs: Any) T
post(path: str, *, stream: Literal[True], params: Mapping[str, int | bool | str | None] | None = None, data: str | Mapping[str, int | bool | str | None] | None = None, json: Dict[str, Any] | None = None, fmt: None = None, converter: Callable[[T], T] = utils.noop, **kwargs: Any) Iterator[T]

Convenience method to make a POST request.

request(method: str, path: str, *, stream: bool = False, params: ~typing.Mapping[str, int | bool | str | None] | None = None, data: str | ~typing.Mapping[str, int | bool | str | None] | None = None, json: ~typing.Dict[str, ~typing.Any] | None = None, fmt: ~berserk.formats.FormatHandler[~typing.Any] | None = None, converter: ~typing.Callable[[~typing.Any], ~typing.Any] = <function noop>, **kwargs: ~typing.Any) Any | Iterator[Any][source]

Make a request for a resource in a paticular format.

Parameters:
  • method (str) – HTTP verb

  • path (str) – the URL suffix

  • stream (bool) – whether to stream the response

  • params (Mapping[str, int | bool | str | None] | None) – request query parametrs

  • data (str | Mapping[str, int | bool | str | None] | None) – request body data (url-encoded)

  • json (Dict[str, Any] | None) – request body json

  • fmt (FormatHandler[Any] | None) – the format handler

  • converter (Callable[[Any], Any]) – function to handle field conversions

  • kwargs (Any) –

Returns:

response

Raises:

berserk.exceptions.ResponseError – if the status is >=400

Return type:

Any | Iterator[Any]

class berserk.session.TokenSession(token: str)[source]

Bases: Session

Session capable of personal API token authentication.

Parameters:

token (str) – personal API token

Formats

class berserk.formats.FormatHandler(mime_type: str)[source]

Bases: Generic[T]

Provide request headers and parse responses for a particular format.

Instances of this class should override the parse_stream() and parse() methods to support handling both streaming and non-streaming responses.

Parameters:

mime_type (str) – the MIME type for the format

handle(response: ~requests.models.Response, is_stream: bool, converter: ~typing.Callable[[~berserk.formats.T], ~berserk.formats.T] = <function noop>) T | Iterator[T][source]

Handle the response by returning the data.

Parameters:
  • response (requests.Response) – raw response

  • is_stream (bool) – True if the response is a stream

  • converter (func) – function to handle field conversions

Returns:

either all response data or an iterator of response data

Return type:

T | Iterator[T]

parse(response: Response) T[source]

Parse all data from a response.

Parameters:

response (requests.Response) – raw response

Returns:

response data

Return type:

T

parse_stream(response: Response) Iterator[T][source]

Yield the parsed data from a stream response.

Parameters:

response (requests.Response) – raw response

Returns:

iterator over the response data

Return type:

Iterator[T]

berserk.formats.JSON = <berserk.formats.JsonHandler object>

Handles vanilla JSON

berserk.formats.JSON_LIST = <berserk.formats.JsonHandler object>

Handle vanilla JSON where the response is a top-level list (this is only needed bc of type checking)

class berserk.formats.JsonHandler(mime_type: str, decoder: ~typing.Type[~json.decoder.JSONDecoder] = <class 'json.decoder.JSONDecoder'>)[source]

Bases: FormatHandler[Dict[str, Any]]

Handle JSON data.

Parameters:
  • mime_type (str) – the MIME type for the format

  • decoder (json.JSONDecoder) – the decoder to use for the JSON format

parse(response: Response) Dict[str, Any][source]

Parse all JSON data from a response.

Parameters:

response (requests.Response) – raw response

Returns:

response data

Return type:

JSON

parse_stream(response: Response) Iterator[Dict[str, Any]][source]

Yield the parsed data from a stream response.

Parameters:

response (requests.Response) – raw response

Returns:

iterator over multiple JSON objects

Return type:

Iterator[Dict[str, Any]]

berserk.formats.LIJSON = <berserk.formats.JsonHandler object>

Handles oddball LiChess JSON (normal JSON, crazy MIME type)

berserk.formats.NDJSON = <berserk.formats.JsonHandler object>

Handles newline-delimited JSON

berserk.formats.NDJSON_LIST = <berserk.formats.JsonHandler object>

Handles newline-delimited JSON where the response is a top-level list (this is only needed bc of type checking, if not streaming NJDSON, the result is always a list)

berserk.formats.PGN = <berserk.formats.PgnHandler object>

Handles PGN

class berserk.formats.PgnHandler[source]

Bases: FormatHandler[str]

Handle PGN data.

parse(response: Response) str[source]

Parse all text data from a response.

Parameters:

response (requests.Response) – raw response

Returns:

response text

Return type:

str

parse_stream(response: Response) Iterator[str][source]

Yield the parsed PGN games from a stream response.

Parameters:

response (requests.Response) – raw response

Returns:

iterator over multiple PGN texts

Return type:

Iterator[str]

berserk.formats.TEXT = <berserk.formats.TextHandler object>

Basic text

class berserk.formats.TextHandler[source]

Bases: FormatHandler[str]

parse(response: Response) str[source]

Parse all data from a response.

Parameters:

response (requests.Response) – raw response

Returns:

response data

Return type:

str

parse_stream(response: Response) Iterator[str][source]

Yield the parsed data from a stream response.

Parameters:

response (requests.Response) – raw response

Returns:

iterator over the response data

Return type:

Iterator[str]

Exceptions

exception berserk.exceptions.ApiError(error: Exception)[source]

Bases: BerserkError

Parameters:

error (Exception) –

exception berserk.exceptions.BerserkError[source]

Bases: Exception

property message: str
exception berserk.exceptions.ResponseError(response: Response)[source]

Bases: ApiError

Response that indicates an error.

Parameters:

response (Response) –

property cause
property reason

HTTP status text of the response.

property status_code

HTTP status code of the response.

berserk.exceptions.get_message(e: Exception) str[source]
Parameters:

e (Exception) –

Return type:

str

berserk.exceptions.set_message(e: Exception, value: str) None[source]
Parameters:
  • e (Exception) –

  • value (str) –

Return type:

None

Utils

class berserk.utils.RatingHistoryEntry(year, month, day, rating)[source]
Parameters:
  • year (int) –

  • month (int) –

  • day (int) –

  • rating (int) –

day: int

Alias for field number 2

month: int

Alias for field number 1

rating: int

Alias for field number 3

year: int

Alias for field number 0

berserk.utils.build_adapter(mapper: Dict[str, str], sep: str = '.')[source]

Build a data adapter.

Uses a map to pull values from an object and assign them to keys. For example:

>>> mapping = {
...   'broadcast_id': 'broadcast.id',
...   'slug': 'broadcast.slug',
...   'name': 'broadcast.name',
...   'description': 'broadcast.description',
...   'syncUrl': 'broadcast.sync.url',
... }

>>> cast = {'broadcast': {'id': 'WxOb8OUT',
...   'slug': 'test-tourney',
...   'name': 'Test Tourney',
...   'description': 'Just a test',
...   'ownerId': 'rhgrant10',
...   'sync': {'ongoing': False, 'log': [], 'url': None}},
...  'url': 'https://lichess.org/broadcast/test-tourney/WxOb8OUT'}

>>> adapt = build_adapter(mapping)
>>> adapt(cast)
{'broadcast_id': 'WxOb8OUT',
'slug': 'test-tourney',
'name': 'Test Tourney',
'description': 'Just a test',
'syncUrl': None}
Parameters:
  • mapper (dict) – map of keys to their location in an object

  • sep (str) – nested key delimiter

Returns:

adapted data

Return type:

dict

berserk.utils.datetime_from_millis(millis: float) datetime[source]

Return the datetime for the given millis since the epoch.

UTC is assumed. The returned datetime is timezone aware.

Parameters:

millis (float) –

Return type:

datetime

berserk.utils.datetime_from_seconds(ts: float) datetime[source]

Return the datetime for the given seconds since the epoch.

UTC is assumed. The returned datetime is timezone aware.

Parameters:

ts (float) –

Return type:

datetime

berserk.utils.datetime_from_str(dt_str: str) datetime[source]

Convert the time in a string to a datetime.

UTC is assumed. The returned datetime is timezone aware. The format must match ISO 8601.

Parameters:

dt_str (str) –

Return type:

datetime

berserk.utils.datetime_from_str_or_millis(millis_or_str: str | int) datetime[source]

Convert a string or int to a datetime.

UTC is assumed. The returned datetime is timezone aware. If the input is a string, the format must match ISO 8601.

Parameters:

millis_or_str (str | int) –

Return type:

datetime

berserk.utils.timedelta_from_millis(millis: float) timedelta[source]

Return a timedelta (A duration expressing the difference between two datetime or date instances to microsecond resolution.) for a given milliseconds.

Parameters:

millis (float) –

Return type:

timedelta

berserk.utils.to_millis(dt: datetime) int[source]

Return the milliseconds between the given datetime and the epoch.

Parameters:

dt (datetime) –

Return type:

int