TheYoBots commited on
Commit
d418201
·
1 Parent(s): 29fb72f

Changes/Aditions

Browse files

- Simplify whitespacing of logs
https://github.com/ShailChoksi/lichess-bot/pull/330
- Changes in README.md file
- Improve Handling of Correspondence Games
https://github.com/ShailChoksi/lichess-bot/pull/316
- Workflows for every OS and python version
https://github.com/ShailChoksi/lichess-bot/pull/320
- Remove unused functions

.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "pip" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "daily"
.github/workflows/python-build.yml CHANGED
@@ -1,4 +1,4 @@
1
- # This workflow will install Python dependencies, run tests and lint with a single version of Python
2
  # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3
 
4
  name: Python Build
@@ -12,19 +12,23 @@ on:
12
  jobs:
13
  build:
14
 
15
- runs-on: ubuntu-latest
 
 
 
 
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
26
  pip install flake8 pytest
27
- if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
28
  - name: Lint with flake8
29
  run: |
30
  # stop the build if there are Python syntax errors or undefined names
 
1
+ # This workflow will install Python dependencies, run tests and lint.
2
  # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3
 
4
  name: Python Build
 
12
  jobs:
13
  build:
14
 
15
+ runs-on: ${{ matrix.os }}
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
23
+ - name: Set up Python ${{ matrix.python }}
24
  uses: actions/setup-python@v2
25
  with:
26
+ python-version: ${{ matrix.python }}
27
  - name: Install dependencies
28
  run: |
29
  python -m pip install --upgrade pip
30
  pip install flake8 pytest
31
+ pip install -r requirements.txt
32
  - name: Lint with flake8
33
  run: |
34
  # stop the build if there are Python syntax errors or undefined names
ColorLogger.py CHANGED
@@ -117,7 +117,7 @@ def add_coloring_to_emit_ansi(fn):
117
  # #'\x1b[35m' # pink
118
  else:
119
  color = '\x1b[0m' # normal
120
- args[1].msg = color + args[1].msg + '\x1b[0m' # normal
121
  # print "after"
122
  return fn(*args)
123
 
 
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
 
README.md CHANGED
@@ -36,8 +36,8 @@ python3 -m pip install -r requirements.txt
36
  - Setup virtualenv:
37
 
38
  ```python
39
- virtualenv .venv -p python # if this fails you probably need to add Python to your PATH.
40
- ./.venv/Scripts/activate # .\.venv\Scripts\activate 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").
41
  pip install -r requirements.txt
42
  ```
43
  - Copy `config.yml.default` to `config.yml`.
 
36
  - Setup virtualenv:
37
 
38
  ```python
39
+ python -m venv .venv # if this fails you probably need to add Python to your PATH.
40
+ ./.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").
41
  pip install -r requirements.txt
42
  ```
43
  - Copy `config.yml.default` to `config.yml`.
config.py CHANGED
@@ -11,7 +11,7 @@ def load_config(config_file):
11
  try:
12
  CONFIG = yaml.safe_load(stream)
13
  except Exception as e:
14
- logger.error(" There appears to be a syntax problem with your config.yml")
15
  raise e
16
 
17
  # [section, type, error message]
 
11
  try:
12
  CONFIG = yaml.safe_load(stream)
13
  except Exception as e:
14
+ logger.error("There appears to be a syntax problem with your config.yml")
15
  raise e
16
 
17
  # [section, type, error message]
config.yml.default CHANGED
@@ -1,8 +1,8 @@
1
- token: "xxxxxxxxxxxxxxxx" # Lishogi OAuth Token (which can be taken from https://lishogi.org/account/oauth/token/create?scopes[]=bot:play&description=Lishogi+Bot+Token) with 'Play games with the bot API' ('bot:play' scopes) enabled.
2
  url: "https://lishogi.org/" # Lishogi base URL. Do not change this unless locally hosted to an external URL.
3
 
4
  engine: # Engine Settings.
