Yohaan Seth Nathan commited on
Commit
17d9988
·
1 Parent(s): 44b8fb6

Update to the latest changes in lichess-bot

Browse files

- Fix strategies.py
https://github.com/ShailChoksi/lichess-bot/pull/353

- Fix Intro Message
https://github.com/ShailChoksi/lichess-bot/pull/410

- Update conversation.py
https://github.com/ShailChoksi/lichess-bot/pull/423

- Python3
https://github.com/ShailChoksi/lichess-bot/pull/425

- Put Active Correspondence Games into Queue on Startup
https://github.com/ShailChoksi/lichess-bot/pull/424

- Separate working directory
https://github.com/ShailChoksi/lichess-bot/pull/416

- Check that correspondence_queue is empty not False
https://github.com/ShailChoksi/lichess-bot/pull/428

- Suppress API error messages by default / Keep connection after game timeout
https://github.com/ShailChoksi/lichess-bot/pull/429

- Tests Update: Fix Depreciation Warning

- Inform user of game conclusion
https://github.com/ShailChoksi/lichess-bot/pull/430

- Fix MinimalEngine init() to match EngineWrapper
https://github.com/ShailChoksi/lichess-bot/pull/426

- Add Online moves through lishogi cloud eval
https://github.com/ShailChoksi/lichess-bot/pull/382

- Add instructions for listing an engine's options
https://github.com/ShailChoksi/lichess-bot/pull/434

- Formatting changes
https://github.com/ShailChoksi/lichess-bot/pull/438

- Flake8 corrections
https://github.com/ShailChoksi/lichess-bot/pull/446

- Simplify dict get
https://github.com/ShailChoksi/lichess-bot/pull/447

- Delete engine factory
https://github.com/ShailChoksi/lichess-bot/pull/445

.github/workflows/lishogi-bot-build.yml CHANGED
@@ -16,10 +16,10 @@ jobs:
16
 
17
  steps:
18
  - uses: actions/checkout@v2
19
- - name: Set up Python 3.9
20
  uses: actions/setup-python@v2
21
  with:
22
- python-version: 3.9
23
  - name: Install dependencies
24
  run: |
25
  python -m pip install --upgrade pip
 
16
 
17
  steps:
18
  - uses: actions/checkout@v2
19
+ - name: Set up Python 3.10
20
  uses: actions/setup-python@v2
21
  with:
22
+ python-version: "3.10"
23
  - name: Install dependencies
24
  run: |
25
  python -m pip install --upgrade pip
.github/workflows/python-build.yml CHANGED
@@ -16,7 +16,7 @@ jobs:
16
  strategy:
17
  matrix:
18
  os: [ubuntu-latest, macos-latest, windows-latest]
19
- python: [3.7, 3.8, 3.9]
20
 
21
  steps:
22
  - uses: actions/checkout@v2
 
16
  strategy:
17
  matrix:
18
  os: [ubuntu-latest, macos-latest, windows-latest]
19
+ python: [3.7, 3.8, 3.9, "3.10"]
20
 
21
  steps:
22
  - uses: actions/checkout@v2
ColorLogger.py CHANGED
@@ -38,7 +38,7 @@ def add_coloring_to_emit_windows(fn):
38
  hdl = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
39
  ctypes.windll.kernel32.SetConsoleTextAttribute(hdl, code)
40
 
41
- setattr(logging.StreamHandler, '_set_color', _set_color)
42
 
43
  # noinspection PyPep8Naming,PyUnusedLocal
44
  def new(*args):
@@ -103,21 +103,21 @@ def add_coloring_to_emit_ansi(fn):
103
  def new(*args):
104
  levelno = args[1].levelno
105
  if levelno >= 50:
106
- color = '\x1b[31m' # red
107
  elif levelno >= 40:
108
- color = '\x1b[31m' # red
109
  elif levelno >= 30:
110
- color = '\x1b[33m' # yellow
111
  elif levelno >= 20:
112
- color = '\x1b[94m' # light blue
113
  elif levelno >= 10:
114
- color = '\x1b[32m' # green
115
- # color = '\x1b[90m' # bright black
116
  #
117
- # #'\x1b[35m' # pink
118
  else:
119
- color = '\x1b[0m' # normal
120
- args[1].msg = f'{color} {args[1].msg}\x1b[0m' # normal
121
  # print "after"
122
  return fn(*args)
123
 
@@ -125,7 +125,7 @@ def add_coloring_to_emit_ansi(fn):
125
 
126
 
127
  def enable_color_logging(debug_lvl=logging.DEBUG):
128
- if platform.system() == 'Windows':
129
  # Windows does not support ANSI escapes and we are using API calls to set the console color
130
  logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit)
131
  else:
@@ -139,7 +139,7 @@ def enable_color_logging(debug_lvl=logging.DEBUG):
139
  ch.setLevel(debug_lvl)
140
 
141
  # FORMAT from https://github.com/xolox/python-coloredlogs
142
- FORMAT = '%(asctime)s %(name)s[%(process)d] \033[1m%(levelname)s\033[0m %(message)s'
143
  formatter = logging.Formatter(FORMAT, "%Y-%m-%d %H:%M:%S")
144
 
145
  ch.setFormatter(formatter)
 
38
  hdl = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
39
  ctypes.windll.kernel32.SetConsoleTextAttribute(hdl, code)
40
 
41
+ setattr(logging.StreamHandler, "_set_color", _set_color)
42
 
43
  # noinspection PyPep8Naming,PyUnusedLocal
44
  def new(*args):
 
103
  def new(*args):
104
  levelno = args[1].levelno
105
  if levelno >= 50:
106
+ color = "\x1b[31m" # red
107
  elif levelno >= 40:
108
+ color = "\x1b[31m" # red
109
  elif levelno >= 30:
110
+ color = "\x1b[33m" # yellow
111
  elif levelno >= 20:
112
+ color = "\x1b[94m" # light blue
113
  elif levelno >= 10:
114
+ color = "\x1b[32m" # green
115
+ # color = "\x1b[90m" # bright black
116
  #
117
+ # #"\x1b[35m" # pink
118
  else:
119
+ color = "\x1b[0m" # normal
120
+ args[1].msg = f"{color} {args[1].msg}\x1b[0m" # normal
121
  # print "after"
122
  return fn(*args)
123
 
 
125
 
126
 
127
  def enable_color_logging(debug_lvl=logging.DEBUG):
128
+ if platform.system() == "Windows":
129
  # Windows does not support ANSI escapes and we are using API calls to set the console color
130
  logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit)
131
  else:
 
139
  ch.setLevel(debug_lvl)
140
 
141
  # FORMAT from https://github.com/xolox/python-coloredlogs
142
+ FORMAT = "%(asctime)s %(name)s[%(process)d] \033[1m%(levelname)s\033[0m %(message)s"
143
  formatter = logging.Formatter(FORMAT, "%Y-%m-%d %H:%M:%S")
144
 
145
  ch.setFormatter(formatter)
README.md CHANGED
@@ -26,13 +26,13 @@ python3 -m pip install -r requirements.txt
26
  - **NOTE: Only Python 3.7 or later is supported!**
27
  - If you don't have Python, you may download it [here](https://www.python.org/downloads/). When installing it, enable `add Python to PATH`, then go to custom installation (this may be not necessary, but on some computers it won't work otherwise) and enable all options (especially `install for all users`), except the last . It's better to install Python in a path without spaces, like `C:\Python\`.
28
  - To type commands it's better to use PowerShell. Go to Start menu and type `PowerShell` (you may use `cmd` too, but sometimes it may not work).
29
- - Then you may need to upgrade pip. Execute `python -m pip install --upgrade pip` in PowerShell.
30
- - Download the repo into lishogi-bot directory.
31
  - Navigate to the directory in PowerShell: `cd [folder's adress]` (example, `cd C:\shogi\lishogi-bot`).
32
  - Install virtualenv: `pip install virtualenv`.
33
  - Setup virtualenv:
34
  ```python
35
- python -m venv .venv # if this fails you probably need to add Python to your PATH.
36
  ./.venv/Scripts/Activate.ps1 # `.\.venv\Scripts\activate.bat` should work in cmd in administator mode. This may not work on Windows, and in this case you need to execute "Set-ExecutionPolicy RemoteSigned" first and choose "Y" there (you may need to run Powershell as administrator). After you executed the script, change execution policy back with "Set-ExecutionPolicy Restricted" and pressing "Y".
37
  pip install -r requirements.txt
38
  ```
@@ -47,16 +47,19 @@ pip install -r requirements.txt
47
  - **NOTE: You won't see this token again on Lishogi, so save it or store it somewhere.**
48
 
49
  ## Setup Engine
50
- - Place your engine(s) in the `engine: dir` directory.
51
- - In the `config.yml` file, enter the binary name as the `engine: name` field (In Windows you may need to type a name with `.exe`, like `YaneuraOu.exe`).
52
- - Using this process any engine can be added to the bot.
53
- - **Note: The engine you add has to be running under the USI protocol, only then it will work.**
 
 
 
54
 
55
  ### Engine Configuration
56
- Besides the above, there are many possible options within `config.yml` for configuring the engine for use with lishogi-bot.
57
  - `protocol`: Specify which protocol your engine uses.
