Giter Site home page Giter Site logo

panagiotisiatrou / chess-auto-bot Goto Github PK

View Code? Open in Web Editor NEW
72.0 5.0 26.0 4.26 MB

A bot for chess.com and lichess.org that automatically plays chess for you

License: MIT License

Python 99.94% Batchfile 0.06%
chess chesscom lichess bot python chess-bot stockfish automation chessbot

chess-auto-bot's Introduction

chess-auto-bot

A bot for chess.com and lichess.org that automatically plays chess for you

Chess.com

Lichess.org

Note that the mouse is being moved by python

How to install

  1. Clone the repository or just download the repository as a .zip
  2. Download Stockfish from https://stockfishchess.org/
    Note that on Linux systems you must manually add execute permissions to the stockfish executable
  3. Open a Terminal
  4. cd chess-auto-bot
  5. Windows: python -m venv venv
    Linux: python3 -m venv venv
  6. Windows: venv\Scripts\pip.exe install -r requirements.txt
    Linux: venv/bin/pip3 install -r requirements.txt

How to use

  1. Open a Terminal
  2. cd chess-auto-bot
  3. Windows: venv\Scripts\python.exe src\gui.py
    Linux: venv/bin/python3 src/gui.py
  4. Click Select Stockfish on the GUI that opens. This will open a file explorer. Navigate to the folder where you downloaded Stockfish and select the Stockfish executable.
  5. Click Open Browser. This will open ChromeDriver and load the selected chess website.
  6. Navigate to a live match (online or vs bot)
  7. Click Start (or press 1)
  8. Enjoy

Note You can stop the bot at any time by pressing Stop or pressing 2.

Currently supports

  • Windows/Linux platforms
  • Chess.com
  • Lichess.org
  • Playing vs humans
  • Playing vs bots
  • Puzzles (with option for non-stop solving):
    • chess.com
    • lichess.org
  • Manual mode (Press or hold 3 to move when enabled)
    An arrow with the best move is also displayed
  • Mouseless mode (The moves are made without the mouse moving, also works while the browser is at the background):
    • chess.com
    • lichess.org
  • Bongcloud mode ( ͡° ͜ʖ ͡° )
  • Skill level selection (0-20)
  • Depth level selection (1-20)
  • Memory (RAM) usage selection
  • CPU threads number selection
  • Slow Mover option (defaults to 100, 10 ≤ Slow Mover ≤ 1000)
    lower values will make Stockfish take less time in games, higher values will make it think longer
  • Exporting finished games to PGN

Disclaimer

Under no circumstances should you use this bot to cheat in online games or tournaments. This bot was made for educational purposes only. Using this bot to cheat in online games or tournaments is against the rules of chess.com and will result in a ban.

chess-auto-bot's People

Contributors

marcusm2092 avatar panagiotisiatrou avatar xheaven avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

chess-auto-bot's Issues

Doesnt work with cloud servers

So there is a chessify plugin by which we can connect any gui to their servers which provide fast speeds of analysis.
But when i keep the executable of chessify stockfish in the path, nothing happens, it just shows Starting...

Add support for detailed information

What I mean is for the program to display additional information per move, such as:

  • Predicted move sequence
  • Evaluation
  • Multiple principal variations (multi-pv)
  • Multiple arrows rendered when using Manual mode, with different opacity levels to symbolize strength (evaluation + pv)
  • Analysis (Similar to Chess.com analysis feature, meaning on every move the program responds with e.g. "Blunder", "Book Move", "Inaccuracy" etc...).
  • Opening name (e.g. "King's Pawn Opening")

These are just some ideas which might be fun to make, and can be quite useful. What I'd also appreciate is to create a specific readme for developers detailing what each file is used for, to make it easier and faster for developers to contribute!

Can't find board.

I've used this tool in the past, mid 2022 I think. I've had the exact same problem in the past but I can't remember how I fixed it, I open the browser after connecting stockfish to it, I press start and it just says "Can't find board" after a couple of seconds.

Thanks in advance.

