Skip to content

Commit

Permalink
Don't save username in config
Browse files Browse the repository at this point in the history
  • Loading branch information
Torom committed Aug 5, 2024
1 parent bebd25d commit 0e11183
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 49 deletions.
7 changes: 3 additions & 4 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@

class API:
def __init__(self, config: Config) -> None:
self.config = config
self.lichess_client = httpx.AsyncClient(base_url=config.url, headers={'Authorization': f'Bearer {config.token}',
'User-Agent': f'BotLi/{config.version}'})
self.external_client = httpx.AsyncClient(headers={'User-Agent': f'BotLi/{config.version}'})

def set_user_agent(self) -> None:
self.lichess_client.headers.update({'User-Agent': f'BotLi/{self.config.version} user:{self.config.username}'})
self.external_client.headers.update({'User-Agent': f'BotLi/{self.config.version} user:{self.config.username}'})
def set_user_agent(self, version: str, username: str) -> None:
self.lichess_client.headers.update({'User-Agent': f'BotLi/{version} user:{username}'})
self.external_client.headers.update({'User-Agent': f'BotLi/{version} user:{username}'})

@retry(retry=retry_if_exception_type(httpx.RequestError), after=after_log(logger, logging.DEBUG))
async def abort_game(self, game_id: str) -> bool:
Expand Down
28 changes: 15 additions & 13 deletions chatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ class Chatter:
def __init__(self,
api: API,
config: Config,
username: str,
game_information: Game_Information,
lichess_game: Lichess_Game
) -> None:
self.api = api
self.config = config
self.username = username
self.game_info = game_information
self.lichess_game = lichess_game
self.cpu_message = self._get_cpu()
self.draw_message = self._get_draw_message()
self.draw_message = self._get_draw_message(config)
self.name_message = self._get_name_message(config.version)
self.ram_message = self._get_ram()
self.player_greeting = self._format_message(config.messages.greeting)
self.player_goodbye = self._format_message(config.messages.goodbye)
Expand All @@ -38,7 +40,7 @@ async def handle_chat_message(self, chatLine_Event: dict) -> None:
print(chat_message.text)
return

if chat_message.username != self.config.username:
if chat_message.username != self.username:
prefix = f'{chat_message.username} ({chat_message.room}): '
output = prefix + chat_message.text
if len(output) > 128:
Expand Down Expand Up @@ -89,10 +91,7 @@ async def _handle_command(self, chat_message: Chat_Message) -> None:
elif command == 'motor':
await self.api.send_chat_message(self.game_info.id_, chat_message.room, self.lichess_game.engine.name)
elif command == 'name':
await self.api.send_chat_message(self.game_info.id_,
chat_message.room,
(f'{self.config.username} running {self.lichess_game.engine.name} '
f'(BotLi {self.config.version})'))
await self.api.send_chat_message(self.game_info.id_, chat_message.room, self.name_message)
elif command == 'printeval':
if not self.game_info.increment_ms and self.game_info.initial_time_ms < 180_000:
await self._send_last_message(chat_message.room)
Expand Down Expand Up @@ -164,22 +163,25 @@ def _get_ram(self) -> str:

return f'{mem_gib:.1f} GiB'

def _get_draw_message(self) -> str:
if not self.config.offer_draw.enabled:
def _get_draw_message(self, config: Config) -> str:
if not config.offer_draw.enabled:
return 'This bot will neither accept nor offer draws.'

max_score = self.config.offer_draw.score / 100
max_score = config.offer_draw.score / 100

return (f'The bot offers draw at move {self.config.offer_draw.min_game_length} or later '
return (f'The bot offers draw at move {config.offer_draw.min_game_length} or later '
f'if the eval is within +{max_score:.2f} to -{max_score:.2f} for the last '
f'{self.config.offer_draw.consecutive_moves} moves.')
f'{config.offer_draw.consecutive_moves} moves.')

def _get_name_message(self, version: str) -> str:
return (f'{self.username} running {self.lichess_game.engine.name} (BotLi {version})')

def _format_message(self, message: str | None) -> str | None:
if not message:
return