5
- dir: "./engines/" # dir 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 # Not supported. Setting it to 'true' will not work.
@@ -12,10 +12,10 @@ engine: # Engine Settings.
12
  Move Overhead: 5000 # Increase if your bot flags games too often.
13
  Threads: 1 # Max CPU threads the engine can use.
14
  Hash: 256 # Max memory (in megabytes) the engine can allocate.
15
- # go_commands: # Additional options to pass to the USI go command.
16
- # nodes: 1 # Search so many nodes only.
17
- # depth: 5 # Search depth ply only.
18
- # movetime: 1000 # Integer. Search exactly movetime milliseconds.
19
  silence_stderr: false # Some engines are very noisy.
20
 
21
  abort_time: 30 # Time in seconds after which the engine will abort the game if there is no activity.
@@ -23,6 +23,11 @@ fake_think_time: false # Artificially slow down the bot to pretend like it
23
  rate_limiting_delay: 0 # Time (in ms) to delay after sending a move to prevent "Too Many Requests" errors.
24
  move_overhead: 5000 # Increase if your bot flags games too often.
25
 
 
 
 
 
 
26
  challenge: # Incoming challenges.
27
  concurrency: 1 # Number of games to play simultaneously.
28
  sort_by: "best" # Possible values here are "best" and "first".
 
1
+ token: "xxxxxxxxxxxxxxxx" # Lishogi OAuth Token (which can be taken from https://lishogi.org/account/oauth/token/create?scopes[]=bot:play&scopes[]=challenge:read&scopes[]=challenge:write&description=Lishogi+Bot+Token) with 'Play games with the bot API' ('bot:play' scopes), 'Read incoming challenges' ('challenge:read' scopes) and 'Create, accept, decline challenges' ('challenge:write' scopes) enabled.
2
  url: "https://lishogi.org/" # Lishogi base URL. Do not change this unless locally hosted to an external 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 # Not supported. Setting it to 'true' will not work.
 
12
  Move Overhead: 5000 # Increase if your bot flags games too often.
13
  Threads: 1 # Max CPU threads the engine can use.
14
  Hash: 256 # Max memory (in megabytes) the engine can allocate.
15
+ # go_commands: # Additional options to pass to the USI go command.
16
+ # nodes: 1 # Search so many nodes only.
17
+ # depth: 5 # Search depth ply only.
18
+ # movetime: 1000 # Integer. Search exactly movetime milliseconds.
19
  silence_stderr: false # Some engines are very noisy.
20
 
21
  abort_time: 30 # Time in seconds after which the engine will abort the game if there is no activity.
 
23
  rate_limiting_delay: 0 # Time (in ms) to delay after sending a move to prevent "Too Many Requests" errors.
24
  move_overhead: 5000 # Increase if your bot flags games too often.
25
 
26
+ correspondence:
27
+ move_time: 60 # Time in seconds to search in correspondence games.
28
+ checkin_period: 600 # How often to check for opponent moves in correspondence games after disconnecting.
29
+ disconnect_time: 300 # Time before disconnecting from a correspondence game.
30
+
31
  challenge: # Incoming challenges.
32
  concurrency: 1 # Number of games to play simultaneously.
33
  sort_by: "best" # Possible values here are "best" and "first".
conversation.py CHANGED
@@ -14,7 +14,7 @@ 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
 
 
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
 
engine_ctrl.py CHANGED
@@ -85,7 +85,7 @@ class Engine:
85
  elif command == "option" or command.startswith("Fairy-Stockfish"):
86
  pass
87
  else:
88
- logger.error(" Unexpected engine response to usi: %s %s" % (command, arg))
89
 
90
  def isready(self):
91
  self.send("isready")
@@ -94,11 +94,11 @@ class Engine:
94
  if command == "readyok":
95
  break
96
  elif command == "info" and arg.startswith("string Error! "):
97
- logger.error(" Unexpected engine response to isready: %s %s" % (command, arg))
98
  elif command == "info" and arg.startswith("string "):
99
  pass
100
  else:
101
- logger.error(" Unexpected engine response to isready: %s %s" % (command, arg))
102
 
