LichessStatTgWeb/LichessClientTG_bot/onboarding.py
vrubelroman 533c0a7694 onboarding phase 1: one-screen /start, any text is a player name, URL/@ normalisation, next-step texts, /addtoken trap closed
Analysis: docs/analysis/onboarding_funnel.md (56% of users never add a player;
drop happens on the first screen; non-ru/en users convert at 25%).
Design: docs/design/onboarding.md.

- /start: one message. New user: promise + "send a Lichess username, e.g.
  DrNykterstein" with [❓ Где взять имя] / [🇬🇧 English] (language switch edits
  the message in place). Returning user: their players + /today /addgamer /help.
- /addgamer asks for the name directly (the two-button menu from 2025-12-03 is gone).
- Any non-command text in a private chat is a player-name attempt: no awaiting
  flag, PicklePersistence removed. onboarding.normalise_username accepts
  lichess.org URLs, @name, quotes, "add Name"; chess.com and non-name text get
  their own hints; nothing is sent to Lichess for them.
- Every reply ends with the next step (success: hourly report is on, /today,
  send another name). One no_players empty state for /today, /week, /getgamers,
  /delgamer, /setperiod, /profile, /year.
- /help: 18 lines in three groups; /year and /lang aliases; command menu set
  from code for en (default) and ru at startup (set_my_commands).
- /addtoken trap: non-lip_ text gets a hint instead of "invalid token"; any
  other command inside the conversation ends it and runs; /cancel outside a
  conversation answers "nothing to cancel".
- All echoed input html-escaped. Terminology unified: игрок / имя на Lichess /
  отчёт (player / Lichess username / report).
- events: user_start screen=, addgamer_input kind= normalised=, addgamer_result
  format|chesscom, lang_set via=, addtoken_result not_a_token; text in_flow= gone.
- i18n: 18 dead keys removed, 21 added; docs (README, USER_GUIDE, about,
  CURRENT_STATE, CHANGELOG Unreleased) updated; 107 bot tests (was 61).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 07:36:31 +00:00

