def main(): with open('resources/.token') as f: token = f.read() f.close() session = berserk.TokenSession(token) process_curent_game(session)
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 main(): try: set_api(sys.argv[1]) os._exit(0) except: try: token_file = Path(__file__).parent.absolute() / "key" token = token_file.read_text() session = berserk.TokenSession(token) client = berserk.clients.Client(session) board = berserk.clients.Board(session) except: print("The API token is either empty or wrong. Please run the command 'lichess' and input your API token as a second argument, i.e 'lichs <api_token>'. If you need more help, please see the instructions in the Github README: \nhttps://github.com/Cqsi/lichs#how-to-generate-a-personal-api-token") os._exit(0) # Gets your account data, e.g ["id"], ["username"] account_data = client.account.get() player_id = account_data["id"] # Welcome text print("Welcome to Lichess!\n") print("What kind of chess do you want to play?") print("1. Rapid (10+0)\n2. Classical (30+0)\n") num = input("Enter 1 or 2: ") time = 0 if num=="1": time=10 elif num=="2": time=30 else: # This needs improvement, something like a while/for loop print("Something went wrong, please enter the lichess command again.") sys.exit() print("Searching after opponent...") board.seek(time, 0) for event in board.stream_incoming_events(): if event['type'] == 'gameStart': print("An opponent was found!") isWhite = True color = "Black" # We set the color to the opposite color of the player if player_id != client.games.export(event['game']['id'])['players']['white']['user']['id']: isWhite = False color = "White" print("You're playing as black!") print("White's turn...") else: print("You're playing as white!") game = Game(board, event['game']['id'], player_id, isWhite, color) game.start()
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 __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()
def test(): try: with open(pathlib.Path(__file__).parent.absolute() + "..\\key.txt") as f: token = f.read() session = berserk.TokenSession(token) client = berserk.clients.Client(session) board = berserk.clients.Board(session) except: print("The API-key is either empty or wrong. Please run the command 'lichesskey' and input your API-key correctly. If you need more help, please see the instructions in the Github README: \nhttps://github.com/Cqsi/lichess_terminal#how-to-generate-a-personal-api-token") os._exit(0) # Gets your account data, e.g ["id"], ["username"] account_data = client.account.get() player_id = account_data["id"] for event in board.stream_incoming_events(): if event['type'] == 'challenge': print("Challenge time!!!") # Accepts the challenge, mainly used for testing game_id = event['challenge']['id'] board.accept_challenge(game_id) elif event['type'] == 'gameStart': #print(client.games.export(event['game']['id'])) isWhite = True color = "Black" # We set the color to the opposite color of the player if player_id != client.games.export(event['game']['id'])['players']['white']['user']['id']: isWhite = False color = "White" print("You're playing as black!") print("White's turn...") else: print("You're playing as white!") game = Game.Game(board, event['game']['id'], player_id, isWhite, color) game.start()
import berserk import time import itertools client = berserk.Client() upgradeToBot = False if upgradeToBot: client.account.upgrade_to_bot() token = "" with open('.apitoken') as f: token = f.read().replace("\n", "") session = berserk.TokenSession("" + token) client = berserk.Client(session) gameRunning = False isWhite = True board = chess.Board() legalMoves = [] maxMoves = 1000 maxGames = 1 def getLegalMoves(board): legalMoves = []
def main(): if len(sys.argv) == 2: set_token(sys.argv[1]) if not token_file.exists(): print("Please provide a token key") print("See the instructions in the Github README:") print( "https://github.com/Cqsi/lichs#how-to-generate-a-personal-api-token" ) set_token(get_token()) token = token_file.read_text() session = berserk.TokenSession(token) client = berserk.clients.Client(session) board = berserk.clients.Board(session) # Gets your account data, e.g ["id"], ["username"] errOccurring = True while errOccurring: try: account_data = client.account.get() player_id = account_data["id"] errOccurring = False except berserk.exceptions.ResponseError as e: print("Error ", e, "occurred.") print("Unable to connect to Lichess") print("Check if your token key is right") print("Or try again later") set_token(get_token()) # Welcome text print("Welcome to Lichess in the Terminal (lichs)\n") print("Type either\nP to play\nH for help\nQ to quit ") optFlag = True # Flag for options menu while optFlag == True: choice = input("Choose your option: ") if choice.lower() == "h": print("You will find help on the website that's opening") os.system( "start https://github.com/Cqsi/lichs/blob/master/README.md#usage" ) elif choice.lower() == "q": print("Quitting...") sys.exit(0) elif choice.lower() == "p": optFlag = False else: print( "Please choose from either P to play, H for help, or Q to quit" ) print( "What kind of chess would you like to play? \n1. Rapid (10+0)\n2. Classical (30+0)\n" ) num = input( "Please choose from either 1 (Rapid, 10+0) or 2 (Classical, 30+0): ") typeFlag = True # Flag for gametype validation while typeFlag == True: if num == "1": time = 10 typeFlag = False elif num == "2": time = 30 typeFlag = False else: num = input( "Please choose from either 1 (Rapid, 10+0) or 2 (Classical, 30+0): " ) print("Searching after opponent...") board.seek(time, 0) for event in board.stream_incoming_events(): if event['type'] == 'gameStart': print("An opponent was found!") isWhite = True color = "Black" # We set the color to the opposite color of the player if player_id != client.games.export( event['game']['id'])['players']['white']['user']['id']: isWhite = False color = "White" print("You're playing as black!") print("White's turn...") else: print("You're playing as white!") game = Game(board, event['game']['id'], player_id, isWhite, color, time) game.start()
import berserk session = berserk.TokenSession("052oFyKs8nbYmmEH") client = berserk.Client(session=session) def blitz(username): return(int((client.users.get_rating_history(username).strip('][').split('{'))[2].split("[")[-1].split(",")[-2].strip("]]}"))) def bullet(username): return (int((client.users.get_rating_history(username).strip('][').split('{'))[1].split("[")[-1].split(",")[-2].strip("]]}"))) def rapid(username): return(int((client.users.get_rating_history(username).strip('][').split('{'))[3].split("[")[-1].split(",")[-2].strip("]]}"))) usernames = ["abhatnagar23", "AChandrasekar23", "LeggiadraVendetta", "ahamrah27", "gnorthup23", "rebeccaharris", "penguingim1"] print("Blitz Leaderboard") BlitzDict = {} for i in range(0, len(usernames)): BlitzDict[usernames[i]] = blitz(usernames[i]) BlitzTuples = sorted(BlitzDict.items(), key=lambda item: item[1], reverse=True) SortedBlitzDict = {k: v for k, v in BlitzTuples} for key, value in SortedBlitzDict.items(): print(key, ":", value) print("") print("Rapid Leaderboard") RapidDict = {} for i in range(0, len(usernames)):
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)
install() # 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)
statuses = {True: "●", False: "○"} if not user["title"]: return f"{statuses[user['online']]} {user['name']}" return f"{statuses[user['online']]} {user['title']} {user['name']}" ldebug = lnone lok = _lok lerr = _lerr CHALLENGE = False AUTO_CHALLENGE = False with open("lichess.token") as file: token = file.read()[:-1] session = berserk.TokenSession(token) client = berserk.Client(session) HELP_USAGE = 'Usage : client.py [-v | -q] [-h] \ [-c "user time increment color" | \ --challenge "user time increment color" | -a | --auto] \ [-n | --neural-network] [-u | --upgrade] [-d | --dev]' HELP_CHALLENGE = "\t-c, --challenge \"user time increment color\" : \ Challenge user in time+increment, BOT is playing with \ color ('white' or 'black')" def limit_time(total_time: float, increment: int) -> float: """Calculate minimum time to calculate best move.""" limit_time: float = increment + (total_time / 40) return limit_time
import os from dotenv import load_dotenv import requests import berserk import csv load_dotenv() # load .env file # load jwt token TOKEN = os.getenv("LICHESS_OAUTH") session = berserk.TokenSession(TOKEN) client = berserk.Client(session=session) puzzle_map = client.users.get_puzzle_activity() with open("puzzles.csv", "w") as f: lines = [] for puzzle in puzzle_map: p_id = puzzle["id"] date = puzzle["date"].strftime("%d/%m/%Y") win = puzzle["win"] puzzle_rating = puzzle["puzzleRating"] lines.append(f"{p_id},{date},{win},{puzzle_rating}\n") f.writelines(lines) current_date = None win_score = 0 lose_score = 0 lines = []
def create_lichess_session(): LICHESS_KEY = load_lichess_api_key() session = berserk.TokenSession(LICHESS_KEY) client = berserk.Client(session=session) return client
print("Finished exporting") dump_file = open(filename, "wb") pickle.dump(d_l, dump_file) dump_file.close() def testMyGames(filename): a_file = open(filename, "rb") output = pickle.load(a_file) for o in output: print(o.keys()) a_file.close() f = open("../../tokens/token.txt", "r") session = berserk.TokenSession(f.read()) client = berserk.Client(session) info = client.account.get() filename = "jmpcgeh_winning_fen.pkl" print("On air: ", info["seenAt"]) #getMyGames('jmcpgeh',filename) #testMyGames(filename) for event in client.bots.stream_incoming_events(): if event['type'] == 'challenge': print("challeng ack") challenge_id = event['challenge']['id'] client.bots.accept_challenge(challenge_id) elif event['type'] == 'gameStart': game_id = event['game']['id'] game = Game(client, game_id)
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 is_white_to_move(game, moves): return len(moves) % 2 == (0 if game.white_starts else 1) def is_engine_move(game, moves): return game.is_white == is_white_to_move(game, moves) # Get API Token from .env file BASE_URL = "https://lichess.org" load_dotenv() API_TOKEN = os.environ.get("API_TOKEN") # start session session = berserk.TokenSession(API_TOKEN) client = berserk.Client(session=session) game_id = 'QTxXIumt' test = berserk.clients.Board(session, BASE_URL) client_games = berserk.clients.Games(session, BASE_URL) test2 = berserk.clients # print(client_games.export(game_id)["lastMoveAt"]) # Twitch sock = socket.socket() twitch = Twitch(sock, "brainlighter") twitch.run() #game = Game(client, twitch, client_games,game_id) # game.start() # Twitch connection
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 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)
B_COST = 3 R_COST = 5 Q_COST = 9 K_COST = 9000 TRUE_CENTER = [35, 36, 27, 28] EXTENDED_CENTER = [34, 37, 26, 29] COSTS = [P_COST, N_COST, B_COST, R_COST, Q_COST, K_COST] GAME_ID = input("game ID: ") ENDGAME = False #LICHESS SETUP session = berserk.TokenSession("qtC39Sb45qvMgyLS") lichess = berserk.Client(session) handle = berserk.formats.FormatHandler(".json") bots = berserk.clients.Bots(session, "https://lichess.org/") class Node(): def __init__(self, brd: chess.Board, parent, scr, move): self.brd = brd self.parent = parent self.score = scr self.value = 0 self.children = [] self.move = move
#retrieves last 100 games of a given player name. #with this I can retrieve any game data I need. import berserk, pickle from the_token import access_token session = berserk.TokenSession(access_token) client = berserk.Client(session=session) games = list( client.games.export_by_player('AlephNaught202', max=10, as_pgn=True)) GamesPlayer = list( client.games.export_by_player('AlephNaught202', max=100, as_pgn=True)) with open('Last-100-games-AlephNaught202.pkl', 'wb') as f: pickle.dump(GamesPlayer, f) with open('Last-100-games-AlephNaught202.pkl', 'rb') as f: GamesPlayer = pickle.load(f) print(GamesPlayer[0]) print(GamesPlayer[99]) #retrieves last 100 games of a given player name. #with this I can retrieve any game data I need.
import pandas as pd import matplotlib.pyplot as plt from discord import File from discord.ext import commands from dotenv import load_dotenv import cairosvg from board import Board load_dotenv() discord_token = os.getenv('DISCORD_TOKEN') lichess_token = os.getenv('LICHESS_TOKEN') bot = commands.Bot(command_prefix='!') session = berserk.TokenSession(lichess_token) client = berserk.Client(session=session) boards: Dict[str, Board] = {} help_str = """ Gets pgn from lichess Syntax: !get_pgn <user> <perf_type> <*args> Examples: # All rapid games from 1.1.2021 - 2.2.2021 played as white !get_pgn tbsmrks rapid since=1.1.2021 until=2.2.2021 color=white # All blitz games played ever !get_pgn tbsmrks blitz
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
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 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 __init__(self, token): session = berserk.TokenSession(token) self.client = berserk.Client(session=session)