103
  def setoption(self, name, value):
104
  if value is True:
@@ -114,10 +114,10 @@ class Engine:
114
  if position != "startpos":
115
  position = "sfen " + position
116
  self.send("position %s moves %s" % (position, " ".join(moves)))
117
- logger.info(" position %s moves %s" % (position, " ".join(moves)))
118
 
119
  builder = []
120
- builder.append(" go")
121
  if movetime is not None:
122
  builder.append("movetime")
123
  builder.append(str(movetime))
@@ -216,4 +216,4 @@ class Engine:
216
  if upperbound:
217
  info["score"]["upperbound"] = upperbound
218
  else:
219
- logger.error(" Unexpected engine response to go: %s %s" % (command, arg))
 
85
  elif command == "option" or command.startswith("Fairy-Stockfish"):
86
  pass
87
  else:
88
+ logger.error("Unexpected engine response to usi: %s %s" % (command, arg))
89
 
90
  def isready(self):
91
  self.send("isready")
 
94
  if command == "readyok":
95
  break
96
  elif command == "info" and arg.startswith("string Error! "):
97
+ logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
98
  elif command == "info" and arg.startswith("string "):
99
  pass
100
  else:
101
+ logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
102
 
103
  def setoption(self, name, value):
104
  if value is True:
 
114
  if position != "startpos":
115
  position = "sfen " + position
116
  self.send("position %s moves %s" % (position, " ".join(moves)))
117
+ logger.info("position %s moves %s" % (position, " ".join(moves)))
118
 
119
  builder = []
120
+ builder.append("go")
121
  if movetime is not None:
122
  builder.append("movetime")
123
  builder.append(str(movetime))
 
216
  if upperbound:
217
  info["score"]["upperbound"] = upperbound
218
  else:
219
+ logger.error("Unexpected engine response to go: %s %s" % (command, arg))
engine_wrapper.py CHANGED
@@ -30,7 +30,7 @@ class EngineWrapper:
30
  def __init__(self, board, commands, options=None, silence_stderr=False):
31
  pass
32
 
33
- def set_time_control(self, game):
34
  pass
35
 
36
  def first_search(self, board, movetime):
@@ -57,7 +57,7 @@ class EngineWrapper:
57
  def print_handler_stats(self, info, stats):
58
  for stat in stats:
59
  if stat in info:
60
- logger.info(" {}: {}".format(stat, info[stat]))
61
 
62
  def get_handler_stats(self, info, stats):
63
  stats_str = []
 
30
  def __init__(self, board, commands, options=None, silence_stderr=False):
31
  pass
32
 
33
+ def search_for(self, board, movetime):
34
  pass
35
 
36
  def first_search(self, board, movetime):
 
57
  def print_handler_stats(self, info, stats):
58
  for stat in stats:
59
  if stat in info:
60
+ logger.info("{}: {}".format(stat, info[stat]))
61
 
62
  def get_handler_stats(self, info, stats):
63
  stats_str = []
lishogi-bot.py CHANGED
@@ -33,7 +33,7 @@ terminated = False
33
 
34
  def signal_handler(signal, frame):
35
  global terminated
36
- logger.debug(" Recieved SIGINT. Terminating client.")
37
  terminated = True
38
 
39
 
@@ -48,7 +48,7 @@ def upgrade_account(li):
48
  if li.upgrade_to_bot_account() is None:
49
  return False
50
 
51
- logger.info(" Succesfully upgraded to Bot Account!")
52
  return True
53
 
54
 
@@ -66,6 +66,11 @@ def watch_control_stream(control_queue, li):
66
  except:
67
  pass
68
 
 
 
 
 
 
69
 
70
  def listener_configurer(level, filename):