216 lines
9.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Onboarding helpers: everything about "a user sends us a player name" that does
not need Telegram objects, so it can be unit-tested on the host.
- normalise_username(): what counts as a Lichess username and how we read one
out of whatever the user typed (profile URL, @name, "add Name", ...), spec
docs/design/onboarding.md section 4.3;
- start_returning_text(): the /start screen of a user who already follows
players (section 2b);
- BOT_COMMANDS: the command menu set via set_my_commands at startup (4.4);
- link_player(): the shared tail of /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 html
import logging
import re
import traceback
from dataclasses import dataclass
from typing import List, Optional, Tuple
from events import event
from i18n import t
logger = logging.getLogger(__name__)
# Every newly linked player starts with hourly periodic notifications.
DEFAULT_PERIOD_MINUTES = 60
# Lichess usernames: 2-20 chars, letters/digits/_/-, first char alphanumeric
# (lila's UserName regex; Lichess itself forbids a leading '-' or '_').
USERNAME_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_-]{1,19}$')
# Quotes users paste around a name («Name», "Name", 'Name').
_QUOTE_CHARS = '«»"\'„“”‘’`'
# Trailing punctuation from a sentence ("DrNykterstein." / "Name,") — a username
# never ends with these, so stripping them only turns a false "format" into a check.
_TRAILING_PUNCT = '.,;:!'
# Filler words that match USERNAME_RE themselves but are never the name when
# the text has several words ("add DrNykterstein", "player Name", "my name is X").
_FILLER_WORDS = frozenset((
'add', 'player', 'name', 'username', 'user', 'nick', 'nickname', 'lichess',
'track', 'follow', 'please', 'pls', 'my', 'me', 'is', 'the', 'a', 'an',
'and', 'for', 'to', 'it', 'this', 'of', 'on', 'in', 'hi', 'hello',
))
# Number of names spelled out on the returning /start screen before "and N more".
START_NAMES_SHOWN = 3
# Command menu (BotFather /setcommands equivalent), by frequency of use;
# set from code at startup for the default (en) and the ru client language.
# /start, /cancel, /profile, /set_lang, /lastYear_or_1000games keep working
# but are not listed.
BOT_COMMANDS = {
'en': (
('addgamer', "Add a player"),
('today', "Today's games"),
('yesterday', "Yesterday's games"),
('week', "Last 7 days"),
('getgamers', "My players and ratings"),
('setperiod', "How often to report"),
('delgamer', "Remove a player"),
('year', "Last year (slow)"),
('addtoken', "Puzzles via your token"),
('lang', "Language / Язык"),
('help', "All commands"),
('support', "Contact the author"),
),
'ru': (
('addgamer', "Добавить игрока"),
('today', "Партии за сегодня"),
('yesterday', "За вчера"),
('week', "За неделю"),
('getgamers', "Мои игроки и рейтинги"),
('setperiod', "Как часто присылать"),
('delgamer', "Удалить игрока"),
('year', "За год (медленно)"),
('addtoken', "Пазлы по своему токену"),
('lang', "Язык / Language"),
('help', "Все команды"),
('support', "Написать автору"),
),
}
def normalise_username(text: Optional[str]) -> Tuple[str, str]:
"""
Read a Lichess username out of free text. Returns (name, kind):
kind='chesscom' the text mentions chess.com — not a Lichess name at all
(name = the stripped text, for the event log only);
kind='url' a lichess.org profile link: name taken after "/@/" (or
after "lichess.org/"), cut at the first of "/ ? # space";
https://, http://, www., ru.lichess.org, trailing "/" all fine;
kind='at' "@Name" -> "Name";
kind='plain' the text as typed (surrounding quotes/spaces removed);
kind='format' whatever is left does not match USERNAME_RE (Cyrillic,
spaces, >20 chars, leading dash, empty...) — name is the
best-effort remainder, for the event log only.
Several words: if exactly one of them looks like a username (filler words
such as "add"/"player" do not count), that word is the name — "add
DrNykterstein", "игрок DrNykterstein"; otherwise kind='format'.
The result is never HTML-escaped here; callers escape before echoing.
"""
s = (text or '').strip().strip(_QUOTE_CHARS).strip()
low = s.lower()
if 'chess.com' in low or 'chesscom' in low:
return s, 'chesscom'
if 'lichess.org' in low:
kind = 'url'
tail = s[re.search(r'lichess\.org', s, re.IGNORECASE).end():]
at = tail.find('/@/')
rest = tail[at + 3:] if at >= 0 else tail.lstrip('/')
s = re.split(r'[/?#\s]', rest, maxsplit=1)[0]
elif s.startswith('@'):
kind = 'at'
s = s[1:]
else:
kind = 'plain'
s = s.strip().strip(_QUOTE_CHARS).rstrip(_TRAILING_PUNCT)
if any(ch.isspace() for ch in s):
candidates = [w.rstrip(_TRAILING_PUNCT).strip(_QUOTE_CHARS) for w in s.split()]
candidates = [w for w in candidates if USERNAME_RE.match(w) and w.lower() not in _FILLER_WORDS]
if len(candidates) == 1:
s = candidates[0]
else:
return s, 'format'
if not USERNAME_RE.match(s):
return s, 'format'
return s, kind
def start_returning_text(usernames: List[str], lang: str) -> str:
"""
/start for a user who already follows players: the first START_NAMES_SHOWN
names alphabetically (case-insensitive) in <code>, then "и ещё N" /
"and N more" when there are more. HTML-escaped; one logical line for the
names (Telegram wraps it), then the three commands.
"""
names = sorted(usernames, key=str.lower)
shown = ", ".join(f"<code>{html.escape(n)}</code>" for n in names[:START_NAMES_SHOWN])
rest = len(names) - START_NAMES_SHOWN
more = t('start_more', lang, n=rest) if rest > 0 else ""
return t('start_returning', lang, names=shown, more=more)
@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)