Behaviour-preserving refactor:
- periodic.py: PeriodicMonitor (periodic_check & friends, moved verbatim with comments)
- notifications.py: one AdminNotifier for both processes (was 4 copies of the same
direct-API code), with a 10 s HTTP timeout and the TTS announcer
- onboarding.py: link_player(), the add-player flow shared by /addgamer and /addtoken
- bot.py 2040 -> 1372 lines; no inline sqlite3 left (Database.gamer_exists/get_counts)
- request_queue.py removed: periodic checks call the local stats service under a
10-slot semaphore; the only real Lichess limiter is SharedTokenGate in the service.
Bot-side RateLimiter kept only for direct lichess.org calls.
- /addtoken "already tracked" check is now case-insensitive like /addgamer
- docs/CURRENT_STATE.md: system map as of 6355cd9 (analyst)
- .claude/agents: analyst / developer / tester definitions
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
81 lines
3.2 KiB
Python
81 lines
3.2 KiB
Python
"""
|
|
Shared tail of the add-player flow (/addgamer and /addtoken).
|
|
|
|
The handlers in bot.py keep what differs between the two commands (Lichess
|
|
existence check vs. token -> profile lookup, reply texts, ConversationHandler
|
|
return values); everything after "we know the canonical username and the token"
|
|
is identical and lives here.
|
|
"""
|
|
import logging
|
|
import traceback
|
|
from dataclasses import dataclass
|
|
from typing import Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Every newly linked player starts with hourly periodic notifications.
|
|
DEFAULT_PERIOD_MINUTES = 60
|
|
|
|
|
|
@dataclass
|
|
class LinkResult:
|
|
gamer_id: int
|
|
is_new_gamer: bool # the username was not in the global gamers table before
|
|
added: bool # False when the (user, gamer) pair already existed
|
|
|
|
|
|
async def link_player(bot, user_id: int, tg_user, username: str, token: Optional[str]) -> LinkResult:
|
|
"""
|
|
Add `username` to the global gamers table (if new), link it to `user_id`
|
|
(with `token`, may be None), give the pair the default period, start its
|
|
periodic task and notify the admin.
|
|
|
|
`bot` is the LichessBot (uses bot.db, bot.counters, bot.monitor,
|
|
bot.notifier); `tg_user` is update.effective_user (may be None).
|
|
|
|
When the returned `added` is False the pair already existed (callers check
|
|
first, so only a race gets here); `add_user_gamer` has then only refreshed
|
|
the token and nothing else was done — the caller decides what to reply.
|
|
"""
|
|
db = bot.db
|
|
is_new_gamer = not db.gamer_exists(username)
|
|
|
|
gamer_id = db.add_gamer(username)
|
|
added = db.add_user_gamer(user_id, gamer_id, token)
|
|
if not added:
|
|
return LinkResult(gamer_id=gamer_id, is_new_gamer=is_new_gamer, added=False)
|
|
|
|
# Set default period to 1 hour (60 minutes) for new gamer
|
|
db.set_user_gamer_period(user_id, gamer_id, DEFAULT_PERIOD_MINUTES)
|
|
bot.counters.increment('gamer_added')
|
|
logger.info(f"addgamer: player {username} added for user {user_id} (new_gamer={is_new_gamer})")
|
|
|
|
# If this is the first gamer for this user, make it active
|
|
user_gamers = db.get_user_gamers(user_id)
|
|
if len(user_gamers) == 1:
|
|
db.set_user_active_gamer(user_id, gamer_id)
|
|
|
|
# Start periodic task for this gamer (60 minutes period)
|
|
try:
|
|
gamer_data = {
|
|
'id': gamer_id,
|
|
'username': username,
|
|
'token': token,
|
|
'period_minutes': DEFAULT_PERIOD_MINUTES
|
|
}
|
|
await bot.monitor.start_periodic_task(gamer_data, user_id, DEFAULT_PERIOD_MINUTES)
|
|
logger.info(f"Started periodic task for {username} (user {user_id}) with period {DEFAULT_PERIOD_MINUTES} minutes")
|
|
except Exception as e:
|
|
logger.error(f"Failed to start periodic task for {username}: {e}")
|
|
logger.error(traceback.format_exc())
|
|
|
|
# Notify admin bot about player link (always notify)
|
|
try:
|
|
await bot.notifier.notify_new_player(
|
|
username, user_id, tg_user.username if tg_user else None, is_new_gamer
|
|
)
|
|
logger.info(f"Admin notification processed for player {username}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to notify admin about new player link: {e}")
|
|
|
|
return LinkResult(gamer_id=gamer_id, is_new_gamer=is_new_gamer, added=True)
|