71
  logging.basicConfig(level=level, filename=filename,
@@ -95,12 +100,19 @@ def game_logging_configurer(queue, level):
95
  def start(li, user_profile, engine_factory, config, logging_level, log_filename):
96
  challenge_config = config["challenge"]
97
  max_games = challenge_config.get("concurrency", 1)
98
- logger.info(" You're now connected to {} and awaiting challenges.".format(config["url"]))
99
  manager = multiprocessing.Manager()
100
  challenge_queue = manager.list()
101
  control_queue = manager.Queue()
102
  control_stream = multiprocessing.Process(target=watch_control_stream, args=[control_queue, li])
103
  control_stream.start()
 
 
 
 
 
 
 
104
  busy_processes = 0
105
  queued_processes = 0
106
 
@@ -132,41 +144,60 @@ def start(li, user_profile, engine_factory, config, logging_level, log_filename)
132
  else:
133
  try:
134
  li.decline_challenge(chlng.id)
135
- logger.info(" Decline {}".format(chlng))
136
  except:
137
  pass
138
  elif event["type"] == "gameStart":
139
  if queued_processes <= 0:
140
- logger.debug(" Something went wrong. Game is starting and we don't have a queued process")
141
  else:
142
  queued_processes -= 1
143
  busy_processes += 1
144
  logger.info("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
145
  game_id = event["game"]["id"]
146
- pool.apply_async(play_game, [li, game_id, control_queue, engine_factory, user_profile, config, challenge_queue, logging_queue, game_logging_configurer, logging_level])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  while ((queued_processes + busy_processes) < max_games and challenge_queue): # keep processing the queue until empty or max_games is reached
148
  chlng = challenge_queue.pop(0)
149
  try:
150
- logger.info(" Accept {}".format(chlng))
151
  queued_processes += 1
152
  li.accept_challenge(chlng.id)
153
  logger.info("--- Process Queue. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
154
  except (HTTPError, ReadTimeout) as exception:
155
  if isinstance(exception, HTTPError) and exception.response.status_code == 404: # ignore missing challenge
156
- logger.info(" Skip missing {}".format(chlng))
157
  queued_processes -= 1
158
 
159
  control_queue.task_done()
160
 
161
- logger.info(" Terminated")
162
  control_stream.terminate()
163
  control_stream.join()
 
 
164
  logging_listener.terminate()
165
  logging_listener.join()
166
 
167
 
168
  @backoff.on_exception(backoff.expo, BaseException, max_time=600, giveup=is_final)
169
- def play_game(li, game_id, control_queue, engine_factory, user_profile, config, challenge_queue, logging_queue, logging_configurer, logging_level):
170
  logging_configurer(logging_queue, logging_level)
171
  logger = logging.getLogger(__name__)
172
 
@@ -183,6 +214,10 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
183
 
184
  logger.info("+++ {}".format(game))
185
 
 
 
 
 
186
  engine_cfg = config["engine"]
187
  is_usi = engine_cfg["protocol"] == "usi"
188
  is_usi_ponder = is_usi and engine_cfg.get("ponder", False)
@@ -201,8 +236,7 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
201
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, binc, winc, byo, True)
202
  ponder_results[game.id] = ( best_move, ponder_move )
203
 
204
- engine.set_time_control(game)
205
- logger.debug(' Game state: {}'.format(game.state))
206
 
207
  if len(board.move_stack) < 2:
208
  while not terminated:
@@ -226,7 +260,7 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
226
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
227
  else:
228
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
229
- logger.info(" Searching for btime {} wtime {}".format(btime, wtime))
230
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, game.state["binc"], game.state["winc"], game.state["byo"])
231
  engine.print_stats()
232
 
@@ -240,20 +274,23 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
240
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + game.state["binc"])
241
  else:
242
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + game.state["winc"])
243
- logger.info(" Pondering for btime {} wtime {}".format(btime, wtime))
244
  ponder_thread = threading.Thread(target=ponder_thread_func, args=(game, engine, ponder_board, btime, wtime, game.state["binc"], game.state["winc"], game.state["byo"]))
245
  ponder_thread.start()
246
  li.make_move(game.id, best_move)
247
  time.sleep(delay_seconds)
248
  elif is_game_over(game):
249
  engine.report_game_result(game, board)
 
 