58
  1. `"usi"` for the [Universal Shogi Interface](http://hgm.nubati.net/usi.html).
59
- 2. `"homemade"` if you want to write your own engine in Python within lichess-bot. See [**Creating a homemade bot**](#creating-a-homemade-bot) below.
60
  - `ponder`: Specify whether your bot will ponder, i.e., think while the bot's opponent is choosing a move.
61
  - `engine_options`: Command line options to pass to the engine on startup. For example, the `config.yml.default` has the configuration
62
  ```yml
@@ -64,7 +67,7 @@ Besides the above, there are many possible options within `config.yml` for confi
64
  cpuct: 3.1
65
  ```
66
  This would create the command-line option `--cpuct=3.1` to be used when starting the engine. Any number of options can be listed here, each getting their own command-line option.
67
- - `usi_options`: A list of options to pass to a USI engine after startup. Different engines have different options, so treat the options in `config.yml.default` as templates and not suggestions. When USI engines start, they print a list of configurations that can modify their behavior. For example, YaneuraOu v6.50 prints the following when run at the command line:
68
  ```
69
  id name YaneuraOu NNUE 6.50
70
  id author by yaneurao
@@ -115,7 +118,7 @@ Any of the names following `option name` can be listed in `usi_options` in order
115
  NetworkDelay: 100
116
  Skill Level: 10
117
  ```
118
- The exception to this are the options `Threads`, `USI_Ponder` and `MultiPv`. These will be handled by lishogi-bot after a game starts and should not be listed in the `config.yml` file. Also, if an option is listed under `usi_options` that is not in the list printed by the engine, it will cause an error when the engine starts because the engine won't understand the option. The word after `type` indicates the expected type of the options: `string` for a text string, `spin` for a numeric value, `check` for a boolean True/False value.
119
 
120
  One last option is `go_commands`. Beneath this option, arguments to the USI `go` command can be passed. For example,
121
  ```yml
@@ -171,7 +174,7 @@ will append `nodes 1 depth 5 movetime 1000` to the command to start thinking of
171
  - rated
172
  - casual
173
  ```
174
- - `greeting`: Send messages via chat to the bot's opponent. The string `{me}` will be replaced by the bot's lichess account name. The string `{opponent}` will be replaced by the opponent's lichess account name. Any other word between curly brackets will be removed. If you want to put a curly bracket in the message, use two: `{{` or `}}`.
175
  - `hello`: Message to send to opponent before the bot makes its first move.
176
  - `goodbye`: Message to send to opponent once the game is over.
177
  ```yml
@@ -189,9 +192,9 @@ After activating the virtual environment created in the installation steps (the
189
  ```python
190
  python3 lishogi-bot.py
191
  ```
192
- The working directory for the engine execution will be the lishogi-bot directory. If your engine requires files located elsewhere, make sure they are specified by absolute path or copy the files to an appropriate location inside the lishogi-bot directory.
193
 
194
- To output more information (including your engine's thinking output and debugging information), the `-v` option can be passed to lishogi-bot:
195
  ```python
196
  python3 lishogi-bot.py -v
197
  ```
@@ -240,4 +243,4 @@ WantedBy=multi-user.target
240
  Thanks to the Lichess Team for creating a [repository](https://github.com/ShailChoksi/lichess-bot) that could be easily accessed and modified to help converting it to a format that supports Lishogi. Thanks to [Tasuku SUENAGA a.k.a. gunyarakun](https://github.com/gunyarakun) and his [python-shogi](https://pypi.org/pypi/python-shogi/) code which allows engine communication seamlessly. Thanks to [WandererXII](https://github.com/WandererXII) for all his effort and help.
241
 
242
  ## License
243
- lishogi-bot is licensed under the AGPLv3 (or any later version at your option). Check out the [LICENSE file](/LICENSE) for the full text.
 
26
  - **NOTE: Only Python 3.7 or later is supported!**
27
  - If you don't have Python, you may download it [here](https://www.python.org/downloads/). When installing it, enable `add Python to PATH`, then go to custom installation (this may be not necessary, but on some computers it won't work otherwise) and enable all options (especially `install for all users`), except the last . It's better to install Python in a path without spaces, like `C:\Python\`.
28
  - To type commands it's better to use PowerShell. Go to Start menu and type `PowerShell` (you may use `cmd` too, but sometimes it may not work).
29
+ - Then you may need to upgrade pip. Execute `python3 -m pip install --upgrade pip` in PowerShell.
30
+ - Download the repo into Lishogi-Bot directory.
31
  - Navigate to the directory in PowerShell: `cd [folder's adress]` (example, `cd C:\shogi\lishogi-bot`).
32
  - Install virtualenv: `pip install virtualenv`.
33
  - Setup virtualenv:
34
  ```python
35
+ python3 -m venv .venv # if this fails you probably need to add Python3 to your PATH.
36
  ./.venv/Scripts/Activate.ps1 # `.\.venv\Scripts\activate.bat` should work in cmd in administator mode. This may not work on Windows, and in this case you need to execute "Set-ExecutionPolicy RemoteSigned" first and choose "Y" there (you may need to run Powershell as administrator). After you executed the script, change execution policy back with "Set-ExecutionPolicy Restricted" and pressing "Y".
37
  pip install -r requirements.txt
38
  ```
 
47
  - **NOTE: You won't see this token again on Lishogi, so save it or store it somewhere.**
48
 
49
  ## Setup Engine
50
+ Within the file `config.yml`:
51
+ - Enter the directory containing the engine executable in the `engine: dir` field.
52
+ - Enter the executable name in the `engine: name` field (In Windows you may need to type a name with `.exe`, like `YaneuraOu.exe`)
53
+ - If you want the engine to run in a different directory (e.g., if the engine needs to read or write files at a certain location), enter that directory in the `engine: working_dir` field.
54
+ - If this field is blank or missing, the current directory will be used.
55
+
56
+ As an optional convenience, there is a folder named `engines` within the Lishogi-Bot folder where you can copy your engine and all the files it needs. This is the default executable location in the `config.yml.default` file.
57
 
58
  ### Engine Configuration
59
+ Besides the above, there are many possible options within `config.yml` for configuring the engine for use with Lishogi-Bot.
60
  - `protocol`: Specify which protocol your engine uses.
61
  1. `"usi"` for the [Universal Shogi Interface](http://hgm.nubati.net/usi.html).
62
+ 2. `"homemade"` if you want to write your own engine in Python within Lishogi-Bot. See [**Creating a homemade bot**](#creating-a-homemade-bot) below.
63
  - `ponder`: Specify whether your bot will ponder, i.e., think while the bot's opponent is choosing a move.
64
  - `engine_options`: Command line options to pass to the engine on startup. For example, the `config.yml.default` has the configuration
65
  ```yml
 
67
  cpuct: 3.1
68
  ```
69
  This would create the command-line option `--cpuct=3.1` to be used when starting the engine. Any number of options can be listed here, each getting their own command-line option.
70
+ - `usi_options`: A list of options to pass to a USI engine after startup. Different engines have different options, so treat the options in `config.yml.default` as templates and not suggestions. When USI engines start, they print a list of configurations that can modify their behavior after receiving the string "usi". For example, to find out what options YaneuraOu v6.50 supports, run the executable in a terminal, type `usi`, and press Enter. The engine will print the following when run at the command line:
71
  ```
72
  id name YaneuraOu NNUE 6.50
73
  id author by yaneurao
 
118
  NetworkDelay: 100
119
  Skill Level: 10
120
  ```
121
+ The exception to this are the options `Threads`, `USI_Ponder` and `MultiPv`. These will be handled by Lishogi-Bot after a game starts and should not be listed in the `config.yml` file. Also, if an option is listed under `usi_options` that is not in the list printed by the engine, it will cause an error when the engine starts because the engine won't understand the option. The word after `type` indicates the expected type of the options: `string` for a text string, `spin` for a numeric value, `check` for a boolean True/False value.
122
 
123
  One last option is `go_commands`. Beneath this option, arguments to the USI `go` command can be passed. For example,
124
  ```yml
 
174
  - rated
175
  - casual
176
  ```
177
+ - `greeting`: Send messages via chat to the bot's opponent. The string `{me}` will be replaced by the bot's lishogi account name. The string `{opponent}` will be replaced by the opponent's lishogi account name. Any other word between curly brackets will be removed. If you want to put a curly bracket in the message, use two: `{{` or `}}`.
178
  - `hello`: Message to send to opponent before the bot makes its first move.
179
  - `goodbye`: Message to send to opponent once the game is over.
180
  ```yml
 
192
  ```python
193
  python3 lishogi-bot.py
194
  ```
195
+ The working directory for the engine execution will be the Lishogi-Bot directory. If your engine requires files located elsewhere, make sure they are specified by absolute path or copy the files to an appropriate location inside the Lishogi-Bot directory.
196
 
197
+ To output more information (including your engine's thinking output and debugging information), the `-v` option can be passed to Lishogi-Bot:
198
  ```python
199
  python3 lishogi-bot.py -v
200
  ```
 
243
  Thanks to the Lichess Team for creating a [repository](https://github.com/ShailChoksi/lichess-bot) that could be easily accessed and modified to help converting it to a format that supports Lishogi. Thanks to [Tasuku SUENAGA a.k.a. gunyarakun](https://github.com/gunyarakun) and his [python-shogi](https://pypi.org/pypi/python-shogi/) code which allows engine communication seamlessly. Thanks to [WandererXII](https://github.com/WandererXII) for all his effort and help.
244
 
245
  ## License
246
+ Lishogi-Bot is licensed under the AGPLv3 (or any later version at your option). Check out the [LICENSE file](/LICENSE) for the full text.
config.py CHANGED
@@ -13,7 +13,7 @@ def load_config(config_file):
13
  except Exception as e:
14
  logger.error("There appears to be a syntax problem with your config.yml")
15
  raise e
16
-
17
  if "LISHOGI_BOT_TOKEN" in os.environ:
18
  CONFIG["token"] = os.environ["LISHOGI_BOT_TOKEN"]
19
 
@@ -24,7 +24,7 @@ def load_config(config_file):
24
  ["challenge", dict, "Section `challenge` must be a dictionary with indented keys followed by colons.."]]
25
  for section in sections:
26
  if section[0] not in CONFIG:
27
- raise Exception("Your config.yml does not have required section `{}`.".format(section[0]))
28
  elif not isinstance(CONFIG[section[0]], section[1]):
29
  raise Exception(section[2])
30
 
@@ -32,15 +32,19 @@ def load_config(config_file):
32
  ["name", str, "´name´ must be a string wrapped in quotes."]]
33
  for subsection in engine_sections:
34
  if subsection[0] not in CONFIG["engine"]:
35
- raise Exception("Your config.yml does not have required `engine` subsection `{}`.".format(subsection))
36
  if not isinstance(CONFIG["engine"][subsection[0]], subsection[1]):
37
- raise Exception("´engine´ subsection {}".format(subsection[2]))
38
 
39
  if CONFIG["token"] == "xxxxxxxxxxxxxxxx":
40
  raise Exception("Your config.yml has the default Lishogi API token. This is probably wrong.")
41
 
42
  if not os.path.isdir(CONFIG["engine"]["dir"]):
43
- raise Exception("Your engine directory `{}` is not a directory.".format(CONFIG["engine"]["dir"]))
 
 
 
 
44
 
45
  engine = os.path.join(CONFIG["engine"]["dir"], CONFIG["engine"]["name"])
46
 
 
13
  except Exception as e:
14
  logger.error("There appears to be a syntax problem with your config.yml")
15
  raise e
16
+
17
  if "LISHOGI_BOT_TOKEN" in os.environ:
18
  CONFIG["token"] = os.environ["LISHOGI_BOT_TOKEN"]
19
 
 
24
  ["challenge", dict, "Section `challenge` must be a dictionary with indented keys followed by colons.."]]
25
  for section in sections:
26
  if section[0] not in CONFIG:
27
+ raise Exception(f"Your config.yml does not have required section `{section[0]}`.")
28
  elif not isinstance(CONFIG[section[0]], section[1]):
29
  raise Exception(section[2])
30
 
 
32
  ["name", str, "´name´ must be a string wrapped in quotes."]]
33
  for subsection in engine_sections:
34
  if subsection[0] not in CONFIG["engine"]:
35
+ raise Exception(f"Your config.yml does not have required `engine` subsection `{subsection}`.")
36
  if not isinstance(CONFIG["engine"][subsection[0]], subsection[1]):
37
+ raise Exception(f"´engine´ subsection {subsection[2]}")
38
 
39
  if CONFIG["token"] == "xxxxxxxxxxxxxxxx":
40
  raise Exception("Your config.yml has the default Lishogi API token. This is probably wrong.")
41
 
42
  if not os.path.isdir(CONFIG["engine"]["dir"]):
43
+ raise Exception(f'Your engine directory `{CONFIG["engine"]["dir"]}` is not a directory.')
44
+
45
+ working_dir = CONFIG["engine"].get("working_dir")
46
+ if working_dir and not os.path.isdir(working_dir):
47
+ raise Exception(f"Your engine's working directory `{working_dir}` is not a directory.")
48
 
49
  engine = os.path.join(CONFIG["engine"]["dir"], CONFIG["engine"]["name"])
50
 
config.yml.default CHANGED
@@ -1,61 +1,70 @@
1
- token: "xxxxxxxxxxxxxxxx" # Lishogi OAuth Token.
2
- url: "https://lishogi.org/" # Lishogi base URL.
3
 
4
- engine: # Engine Settings.
5
- dir: "./engines/" # Directory containing engines, relative to this project.
6
- name: "engine_name" # Binary name of the engine to use. Make sure the engine you use is running under the USI protocol.
7
- protocol: "usi" # Protocol that engine is run under. Only "usi" is supported currently.
8
- ponder: false # Think on opponent's time.
9
- # engine_options: # Any custom command line params to pass to the engine.
 
 
 
 
 
 
 
 
 
10
  # cpuct: 3.1
11
  homemade_options:
12
  # Hash: 256
13
- usi_options: # Arbitrary USI options passed to the engine.
14
- # Move Overhead: 500 # Increase if your bot flags games too often.
15
- Threads: 1 # Max CPU threads the engine can use.
16
- # Hash: 256 # Max memory (in megabytes) the engine can allocate.
17
- # go_commands: # Additional options to pass to the USI go command.
18
- # nodes: 1 # Search so many nodes only.
19
- # depth: 5 # Search depth ply only.
20
- # movetime: 1000 # Integer. Search exactly movetime milliseconds.
21
- silence_stderr: false # Some engines are very noisy.
22
 
23
- abort_time: 30 # Time in seconds after which the engine will abort the game if there is no activity.
24
- fake_think_time: false # Artificially slow down the bot to pretend like it's thinking.
25
- rate_limiting_delay: 0 # Time (in ms) to delay after sending a move to prevent "Too Many Requests" errors.
26
- move_overhead: 1900 # Increase if your bot flags games too often.
27
 
28
  correspondence:
29
- move_time: 60 # Time in seconds to search in correspondence games.
30
- checkin_period: 600 # How often to check for opponent moves in correspondence games after disconnecting.
31
- disconnect_time: 300 # Time before disconnecting from a correspondence game.
32
- ponder: false # ponder in correspondence games the bot is connected to
33
 
34
- challenge: # Incoming challenges.
35
- concurrency: 1 # Number of games to play simultaneously.
36
- sort_by: "best" # Possible values here are "best" and "first".
37
- accept_bot: true # Accepts challenges coming from other bots. Setting this to 'true' will allow games from both human and bot, but setting it to false will allow games only from human.
38
- only_bot: false # Enable this to accept challenges only from bots. This will disable accepting challenges from human.
39
- max_increment: 180 # Maximum amount of increment to accaept a challenge. The max is 180. Set to 0 for no increment.
40
- min_increment: 0 # Minimum amount of increment to accept a challenge.
41
- max_byoyomi: 180 # Maximum amount of increment to accept a challenge. The max is 180. Set to 0 for no byoyomi.
42
- min_byoyomi: 0 # Minimum amount of increment to accept a challenge.
43
- max_base: 315360000 # Maximum amount of base time to accept a challenge. The max is 315360000 (10 years).
44
- min_base: 0 # Minimum amount of base time to accept a challenge.
45
- variants: # Shogi variants to accept (https://lishogi.org/variant).
46
  - standard
47
  # - fromPosition
48
  # - minishogi
49
- time_controls: # Time controls to accept.
50
  - ultraBullet
51
  - bullet
52
  - blitz
53
  - rapid
54
  - classical
55
  # - correspondence
56
- modes: # Game modes to accept.
57
- - casual # Unrated games.
58
- - rated # Rated games - must comment if the engine doesn't try to win.
59
 
60
  greeting:
61
  # Optional substitution keywords (include curly braces):
@@ -63,4 +72,4 @@ greeting:
63
  # {me} to insert bot's name.
64
  # Any other words in curly braces will be removed.
65
  hello: "Hi! I'm {me}. Good luck! Type !help for a list of commands I can respond to." # Message to send to chat at the start of a game.
66
- goodbye: "Good game!" # Message to send to chat at the end of a game.
 
1
+ token: "xxxxxxxxxxxxxxxx" # Lishogi OAuth Token.
2
+ url: "https://lishogi.org/" # Lishogi base URL.
3
 
4
+ engine: # Engine Settings.
5
+ dir: "./engines/" # Directory containing the engine. This can be an absolute path or one relative to Lishogi-Bot/.
6
+ name: "engine_name" # Binary name of the engine to use. Make sure the engine you use is running under the USI protocol.
7
+ working_dir: "" # Directory where the chess engine will read and write files. If blank or missing, the current directory is used.
8
+ protocol: "usi" # Protocol that engine is run under. Only "usi" is supported currently.
9
+ ponder: false # Think on opponent's time.
10
+ online_moves:
11
+ lishogi_cloud_analysis:
12
+ enabled: false
13
+ min_time: 20
14
+ move_quality: "good" # One of "good", "best"
15
+ max_score_difference: 50 # Only for move_quality: "good". The maximum score difference (in cp) between the best move and the other moves.
16
+ min_depth: 20
17
+ min_knodes: 0
18
+ # engine_options: # Any custom command line params to pass to the engine.
19
  # cpuct: 3.1
20
  homemade_options:
21
  # Hash: 256
22
+ usi_options: # Arbitrary USI options passed to the engine.
23
+ # Move Overhead: 500 # Increase if your bot flags games too often.
24
+ Threads: 1 # Max CPU threads the engine can use.
25
+ # Hash: 256 # Max memory (in megabytes) the engine can allocate.
26
+ # go_commands: # Additional options to pass to the USI go command.
27
+ # nodes: 1 # Search so many nodes only.
28
+ # depth: 5 # Search depth ply only.
29
+ # movetime: 1000 # Integer. Search exactly movetime milliseconds.
30
+ silence_stderr: false # Some engines are very noisy.
31
 
32
+ abort_time: 30 # Time in seconds after which the engine will abort the game if there is no activity.
33
+ fake_think_time: false # Artificially slow down the bot to pretend like it's thinking.
34
+ rate_limiting_delay: 0 # Time (in ms) to delay after sending a move to prevent "Too Many Requests" errors.
35
+ move_overhead: 1900 # Increase if your bot flags games too often.
36
 
37
  correspondence:
38
+ move_time: 60 # Time in seconds to search in correspondence games.
39
+ checkin_period: 600 # How often to check for opponent moves in correspondence games after disconnecting.
40
+ disconnect_time: 300 # Time before disconnecting from a correspondence game.
41
+ ponder: false # ponder in correspondence games the bot is connected to
42
 
43
+ challenge: # Incoming challenges.
44
+ concurrency: 1 # Number of games to play simultaneously.
45
+ sort_by: "best" # Possible values here are "best" and "first".
46
+ accept_bot: true # Accepts challenges coming from other bots. Setting this to "true" will allow games from both human and bot, but setting it to false will allow games only from human.
47
+ only_bot: false # Enable this to accept challenges only from bots. This will disable accepting challenges from human.
48
+ max_increment: 180 # Maximum amount of increment to accaept a challenge. The max is 180. Set to 0 for no increment.
49
+ min_increment: 0 # Minimum amount of increment to accept a challenge.
50
+ max_byoyomi: 180 # Maximum amount of increment to accept a challenge. The max is 180. Set to 0 for no byoyomi.
51
+ min_byoyomi: 0 # Minimum amount of increment to accept a challenge.
52
+ max_base: 315360000 # Maximum amount of base time to accept a challenge. The max is 315360000 (10 years).
53
+ min_base: 0 # Minimum amount of base time to accept a challenge.
54
+ variants: # Shogi variants to accept (https://lishogi.org/variant).
55
  - standard
56
  # - fromPosition
57
  # - minishogi
58
+ time_controls: # Time controls to accept.
59
  - ultraBullet
60
  - bullet
61
  - blitz
62
  - rapid
63
  - classical
64
  # - correspondence
65
+ modes: # Game modes to accept.
66
+ - casual # Unrated games.
67
+ - rated # Rated games - must comment if the engine doesn't try to win.
68
 
69
  greeting:
70
  # Optional substitution keywords (include curly braces):
 
72
  # {me} to insert bot's name.
73
  # Any other words in curly braces will be removed.
74
  hello: "Hi! I'm {me}. Good luck! Type !help for a list of commands I can respond to." # Message to send to chat at the start of a game.
75
+ goodbye: "Good game!" # Message to send to chat at the end of a game.
conversation.py CHANGED
@@ -14,19 +14,19 @@ class Conversation:
14
  command_prefix = "!"
15
 
16
  def react(self, line, game):
17
- logger.info("*** {} [{}] {}: {}".format(self.game.url(), line.room, line.username, line.text.encode("utf-8")))
18
- if (line.text[0] == self.command_prefix):
19
  self.command(line, game, line.text[1:].lower())
20
 
21
  def command(self, line, game, cmd):
22
  if cmd == "commands" or cmd == "help":
23
  self.send_reply(line, "Supported commands: !wait (only applicable at the start of the game), !name, !howto, !eval, !queue")
24
  elif cmd == "wait" and game.is_abortable():
25
- game.ping(60, 120)
26
  self.send_reply(line, "Waiting 60 seconds...")
27
  elif cmd == "name":
28
  name = game.me.name
29
- self.send_reply(line, "{} running {} (Lishogi-Bot v{})".format(name, self.engine.name(), self.version))
30
  elif cmd == "howto":
31
  self.send_reply(line, "How to run: https://github.com/TheYoBots/Lishogi-Bot")
32
  elif cmd == "eval" and line.room == "spectator":
@@ -36,8 +36,8 @@ class Conversation:
36
  self.send_reply(line, "I don't tell that to my opponent, sorry.")
37
  elif cmd == "queue":
38
  if self.challengers:
39
- challengers = ", ".join(["@" + challenger.challenger_name for challenger in reversed(self.challengers)])
40
- self.send_reply(line, "Challenge queue: {}".format(challengers))
41
  else:
42
  self.send_reply(line, "No challenges queued.")
43
 
 
14
  command_prefix = "!"
15
 
16
  def react(self, line, game):
17
+ logger.info(f'*** {self.game.url()} [{line.room}] {line.username}: {line.text.encode("utf-8")}')
18
+ if line.text[0] == self.command_prefix:
19
  self.command(line, game, line.text[1:].lower())
20
 
21
  def command(self, line, game, cmd):
22
  if cmd == "commands" or cmd == "help":
23
  self.send_reply(line, "Supported commands: !wait (only applicable at the start of the game), !name, !howto, !eval, !queue")
24
  elif cmd == "wait" and game.is_abortable():
25
+ game.ping(60, 120, 120)
26
  self.send_reply(line, "Waiting 60 seconds...")
27
  elif cmd == "name":
28
  name = game.me.name
29
+ self.send_reply(line, f"{name} running {self.engine.name()} (Lishogi-Bot v{self.version})")
30
  elif cmd == "howto":
31
  self.send_reply(line, "How to run: https://github.com/TheYoBots/Lishogi-Bot")
32
  elif cmd == "eval" and line.room == "spectator":
 
36
  self.send_reply(line, "I don't tell that to my opponent, sorry.")
37
  elif cmd == "queue":
38
  if self.challengers:
39
+ challengers = ", ".join([f"@{challenger.challenger_name}" for challenger in reversed(self.challengers)])
40
+ self.send_reply(line, f"Challenge queue: {challengers}")
41
  else:
42
  self.send_reply(line, "No challenges queued.")
43
 
engine_ctrl.py CHANGED
@@ -10,10 +10,11 @@ from util import *
10
 
11
 
12
  class Engine:
13
- def __init__(self, command):
14
  self.proccess = self.open_process(command)
15
  self.go_commands = None
16
  self.info = {}
 
17
 
18
  def set_go_commands(self, go_comm):
19
  self.go_commands = go_comm
@@ -161,7 +162,7 @@ class Engine:
161
  if bestmove and bestmove != "(none)":
162
  info["bestmove"] = bestmove
163
  if len(arg_split) == 3:
164
- if arg_split[1] == 'ponder':
165
  ponder_move = arg_split[2]
166
  if ponder_move and ponder_move != "(none)":
167
  info["pondermove"] = ponder_move
 
10
 
11
 
12
  class Engine:
13
+ def __init__(self, command, cwd=None):
14
  self.proccess = self.open_process(command)
15
  self.go_commands = None
16
  self.info = {}
17
+ cwd = cwd or os.path.realpath(os.path.expanduser("."))
18
 
19
  def set_go_commands(self, go_comm):
20
  self.go_commands = go_comm
 
162
  if bestmove and bestmove != "(none)":
163
  info["bestmove"] = bestmove
164
  if len(arg_split) == 3:
165
+ if arg_split[1] == "ponder":
166
  ponder_move = arg_split[2]
167
  if ponder_move and ponder_move != "(none)":
168
  info["pondermove"] = ponder_move
engine_wrapper.py CHANGED
@@ -2,6 +2,7 @@ import os
2
  import backoff
3
  import logging
4
  from util import makeusi
 
5
 
6
  logger = logging.getLogger(__name__)
7
 
@@ -12,15 +13,16 @@ import engine_ctrl
12
  def create_engine(config, variant):
13
  cfg = config["engine"]
14
  engine_path = os.path.realpath(os.path.join(cfg["dir"], cfg["name"]))
 
15
  engine_type = cfg.get("protocol")
16
  engine_options = cfg.get("engine_options")
17
- usi_options = cfg.get("usi_options", {}) or {}
18
- if variant not in ['Standard', 'From Position']:
19
- usi_options['USI_Variant'] = variant.lower()
20
  commands = [engine_path]
21
  if engine_options:
22
  for k, v in engine_options.items():
23
- commands.append("--{}={}".format(k, v))
24
 
25
  silence_stderr = cfg.get("silence_stderr", False)
26
 
@@ -32,20 +34,32 @@ def create_engine(config, variant):
32
  raise ValueError(
33
  f"Invalid engine type: {engine_type}. Expected usi or homemade.")
34
 
35
- return Engine(commands, usi_options, silence_stderr)
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
  class EngineWrapper:
39
- def __init__(self, commands, options=None, silence_stderr=False):
40
  pass
41
 
42
  def search_for(self, board, game, movetime):
43
- moves = "" if game.variant_name == 'Standard' or game.variant_name == 'From Position' else list(map(makeusi, game.state["moves"].split()))
44
- sfen = board.sfen() if game.variant_name == 'Standard' or game.variant_name == 'From Position' else game.initial_sfen
45
  return self.search(sfen, moves, movetime=movetime // 1000)
46
 
47
  def search_with_ponder(self, game, board, btime, wtime, binc, winc, byo, ponder=False):
48
- moves = [m.usi() for m in list(board.move_stack)] if game.variant_name == 'Standard' or game.variant_name == 'From Position' else list(map(makeusi, game.state["moves"].split()))
49
  sfen = game.initial_sfen
50
  cmds = self.go_commands
51
  movetime = cmds.get("movetime")
@@ -85,7 +99,7 @@ class EngineWrapper:
85
 
86
  def get_stats(self, stats=None):
87
  if stats is None:
88
- stats = ['score', 'depth', 'nodes', 'nps']
89
  info = self.engine.info
90
  return [f"{stat}: {info[stat]}" for stat in stats if stat in info]
91
 
@@ -112,11 +126,11 @@ class EngineWrapper:
112
 
113
 
114
  class USIEngine(EngineWrapper):
115
- def __init__(self, commands, options, silence_stderr=False):
116
  commands = commands[0] if len(commands) == 1 else commands
117
  self.go_commands = options.pop("go_commands", {}) or {}
118
 
119
- self.engine = engine_ctrl.Engine(commands)
120
  self.engine.usi()
121
 
122
  if options:
@@ -150,4 +164,4 @@ class USIEngine(EngineWrapper):
150
 
151
  def getHomemadeEngine(name):
152
  import strategies
153
- return eval(f"strategies.{name}")
 
2
  import backoff
3
  import logging
4
  from util import makeusi
5
+ from enum import Enum
6
 
7
  logger = logging.getLogger(__name__)
8
 
 
13
  def create_engine(config, variant):
14
  cfg = config["engine"]
15
  engine_path = os.path.realpath(os.path.join(cfg["dir"], cfg["name"]))
16
+ engine_working_dir = cfg.get("working_dir") or os.getcwd()
17
  engine_type = cfg.get("protocol")
18
  engine_options = cfg.get("engine_options")
19
+ usi_options = cfg.get("usi_options") or {}
20
+ if variant not in ["Standard", "From Position"]:
21
+ usi_options["USI_Variant"] = variant.lower()
22
  commands = [engine_path]
23
  if engine_options:
24
  for k, v in engine_options.items():
25
+ commands.append(f"--{k}={v}")
26
 
27
  silence_stderr = cfg.get("silence_stderr", False)
28
 
 
34
  raise ValueError(
35
  f"Invalid engine type: {engine_type}. Expected usi or homemade.")
36
 
37
+ return Engine(commands, usi_options, silence_stderr, cwd=engine_working_dir)
38
+
39
+
40
+ class Termination(str, Enum):
41
+ MATE = "mate"
42
+ TIMEOUT = "outoftime"
43
+ RESIGN = "resign"
44
+ ABORT = "aborted"
45
+ DRAW = "draw"
46
+ STALEMATE = "stalemate"
47
+ TRYRULE = "tryRule"
48
+ IMPASSE = "impasse27"
49
+ PERPETUALCHECK = "perpetualCheck"
50
 
51
 
52
  class EngineWrapper:
53
+ def __init__(self, options=None):
54
  pass
55
 
56
  def search_for(self, board, game, movetime):
57
+ moves = "" if game.variant_name == "Standard" or game.variant_name == "From Position" else list(map(makeusi, game.state["moves"].split()))
58
+ sfen = board.sfen() if game.variant_name == "Standard" or game.variant_name == "From Position" else game.initial_sfen
59
  return self.search(sfen, moves, movetime=movetime // 1000)
60
 
61
  def search_with_ponder(self, game, board, btime, wtime, binc, winc, byo, ponder=False):
62
+ moves = [m.usi() for m in list(board.move_stack)] if game.variant_name == "Standard" or game.variant_name == "From Position" else list(map(makeusi, game.state["moves"].split()))
63
  sfen = game.initial_sfen
64
  cmds = self.go_commands
65
  movetime = cmds.get("movetime")
 
99
 
100
  def get_stats(self, stats=None):
101
  if stats is None:
102
+ stats = ["score", "depth", "nodes", "nps"]
103
  info = self.engine.info
104
  return [f"{stat}: {info[stat]}" for stat in stats if stat in info]
105
 
 
126
 
127
 
128
  class USIEngine(EngineWrapper):
129
+ def __init__(self, commands, options, silence_stderr=False, cwd=None):
130
  commands = commands[0] if len(commands) == 1 else commands
131
  self.go_commands = options.pop("go_commands", {}) or {}
132
 
133
+ self.engine = engine_ctrl.Engine(commands, cwd=cwd)
134
  self.engine.usi()
135
 
136
  if options:
 
164
 
165
  def getHomemadeEngine(name):
166
  import strategies
167
+ return eval(f"strategies.{name}")
lishogi-bot.py CHANGED
@@ -13,20 +13,19 @@ import time
13
  import backoff
14
  import sys
15
  import threading
 
16
  from config import load_config
17
  from conversation import Conversation, ChatLine
18
- from functools import partial
19
  from requests.exceptions import ChunkedEncodingError, ConnectionError, HTTPError, ReadTimeout
20
  from urllib3.exceptions import ProtocolError
21
  from ColorLogger import enable_color_logging
22
  from util import *
23
  import copy
24
  from collections import defaultdict
 
25
 
26
  logger = logging.getLogger(__name__)
27
 
28
- from http.client import RemoteDisconnected
29
-
30
  __version__ = "1.1.1"
31
 
32
  terminated = False
@@ -60,7 +59,7 @@ def watch_control_stream(control_queue, li):
60
  lines = response.iter_lines()
61
  for line in lines:
62
  if line:
63
- event = json.loads(line.decode('utf-8'))
64
  control_queue.put_nowait(event)
65
  else:
66
  control_queue.put_nowait({"type": "ping"})
@@ -90,7 +89,7 @@ def logging_listener_proc(queue, configurer, level, log_filename):
90
 
91
 
92
  def game_logging_configurer(queue, level):
93
- if sys.platform == 'win32':
94
  h = logging.handlers.QueueHandler(queue)
95
  root = logging.getLogger()
96
  root.handlers.clear()
@@ -98,21 +97,22 @@ def game_logging_configurer(queue, level):
98
  root.setLevel(level)
99
 
100
 
101
- def start(li, user_profile, engine_factory, config, logging_level, log_filename, one_game=False):
102
  challenge_config = config["challenge"]
103
  max_games = challenge_config.get("concurrency", 1)
104
- logger.info("You're now connected to {} and awaiting challenges.".format(config["url"]))
105
  manager = multiprocessing.Manager()
106
  challenge_queue = manager.list()
107
  control_queue = manager.Queue()
108
  control_stream = multiprocessing.Process(target=watch_control_stream, args=[control_queue, li])
109
  control_stream.start()
110
- correspondence_cfg = config.get("correspondence", {}) or {}
111
  correspondence_checkin_period = correspondence_cfg.get("checkin_period", 600)
112
  correspondence_pinger = multiprocessing.Process(target=do_correspondence_ping, args=[control_queue, correspondence_checkin_period])
113
  correspondence_pinger.start()
114
  correspondence_queue = manager.Queue()
115
  correspondence_queue.put("")
 
116
  wait_for_correspondence_ping = False
117
 
118
  busy_processes = 0
@@ -137,40 +137,45 @@ def start(li, user_profile, engine_factory, config, logging_level, log_filename,
137
  if event.get("error") == "Missing scope":
138
  logger.warning('Please check that the API access token for your bot has the scope "Play games with the bot API" (bot:play).')
139
  continue
140
-
141
  if event["type"] == "terminated":
142
  break
143
  elif event["type"] == "local_game_done":
144
  busy_processes -= 1
145
- logger.info("+++ Process Free. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
146
  if one_game:
147
  break
148
  elif event["type"] == "challenge":
149
  chlng = model.Challenge(event["challenge"])
150
  if chlng.is_supported(challenge_config):
151
  challenge_queue.append(chlng)
152
- if (challenge_config.get("sort_by", "best") == "best"):
153
  list_c = list(challenge_queue)
154
  list_c.sort(key=lambda c: -c.score())
155
  challenge_queue = list_c
156
  else:
157
  try:
158
  li.decline_challenge(chlng.id)
159
- logger.info("Decline {}".format(chlng))
160
  except:
161
  pass
162
  elif event["type"] == "gameStart":
163
- if queued_processes <= 0:
164
- logger.debug("Something went wrong. Game is starting and we don't have a queued process")
165
- else:
166
- queued_processes -= 1
167
- busy_processes += 1
168
- logger.info("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
169
  game_id = event["game"]["id"]
170
- pool.apply_async(play_game, [li, game_id, control_queue, engine_factory, user_profile, config, challenge_queue, correspondence_queue, logging_queue, game_logging_configurer, logging_level])
171
-
172
- if (event["type"] == "correspondence_ping" or (event["type"] == "local_game_done" and not wait_for_correspondence_ping)) and not challenge_queue:
173
- if event["type"] == "correspondence_ping" and wait_for_correspondence_ping:
 
 
 
 
 
 
 
 
 
 
 
174
  correspondence_queue.put("")
175
 
176
  wait_for_correspondence_ping = False
@@ -178,23 +183,26 @@ def start(li, user_profile, engine_factory, config, logging_level, log_filename,
178
  game_id = correspondence_queue.get()
179
  # stop checking in on games if we have checked in on all games since the last correspondence_ping
180
  if not game_id:
181
- wait_for_correspondence_ping = True
182
- break
 
 
 
183
  else:
184
  busy_processes += 1
185
- logger.info("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
186
- pool.apply_async(play_game, [li, game_id, control_queue, engine_factory, user_profile, config, challenge_queue, correspondence_queue, logging_queue, game_logging_configurer, logging_level])
187
 
188
- while ((queued_processes + busy_processes) < max_games and challenge_queue): # keep processing the queue until empty or max_games is reached
189
  chlng = challenge_queue.pop(0)
190
  try:
191
- logger.info("Accept {}".format(chlng))
192
  queued_processes += 1
193
  li.accept_challenge(chlng.id)
194
- logger.info("--- Process Queue. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
195
  except (HTTPError, ReadTimeout) as exception:
196
  if isinstance(exception, HTTPError) and exception.response.status_code == 404: # ignore missing challenge
197
- logger.info("Skip missing {}".format(chlng))
198
  queued_processes -= 1
199
 
200
  control_queue.task_done()
@@ -212,7 +220,7 @@ ponder_results = {}
212
 
213
 
214
  @backoff.on_exception(backoff.expo, BaseException, max_time=600, giveup=is_final)
215
- def play_game(li, game_id, control_queue, engine_factory, user_profile, config, challenge_queue, correspondence_queue, logging_queue, logging_configurer, logging_level):
216
  logging_configurer(logging_queue, logging_level)
217
  logger = logging.getLogger(__name__)
218
 
@@ -220,17 +228,17 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
220
  lines = response.iter_lines()
221
 
222
  # Initial response of stream will be the full game info. Store it
223
- initial_state = json.loads(next(lines).decode('utf-8'))
224
  game = model.Game(initial_state, user_profile["username"], li.baseUrl, config.get("abort_time", 20))
225
 
226
- engine = engine_factory(game.variant_name)
227
  engine.get_opponent_info(game)
228
  conversation = Conversation(game, engine, li, __version__, challenge_queue)
229
 
230
- logger.info("+++ {}".format(game))
231
 
232
  is_correspondence = game.perf_name == "Correspondence"
233
- correspondence_cfg = config.get("correspondence", {}) or {}
234
  correspondence_move_time = correspondence_cfg.get("move_time", 60) * 1000
235
 
236
  engine_cfg = config["engine"]
@@ -238,31 +246,33 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
238
  can_ponder = ponder_cfg.get("ponder", False)
239
  move_overhead = config.get("move_overhead", 1000)
240
  delay_seconds = config.get("rate_limiting_delay", 0)/1000
 
241
 
242
  ponder_thread = None
243
  ponder_usi = None
244
 
245
- logger.debug("Game state: {}".format(game.state))
246
 
247
- greeting_cfg = config.get("greeting", {}) or {}
248
  keyword_map = defaultdict(str, me=game.me.name, opponent=game.opponent.name)
249
- get_greeting = lambda greeting: str(greeting_cfg.get(greeting, "") or "").format_map(keyword_map)
250
  hello = get_greeting("hello")
251
  goodbye = get_greeting("goodbye")
252
-
253
  first_move = True
254
  correspondence_disconnect_time = 0
255
 
256
  while not terminated:
 
257
  try:
258
  if first_move:
259
  upd = game.state
260
  first_move = False
261
  else:
262
  binary_chunk = next(lines)
263
- upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
264
 
265
- logger.debug("Update: {}".format(upd))
266
  u_type = upd["type"] if upd else "ping"
267
  if u_type == "chatLine":
268
  conversation.react(ChatLine(upd), game)
@@ -270,44 +280,51 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
270
  game.state = upd
271
  board = setup_board(game)
272
  if not is_game_over(game) and is_engine_move(game, board):
 
 
273
  start_time = time.perf_counter_ns()
274
  fake_thinking(config, board, game)
275
  print_move_number(board)
276
  correspondence_disconnect_time = correspondence_cfg.get("disconnect_time", 300)
277
 
278
  if len(board.move_stack) < 2:
279
- conversation.send_message("player", hello)
280
  best_move, ponder_move = choose_first_move(engine, board, game)
281
  elif is_correspondence:
282
  best_move, ponder_move = choose_move_time(engine, board, game, correspondence_move_time)
283
  else:
284
  best_move, ponder_move = get_pondering_result(engine, game, board.move_stack, ponder_thread, ponder_usi)
 
285
  if best_move is None:
286
  best_move, ponder_move = play_midgame_move(engine, board, upd["btime"], upd["wtime"], move_overhead, start_time, logger, game)
 
 
287
  li.make_move(game.id, best_move)
288
  ponder_thread, ponder_usi = start_pondering(engine, board, best_move, ponder_move, upd["btime"], upd["wtime"], game, logger, move_overhead, start_time, can_ponder)
289
  time.sleep(delay_seconds)
290
  elif is_game_over(game):
291
  engine.report_game_result(game, board)
 
292
  conversation.send_message("player", goodbye)
293
  elif len(board.move_stack) == 0:
294
  correspondence_disconnect_time = correspondence_cfg.get("disconnect_time", 300)
295
 
296
- bw = 'b' if board.turn == shogi.BLACK else 'w'
297
  game.ping(config.get("abort_time", 30), (upd[f"{bw}time"] + upd[f"{bw}inc"] + upd["byo"]) / 1000 + 60, correspondence_disconnect_time)
298
  elif u_type == "ping":
299
  if is_correspondence and not is_engine_move(game, board) and game.should_disconnect_now():
300
  break
301
  elif game.should_abort_now():
302
- logger.info("Aborting {} by lack of activity".format(game.url()))
303
  li.abort(game.id)
304
  break
305
  elif game.should_terminate_now():
306
- logger.info("Terminating {} by lack of activity".format(game.url()))
307
  if game.is_abortable():
308
  li.abort(game.id)
309
  break
310
  except (HTTPError, ReadTimeout, RemoteDisconnected, ChunkedEncodingError, ConnectionError, ProtocolError):
 
 
311
  if game.id not in (ongoing_game["gameId"] for ongoing_game in li.get_ongoing_games()):
312
  break
313
  except StopIteration:
@@ -322,17 +339,17 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
322
  engine.kill_process()
323
 
324
  if is_correspondence and not is_game_over(game):
325
- logger.info("--- Disconnecting from {}".format(game.url()))
326
  correspondence_queue.put(game_id)
327
  else:
328
- logger.info("--- {} Game over".format(game.url()))
329
 
330
  control_queue.put_nowait({"type": "local_game_done"})
331
 
332
 
333
  def play_midgame_move(engine, board, btime, wtime, move_overhead, start_time, logger, game):
334
  btime, wtime = adjust_game_time(btime, wtime, board, move_overhead, start_time)
335
- logger.info("Searching for btime {} wtime {}".format(btime, wtime))
336
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, game.state["binc"], game.state["winc"], game.state["byo"])
337
  return best_move, ponder_move
338
 
@@ -349,7 +366,7 @@ def start_pondering(engine, board, best_move, ponder_move, btime, wtime, game, l
349
  if not can_ponder or ponder_move is None:
350
  return None, None
351
  ponder_board = copy.deepcopy(board)
352
- if game.variant_name == 'Standard' or game.variant_name == 'From Position':
353
  ponder_board.push(shogi.Move.from_usi(best_move))
354
  ponder_board.push(shogi.Move.from_usi(ponder_move))
355
  else:
@@ -358,7 +375,7 @@ def start_pondering(engine, board, best_move, ponder_move, btime, wtime, game, l
358
  ponder_usi = ponder_move
359
 
360
  btime, wtime = adjust_game_time(btime, wtime, board, move_overhead, start_time, game.state["winc"], game.state["binc"], game.state["byo"])
361
- logger.info("Pondering {} for btime {} wtime {}".format(ponder_move, btime, wtime))
362
 
363
  def ponder_thread_func(game, engine, board, btime, wtime, binc, winc, byo):
364
  global ponder_results
@@ -384,8 +401,60 @@ def get_pondering_result(engine, game, moves, ponder_thread, ponder_usi):
384
  return None, None
385
 
386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  def choose_move_time(engine, board, game, search_time):
388
- logger.info("Searching for time {}".format(search_time))
389
  return engine.search_for(board, game, search_time)
390
 
391
 
@@ -404,11 +473,11 @@ def fake_thinking(config, board, game):
404
 
405
  def print_move_number(board):
406
  logger.info("")
407
- logger.info("move: {}".format(len(board.move_stack) // 1 + 1))
408
 
409
 
410
  def setup_board(game):
411
- if game.variant_name == 'Standard' or game.variant_name == 'From Position':
412
  if game.variant_name == "From Position":
413
  board = shogi.Board(game.initial_sfen)
414
  else:
@@ -419,7 +488,7 @@ def setup_board(game):
419
  if board.is_legal(usi_move):
420
  board.push(usi_move)
421
  else:
422
- logger.debug("Ignoring illegal move {} on board {}".format(makeusi(move), board.sfen()))
423
  else:
424
  board = shogi.Board()
425
  for move in game.state["moves"].split():
@@ -436,6 +505,39 @@ def is_game_over(game):
436
  return game.state["status"] != "started"
437
 
438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  def intro():
440
  return r"""
441
  . _/\_
@@ -447,11 +549,11 @@ def intro():
447
 
448
 
449
  if __name__ == "__main__":
450
- parser = argparse.ArgumentParser(description='Play on Lishogi with a bot')
451
- parser.add_argument('-u', action='store_true', help='Add this flag to upgrade your account to a bot account.')
452
- parser.add_argument('-v', action='store_true', help='Verbose output. Changes log level from INFO to DEBUG.')
453
- parser.add_argument('--config', help='Specify a configuration file (defaults to ./config.yml)')
454
- parser.add_argument('-l', '--logfile', help="Log file to append logs to.", default=None)
455
  args = parser.parse_args()
456
 
457
  logging_level = logging.DEBUG if args.v else logging.INFO
@@ -460,18 +562,17 @@ if __name__ == "__main__":
460
  enable_color_logging(debug_lvl=logging_level)
461
  logger.info(intro())
462
  CONFIG = load_config(args.config or "./config.yml")
463
- li = lishogi.Lishogi(CONFIG["token"], CONFIG["url"], __version__)
464
 
465
  user_profile = li.get_profile()
466
  username = user_profile["username"]
467
  is_bot = user_profile.get("title") == "BOT"
468
- logger.info("Welcome {}!".format(username))
469
 
470
  if args.u and not is_bot:
471
  is_bot = upgrade_account(li)
472
 
473
  if is_bot:
474
- engine_factory = partial(engine_wrapper.create_engine, CONFIG)
475
- start(li, user_profile, engine_factory, CONFIG, logging_level, args.logfile)
476
  else:
477
- logger.error("{} is not a bot account. Please upgrade it to a bot account!".format(user_profile["username"]))
 
13
  import backoff
14
  import sys
15
  import threading
16
+ import random
17
  from config import load_config
18
  from conversation import Conversation, ChatLine
 
19
  from requests.exceptions import ChunkedEncodingError, ConnectionError, HTTPError, ReadTimeout
20
  from urllib3.exceptions import ProtocolError
21
  from ColorLogger import enable_color_logging
22
  from util import *
23
  import copy
24
  from collections import defaultdict
25
+ from http.client import RemoteDisconnected
26
 
27
  logger = logging.getLogger(__name__)
28
 
 
 
29
  __version__ = "1.1.1"
30
 
31
  terminated = False
 
59
  lines = response.iter_lines()
60
  for line in lines:
61
  if line:
62
+ event = json.loads(line.decode("utf-8"))
63
  control_queue.put_nowait(event)
64
  else:
65
  control_queue.put_nowait({"type": "ping"})
 
89
 
90
 
91
  def game_logging_configurer(queue, level):
92
+ if sys.platform == "win32":
93
  h = logging.handlers.QueueHandler(queue)
94
  root = logging.getLogger()
95
  root.handlers.clear()
 
97
  root.setLevel(level)
98
 
99
 
100
+ def start(li, user_profile, config, logging_level, log_filename, one_game=False):
101
  challenge_config = config["challenge"]
102
  max_games = challenge_config.get("concurrency", 1)
103
+ logger.info(f"You're now connected to {config['url']} and awaiting challenges.")
104
  manager = multiprocessing.Manager()
105
  challenge_queue = manager.list()
106
  control_queue = manager.Queue()
107
  control_stream = multiprocessing.Process(target=watch_control_stream, args=[control_queue, li])
108
  control_stream.start()
109
+ correspondence_cfg = config.get("correspondence") or {}
110
  correspondence_checkin_period = correspondence_cfg.get("checkin_period", 600)
111
  correspondence_pinger = multiprocessing.Process(target=do_correspondence_ping, args=[control_queue, correspondence_checkin_period])
112
  correspondence_pinger.start()
113
  correspondence_queue = manager.Queue()
114
  correspondence_queue.put("")
115
+ startup_correspondence_games = [game["gameId"] for game in li.get_ongoing_games() if game["perf"] == "correspondence"]
116
  wait_for_correspondence_ping = False
117
 
118
  busy_processes = 0
 
137
  if event.get("error") == "Missing scope":
138
  logger.warning('Please check that the API access token for your bot has the scope "Play games with the bot API" (bot:play).')
139
  continue
140
+
141
  if event["type"] == "terminated":
142
  break
143
  elif event["type"] == "local_game_done":
144
  busy_processes -= 1
145
+ logger.info(f"+++ Process Free. Total Queued: {queued_processes}. Total Used: {busy_processes}")
146
  if one_game:
147
  break
148
  elif event["type"] == "challenge":
149
  chlng = model.Challenge(event["challenge"])
150
  if chlng.is_supported(challenge_config):
151
  challenge_queue.append(chlng)
152
+ if challenge_config.get("sort_by", "best") == "best":
153
  list_c = list(challenge_queue)
154
  list_c.sort(key=lambda c: -c.score())
155
  challenge_queue = list_c
156
  else:
157
  try:
158
  li.decline_challenge(chlng.id)
159
+ logger.info(f"Decline {chlng}")
160
  except:
161
  pass
162
  elif event["type"] == "gameStart":
 
 
 
 
 
 
163
  game_id = event["game"]["id"]
164
+ if game_id in startup_correspondence_games:
165
+ logger.info(f'--- Enqueue {config["url"] + game_id}')
166
+ correspondence_queue.put(game_id)
167
+ startup_correspondence_games.remove(game_id)
168
+ else:
169
+ if queued_processes > 0:
170
+ queued_processes -= 1
171
+ busy_processes += 1
172
+ logger.info(f"--- Process Used. Total Queued: {queued_processes}. Total Used: {busy_processes}")
173
+ pool.apply_async(play_game, [li, game_id, control_queue, user_profile, config, challenge_queue, correspondence_queue, logging_queue, game_logging_configurer, logging_level])
174
+
175
+ is_correspondence_ping = event["type"] == "correspondence_ping"
176
+ is_local_game_done = event["type"] == "local_game_done"
177
+ if (is_correspondence_ping or (is_local_game_done and not wait_for_correspondence_ping)) and not challenge_queue:
178
+ if is_correspondence_ping and wait_for_correspondence_ping:
179
  correspondence_queue.put("")
180
 
181
  wait_for_correspondence_ping = False
 
183
  game_id = correspondence_queue.get()
184
  # stop checking in on games if we have checked in on all games since the last correspondence_ping
185
  if not game_id:
186
+ if is_correspondence_ping and not correspondence_queue.empty():
187
+ correspondence_queue.put("")
188
+ else:
189
+ wait_for_correspondence_ping = True
190
+ break
191
  else:
192
  busy_processes += 1
193
+ logger.info(f"--- Process Used. Total Queued: {queued_processes}. Total Used: {busy_processes}")
194
+ pool.apply_async(play_game, [li, game_id, control_queue, user_profile, config, challenge_queue, correspondence_queue, logging_queue, game_logging_configurer, logging_level])
195
 
196
+ while (queued_processes + busy_processes) < max_games and challenge_queue: # keep processing the queue until empty or max_games is reached
197
  chlng = challenge_queue.pop(0)
198
  try:
199
+ logger.info(f"Accept {chlng}")
200
  queued_processes += 1
201
  li.accept_challenge(chlng.id)
202
+ logger.info(f"--- Process Queue. Total Queued: {queued_processes}. Total Used: {busy_processes}")
203
  except (HTTPError, ReadTimeout) as exception:
204
  if isinstance(exception, HTTPError) and exception.response.status_code == 404: # ignore missing challenge
205
+ logger.info(f"Skip missing {chlng}")
206
  queued_processes -= 1
207
 
208
  control_queue.task_done()
 
220
 
221
 
222
  @backoff.on_exception(backoff.expo, BaseException, max_time=600, giveup=is_final)
223
+ def play_game(li, game_id, control_queue, user_profile, config, challenge_queue, correspondence_queue, logging_queue, logging_configurer, logging_level):
224
  logging_configurer(logging_queue, logging_level)
225
  logger = logging.getLogger(__name__)
226
 
 
228
  lines = response.iter_lines()
229
 
230
  # Initial response of stream will be the full game info. Store it
231
+ initial_state = json.loads(next(lines).decode("utf-8"))
232
  game = model.Game(initial_state, user_profile["username"], li.baseUrl, config.get("abort_time", 20))
233
 
234
+ engine = engine_wrapper.create_engine(config, game.variant_name)
235
  engine.get_opponent_info(game)
236
  conversation = Conversation(game, engine, li, __version__, challenge_queue)
237
 
238
+ logger.info(f"+++ {game}")
239
 
240
  is_correspondence = game.perf_name == "Correspondence"
241
+ correspondence_cfg = config.get("correspondence") or {}
242
  correspondence_move_time = correspondence_cfg.get("move_time", 60) * 1000
243
 
244
  engine_cfg = config["engine"]
 
246
  can_ponder = ponder_cfg.get("ponder", False)
247
  move_overhead = config.get("move_overhead", 1000)
248
  delay_seconds = config.get("rate_limiting_delay", 0)/1000
249
+ online_moves_cfg = engine_cfg.get("online_moves", {})
250
 
251
  ponder_thread = None
252
  ponder_usi = None
253
 
254
+ logger.debug(f"Game state: {game.state}")
255
 
256
+ greeting_cfg = config.get("greeting") or {}
257
  keyword_map = defaultdict(str, me=game.me.name, opponent=game.opponent.name)
258
+ get_greeting = lambda greeting: str(greeting_cfg.get(greeting) or "").format_map(keyword_map)
259
  hello = get_greeting("hello")
260
  goodbye = get_greeting("goodbye")
261
+
262
  first_move = True
263
  correspondence_disconnect_time = 0
264
 
265
  while not terminated:
266
+ move_attempted = False
267
  try:
268
  if first_move:
269
  upd = game.state
270
  first_move = False
271
  else:
272
  binary_chunk = next(lines)
273
+ upd = json.loads(binary_chunk.decode("utf-8")) if binary_chunk else None
274
 
275
+ logger.debug(f"Update: {upd}")
276
  u_type = upd["type"] if upd else "ping"
277
  if u_type == "chatLine":
278
  conversation.react(ChatLine(upd), game)
 
280
  game.state = upd
281
  board = setup_board(game)
282
  if not is_game_over(game) and is_engine_move(game, board):
283
+ if len(board.move_stack) < 2:
284
+ conversation.send_message("player", hello)
285
  start_time = time.perf_counter_ns()
286
  fake_thinking(config, board, game)
287
  print_move_number(board)
288
  correspondence_disconnect_time = correspondence_cfg.get("disconnect_time", 300)
289
 
290
  if len(board.move_stack) < 2:
 
291
  best_move, ponder_move = choose_first_move(engine, board, game)
292
  elif is_correspondence:
293
  best_move, ponder_move = choose_move_time(engine, board, game, correspondence_move_time)
294
  else:
295
  best_move, ponder_move = get_pondering_result(engine, game, board.move_stack, ponder_thread, ponder_usi)
296
+ move_attempted = True
297
  if best_move is None:
298
  best_move, ponder_move = play_midgame_move(engine, board, upd["btime"], upd["wtime"], move_overhead, start_time, logger, game)
299
+ if best_move is None:
300
+ best_move, ponder_move = get_online_move(li, board, game, online_moves_cfg)
301
  li.make_move(game.id, best_move)
302
  ponder_thread, ponder_usi = start_pondering(engine, board, best_move, ponder_move, upd["btime"], upd["wtime"], game, logger, move_overhead, start_time, can_ponder)
303
  time.sleep(delay_seconds)
304
  elif is_game_over(game):
305
  engine.report_game_result(game, board)
306
+ tell_user_game_result(game, board)
307
  conversation.send_message("player", goodbye)
308
  elif len(board.move_stack) == 0:
309
  correspondence_disconnect_time = correspondence_cfg.get("disconnect_time", 300)
310
 
311
+ bw = "b" if board.turn == shogi.BLACK else "w"
312
  game.ping(config.get("abort_time", 30), (upd[f"{bw}time"] + upd[f"{bw}inc"] + upd["byo"]) / 1000 + 60, correspondence_disconnect_time)
313
  elif u_type == "ping":
314
  if is_correspondence and not is_engine_move(game, board) and game.should_disconnect_now():
315
  break
316
  elif game.should_abort_now():
317
+ logger.info(f"Aborting {game.url()} by lack of activity")
318
  li.abort(game.id)
319
  break
320
  elif game.should_terminate_now():
321
+ logger.info(f"Terminating {game.url()} by lack of activity")
322
  if game.is_abortable():
323
  li.abort(game.id)
324
  break
325
  except (HTTPError, ReadTimeout, RemoteDisconnected, ChunkedEncodingError, ConnectionError, ProtocolError):
326
+ if move_attempted:
327
+ continue
328
  if game.id not in (ongoing_game["gameId"] for ongoing_game in li.get_ongoing_games()):
329
  break
330
  except StopIteration:
 
339
  engine.kill_process()
340
 
341
  if is_correspondence and not is_game_over(game):
342
+ logger.info(f"--- Disconnecting from {game.url()}")
343
  correspondence_queue.put(game_id)
344
  else:
345
+ logger.info(f"--- {game.url()} Game over")
346
 
347
  control_queue.put_nowait({"type": "local_game_done"})
348
 
349
 
350
  def play_midgame_move(engine, board, btime, wtime, move_overhead, start_time, logger, game):
351
  btime, wtime = adjust_game_time(btime, wtime, board, move_overhead, start_time)
352
+ logger.info(f"Searching for btime {btime} wtime {wtime}")
353
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, game.state["binc"], game.state["winc"], game.state["byo"])
354
  return best_move, ponder_move
355
 
 
366
  if not can_ponder or ponder_move is None:
367
  return None, None
368
  ponder_board = copy.deepcopy(board)
369
+ if game.variant_name == "Standard" or game.variant_name == "From Position":
370
  ponder_board.push(shogi.Move.from_usi(best_move))
371
  ponder_board.push(shogi.Move.from_usi(ponder_move))
372
  else:
 
375
  ponder_usi = ponder_move
376
 
377
  btime, wtime = adjust_game_time(btime, wtime, board, move_overhead, start_time, game.state["winc"], game.state["binc"], game.state["byo"])
378
+ logger.info(f"Pondering {ponder_move} for btime {btime} wtime {wtime}")
379
 
380
  def ponder_thread_func(game, engine, board, btime, wtime, binc, winc, byo):
381
  global ponder_results
 
401
  return None, None
402
 
403
 
404
+ def get_lishogi_cloud_move(li, board, game, lishogi_cloud_cfg):
405
+ bw = "b" if board.turn == shogi.BLACK else "w"
406
+ if not lishogi_cloud_cfg.get("enabled", False) or game.state[f"{bw}time"] < lishogi_cloud_cfg.get("min_time", 20) * 1000:
407
+ return None
408
+
409
+ move = None
410
+
411
+ quality = lishogi_cloud_cfg.get("move_quality", "best")
412
+ multipv = 1 if quality == "best" else 5
413
+ variant = "standard" if game.variant_name == "From Position" else game.variant_name.lower()
414
+
415
+ try:
416
+ data = li.api_get(f"https://lishogi.org/api/cloud-eval?fen={board.sfen()}&multiPv={multipv}&variant={variant}", raise_for_status=False)
417
+ if "error" not in data:
418
+ if quality == "best":
419
+ depth = data["depth"]
420
+ knodes = data["knodes"]
421
+ if depth >= lishogi_cloud_cfg.get("min_depth", 20) and knodes >= lishogi_cloud_cfg.get("min_knodes", 0):
422
+ pv = data["pvs"][0]
423
+ move = pv["moves"].split()[0]
424
+ score = pv["cp"]
425
+ logger.info(f"Got move {move} from lishogi cloud analysis (depth: {depth}, score: {score}, knodes: {knodes})")
426
+ else:
427
+ depth = data["depth"]
428
+ knodes = data["knodes"]
429
+ if depth >= lishogi_cloud_cfg.get("min_depth", 20) and knodes >= lishogi_cloud_cfg.get("min_knodes", 0):
430
+ best_eval = data["pvs"][0]["cp"]
431
+ pvs = data["pvs"]
432
+ max_difference = lishogi_cloud_cfg.get("max_score_difference", 50)
433
+ if bw == "b":
434
+ pvs = list(filter(lambda pv: pv["cp"] >= best_eval - max_difference, pvs))
435
+ else:
436
+ pvs = list(filter(lambda pv: pv["cp"] <= best_eval + max_difference, pvs))
437
+ pv = random.choice(pvs)
438
+ move = pv["moves"].split()[0]
439
+ score = pv["cp"]
440
+ logger.info(f"Got move {move} from lishogi cloud analysis (depth: {depth}, score: {score}, knodes: {knodes})")
441
+ except Exception:
442
+ pass
443
+
444
+ return move
445
+
446
+
447
+ def get_online_move(li, board, game, online_moves_cfg):
448
+ lishogi_cloud_cfg = online_moves_cfg.get("lishogi_cloud_analysis", {})
449
+ if best_move is None:
450
+ best_move, ponder_move = get_lichess_cloud_move(li, board, game, lishogi_cloud_cfg)
451
+ if best_move:
452
+ return shogi.Move.from_uci(best_move, ponder_move)
453
+ return shogi.Move.from_uci(best_move, ponder_move)
454
+
455
+
456
  def choose_move_time(engine, board, game, search_time):
457
+ logger.info(f"Searching for time {search_time}")
458
  return engine.search_for(board, game, search_time)
459
 
460
 
 
473
 
474
  def print_move_number(board):
475
  logger.info("")
476
+ logger.info(f"move: {len(board.move_stack) // 1 + 1}")
477
 
478
 
479
  def setup_board(game):
480
+ if game.variant_name == "Standard" or game.variant_name == "From Position":
481
  if game.variant_name == "From Position":
482
  board = shogi.Board(game.initial_sfen)
483
  else:
 
488
  if board.is_legal(usi_move):
489
  board.push(usi_move)
490
  else:
491
+ logger.debug(f"Ignoring illegal move {makeusi(move)} on board {board.sfen()}")
492
  else:
493
  board = shogi.Board()
494
  for move in game.state["moves"].split():
 
505
  return game.state["status"] != "started"
506
 
507
 
508
+ def tell_user_game_result(game, board):
509
+ winner = game.state.get("winner")
510
+ termination = game.state.get("status")
511
+
512
+ winning_name = game.sente if winner == "sente" else game.gote
513
+ losing_name = game.gote if winner == "gote" else game.gote
514
+
515
+ if winner is not None:
516
+ logger.info(f"{winning_name} won!")
517
+ elif termination == engine_wrapper.Termination.DRAW:
518
+ logger.info("Game ended in draw.")
519
+ else:
520
+ logger.info("Game adjourned.")
521
+
522
+ if termination == engine_wrapper.Termination.MATE:
523
+ logger.info("Game won by checkmate.")
524
+ elif termination == engine_wrapper.Termination.TIMEOUT:
525
+ logger.info(f"{losing_name} forfeited on time.")
526
+ elif termination == engine_wrapper.Termination.RESIGN:
527
+ logger.info(f"{losing_name} resigned.")
528
+ elif termination == engine_wrapper.Termination.ABORT:
529
+ logger.info("Game aborted.")
530
+ elif termination == engine_wrapper.Termination.DRAW:
531
+ if board.is_fifty_moves():
532
+ logger.info("Game drawn by 50-move rule.")
533
+ elif board.is_repetition():
534
+ logger.info("Game drawn by threefold repetition.")
535
+ else:
536
+ logger.info("Game drawn by agreement.")
537
+ elif termination:
538
+ logger.info(f"Game ended by {termination}")
539
+
540
+
541
  def intro():
542
  return r"""
543
  . _/\_
 
549
 
550
 
551
  if __name__ == "__main__":
552
+ parser = argparse.ArgumentParser(description="Play on Lishogi with a bot")
553
+ parser.add_argument("-u", action="store_true", help="Add this flag to upgrade your account to a bot account.")
554
+ parser.add_argument("-v", action="store_true", help="Verbose output. Changes log level from INFO to DEBUG.")
555
+ parser.add_argument("--config", help="Specify a configuration file (defaults to ./config.yml)")
556
+ parser.add_argument("-l", "--logfile", help="Log file to append logs to.", default=None)
557
  args = parser.parse_args()
558
 
559
  logging_level = logging.DEBUG if args.v else logging.INFO
 
562
  enable_color_logging(debug_lvl=logging_level)
563
  logger.info(intro())
564
  CONFIG = load_config(args.config or "./config.yml")
565
+ li = lishogi.Lishogi(CONFIG["token"], CONFIG["url"], __version__, logging_level)
566
 
567
  user_profile = li.get_profile()
568
  username = user_profile["username"]
569
  is_bot = user_profile.get("title") == "BOT"
570
+ logger.info(f"Welcome {username}!")
571
 
572
  if args.u and not is_bot:
573
  is_bot = upgrade_account(li)
574
 
575
  if is_bot:
576
+ start(li, user_profile, CONFIG, logging_level, args.logfile)
 
577
  else:
578
+ logger.error(f"{username} is not a bot account. Please upgrade it to a bot account!")
lishogi.py CHANGED
@@ -5,6 +5,7 @@ from urllib3.exceptions import ProtocolError
5
  from util import makeuci
6
  from http.client import RemoteDisconnected
7
  import backoff
 
8
 
9
  ENDPOINTS = {
10
  "profile": "/api/account",
@@ -23,17 +24,18 @@ ENDPOINTS = {
23
  }
24
 
25
 
26
- # docs: https://lichess.org/api till lishogi API is made
27
  class Lishogi:
28
- def __init__(self, token, url, version):
29
  self.version = version
30
  self.header = {
31
- "Authorization": "Bearer {}".format(token)
32
  }
33
  self.baseUrl = url
34
  self.session = requests.Session()
35
  self.session.headers.update(self.header)
36
  self.set_user_agent("?")
 
37
 
38
  def is_final(exception):
39
  return isinstance(exception, HTTPError) and exception.response.status_code < 500
@@ -42,8 +44,11 @@ class Lishogi:
42
  (RemoteDisconnected, ConnectionError, ProtocolError, HTTPError, ReadTimeout),
43
  max_time=60,
44
  interval=0.1,
45
- giveup=is_final)
 
 
46
  def api_get(self, path, raise_for_status=True):
 
47
  url = urljoin(self.baseUrl, path)
48
  response = self.session.get(url, timeout=2)
49
  if raise_for_status:
@@ -54,8 +59,11 @@ class Lishogi:
54
  (RemoteDisconnected, ConnectionError, ProtocolError, HTTPError, ReadTimeout),
55
  max_time=60,
56
  interval=0.1,
57
- giveup=is_final)
 
 
58
  def api_post(self, path, data=None):
 
59
  url = urljoin(self.baseUrl, path)
60
  response = self.session.post(url, data=data, timeout=2)
61
  response.raise_for_status()
@@ -71,7 +79,7 @@ class Lishogi:
71
  return self.api_post(ENDPOINTS["move"].format(game_id, makeuci(move)))
72
 
73
  def chat(self, game_id, room, text):
74
- payload = {'room': room, 'text': text}
75
  return self.api_post(ENDPOINTS["chat"].format(game_id), data=payload)
76
 
77
  def abort(self, game_id):
@@ -104,7 +112,7 @@ class Lishogi:
104
  self.api_post(ENDPOINTS["resign"].format(game_id))
105
 
106
  def set_user_agent(self, username):
107
- self.header.update({"User-Agent": "Lishogi-Bot/{} user:{}".format(self.version, username)})
108
  self.session.headers.update(self.header)
109
 
110
  def challenge_ai(self):
 
5
  from util import makeuci
6
  from http.client import RemoteDisconnected
7
  import backoff
8
+ import logging
9
 
10
  ENDPOINTS = {
11
  "profile": "/api/account",
 
24
  }
25
 
26
 
27
+ # docs: https://lichess.org/api
28
  class Lishogi:
29
+ def __init__(self, token, url, version, logging_level):
30
  self.version = version
31
  self.header = {
32
+ "Authorization": f"Bearer {token}"
33
  }
34
  self.baseUrl = url
35
  self.session = requests.Session()
36
  self.session.headers.update(self.header)
37
  self.set_user_agent("?")
38
+ self.logging_level = logging_level
39
 
40
  def is_final(exception):
41
  return isinstance(exception, HTTPError) and exception.response.status_code < 500
 
44
  (RemoteDisconnected, ConnectionError, ProtocolError, HTTPError, ReadTimeout),
45
  max_time=60,
46
  interval=0.1,
47
+ giveup=is_final,
48
+ backoff_log_level=logging.DEBUG,
49
+ giveup_log_level=logging.DEBUG)
50
  def api_get(self, path, raise_for_status=True):
51
+ logging.getLogger("backoff").setLevel(self.logging_level)
52
  url = urljoin(self.baseUrl, path)
53
  response = self.session.get(url, timeout=2)
54
  if raise_for_status:
 
59
  (RemoteDisconnected, ConnectionError, ProtocolError, HTTPError, ReadTimeout),
60
  max_time=60,
61
  interval=0.1,
62
+ giveup=is_final,
63
+ backoff_log_level=logging.DEBUG,
64
+ giveup_log_level=logging.DEBUG)
65
  def api_post(self, path, data=None):
66
+ logging.getLogger("backoff").setLevel(self.logging_level)
67
  url = urljoin(self.baseUrl, path)
68
  response = self.session.post(url, data=data, timeout=2)
69
  response.raise_for_status()
 
79
  return self.api_post(ENDPOINTS["move"].format(game_id, makeuci(move)))
80
 
81
  def chat(self, game_id, room, text):
82
+ payload = {"room": room, "text": text}
83
  return self.api_post(ENDPOINTS["chat"].format(game_id), data=payload)
84
 
85
  def abort(self, game_id):
 
112
  self.api_post(ENDPOINTS["resign"].format(game_id))
113
 
114
  def set_user_agent(self, username):
115
+ self.header.update({"User-Agent": f"Lishogi-Bot/{self.version} user:{username}"})
116
  self.session.headers.update(self.header)
117
 
118
  def challenge_ai(self):
model.py CHANGED
@@ -1,6 +1,7 @@
1
  import time
2
  from urllib.parse import urljoin
3
 
 
4
  class Challenge:
5
  def __init__(self, c_info):
6
  self.id = c_info["id"]
@@ -55,10 +56,10 @@ class Challenge:
55
  return "rated" if self.rated else "casual"
56
 
57
  def challenger_full_name(self):
58
- return "{}{}".format(self.challenger_title + " " if self.challenger_title else "", self.challenger_name)
59
 
60
  def __str__(self):
61
- return "{} {} challenge from {}({})".format(self.perf_name, self.mode(), self.challenger_full_name(), self.challenger_rating)
62
 
63
  def __repr__(self):
64
  return self.__str__()
@@ -69,7 +70,7 @@ class Game:
69
  self.username = username
70
  self.id = json.get("id")
71
  self.speed = json.get("speed")
72
- clock = json.get("clock", {}) or {}
73
  self.clock_initial = clock.get("initial", 1000 * 3600 * 24 * 365 * 10) # unlimited = 10 years
74
  self.clock_increment = clock.get("increment", 0)
75
  self.perf_name = json.get("perf").get("name") if json.get("perf") else "{perf?}"
@@ -90,7 +91,7 @@ class Game:
90
  self.disconnect_at = time.time()
91
 
92
  def url(self):
93
- return urljoin(self.base_url, "{}/{}".format(self.id, self.my_color))
94
 
95
  def is_abortable(self):
96
  return len(self.state["moves"]) < 6
@@ -114,7 +115,7 @@ class Game:
114
  return (self.state["btime"] if self.is_sente else self.state["wtime"]) / 1000
115
 
116
  def __str__(self):
117
- return "{} {} vs {}".format(self.url(), self.perf_name, self.opponent.__str__())
118
 
119
  def __repr__(self):
120
  return self.__str__()
@@ -131,10 +132,10 @@ class Player:
131
 
132
  def __str__(self):
133
  if self.aiLevel:
134
- return "AI level {}".format(self.aiLevel)
135
  else:
136
- rating = "{}{}".format(self.rating, "?" if self.provisional else "")
137
- return "{}{}({})".format(self.title + " " if self.title else "", self.name, rating)
138
 
139
  def __repr__(self):
140
  return self.__str__()
 
1
  import time
2
  from urllib.parse import urljoin
3
 
4
+
5
  class Challenge:
6
  def __init__(self, c_info):
7
  self.id = c_info["id"]
 
56
  return "rated" if self.rated else "casual"
57
 
58
  def challenger_full_name(self):
59
+ return f'{self.challenger_title + " " if self.challenger_title else ""}{self.challenger_name}'
60
 
61
  def __str__(self):
62
+ return f"{self.perf_name} {self.mode()} challenge from {self.challenger_full_name()}({self.challenger_rating})"
63
 
64
  def __repr__(self):
65
  return self.__str__()
 
70
  self.username = username
71
  self.id = json.get("id")
72
  self.speed = json.get("speed")
73
+ clock = json.get("clock") or {}
74
  self.clock_initial = clock.get("initial", 1000 * 3600 * 24 * 365 * 10) # unlimited = 10 years
75
  self.clock_increment = clock.get("increment", 0)
76
  self.perf_name = json.get("perf").get("name") if json.get("perf") else "{perf?}"
 
91
  self.disconnect_at = time.time()
92
 
93
  def url(self):
94
+ return urljoin(self.base_url, f"{self.id}/{self.my_color}")
95
 
96
  def is_abortable(self):
97
  return len(self.state["moves"]) < 6
 
115
  return (self.state["btime"] if self.is_sente else self.state["wtime"]) / 1000
116
 
117
  def __str__(self):
118
+ return f"{self.url()} {self.perf_name} vs {self.opponent.__str__()}"
119
 
120
  def __repr__(self):
121
  return self.__str__()
 
132
 
133
  def __str__(self):
134
  if self.aiLevel:
135
+ return f"AI level {self.aiLevel}"
136
  else:
137
+ rating = f'{self.rating}{"?" if self.provisional else ""}'
138
+ return f'{self.title + " " if self.title else ""}{self.name}({rating})'
139
 
140
  def __repr__(self):
141
  return self.__str__()
strategies.py CHANGED
@@ -41,7 +41,7 @@ class MinimalEngine(EngineWrapper):
41
  `notify`, `first_search`, `get_time_control`, etc.
42
  """
43
  def __init__(self, commands, options, stderr, name=None):
44
- super().__init__(commands, options, stderr)
45
  self.go_commands = options.pop("go_commands", {}) or {}
46
 
47
  self.engine_name = self.__class__.__name__ if name is None else name
@@ -55,15 +55,7 @@ class MinimalEngine(EngineWrapper):
55
  def search_for(self, board, game, movetime):
56
  return self.search(board, movetime, False)
57
 
58
- def search_with_ponder(self, game, board, btime, wtime, binc, winc, byo, ponder=False):
59
- timeleft = 0
60
- if board.turn:
61
- timeleft = btime
62
- else:
63
- timeleft = wtime
64
- return self.search(board, timeleft, ponder)
65
-
66
- def search(self, board, timeleft, ponder):
67
  raise NotImplementedError("The search method is not implemented")
68
 
69
  def notify(self, method_name, *args, **kwargs):
@@ -96,4 +88,4 @@ class FirstMove(ExampleEngine):
96
  def search(self, board, *args):
97
  moves = list(board.legal_moves)
98
  moves.sort(key=str)
99
- return moves[0].usi(), None
 
41
  `notify`, `first_search`, `get_time_control`, etc.
42
  """
43
  def __init__(self, commands, options, stderr, name=None):
44
+ super().__init__(options)
45
  self.go_commands = options.pop("go_commands", {}) or {}
46
 
47
  self.engine_name = self.__class__.__name__ if name is None else name
 
55
  def search_for(self, board, game, movetime):
56
  return self.search(board, movetime, False)
57
 
58
+ def search(self, board, ponder):
 
 
 
 
 
 
 
 
59
  raise NotImplementedError("The search method is not implemented")
60
 
61
  def notify(self, method_name, *args, **kwargs):
 
88
  def search(self, board, *args):
89
  moves = list(board.legal_moves)
90
  moves.sort(key=str)
91
+ return moves[0].usi(), None
tests.py CHANGED
@@ -6,11 +6,11 @@ import zipfile
6
  import yaml
7
  import shogi
8
  import shogi.KIF as kif
9
- from shutil import copyfile
10
  import importlib
11
  lishogi_bot = importlib.import_module("lishogi-bot")
12
 
13
- TOKEN = 'Ao7zQxDqoBhE7tpG'
14
 
15
 
16
  def test_nothing():
@@ -18,35 +18,29 @@ def test_nothing():
18
 
19
 
20
  def download_yo():
21
- response = requests.get('https://github.com/TheYoBots/shoginet/blob/windows/YaneuraOu-by-mingw.exe?raw=true', allow_redirects=True)
22
- with open('yo.exe', 'wb') as file:
23
  file.write(response.content)
24
-
25
-
26
- def download_suisho():
27
- response = requests.get('https://github.com/WandererXII/shoginet/archive/refs/heads/main.zip', allow_redirects=True)
28
- with open('shogi.zip', 'wb') as file:
29
- file.write(response.content)
30
- with zipfile.ZipFile('shogi.zip', 'r') as zip_ref:
31
- zip_ref.extractall('.')
32
 
33
 
34
  def run_bot(CONFIG, logging_level):
35
  lishogi_bot.logger.info(lishogi_bot.intro())
36
- li = lishogi_bot.lishogi.Lishogi(CONFIG["token"], CONFIG["url"], lishogi_bot.__version__)
37
 
38
  user_profile = li.get_profile()
39
  username = user_profile["username"]
40
  is_bot = user_profile.get("title") == "BOT"
41
- lishogi_bot.logger.info("Welcome BOT {}!".format(username))
42
 
43
  if not is_bot:
44
  is_bot = lishogi_bot.upgrade_account(li)
45
 
46
  if is_bot:
47
- engine_factory = lishogi_bot.partial(lishogi_bot.engine_wrapper.create_engine, CONFIG)
48
  games = li.get_ongoing_games()
49
- game_ids = list(map(lambda game: game['gameId'], games))
50
  for game in game_ids:
51
  try:
52
  li.abort(game)
@@ -55,10 +49,10 @@ def run_bot(CONFIG, logging_level):
55
  time.sleep(2)
56
  while li.get_ongoing_games():
57
  time.sleep(60)
58
- game_id = li.challenge_ai()['id']
59
  time.sleep(2)
60
  games = li.get_ongoing_games()
61
- game_ids = list(map(lambda game: game['gameId'], games))
62
  for game in game_ids:
63
  if game != game_id:
64
  try:
@@ -69,23 +63,23 @@ def run_bot(CONFIG, logging_level):
69
 
70
  @pytest.mark.timeout(300)
71
  def run_test():
72
- lishogi_bot.start(li, user_profile, engine_factory, CONFIG, logging_level, None, one_game=True)
73
- response = requests.get('https://lishogi.org/game/export/{}'.format(game_id))
74
  response = response.content.decode()
75
  parser = kif.Parser()
76
  summary = parser.parse_str(response)[0]
77
- starting = 'lishogi' in summary['names'][1]
78
  board = shogi.Board()
79
- for move in summary['moves']:
80
  board.push_usi(move)
81
  win = board.turn == (shogi.WHITE if starting else shogi.BLACK) and board.is_game_over()
82
  assert win
83
 
84
  run_test()
85
  else:
86
- lishogi_bot.logger.error("{} is not a bot account. Please upgrade it to a bot account!".format(user_profile["username"]))
87
  games = li.get_ongoing_games()
88
- game_ids = list(map(lambda game: game['gameId'], games))
89
  for game in game_ids:
90
  try:
91
  li.abort(game)
@@ -98,20 +92,17 @@ def test_bot():
98
  logging_level = lishogi_bot.logging.INFO # lishogi_bot.logging_level.DEBUG
99
  lishogi_bot.logging.basicConfig(level=logging_level, filename=None, format="%(asctime)-15s: %(message)s")
100
  lishogi_bot.enable_color_logging(debug_lvl=logging_level)
101
- download_suisho()
102
- lishogi_bot.logger.info("Downloaded Suisho NNUE")
103
  download_yo()
104
  lishogi_bot.logger.info("Downloaded YaneuraOu for NNUE")
105
  with open("./config.yml.default") as file:
106
  CONFIG = yaml.safe_load(file)
107
- CONFIG['token'] = TOKEN
108
- CONFIG['engine']['dir'] = './'
109
- CONFIG['engine']['name'] = 'yo.exe'
110
- CONFIG['engine']['usi_options']['BookFile'] = 'no_book'
111
- CONFIG['engine']['usi_options']['EvalDir'] = './shoginet-main/eval'
112
- CONFIG['engine']['usi_options']['NetworkDelay'] = 500
113
  run_bot(CONFIG, logging_level)
114
 
115
 
116
- if __name__ == '__main__':
117
- test_bot()
 
6
  import yaml
7
  import shogi
8
  import shogi.KIF as kif
9
+ import shutil
10
  import importlib
11
  lishogi_bot = importlib.import_module("lishogi-bot")
12
 
13
+ TOKEN = "Ao7zQxDqoBhE7tpG"
14
 
15
 
16
  def test_nothing():
 
18
 
19
 
20
  def download_yo():
21
+ response = requests.get("https://github.com/mizar/YaneuraOu/releases/download/v7.0.0/Suisho5-YaneuraOu-v7.0.0-windows.zip", allow_redirects=True)
22
+ with open("yo.zip", "wb") as file:
23
  file.write(response.content)
24
+ with zipfile.ZipFile("yo.zip", "r") as zip_ref:
25
+ zip_ref.extractall(".")
26
+ shutil.copyfile(f"YaneuraOu_NNUE-tournament-clang++-sse42.exe", f"yo.exe")
 
 
 
 
 
27
 
28
 
29
  def run_bot(CONFIG, logging_level):
30
  lishogi_bot.logger.info(lishogi_bot.intro())
31
+ li = lishogi_bot.lishogi.Lishogi(CONFIG["token"], CONFIG["url"], lishogi_bot.__version__, logging_level)
32
 
33
  user_profile = li.get_profile()
34
  username = user_profile["username"]
35
  is_bot = user_profile.get("title") == "BOT"
36
+ lishogi_bot.logger.info(f"Welcome BOT {username}!")
37
 
38
  if not is_bot:
39
  is_bot = lishogi_bot.upgrade_account(li)
40
 
41
  if is_bot:
 
42
  games = li.get_ongoing_games()
43
+ game_ids = list(map(lambda game: game["gameId"], games))
44
  for game in game_ids:
45
  try:
46
  li.abort(game)
 
49
  time.sleep(2)
50
  while li.get_ongoing_games():
51
  time.sleep(60)
52
+ game_id = li.challenge_ai()["id"]
53
  time.sleep(2)
54
  games = li.get_ongoing_games()
55
+ game_ids = list(map(lambda game: game["gameId"], games))
56
  for game in game_ids:
57
  if game != game_id:
58
  try:
 
63
 
64
  @pytest.mark.timeout(300)
65
  def run_test():
66
+ lishogi_bot.start(li, user_profile, CONFIG, logging_level, None, one_game=True)
67
+ response = requests.get(f"https://lishogi.org/game/export/{game_id}")
68
  response = response.content.decode()
69
  parser = kif.Parser()
70
  summary = parser.parse_str(response)[0]
71
+ starting = "lishogi" in summary["names"][1]
72
  board = shogi.Board()
73
+ for move in summary["moves"]:
74
  board.push_usi(move)
75
  win = board.turn == (shogi.WHITE if starting else shogi.BLACK) and board.is_game_over()
76
  assert win
77
 
78
  run_test()
79
  else:
80
+ lishogi_bot.logger.error(f"{username} is not a bot account. Please upgrade it to a bot account!")
81
  games = li.get_ongoing_games()
82
+ game_ids = list(map(lambda game: game["gameId"], games))
83
  for game in game_ids:
84
  try:
85
  li.abort(game)
 
92
  logging_level = lishogi_bot.logging.INFO # lishogi_bot.logging_level.DEBUG
93
  lishogi_bot.logging.basicConfig(level=logging_level, filename=None, format="%(asctime)-15s: %(message)s")
94
  lishogi_bot.enable_color_logging(debug_lvl=logging_level)
 
 
95
  download_yo()
96
  lishogi_bot.logger.info("Downloaded YaneuraOu for NNUE")
97
  with open("./config.yml.default") as file:
98
  CONFIG = yaml.safe_load(file)
99
+ CONFIG["token"] = TOKEN
100
+ CONFIG["engine"]["dir"] = "./"
101
+ CONFIG["engine"]["name"] = "yo.exe"
102
+ CONFIG["engine"]["usi_options"]["BookFile"] = "no_book"
103
+ CONFIG["engine"]["usi_options"]["NetworkDelay"] = 500
 
104
  run_bot(CONFIG, logging_level)
105
 
106
 
107
+ if __name__ == "__main__":
108
+ test_bot()
util.py CHANGED
@@ -4,11 +4,11 @@ import re
4
 
5
 
6
  def isusi(move):
7
- return bool(re.match("([1-9][a-i][1-9][a-i]\+?$)|([PLNSGBR]\*[1-9][a-i]$)", move))
8
 
9
 
10
  def isuci(move):
11
- return bool(re.match("([a-i][1-9][a-i][1-9]\+?$)|([PLNSGBR]\*[a-i][1-9]$)", move))
12
 
13
 
14
  # changes uci to usi and usi to uci
 
4
 
5
 
6
  def isusi(move):
7
+ return bool(re.match(r"([1-9][a-i][1-9][a-i]\+?$)|([PLNSGBR]\*[1-9][a-i]$)", move))
8
 
9
 
10
  def isuci(move):
11
+ return bool(re.match(r"([a-i][1-9][a-i][1-9]\+?$)|([PLNSGBR]\*[a-i][1-9]$)", move))
12
 
13
 
14
  # changes uci to usi and usi to uci