Some checks failed
CI/CD Pipeline / build-and-deploy (push) Failing after 2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
273 lines
12 KiB
Python
273 lines
12 KiB
Python
"""
|
||
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: en is the default, every other language of
|
||
# i18n.LANGUAGES is set for clients with that Telegram 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', "Написать автору"),
|
||
),
|
||
'uz': (
|
||
('addgamer', "O'yinchi qo'shish"),
|
||
('today', "Bugungi partiyalar"),
|
||
('yesterday', "Kechagi partiyalar"),
|
||
('week', "So'nggi 7 kun"),
|
||
('getgamers', "O'yinchilarim va reytinglar"),
|
||
('setperiod', "Hisobotlar chastotasi"),
|
||
('delgamer', "O'yinchini o'chirish"),
|
||
('year', "So'nggi yil (sekin)"),
|
||
('addtoken', "Token bilan masalalar"),
|
||
('lang', "Til / Язык / Language"),
|
||
('help', "Barcha buyruqlar"),
|
||
('support', "Muallifga yozish"),
|
||
),
|
||
'tr': (
|
||
('addgamer', "Oyuncu ekle"),
|
||
('today', "Bugünkü oyunlar"),
|
||
('yesterday', "Dünkü oyunlar"),
|
||
('week', "Son 7 gün"),
|
||
('getgamers', "Oyuncularım ve puanlar"),
|
||
('setperiod', "Rapor sıklığı"),
|
||
('delgamer', "Oyuncu sil"),
|
||
('year', "Son bir yıl (yavaş)"),
|
||
('addtoken', "Token ile bulmacalar"),
|
||
('lang', "Dil / Язык / Language"),
|
||
('help', "Tüm komutlar"),
|
||
('support', "Geliştiriciye yazın"),
|
||
),
|
||
'fa': (
|
||
('addgamer', "افزودن بازیکن"),
|
||
('today', "بازیهای امروز"),
|
||
('yesterday', "بازیهای دیروز"),
|
||
('week', "7 روز اخیر"),
|
||
('getgamers', "بازیکنان من و ریتینگها"),
|
||
('setperiod', "تناوب گزارشها"),
|
||
('delgamer', "حذف بازیکن"),
|
||
('year', "یک سال اخیر (کند)"),
|
||
('addtoken', "معماها با توکن"),
|
||
('lang', "زبان / Язык / Language"),
|
||
('help', "همه دستورها"),
|
||
('support', "تماس با سازنده"),
|
||
),
|
||
'ar': (
|
||
('addgamer', "إضافة لاعب"),
|
||
('today', "مباريات اليوم"),
|
||
('yesterday', "مباريات أمس"),
|
||
('week', "آخر 7 أيام"),
|
||
('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)
|