250
 
 
251
  while not terminated:
252
  try:
253
  binary_chunk = next(lines)
254
 
255
  upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
256
- logger.debug(' Update: {}'.format(upd))
257
  u_type = upd["type"] if upd else "ping"
258
  if u_type == "chatLine":
259
  conversation.react(ChatLine(upd), game)
@@ -266,6 +303,7 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
266
  start_time = time.perf_counter_ns()
267
  fake_thinking(config, board, game)
268
  print_move_number(board)
 
269
 
270
  best_move = None
271
  ponder_move = None
@@ -280,7 +318,7 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
280
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
281
  else:
282
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
283
- logger.info(" Searching for btime {} wtime {}".format(btime, wtime))
284
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, upd["binc"], upd["winc"], upd["byo"])
285
  engine.print_stats()
286
 
@@ -293,7 +331,7 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
293
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + upd["binc"])
294
  else:
295
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + upd["winc"])
296
- logger.info(" Pondering for btime {} wtime {}".format(btime, wtime))
297
  ponder_thread = threading.Thread(target=ponder_thread_func, args=(game, engine, ponder_board, btime, wtime, upd["binc"], upd["winc"], upd["byo"]))
298
  ponder_thread.start()
299
  li.make_move(game.id, best_move)
@@ -301,14 +339,16 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
301
  play_first_move(game, engine, board, li)
302
  deferredFirstMove = False
303
  wb = 'w' if board.turn == shogi.BLACK else 'b'
304
- game.ping(config.get("abort_time", 30), (upd[f"{wb}time"] + upd[f"{wb}inc"]) / 1000 + 60)
305
  elif u_type == "ping":
306
- if game.should_abort_now():
307
- logger.info(" Aborting {} by lack of activity".format(game.url()))
 
 
308
  li.abort(game.id)
309
  break
310
  elif game.should_terminate_now():
311
- logger.info(" Terminating {} by lack of activity".format(game.url()))
312
  if game.is_abortable():
313
  li.abort(game.id)
314
  break
@@ -318,16 +358,23 @@ def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
318
  except StopIteration:
319
  break
320
 
321
- logger.info("--- {} Game over".format(game.url()))
322
  engine.stop()
323
  if not ( ponder_thread is None ):
324
  ponder_thread.join()
325
 
326
- # This can raise queue.NoFull, but that should only happen if we're not processing
327
- # events fast enough and in this case I believe the exception should be raised
 
 
 
 
328
  control_queue.put_nowait({"type": "local_game_done"})
329
 
330
 
 
 
 
 
331
  def play_first_move(game, engine, board, li):
332
  moves = game.state["moves"].split()
333
  if is_engine_move(game, moves):
@@ -357,7 +404,7 @@ def fake_thinking(config, board, game):
357
 
358
  def print_move_number(board):
359
  logger.info("")