Stop detecting or moving after first move :(

I installed it tonight, it was working too good, but then after dinner i came back to try again and everything was looking ok , but bot wasnt playing after 1st move. I noticed it wasnt event detecting opponents move either.

I am no good with python or any languages, but i tried to follow your instructions. It did work , but stopped working now. tried it on virtual machine as well , same problem there too.
(i dont know how to debug/find problem more specifically, so if there is any way to send you logs/anything you can tell me. )

Cant detect that chrome is installed

obraz_2023-08-23_212920703

Think it mightve happened since chrome got 116 update as i already implemented the change to gui.py to get the 114 chromium driver and it worked fine till today but no matter what i do (reinstall chrome, install 114 chrome ver, make sure to check if 114 chromium driver works) it always just pops up this error.

Any kind soul with better understanding of python knows a workaround to make it work again and open chrome like it used to?

"Mouseless Mode" is broken

Message: javascript error: lichess is not defined
(Session info: chrome=123.0.6312.59)
Stacktrace:
GetHandleVerifier [0x00D24CC3+225091]
(No symbol) [0x00C54E11]
(No symbol) [0x00AF9A7A]
(No symbol) [0x00AFDEB0]
(No symbol) [0x00AFFA76]
(No symbol) [0x00B665E2]
(No symbol) [0x00B4F55C]
(No symbol) [0x00B65CB0]
(No symbol) [0x00B4F2F6]
(No symbol) [0x00B279B9]
(No symbol) [0x00B2879D]
sqlite3_dbdata_init [0x01199A63+4064547]
sqlite3_dbdata_init [0x011A106A+4094762]
sqlite3_dbdata_init [0x0119B968+4072488]
sqlite3_dbdata_init [0x00E9C9C9+930953]
(No symbol) [0x00C607E4]
(No symbol) [0x00C5AD08]
(No symbol) [0x00C5AE31]
(No symbol) [0x00C4CAA0]
BaseThreadInitThunk [0x75C0FCC9+25]
RtlGetAppContainerNamedObjectPath [0x77AC7C5E+286]
RtlGetAppContainerNamedObjectPath [0x77AC7C2E+238]

<class 'selenium.common.exceptions.JavascriptException'> stockfish_bot.py 214

Can't find board

Won't work on Windows 11 at chess.com

Works fine on lichess but for some reason it just cannot find board on chess.com

Random download block in the terminal

Hi,

I'm just wondering why after playing around with this for a bit, why did this script randomly start to download something? I saw it displayed in the Terminal and I unfortunately didn't copy it or screenshot it but it was like "████████████ 100% " randomly in the console.

I've used it for 2 days now and it didn't do this until last night.

Could you explain what that would be or does this bot update automatically?

Frequent Illegal Move Error on Chess.com

I often come across an illegal move error on chess.com. The exception is thrown at stockfish_bot.py line 240 or 200.

Also I have noticed that the bot is quite slow on Chess.com compared to lichess, it makes a big difference in bullet for example.

Love it otherwise, good work.

Arrow bug

Arrow disappear when the enemy premoves.

showing error

module 'chess' has no attribute 'parse_square'
<class 'AttributeError'> stockfish_bot.py 208

error

list index out of range
<class 'IndexError'> stockfish_bot.py 129

nothing happens

when i click on the "Open Browser" button, nothing happens, it shows "Opening Browser..." endlessly. What should I do? I chose stockfish and cores and memory, but nothing happens.

Installation problem

image
The unfortunate cd chess-auto-bot command barely worked, but after the command python -m venv venv nothing happened, and subsequent commands basically refuse to work, how can I fix it?

error "list index out of range"

Against bots the script works fine, but against players when you run it in the console you get an error "list index out of range
<class 'IndexError'> stockfish_bot.py 129" and does not run

Last update bug.

Hello @PanagiotisIatrou, in the last update the bot no longer makes moves on the board. Regardless of whether it is set to manual or not. Arrows appear outside the boards.
Specs:
Win 10
Python 3.10
Default option bot (no modification).
Attachments:

Autoplay:
Untitled
Manual:
Untitled1

Can't find moves list + fix

Chess.com changed so now you get can't find moves list
Fix:
line 71| move_list_elem = self.chrome.find_element(By.TAG_NAME, "vertical-move-list")
change to
line 71 move_list_elem = self.chrome.find_element(By.TAG_NAME, "wc-vertical-move-list")

I can't install

I entered this platform for the first time to run this code and I don't know what to do, I did Win + R to open terminal and I wrote 'cmd' to the resulting window and I wrote all the commands you wrote separately in the window that opened, but I got the result 'cannot find the system' in all of them, new here I don't know if there is something I need to download and I want your help with the installation.
Also, I translated it because my mother tongue is not English, I apologize if it was translated incorrectly.

PyQt5 not installing

I'm only getting error messages when trying to use the install code, check the issue

option to disable keypress listener on linux.

Exception in thread Thread-4 (keypress_listener_thread):
Traceback (most recent call last):
  File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.10/threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "/home/crypt/ssd1/chess-auto-bot/src/gui.py", line 349, in keypress_listener_thread
    if keyboard.is_pressed("1"):
  File "/home/crypt/ssd1/chess-auto-bot/venv/lib/python3.10/site-packages/keyboard/__init__.py", line 410, in is_pressed
    _listener.start_if_necessary()
  File "/home/crypt/ssd1/chess-auto-bot/venv/lib/python3.10/site-packages/keyboard/_generic.py", line 35, in start_if_necessary
    self.init()
  File "/home/crypt/ssd1/chess-auto-bot/venv/lib/python3.10/site-packages/keyboard/__init__.py", line 196, in init
    _os_keyboard.init()
  File "/home/crypt/ssd1/chess-auto-bot/venv/lib/python3.10/site-packages/keyboard/_nixkeyboard.py", line 113, in init
    build_device()
  File "/home/crypt/ssd1/chess-auto-bot/venv/lib/python3.10/site-packages/keyboard/_nixkeyboard.py", line 109, in build_device
    ensure_root()
  File "/home/crypt/ssd1/chess-auto-bot/venv/lib/python3.10/site-packages/keyboard/_nixcommon.py", line 174, in ensure_root
    raise ImportError('You must be root to use this library on linux.')
ImportError: You must be root to use this library on linux.
You must be root to use this library on linux.
<class 'ImportError'> stockfish_bot.py 195

Linux users can't just run it with sudo, this will cause issues with graphical apps that use X (chrome, for example).

extending the move time

Hi, could you please extend the timer a bit longer ? because even with 1000, the bot always choose the same move and i had games where i was ahead like +8 but it always chose the same moves and ended up draw

"Stockfish path provided is not valid"

When I download stockfish, select it in the GUI, and start it, I get this error. On the terminal it says,

Exception ignored in: <function Stockfish.del at 0x0000015273DDE5C0>
Traceback (most recent call last):
File "C:\Users\Gaming Laptop\chess-auto-bot-main\venv\Lib\site-packages\stockfish\models.py", line 777, in del
self.send_quit_command()
File "C:\Users\Gaming Laptop\chess-auto-bot-main\venv\Lib\site-packages\stockfish\models.py", line 770, in send_quit_command
if self._stockfish.poll() is None:
^^^^^^^^^^^^^^^
AttributeError: 'Stockfish' object has no attribute '_stockfish'

I read all of the past issues and none of then help my problem.

Error when using SF development built

Process StockfishBot-40:
Traceback (most recent call last):
File "C:\Users\henta\Downloads\chess-auto-bot-main\venv\Lib\site-packages\multiprocess\process.py", line 314, in _bootstrap
self.run()
File "C:\Users\henta\Downloads\chess-auto-bot-main\src\stockfish_bot.py", line 103, in run
stockfish = Stockfish(path=self.stockfish_path, parameters=parameters)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\henta\Downloads\chess-auto-bot-main\venv\Lib\site-packages\stockfish\models.py", line 57, in init
self._stockfish_major_version: int = int(
^^^^
ValueError: invalid literal for int() with base 10: 'dev202212127cf93f8b'

I got this error while trying to use dev built SF instead of official one

Error "list index out of range" and about illegal moves

So for some reason sometimes I get the error "list index out of range <class 'IndexError'> stockfish_bot.py 130" not sure why. I can't tell you anything because it is inconsistent and whatever I do I can't replicate it (I guess it is random).

Also, I have seen some illegal moves errors, but it doesn't seem to affect anything. For e.g. I got this error "illegal san: 'e5' in rnbqkbnr/ppp1pppp/8/8/3Pp3/8/PPP2PPP/RNBQKBNR w KQkq - 0 3 <class 'chess.IllegalMoveError'> stockfish_bot.py 288" but the bot didn't stop or broke, just reporting.

Other chess bots other than Stockfish

Hi! I recall opening an issue about this because I thought it was already implemented, and was confused when it didn't move despite being connected.

I would love to see any engine being used in your program. I'm no developer, but it would really cool for me to be able to use the zappa engine, which is a bot that likes to make moves that seem like blunders but aren't. There are a lot of bots I would love to try out!

Cannot open:

cd : Cannot find path 'C:\Users\drewl\chess-auto-bot' because it does not exist.
At line:1 char:1

  • cd chess-auto-bot
  •   + CategoryInfo          : ObjectNotFound: (C:\Users\drewl\chess-auto-bot:String) [Set-Location], ItemNotFoundExcep
     tion
      + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
    

Usage with Accounts

My friends wanted me to use the bot on an account and verse them but it wont work, pressing start would just say starting then go back to start and not function. Works perfectly as a Guest account. I want to use an account because its convenient having my friends added and sending them match requests easily to see if they can beat the auto-bot. When using an account I played matches from invite links.

Feature Suggestion: Depth Limit and Overlay Mode

Rather than use get_best_move(), I think you can use _put("go depth x") where x is the value of the depth set by the user. This would allow limitation in strength of the engine used. Also, it would probably be a little more work, but an overlay mode, where best move is displayed but not played, would be pretty nice.

Add support for other engines (Lc0, Komodo, Houdini,...) and remember the path of engines

Hello, as the title said, can you add feature for integrating with other engines, I found this library that can communicate with lc0, you can follow up the code to implement the feature! https://pypi.org/project/chessEngines/

And every time I run the gui.py file, I have to configure the path to SF myself again, can you make a config.json (like cutechess or nibbler) that holds all the engines information as well as configurations, then when running the GUI, we have options to choose between engines parsed from config.json file, that would really convenient.

Thank you, this is a really nice and awesome project!!

[possible lichess feat] quick solving puzzles - no Stockfish needed

The idea

Stockfish sometimes messes up in Puzzles. Overcomplicates, wants to move with a figure that is not the solution, etc.

When you start the puzzles, since there is absolutely zero on-network check for the solution - or at least for a while* -, the solution must be hidden somewhere on the page. Right? Right!

  1. When you start playing Puzzles, there will be a <script> block, containing the code for rendering the first puzzle.
    • You can find it by searching for lichess.load.then(()=>{LichessPuzzle(
  2. You can then retrieve the solution from the initial puzzle just with a simple regex, and then do the necessary moves with the software - without relying on Stockfish at all.
  3. After the first move on the board, a fetch() request is being made to retrieve the next puzzle - along with its solution and all the informations related to it. We can intercept this so we can use this knowledge after we solve the current puzzle.
  4. Every ODD(!) move from the solution list is a move that WE have to do. Every even move is a move that the computer will do.
  5. Puzzle solved -> New puzzle loaded -> We already know the solution from step 3 -> Puzzle solved -> and so on

PoC for reading the solution of the initial puzzle, from DOM:

const solutionElement = document.evaluate(
  "/html/body/script[4]",
  document,
  null,
  XPathResult.FIRST_ORDERED_NODE_TYPE,
  null
).singleNodeValue;

const solutionRegex = /"solution":\[(.*?)\]/;
const solutionText = solutionElement.innerText.match(solutionRegex)[1].replaceAll("\"", "");
const fullSolution = solutionText.split(",");
const toPlaySolution = fullSolution.filter((move, index) => index % 2 === 0);

let initialPuzzleSolution = document.querySelector("#initial-puzzle-solution");
if (!initialPuzzleSolution) {
	initialPuzzleSolution = document.createElement('div');
	initialPuzzleSolution.id = "initial-puzzle-solution";
	initialPuzzleSolution.innerText = toPlaySolution.join(',');
	document.body.appendChild(initialPuzzleSolution);
} else {
	initialPuzzleSolution.innerText = toPlaySolution.join(',');
}

We can read #initial-puzzle-solution via Python Selenium, split the solution.text up by , and process the necessary move(s). This only needs to be executed when we are at the first puzzle. The script won't change when you start a new puzzle, only network activity is relevant for the non-first puzzles. See below.

PoC for intercepting and reading every incoming puzzle's solution from network activity

// Just in case we need the original fetch method for whatever reason
const { fetch: originalFetch } = window;

window.fetch = async (...args) => {
	let [resource, config] = args;

	let response = await originalFetch(resource, config);

	let responseJson = await response.clone().json();

	if (
		'next' in responseJson &&
		'puzzle' in responseJson.next &&
		'solution' in responseJson.next.puzzle
		) {
		let fullSolution = responseJson.next.puzzle.solution;
		let toPlaySolution = fullSolution.filter((move, index) => index % 2 === 0);
		
		let nextPuzzleSolution = document.querySelector("#next-puzzle-solution");
		if (!nextPuzzleSolution) {
			nextPuzzleSolution = document.createElement('div');
			nextPuzzleSolution.id = "next-puzzle-solution";
			nextPuzzleSolution.innerText = toPlaySolution.join(',');
			document.body.appendChild(nextPuzzleSolution);
		} else {
			nextPuzzleSolution.innerText = toPlaySolution.join(',');
		}
	}

	return response;
};

We can read #next-puzzle-solution via Python Selenium, split the solution.text up by , and process the necessary move(s).

Screen resolution issue

I have an issue using this program regarding my screen resolution. My screen is 1440p, which makes the arrow overlay and mouse movements to be incorrect. Once changed to 1080p, the problem seemed to be resolved, which is a workaround but is a bit annoying.

Realistic time management

Hey! This is another idea I have. Essentially it'd be a togglable option that allows an engine to realistically control the time it has. This could be influenced by a number of factors, including but not limited to:

  • Time control (for both you, and opposite player),
  • Evaluation (e.g. blunder by the opposite player would cause the bot to act quicker, or when you're losing it'd act slower),
  • Phase of the game (e.g. beginning, midgame and endgame)
  • Opening moves (of course, this would make the bot play out faster)
  • Trades (the bot could make piece trades faster)

Of course, there can be a lot more factors, but it'd be interesting to see how this would behave since it'll allow for a lot more realistic timed games which current bots lack.

latest driver no longer works from 115 up

File "C:\Users\admin\Documents\chess-auto-bot-main\src\gui.py", line 367, in on_open_browser_button_listener
self.chrome = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\chrome.py", line 39, in install
driver_path = self._get_driver_path(self.driver)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\core\manager.py", line 30, in _get_driver_path
file = self._download_manager.download_file(driver.get_driver_download_url())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\drivers\chrome.py", line 40, in get_driver_download_url
driver_version_to_download = self.get_driver_version_to_download()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\core\driver.py", line 51, in get_driver_version_to_download
self._driver_to_download_version = self._version if self._version not in (None, "latest") else self.get_latest_release_version()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\drivers\chrome.py", line 62, in get_latest_release_version
resp = self._http_client.get(url=latest_release_url)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\core\http.py", line 37, in get
self.validate_response(resp)
File "C:\Users\admin\Documents\chess-auto-bot-main\venv\Lib\site-packages\webdriver_manager\core\http.py", line 16, in validate_response
raise ValueError(f"There is no such driver by url {resp.url}")
ValueError: There is no such driver by url https://chromedriver.storage.googleapis.com/LATEST_RELEASE_115.0.5790

Can't find moves list

Whenever I press 'Start' I only get an message box saying "Cant find moves list!" and no error output in the console.
I am using Python 3.11.

Can't move a piece

imagethe mouse doesn't click in the right place, even though I have set the resolution to 100%

is there any solution for me?

Add support for a configuration file.

Hey! A config file would be a great improvement to this project. This library might be helpful to get this done with ease: ConfigParser Library.

Example of a default configuration file (referencing also: #21):

# global settings
[DEFAULT]
engine=stockfish
delay_time=1 # seconds
ponder=False
nodes=1
depth=1

# settings to be remembered on every close
[settings]
website=0
pinned_window=True
manual=False
mouseless=False
infinite_puzzles=False
bongcloud=False

# system-related settings
[system]
memory=512
cpu_threads=1

# paths set by user to be remembered
[paths]
stockfish=
lc0=

# specific engine options
[lc0]
weight=

What would also be nice to have would be presets with specific settings in them!
This is really awesome and well done either way! I had a project like this, but instead of directly getting information from the website, I used image recognition.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.