opponent_username = self.game_info.black_name if self.lichess_game.is_white else self.game_info.white_name
mapping = defaultdict(str, {'opponent': opponent_username, 'me': self.config.username,
mapping = defaultdict(str, {'opponent': opponent_username, 'me': self.username,
'engine': self.lichess_game.engine.name, 'cpu': self.cpu_message,
'ram': self.ram_message})
return message.format_map(mapping)
Expand Down
4 changes: 1 addition & 3 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ class Config:
whitelist: list[str]
blacklist: list[str]
version: str
username: str

@classmethod
def from_yaml(cls, yaml_path: str) -> 'Config':
Expand Down Expand Up @@ -72,8 +71,7 @@ def from_yaml(cls, yaml_path: str) -> 'Config':
messages_config,
whitelist,
blacklist,
cls._get_version(),
username='')
cls._get_version())

@staticmethod
def _check_sections(config: dict) -> None:
Expand Down
10 changes: 5 additions & 5 deletions event_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@


class Event_Handler:
def __init__(self, api: API, config: Config, game_manager: Game_Manager) -> None:
def __init__(self, api: API, config: Config, username: str, game_manager: Game_Manager) -> None:
self.api = api
self.config = config
self.username = username
self.game_manager = game_manager
self.challenge_validator = Challenge_Validator(config)
self.last_challenge_event: dict[str, Any] | None = None

async def run(self) -> None:
async for event in self.api.get_event_stream():
if event['type'] == 'challenge':
if event['challenge']['challenger']['name'] == self.config.username:
if event['challenge']['challenger']['name'] == self.username:
continue

self.last_challenge_event = event['challenge']
Expand All @@ -40,12 +40,12 @@ async def run(self) -> None:
elif event['type'] == 'challengeDeclined':
opponent_name = event['challenge']['destUser']['name']

if opponent_name == self.config.username:
if opponent_name == self.username:
continue

print(f'{opponent_name} declined challenge: {event["challenge"]["declineReason"]}')
elif event['type'] == 'challengeCanceled':
if event['challenge']['challenger']['name'] == self.config.username:
if event['challenge']['challenger']['name'] == self.username:
continue