360
- logger.info(" move: {}".format(len(board.move_stack) // 1 + 1))
361
 
362
 
363
  def setup_board(game):
@@ -389,7 +436,7 @@ def update_board(board, move):
389
  if board.is_legal(usi_move):
390
  board.push(usi_move)
391
  else:
392
- logger.debug(' Ignoring illegal move {} on board {}'.format(makeusi(move), board.sfen()))
393
  return board
394
 
395
 
@@ -422,7 +469,7 @@ if __name__ == "__main__":
422
  user_profile = li.get_profile()
423
  username = user_profile["username"]
424
  is_bot = user_profile.get("title") == "BOT"
425
- logger.info(" Welcome {}!".format(username))
426
 
427
  if args.u and not is_bot:
428
  is_bot = upgrade_account(li)
@@ -431,4 +478,4 @@ if __name__ == "__main__":
431
  engine_factory = partial(engine_wrapper.create_engine, CONFIG)
432
  start(li, user_profile, engine_factory, CONFIG, logging_level, args.logfile)
433
  else:
434
- logger.error(" {} is not a bot account. Please upgrade it to a bot account!".format(user_profile["username"]))
 
33
 
34
  def signal_handler(signal, frame):
35
  global terminated
36
+ logger.debug("Recieved SIGINT. Terminating client.")
37
  terminated = True
38
 
39
 
 
48
  if li.upgrade_to_bot_account() is None:
49
  return False
50
 
51
+ logger.info("Succesfully upgraded to Bot Account!")
52
  return True
53
 
54
 
 
66
  except:
67
  pass
68
 
69
+
70
+ def do_correspondence_ping(control_queue, period):
71
+ while not terminated:
72
+ time.sleep(period)
73
+ control_queue.put_nowait({"type": "correspondence_ping"})
74
 
75
  def listener_configurer(level, filename):
76
  logging.basicConfig(level=level, filename=filename,
 
100
  def start(li, user_profile, engine_factory, config, logging_level, log_filename):
101
  challenge_config = config["challenge"]
102
  max_games = challenge_config.get("concurrency", 1)
103
+ logger.info("You're now connected to {} and awaiting challenges.".format(config["url"]))
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
+ wait_for_correspondence_ping = False
116
  busy_processes = 0
117
  queued_processes = 0
118
 
 
144
  else:
145
  try:
146
  li.decline_challenge(chlng.id)
147
+ logger.info("Decline {}".format(chlng))
148
  except:
149
  pass
150
  elif event["type"] == "gameStart":
151
  if queued_processes <= 0:
152
+ logger.debug("Something went wrong. Game is starting and we don't have a queued process")
153
  else:
154
  queued_processes -= 1
155
  busy_processes += 1
156
  logger.info("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
157
  game_id = event["game"]["id"]
158
+ 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])
159
+
160
+ if event["type"] == "correspondence_ping" or (event["type"] == "local_game_done" and not wait_for_correspondence_ping):
161
+ if event["type"] == "correspondence_ping" and wait_for_correspondence_ping:
162
+ correspondence_queue.put("")
163
+
164
+ wait_for_correspondence_ping = False
165
+ while (busy_processes + queued_processes) < max_games:
166
+ game_id = correspondence_queue.get()
167
+ # stop checking in on games if we have checked in on all games since the last correspondence_ping
168
+ if not game_id:
169
+ wait_for_correspondence_ping = True
170
+ break
171
+ else:
172
+ busy_processes += 1
173
+ logger.info("--- Process Used. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
174
+ 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])
175
+
176
  while ((queued_processes + busy_processes) < max_games and challenge_queue): # keep processing the queue until empty or max_games is reached
177
  chlng = challenge_queue.pop(0)
178
  try:
179
+ logger.info("Accept {}".format(chlng))
180
  queued_processes += 1
181
  li.accept_challenge(chlng.id)
182
  logger.info("--- Process Queue. Total Queued: {}. Total Used: {}".format(queued_processes, busy_processes))
183
  except (HTTPError, ReadTimeout) as exception:
184
  if isinstance(exception, HTTPError) and exception.response.status_code == 404: # ignore missing challenge
185
+ logger.info("Skip missing {}".format(chlng))
186
  queued_processes -= 1
187
 
188
  control_queue.task_done()
189
 
190
+ logger.info("Terminated")
191
  control_stream.terminate()
192
  control_stream.join()
193
+ correspondence_pinger.terminate()
194
+ correspondence_pinger.join()
195
  logging_listener.terminate()
196
  logging_listener.join()
197
 
198
 
199
  @backoff.on_exception(backoff.expo, BaseException, max_time=600, giveup=is_final)
200
+ def play_game(li, game_id, control_queue, engine_factory, user_profile, config, challenge_queue, correspondence_queue, logging_queue, logging_configurer, logging_level):
201
  logging_configurer(logging_queue, logging_level)
202
  logger = logging.getLogger(__name__)
203
 
 
214
 
215
  logger.info("+++ {}".format(game))
216
 
217
+ is_correspondence = game.perf_name == "Correspondence"
218
+ correspondence_cfg = config.get("correspondence", {}) or {}
219
+ correspondence_move_time = correspondence_cfg.get("move_time", 60) * 1000
220
+
221
  engine_cfg = config["engine"]
222
  is_usi = engine_cfg["protocol"] == "usi"
223
  is_usi_ponder = is_usi and engine_cfg.get("ponder", False)
 
236
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, binc, winc, byo, True)
237
  ponder_results[game.id] = ( best_move, ponder_move )
