LichessStatTgWeb/LichessClientTG_bot/onboarding.py
vrubelroman d24cc1a2bd structured events.log, count games in the window they finished in, immediate reopened notice
- events.py (bot): one grep-able line per event into data/events.log (10 MB x 5 rotation,
  survives container recreation): user_start, cmd, text/callback/non_text, addgamer_input/
  addgamer_result, addtoken_result, gamer_added, gamer_deleted, period_set, lang_set,
  check (decision=request|skip_unchanged|skip_closed, games, notified, lag), check_error,
  closed_notice, reopened_notice, blocked, token_rejected, status_refresh, admin_notify,
  tg_error; a SUMMARY line at midnight, also shown by admin /status as "Вчера".
  Service side: EVT lichess_429 (kind=concurrency|burst|unknown) and lichess_error in its log.
- /games/{username}/period?by_finish=true: query Lichess from since-3h and keep games with
  since < lastMoveAt <= until. Periodic checks use it, so a game created 14:58 and finished
  15:06 is reported in the 15:00-16:00 window instead of being lost on the boundary.
- reopened-account notice is sent as soon as the status flips, not after the next game.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 22:51:11 +00:00

85 lines
3.4 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
from events import event
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], via: str = 'addgamer') -> 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); `via` is
the command that got here ('addgamer' | 'addtoken'), for the event log only.
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})")
event('gamer_added', uid=user_id, gamer=username, gamer_id=gamer_id, new_gamer=is_new_gamer, via=via)
# 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)