self.game_manager.remove_challenge(Challenge(event['challenge']['id'],
Expand Down
6 changes: 3 additions & 3 deletions game.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@ def __init__(self,
self.has_timed_out = False

@classmethod
async def create(cls, api: API, config: Config, game_id: str, game_finished_event: Event) -> 'Game':
async def create(cls, api: API, config: Config, username: str, game_id: str, game_finished_event: Event) -> 'Game':
game_stream = api.get_game_stream(game_id)
info = Game_Information.from_gameFull_event(await anext(game_stream))
lichess_game = Lichess_Game(api, config, info)
lichess_game = Lichess_Game(api, config, username, info)
await lichess_game.init_engine()
game = cls(api,
game_id,
game_finished_event,
game_stream,
info,
lichess_game,
Chatter(api, config, info, lichess_game))
Chatter(api, config, username, info, lichess_game))
return game

async def run(self) -> None:
Expand Down
7 changes: 4 additions & 3 deletions game_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@


class Game_Manager:
def __init__(self, api: API, config: Config) -> None:
def __init__(self, api: API, config: Config, username: str) -> None:
self.config = config
self.username = username
self.api = api
self.is_running = True
self.games: dict[Game, Task[None]] = {}
Expand All @@ -22,7 +23,7 @@ def __init__(self, api: API, config: Config) -> None:
self.started_game_ids: deque[str] = deque()
self.challenge_requests: deque[Challenge_Request] = deque()
self.changed_event = Event()
self.matchmaking = Matchmaking(api, config)
self.matchmaking = Matchmaking(api, config, username)
self.current_matchmaking_game_id: str | None = None
self.challenger = Challenger(api)
self.is_rate_limited = False
Expand Down Expand Up @@ -131,7 +132,7 @@ async def _start_game(self, game_id: str) -> None:
await self.api.abort_game(game_id)
return

game = await Game.create(self.api, self.config, game_id, self.changed_event)
game = await Game.create(self.api, self.config, self.username, game_id, self.changed_event)
self.games[game] = create_task(game.run())

def _get_next_challenge(self) -> Challenge | None:
Expand Down
4 changes: 2 additions & 2 deletions lichess_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@


class Lichess_Game:
def __init__(self, api: API, config: Config, game_information: Game_Information) -> None:
def __init__(self, api: API, config: Config, username: str, game_information: Game_Information) -> None:
self.api = api
self.config = config
self.game_info = game_information
self.board = self._setup_board()
self.white_time: float = self.game_info.state['wtime'] / 1000
self.black_time: float = self.game_info.state['btime'] / 1000
self.increment = self.game_info.increment_ms / 1000
self.is_white: bool = self.game_info.white_name == config.username
self.is_white: bool = self.game_info.white_name == username
self.book_settings = self._get_book_settings()
self.syzygy_tablebase = self._get_syzygy_tablebase()
self.gaviota_tablebase = self._get_gaviota_tablebase()
Expand Down
7 changes: 4 additions & 3 deletions matchmaking.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@


class Matchmaking:
def __init__(self, api: API, config: Config) -> None:
def __init__(self, api: API, config: Config, username: str) -> None:
self.api = api
self.config = config
self.username = username
self.next_update = datetime.now()
self.timeout = max(config.matchmaking.timeout, 1)
self.types = self._get_types()
self.suspended_types: list[Matchmaking_Type] = []
self.opponents = Opponents(config.matchmaking.delay, config.username)
self.opponents = Opponents(config.matchmaking.delay, username)
self.challenger = Challenger(api)

self.game_start_time: datetime = datetime.now()
Expand Down Expand Up @@ -139,7 +140,7 @@ async def _get_online_bots(self) -> list[Bot]:
tos_violation = True
bot_counts['with tosViolation'] += 1

if bot['username'] == self.config.username:
if bot['username'] == self.username:
continue

if 'disabled' in bot:
Expand Down
23 changes: 10 additions & 13 deletions user_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,14 @@ def __init__(self, config_path: str, start_matchmaking: bool, allow_upgrade: boo
async def main(self) -> None:
print(f'{LOGO} {self.config.version}\n')

await self._post_init()
account = await self.api.get_account()
username: str = account['username']
self.api.set_user_agent(self.config.version, username)
await self._handle_bot_status(account.get('title'))
await self._test_engines()

game_manager = Game_Manager(self.api, self.config)
event_handler = Event_Handler(self.api, self.config, game_manager)
game_manager = Game_Manager(self.api, self.config, username)
event_handler = Event_Handler(self.api, self.config, username, game_manager)
game_manager_task = create_task(game_manager.run())
event_handler_task = create_task(event_handler.run())
game_manager.is_running = True
Expand Down Expand Up @@ -102,20 +105,14 @@ async def main(self) -> None:
else:
self._help()

async def _post_init(self) -> None:
account = await self.api.get_account()
self.config.username = account['username']
self.api.set_user_agent()
await self._handle_bot_status(account)

async def _handle_bot_status(self, account: dict) -> None:
async def _handle_bot_status(self, title: str | None) -> None:
if 'bot:play' not in await self.api.get_token_scopes(self.config.token):
print('Your token is missing the bot:play scope. This is mandatory to use BotLi.\n'
'You can create such a token by following this link:\n'
'https://lichess.org/account/oauth/token/create?scopes%5B%5D=bot:play&description=BotLi')
sys.exit(1)

if account.get('title') == 'BOT':
if title == 'BOT':
return

print('\nBotLi can only be used by BOT accounts!\n')
Expand All @@ -133,7 +130,7 @@ async def _handle_bot_status(self, account: dict) -> None:
print('Upgrade aborted.')
sys.exit()

if self.api.upgrade_account():
if await self.api.upgrade_account():
print('Upgrade successful.')
else:
print('Upgrade failed.')
Expand Down Expand Up @@ -320,4 +317,4 @@ def complete(self, text: str, state: int) -> str | None:

ui = UserInterface(args.config, args.matchmaking, args.upgrade)
set_event_loop_policy(EventLoopPolicy())
run(ui.main())
run(ui.main(), debug=True)

0 comments on commit 0e11183

Please sign in to comment.