238
 
239
+ logger.debug("Game state: {}".format(game.state))
 
240
 
241
  if len(board.move_stack) < 2:
242
  while not terminated:
 
260
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
261
  else:
262
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
263
+ logger.info("Searching for btime {} wtime {}".format(btime, wtime))
264
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, game.state["binc"], game.state["winc"], game.state["byo"])
265
  engine.print_stats()
266
 
 
274
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + game.state["binc"])
275
  else:
276
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + game.state["winc"])
277
+ logger.info("Pondering for btime {} wtime {}".format(btime, wtime))
278
  ponder_thread = threading.Thread(target=ponder_thread_func, args=(game, engine, ponder_board, btime, wtime, game.state["binc"], game.state["winc"], game.state["byo"]))
279
  ponder_thread.start()
280
  li.make_move(game.id, best_move)
281
  time.sleep(delay_seconds)
282
  elif is_game_over(game):
283
  engine.report_game_result(game, board)
284
+ elif len(board.move_stack) == 0:
285
+ correspondence_disconnect_time = correspondence_cfg.get("disconnect_time", 300)
286
 
287
+ correspondence_disconnect_time = 0
288
  while not terminated:
289
  try:
290
  binary_chunk = next(lines)
291
 
292
  upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
293
+ logger.debug("Update: {}".format(upd))
294
  u_type = upd["type"] if upd else "ping"
295
  if u_type == "chatLine":
296
  conversation.react(ChatLine(upd), game)
 
303
  start_time = time.perf_counter_ns()
304
  fake_thinking(config, board, game)
305
  print_move_number(board)
306
+ correspondence_disconnect_time = correspondence_cfg.get("disconnect_time", 300)
307
 
308
  best_move = None
309
  ponder_move = None
 
318
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
319
  else:
320
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000))
321
+ logger.info("Searching for btime {} wtime {}".format(btime, wtime))
322
  best_move, ponder_move = engine.search_with_ponder(game, board, btime, wtime, upd["binc"], upd["winc"], upd["byo"])
323
  engine.print_stats()
324
 
 
331
  btime = max(0, btime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + upd["binc"])
332
  else:
333
  wtime = max(0, wtime - move_overhead - int((time.perf_counter_ns() - start_time) / 1000000) + upd["winc"])
334
+ logger.info("Pondering for btime {} wtime {}".format(btime, wtime))
335
  ponder_thread = threading.Thread(target=ponder_thread_func, args=(game, engine, ponder_board, btime, wtime, upd["binc"], upd["winc"], upd["byo"]))
336
  ponder_thread.start()
337
  li.make_move(game.id, best_move)
 
339
  play_first_move(game, engine, board, li)
340
  deferredFirstMove = False
341
  wb = 'w' if board.turn == shogi.BLACK else 'b'
342
+ game.ping(config.get("abort_time", 30), (upd[f"{wb}time"] + upd[f"{wb}inc"]) / 1000 + 60, correspondence_disconnect_time)
343
  elif u_type == "ping":
344
+ if is_correspondence and not is_engine_move(game, board) and game.should_disconnect_now():
345
+ break
346
+ elif game.should_abort_now():
347
+ logger.info("Aborting {} by lack of activity".format(game.url()))
348
  li.abort(game.id)
349
  break
350
  elif game.should_terminate_now():
351
+ logger.info("Terminating {} by lack of activity".format(game.url()))
352
  if game.is_abortable():
353
  li.abort(game.id)
354
  break
 
358
  except StopIteration:
359
  break
360
 
 
361
  engine.stop()
362
  if not ( ponder_thread is None ):
363
  ponder_thread.join()
364
 
