def main(): mycertabo = certabo.certabo.Certabo(port=portname, calibrate=calibrate) try: with open('./lichess.token') as f: token = f.read().strip() except FileNotFoundError: print(f'ERROR: cannot find token file') sys.exit(-1) except PermissionError: print(f'ERROR: permission denied on token file') sys.exit(-1) try: session = berserk.TokenSession(token) except: e = sys.exc_info()[0] print(f"cannot create session: {e}") logging.info(f'cannot create session {e}') sys.exit(-1) try: if args.devmode: client = berserk.Client(session, base_url="https://lichess.dev") else: client = berserk.Client(session) except: e = sys.exc_info()[0] logging.info(f'cannot create lichess client: {e}') print(f"cannot create lichess client: {e}") sys.exit(-1) tmp_chessboard = chess.Board() logging.info(f'final FEN: {tmp_chessboard.fen()}') board = chess.Board() game = chess.pgn.Game() node = game while True: while mycertabo.has_user_move() == []: time.sleep(0.1) try: node = node.add_variation( chess.Move.from_uci(mycertabo.has_user_move()[0])) exporter = chess.pgn.StringExporter(headers=True, variations=True, comments=True) pgn_string = pgn_string = game.accept(exporter) client.broadcasts.push_pgn_update('M6aFOEQh', [pgn_string]) board.push_uci(mycertabo.has_user_move()[0]) mycertabo.set_board_from_fen(board.fen()) except berserk.exceptions.ResponseError as e: print(f'ERROR: Invalid server response: {e}') logging.info('Invalid server response: {e}') if 'Too Many Requests for url' in str(e): time.sleep(10) time.sleep(5)
def __init__(self, tokenName="token", debug=False): self.debug = debug token = self.getToken(tokenName) if token is not None: self.session = berserk.TokenSession(token) self.client = berserk.Client(self.session) else: self.client = None self.account = None
def initLiChessClient(self) -> None: try: with open(self.config.get('lichess', 'tokenFile')) as file: token = file.read() except: sg.PopupError('Unable to open lichess token file', title='ERROR') return session = berserk.TokenSession(token) self.lichessClient = berserk.Client(session)
def test(): with open('./lichess.token') as f: token = f.read().strip() session = berserk.TokenSession(token) client = berserk.Client(session) ratings = [(p['date'], p['rating']) for p in client.users.get_puzzle_activity()] plt.plot(list(range(len(ratings))), [x[1] for x in ratings]) plt.show()
def get_games(user: str, start: datetime, end: datetime, games: int = 100): client = berserk.Client() start = berserk.utils.to_millis(start) end = berserk.utils.to_millis(end) return client.games.export_by_player(user, since=start, until=end, max=games, as_pgn=True)
def main(): """ Entrypoint for calling this script. """ # Get live streamers. client = berserk.Client() streamers = client.users.get_live_streamers() # Update with {'front-page': true/false}. # Abuses the fact that the main page lists the streamers ids as part of the relative URLs). r = requests.get('https://lichess.org/') front_page_ids = [x[0:x.find('"')] for x in str(r.content).split('/streamer/')[1:]] streamers = [dict(x, **{'front-page': x['id'] in front_page_ids}) for x in streamers] update_streamers_file(streamers)
def fetch_lichess_org_games(user: str) -> list: """Uses the lichess API to fetch the requested users games. Args: user: A lichess username Returns: list: A list of all games for that user. """ client = berserk.Client() req = client.games.export_by_player(user, as_pgn=True) games_list = list(req) print(f"INFO: Imported {len(games_list)} games from lichess.org") return games_list
def __init__(self, TOKEN): if TOKEN in (None, ""): raise Exception('Token is empty!') try: session = berserk.TokenSession(TOKEN) except Exception as e: print(f'Could not create session: {e}') sys.exit(-1) try: self.client = berserk.Client(session=session) except Exception as e: print(f'Could not create client: {e}') sys.exit(-1) self.profile = self.client.account.get() print(f'Logged in as {self.profile["username"]}')
def get_data(games): # acpl: average centipawn loss with open('./token.txt') as f: token = f.read() session = berserk.TokenSession(token) client = berserk.Client() # for game in games: game_results = client.games.export_multi(*games, evals="true", moves="true") for game_result in game_results: if "aiLevel" not in game_result["players"]["black"]: buckets[int(game_result["players"]["black"]["rating"] / bucket_size)].\ append(game_result["players"]["black"]["analysis"]) if "aiLevel" not in game_result["players"]["white"]: buckets[int(game_result["players"]["white"]["rating"] / bucket_size)]. \ append(game_result["players"]["white"]["analysis"])
def main(): args = config_argparser() logging.debug("Using token: %s", args.token_file) user_name = args.token_file.split('.')[0] user_id = user_name.lower() logging.debug("user_id=%s", user_id) with open(args.token_file, 'r') as id_file: token = id_file.read().strip() logging.debug("token=%s", token) lichess = berserk.Client(berserk.TokenSession(token)) for event in lichess.bots.stream_incoming_events(): logging.debug("Incoming event for '%s': %s", user_id, event) if event["type"] == Event.CHALLENGE.value: challenge = event[Event.CHALLENGE.value] challenge_id = challenge["id"] challenger_id = challenge["challenger"]["id"] if not challenge["rated"]: lichess.bots.accept_challenge(challenge_id) logging.info("Casual challenge '%s' accepted from '%s'", challenge_id, challenger_id) game = getGame(lichess, challenge_id, user_id, user_name) logging.debug("game=%s", game) game.play() else: lichess.bots.decline_challenge(challenge_id) logging.info("Rated challenge '%s' declined from '%s'", challenge_id, challenger_id) else: challenge_id = event[Event.GAME.value]["id"] logging.info("Trying to play existing game: '%s'", challenge_id) game = getGame(lichess, challenge_id, user_id, user_name) game.play()
import berserk import game import chess # The following code has been adapted from cheran-senthil's SultanKhan2 chess engine to interface with the lichess API # Gets account token and bot id token = 'gkj6XyUvUSTPg4mJ' bot_id = 'Gecko_Bot' # opens sesion with lichess.orf session = berserk.TokenSession(token) lichess = berserk.Client(session) g = None is_white = True tc = None game_id = None rv = False # Loops while active while True: # If disconnected, will try to reconnect try: # loops for challenges for event in lichess.bots.stream_incoming_events(): print("Event Type: " + event['type']) if event['type'] == 'challenge': challenge = event['challenge'] # Accepts challenges that are standard variant if challenge['variant']['key'] == 'standard': game_id = challenge['id'] tc = challenge['timeControl']['limit'], challenge[ 'timeControl']['increment'] lichess.bots.accept_challenge(game_id)
from CheckmatePattern import CheckmatePattern import chess, chess.pgn import io import berserk import json with open('token.json') as f: token = json.load(f) client = berserk.Client(session=berserk.TokenSession(token["token"])) player = input('Please enter the lichess.org account you want to analyze: ') print( "Fetching " + player + "'s games. This may take a moment on the number of games they have played...\n" ) games = list(client.games.export_by_player(player)) gave_checkmate_moves = [] recieved_checkmate_moves = [] gave_checkmate_ids = [] recieved_checkmate_ids = [] for i in range(len(games)): try: if games[i]['status'] == 'mate' and games[i]['variant'] == 'standard': if games[i]['players']['white']['user'][ 'name'] == player and games[i]['winner'] == 'white': gave_checkmate_moves.append(games[i]['moves']) gave_checkmate_ids.append(games[i]['id'])
def init() -> tuple: gh_gist = Github(ENV_VAR_GITHUB_TOKEN).get_gist(ENV_VAR_GIST_ID) lichess_acc = berserk.Client().users.get_public_data(ENV_VAR_LICHESS_USERNAME) return (gh_gist, lichess_acc)
def start(): session = berserk.TokenSession(token) client = berserk.Client(session) is_white = None game_id = None def should_accept(challenge): return True standard = challenge['variant']['key'] == 'standard' rated = challenge['rated'] return standard and not rated for event in client.bots.stream_incoming_events(): print(event) if event['type'] == 'challenge': challenge = event['challenge'] # We did challenge if challenge['challenger']['id'] == bot_id: continue if should_accept(challenge): client.bots.accept_challenge(challenge['id']) else: client.bots.decline_challenge(challenge['id']) elif event['type'] == 'gameStart': gameEvent = event['game'] #engine = Engine(evaluators.simple_evaluator) engine = Engine(evaluators.net_evaluator, depth=3) game = Game(client, gameEvent['id'], engine, bot_id) games[gameEvent['id']] = game game.start() elif event['type'] == 'gameFinish': gameEvent = event['game'] game_id = gameEvent['id'] client.bots.post_message(game_id, 'GG') if game_id in games: game = games[game_id] game.join() del games[game_id] if TRIGGER_REMATCH: game = client.games.export(game_id) players = game['players'] print(players) white = players['white']['user'] if 'user' in players[ 'white'] else None black = players['black']['user'] if 'user' in players[ 'black'] else None if not white or not black: # ai ailevel = players['white'][ 'aiLevel'] if white is None else players['black'][ 'aiLevel'] time.sleep(1) client.challenges.create_ai(ailevel, clock_limit=60 * 30, clock_increment=30) else: opponent = white if white['id'] != bot_id else black time.sleep(1) client.challenges.create(opponent['id'], False, clock_limit=60 * 5, clock_increment=5)
def main(): simplejson_spec = importlib.util.find_spec("simplejson") if simplejson_spec is not None: print( f'ERROR: simplejson is installed. The berserk lichess client will not work with simplejson. Please remove the module. Aborting.' ) sys.exit(-1) mycertabo = certabo.certabo.Certabo(port=portname, calibrate=calibrate) try: logging.info(f'reading token from {TOKEN_FILE}') with open(TOKEN_FILE) as f: token = f.read().strip() except FileNotFoundError: print(f'ERROR: cannot find token file') sys.exit(-1) except PermissionError: print(f'ERROR: permission denied on token file') sys.exit(-1) try: session = berserk.TokenSession(token) except: e = sys.exc_info()[0] print(f"cannot create session: {e}") logging.info(f'cannot create session {e}') sys.exit(-1) try: if args.devmode: client = berserk.Client(session, base_url="https://lichess.dev") else: client = berserk.Client(session) except: e = sys.exc_info()[0] logging.info(f'cannot create lichess client: {e}') print(f"cannot create lichess client: {e}") sys.exit(-1) def is_correspondence(gameId): try: for game in client.games.get_ongoing(): if game['gameId'] == gameId: if game['speed'] == "correspondence": return True except: e = sys.exc_info()[0] print(f"cannot determine game speed: {e}") logging.info(f'cannot determine if game is correspondence: {e}') return False return False def setup_new_gameid(gameId): for game in client.games.get_ongoing(): if game['gameId'] == gameId: mycertabo.new_game() mycertabo.set_reference(game['gameId']) logging.info( f'setup_new_gameid() found gameId: {mycertabo.get_reference()}' ) tmp_chessboard = chess.Board() # unfortunately this is not a complete FEN. So we can only determine position and who's turn it is for an already ongoing game, but have no idea about castling # rights and en passant. But that's the best we can do for now, and on the next state update we'll get all moves and can replay them to get a complete board state tmp_chessboard.set_fen(game['fen']) if game['isMyTurn'] and game['color'] == 'black': tmp_chessboard.turn = chess.BLACK else: tmp_chessboard.turn = chess.WHITE mycertabo.set_board_from_fen(tmp_chessboard.fen()) logging.info(f'final FEN: {tmp_chessboard.fen()}') if game['color'] == 'black': mycertabo.set_color(chess.BLACK) else: mycertabo.set_color(chess.WHITE) if game['isMyTurn']: mycertabo.set_state('myturn') while True: try: logging.debug(f'board event loop') for event in client.board.stream_incoming_events(): if event['type'] == 'challenge': print("Challenge received") print(event) elif event['type'] == 'gameStart': # {'type': 'gameStart', 'game': {'id': 'pCHwBReX'}} game_data = event['game'] logging.info(f"game start received: {game_data['id']}") # check if game speed is correspondence, skip those if --correspondence argument is not set if not correspondence: if is_correspondence(game_data['id']): logging.info( f"skipping corespondence game: {game_data['id']}" ) continue try: game = Game(client, mycertabo, game_data['id']) game.daemon = True game.start() except berserk.exceptions.ResponseError as e: if 'This game cannot be played with the Board API' in str( e): print('cannot play this game via board api') logging.info(f'ERROR: {e}') continue setup_new_gameid(game_data['id']) if mycertabo.get_state() == 'myturn': logging.info( f'starting new game, checking for user move') mycertabo.set_state('init') moves = mycertabo.get_user_move() client.board.make_move(mycertabo.get_reference(), moves[0]) except berserk.exceptions.ResponseError as e: print(f'ERROR: Invalid server response: {e}') logging.info('Invalid server response: {e}') if 'Too Many Requests for url' in str(e): time.sleep(10)
# SETUP STUFF HERE dotenv.load_dotenv() LICHESS_TOKEN = os.getenv('LICHESS_TOKEN') DISCORD_TOKEN = os.getenv('DISCORD_TOKEN') DISCORD_SERVER_ID = int(os.getenv('DISCORD_SERVER_ID')) DISCORD_CHANNEL_ID = int(os.getenv('DISCORD_CHANNEL_ID')) CHESS_GAME_ID = os.getenv('CHESS_GAME_ID') # Make game board board = chess.Board() # Setup lichess connection session = berserk.TokenSession(LICHESS_TOKEN) chess_client = berserk.Client(session) # Get game info game = chess_client.games.export(CHESS_GAME_ID) # DISCORD STUFF HERE discord_client = discord.Client() @discord_client.event async def on_ready(): print(f'{discord_client.user} has connected to Discord!') channel = discord_client.get_channel(DISCORD_CHANNEL_ID) stream = chess_client.board.stream_game_state(CHESS_GAME_ID) for event in stream:
def main(argv: list) -> None: global client, lok, CHALLENGE, challenge_time, challenge_user, challenge_increment, challenge_color, ldebug, AUTO_CHALLENGE print("Starting...") if len(argv) > 1: argc = 0 for arg in argv: if argc == 0: if arg == "-v" or arg == "--verbose": ldebug = _ldebug if arg == "-q" or arg == "--quiet": lok = lnone ldebug = lnone lerr = lnone if arg == "-h" or arg == "--help": print(HELP_USAGE) print("Description : Crocrodile Lichess client") print("Commands :") print("\t-h, --help : Show this message and exit") print("\t-v, --verbose : Show debug logs") print("\t-q, --quiet : Don't show any logs") print(HELP_CHALLENGE) print("\t-a, --auto : Auto challenge BOTs") print("\t-n, --neural-network : Enable Neural Network") print("\t-u, --upgrade: Upgrade to bot account") print("\t-d, --dev : Dev account") sys.exit(0) if arg == "-c" or arg == "--challenge": argc = 1 if arg in ("-a", "--auto"): AUTO_CHALLENGE = True if arg in ("-n", "--neural-network"): minimax = yukoo.search if arg in ("-u", "--upgrade"): client.account.upgrade_to_bot() if arg in ("-d", "--dev"): session = berserk.TokenSession(open("dev.token").read()) client = berserk.Client(session) else: arg_list = arg.split(" ") print(arg_list) if len(arg) > 3: CHALLENGE = True challenge_user = arg_list[0] challenge_time = arg_list[1] challenge_increment = arg_list[2] challenge_color = arg_list[3] argc = 0 else: ldebug = lnone lok(None, "Token is", token, store=False) lok( None, "Connected to", client.account.get().get("title", "USER"), client.account.get().get("username", "Anonymous"), store=False, ) lok(None, "Waiting for challenges") continue_loop = True colors = {} fens = {} if CHALLENGE: print(challenge_time) challenge = client.challenges.create( challenge_user, True, clock_limit=int(float(challenge_time)) * 60, clock_increment=int(challenge_increment), color=challenge_color, ) ldebug(challenge) if challenge["challenge"]["color"] == "white": colors[challenge["challenge"]["id"]] = "black" else: colors[challenge["challenge"]["id"]] = "white" fens[challenge["challenge"]["id"]] = chess.STARTING_FEN while continue_loop: for event in client.bots.stream_incoming_events(): ldebug(event) if event["type"] == "challenge": lok( event["challenge"]["id"], "From", show_user_description(event["challenge"]["challenger"]), "- received", ) if (event["challenge"]["speed"] in SPEEDS and event["challenge"]["variant"]["key"] in VARIANTS and not event["challenge"]["id"] in colors and event["challenge"]["challenger"]["id"] != "crocrodile"): # patch-002 client.bots.accept_challenge(event["challenge"]["id"]) lok(event["challenge"]["id"], "Accepted") colors[event["challenge"] ["id"]] = event["challenge"]["color"] if event["challenge"]["variant"]["key"] == "fromPosition": fens[event["challenge"] ["id"]] = event["challenge"]["initialFen"] else: fens[event["challenge"]["id"]] = chess.STARTING_FEN else: if event["challenge"]["challenger"]["id"] != "crocrodile": if event["challenge"]["id"] in colors: lok( event["challenge"]["id"], "Declining because this is a rematch", ) elif event["challenge"]["speed"] not in SPEEDS: lok( event["challenge"]["id"], "Declining because the bot doesn't play this \ speed (" + event["challenge"]["speed"].capitalize() + ")", ) elif event["challenge"]["variant"][ "key"] not in VARIANTS: lok( event["challenge"]["id"], "Declining because the bot doesn't play this \ variant (" + event["challenge"]["variant"]["name"] + ")", ) else: lok( event["challenge"]["id"], "Declining", ) client.bots.decline_challenge(event["challenge"]["id"]) if event["challenge"]["id"] in colors: client.bots.post_message( event["challenge"]["id"], "I don't accept rematches (lot of bugs)", ) else: lok( event["challenge"]["id"], "Challenging " + show_user_description( event["challenge"]["destUser"]), ) elif event["type"] == "gameStart": game = Game( client, event["game"]["id"], colors[event["game"]["id"]], fens[event["game"]["id"]], ) game.start() elif event["type"] == "gameFinish": if AUTO_CHALLENGE: challenge = client.challenges.create( challenge_user, True, clock_limit=int(float(challenge_time)) * 60, clock_increment=int(challenge_increment), color=challenge_color, ) if challenge["challenge"]["color"] == "white": colors[challenge["challenge"]["id"]] = "black" else: colors[challenge["challenge"]["id"]] = "white" fens[challenge["challenge"]["id"]] = chess.STARTING_FEN lok(event["game"]["id"], "Finished") elif event["type"] == "challengeDeclined": if event["challenge"]["challenger"]["id"] == "crocrodile": lok( event["challenge"]["id"], "Declined by " + show_user_description(event["challenge"]["destUser"]), ) else: lok(event["challenge"]["id"], "Declined") else: ldebug(event["type"], ":", event)
def create_lichess_session(): LICHESS_KEY = load_lichess_api_key() session = berserk.TokenSession(LICHESS_KEY) client = berserk.Client(session=session) return client
def main(): home = str(Path.home()) engine = chess.engine.SimpleEngine.popen_uci(home + "/stockfish_10_x64") username = prompt(HTML('<violet>Enter your lichess username: </violet>')) client = berserk.Client() move_place = 0 moves = [] game_list = [] game_number = 0 analysis_archive = [] kb = KeyBindings() kba = KeyBindings() @kb.add('c-q') def exit_(event): nonlocal move_place nonlocal moves move_place = 0 moves = [] game_list = [] game_number = 0 event.app.exit() @kb.add('c-a') def prev(event): nonlocal move_place nonlocal moves if move_place > 0: move_place = move_place - 1 display_simple_screen(event, game_list, game_number, moves, move_place) @kb.add('c-d') def next(event): nonlocal move_place nonlocal moves if move_place < len(moves) - 1: move_place = move_place + 1 display_simple_screen(event, game_list, game_number, moves, move_place) @kba.add('c-q') def exit_(event): nonlocal move_place nonlocal moves move_place = 0 moves = [] game_list = [] game_number = 0 analysis_archive = [] event.app.exit() @kba.add('c-a') def prev(event): nonlocal move_place nonlocal moves if move_place > 0: move_place = move_place - 1 display_analysis_screen(event, game_list, game_number, moves, move_place, analysis_archive) @kba.add('c-d') def next(event): nonlocal move_place nonlocal moves if move_place < len(moves) - 1: move_place = move_place + 1 display_analysis_screen(event, game_list, game_number, moves, move_place, analysis_archive) try: game_generator = client.games.export_by_player(username, as_pgn=False, max=10) game_list = list(game_generator) command = prompt( HTML( '\n\u265A <cyan>Welcome to ChessView!</cyan> \u2654\nType "help" for info on commands\n>' )) while (command != 'exit'): if (command == 'list'): print_games(game_list) elif (command == 'help'): help() elif (command.startswith('info(')): print_formatted_text(game_list[int(command[5:6])]) elif (re.match('view\(\d\)', command)): game_number = int(command[5:6]) moves = game_to_fenlist(game_list[game_number]['moves']) chess_text = set_simple_chess_text(game_list, game_number, moves, 0) root_container = VSplit([ Window(width=30, content=FormattedTextControl(), dont_extend_width=True, wrap_lines=True, allow_scroll_beyond_bottom=True, always_hide_cursor=True), Window(width=1, char='|', always_hide_cursor=True), Window(content=FormattedTextControl(text=HTML(chess_text)), always_hide_cursor=True) ]) layout = Layout(root_container) app = Application(key_bindings=kb, layout=layout, full_screen=True) app.run() elif (re.match('analyze\(\d\)', command)): game_number = int(command[8:9]) moves = game_to_fenlist(game_list[game_number]['moves']) analysis_archive = analysis_to_move_archive( game_list[game_number]['moves'], engine) chess_text = set_analysis_chess_text(game_list, game_number, moves, 0, analysis_archive) root_container = VSplit([ Window(width=30, content=FormattedTextControl(), dont_extend_width=True, wrap_lines=True, allow_scroll_beyond_bottom=True, always_hide_cursor=True), Window(width=1, char='|', always_hide_cursor=True), Window(content=FormattedTextControl(text=HTML(chess_text)), always_hide_cursor=True) ]) layout = Layout(root_container) app = Application(key_bindings=kba, layout=layout, full_screen=True) app.run() command = prompt(HTML('>')) except Exception as e: print("Username not found or does not exist.") engine.quit()
try: profile['profile']['fideRating'] except KeyError: # If not just return an empty array other than username return (profile['id'], None, None, None, None, None) return ( profile['id'], profile['perfs']['bullet']['rating'], profile['perfs']['blitz']['rating'], profile['perfs']['rapid']['rating'], profile['perfs']['classical']['rating'], profile['profile']['fideRating'] ) client = berserk.Client() # Set this to the size of the raw dataset (before filtering out FIDE) cutoff_users = 100 # User to start on current_user = "******" # Using sets becuase they do not have duplicates profiles = set() users_crawled = set() # Perform the search while len(profiles) < cutoff_users: # Print cool status print('> ' + str(len(profiles)) + '/' + str(cutoff_users) + ' | scraping: ' + current_user + ' ', end='\r', flush=True)
# install data settings.install_data("./nltk_data") ##### # load setting settings.config_filename = "settings/config.json" config = settings.load_config() DISCORD_TOKEN = config['DISCORD_TOKEN'] LICHESS_TOKEN = config['LICHESS_TOKEN'] intents_filename = config['intentsFilename'] ##### # configuring lichess module session = berserk.TokenSession(LICHESS_TOKEN) lichess.client = berserk.Client(session=session) ##### # configuring detection module detection.load_intents(intents_filename) detection.extend_keywords() detection.build_regex_dict() ##### # dump all produced keywords to file (just from curiosity) settings.dump_all_keywords("all_keywords.txt", detection.intents) ##### client = discord.Client() currently_processed_intent = None
import discord import berserk import os from replit import db from keep_alive import keep_alive client = discord.Client() session = berserk.TokenSession(os.getenv('TOKEN')) liclient = berserk.Client(session) if "helper" not in db.keys(): db["helper"] = [ "'li help' -> information on how use li bot.", "li challenge [username] [rated=(True,False)] [clock_limit=(minutes)] [clock_increment=(seconds)]' -> challenge other person with that username", "'li create [clock_limit=(minutes)] [clock_increment=(seconds)] ' -> creates a open challenge where two players can join.", "'li tourny [name] [clock_time=(minutes)] [clock_increment=(seconds)] [wait_minutes] [rated=(True,False)] [length_of_tournament_in_minutes] ' -> creates a tournament with given parameters ." ] @client.event async def on_ready(): print('We have logged in as {0.user} discord bot account'.format(client)) usr_mail = liclient.account.get_email() print(f'We have logged in as {usr_mail} of lichess account') @client.event async def on_message(message): if message.author == client.user: return
def main(): #token = "lMysRaNxd9sNQkXj" rodfish token = "b0X9NKGbCQ3XWpz3" # coffebot session = berserk.TokenSession(token) client = berserk.Client(session) #client.account.upgrade_to_bot() 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) client.bots.post_message(game_id, "glhf") in_game = True print("The game has started!") gs = ChessEngine.GameState() moveMade = False # flag variable for when a move is made while (in_game): movecount = 0 state = client.games.export(game_id) move = state["moves"] if (gs.whiteToMove): # importing enemy move state = client.games.export(game_id) moves = state["moves"] move = moves.split() if len(move) % 2 == 1: moveE = gs.notationTransform(move[-1]) # enemy move print(moveE.getChessNotation()) move = gs.makeMove(moveE) movecount += 1 moveMade = True if moveMade: validMoves = gs.getValidMoves( gs.whiteToMove, False) # detects checkmate, stalemate if gs.checkMate: client.bots.post_message(game_id, "gg") print("MATE") moveMade = False else: time.sleep(0.5) if (not gs.whiteToMove): # bot playing a move validMoves = gs.getValidMoves(gs.whiteToMove, False) if len(validMoves) > 0: move = gs.computerMoveProoo() print(str(move.getChessNotation())) client.bots.make_move(game_id, str(move.getChessNotation())) print("evaluation: ", round(gs.evaluation(gs.whiteToMove), 2)) moveMade = True if moveMade: validMoves = gs.getValidMoves( gs.whiteToMove, False) # detects checkmate, stalemate if gs.checkMate: client.bots.post_message(game_id, "gg") print("MATE") moveMade = False
def __init__(self, api_key: str): session = berserk.TokenSession(api_key) self.client = berserk.Client(session) self.user_id = self.client.account.get()['id']
def __init__(self, token): session = berserk.TokenSession(token) self.client = berserk.Client(session=session)