365
+ if is_correspondence and not is_game_over(game):
366
+ logger.info("--- Disconnecting from {}".format(game.url()))
367
+ correspondence_queue.put(game_id)
368
+ else:
369
+ logger.info("--- {} Game over".format(game.url()))
370
+
371
  control_queue.put_nowait({"type": "local_game_done"})
372
 
373
 
374
+ def choose_move_time(engine, board, search_time, ponder):
375
+ logger.info("Searching for time {}".format(search_time))
376
+ return engine.search_for(board, search_time, ponder)
377
+
378
  def play_first_move(game, engine, board, li):
379
  moves = game.state["moves"].split()
380
  if is_engine_move(game, moves):
 
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):
 
436
  if board.is_legal(usi_move):
437
  board.push(usi_move)
438
  else:
439
+ logger.debug("Ignoring illegal move {} on board {}".format(makeusi(move), board.sfen()))
440
  return board
441
 
442
 
 
469
  user_profile = li.get_profile()
470
  username = user_profile["username"]
471
  is_bot = user_profile.get("title") == "BOT"
472
+ logger.info("Welcome {}!".format(username))
473
 
474
  if args.u and not is_bot:
475
  is_bot = upgrade_account(li)
 
478
  engine_factory = partial(engine_wrapper.create_engine, CONFIG)
479
  start(li, user_profile, engine_factory, CONFIG, logging_level, args.logfile)
480
  else:
481
+ logger.error("{} is not a bot account. Please upgrade it to a bot account!".format(user_profile["username"]))
model.py CHANGED
@@ -88,6 +88,7 @@ class Game:
88
  self.sente_starts = self.initial_fen == "startpos" or self.initial_fen.split()[1] == "b"
89
  self.abort_at = time.time() + abort_time
90
  self.terminate_at = time.time() + (self.clock_initial + self.clock_increment) / 1000 + abort_time + 60
 
91
 
92
  def url(self):
93
  return urljoin(self.base_url, "{}/{}".format(self.id, self.my_color))
@@ -95,10 +96,11 @@ class Game:
95
  def is_abortable(self):
96
  return len(self.state["moves"]) < 6
97
 
98
- def ping(self, abort_in, terminate_in):
99
  if self.is_abortable():
100
  self.abort_at = time.time() + abort_in
101
  self.terminate_at = time.time() + terminate_in
 
102
 
103
  def should_abort_now(self):
104
  return self.is_abortable() and time.time() > self.abort_at
@@ -106,6 +108,9 @@ class Game:
106
  def should_terminate_now(self):
107
  return time.time() > self.terminate_at
108
 
 
 
 
109
  def my_remaining_seconds(self):
110
  return (self.state["btime"] if self.is_sente else self.state["wtime"]) / 1000
111
 
 
88
  self.sente_starts = self.initial_fen == "startpos" or self.initial_fen.split()[1] == "b"
89
  self.abort_at = time.time() + abort_time
90
  self.terminate_at = time.time() + (self.clock_initial + self.clock_increment) / 1000 + abort_time + 60
91
+ self.disconnect_at = time.time()
92
 
93
  def url(self):
94
  return urljoin(self.base_url, "{}/{}".format(self.id, self.my_color))
 
96
  def is_abortable(self):
97
  return len(self.state["moves"]) < 6
98
 
99
+ def ping(self, abort_in, terminate_in, disconnect_in):
100
  if self.is_abortable():
101
  self.abort_at = time.time() + abort_in
102
  self.terminate_at = time.time() + terminate_in
103
+ self.disconnect_at = time.time() + disconnect_in
104
 
105
  def should_abort_now(self):
106
  return self.is_abortable() and time.time() > self.abort_at
 
108
  def should_terminate_now(self):
109
  return time.time() > self.terminate_at
110
 
111
+ def should_disconnect_now(self):
112
+ return time.time() > self.disconnect_at
113
+
114
  def my_remaining_seconds(self):
115
  return (self.state["btime"] if self.is_sente else self.state["wtime"]) / 1000
116