Files
LihonT/services/members/authbot.py
cheb0chik 5df4cddf7d LihonT 3 Luna pre-alpha: the streak pet becomes an animal
A pair of people can have a kitten, a puppy or a lion cub in place of TikTok's streak creature: it grows with the days of the
streak (cub, teen, adult, elder), goes grey while the streak is about to burn out, can be dragged in the chat and is also shown
on the big streak screen. An animal is given by a link (lihont.space/pet) that the friend accepts. The drawings are made by
scripts/make_pet_designs.py and served as strips of frames. Also here: the promo video scripts (make_pet_video.py on top of
make_store_video.py), a retry pause for strips that failed to load, stricter checks in the answer to a gift.

Work in progress: the gift service is not switched on for everyone yet and there is no public build with the animals.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 15:14:48 +03:00

185 lines
9.6 KiB
Python
Raw Permalink 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.
"""The sign-in bot of the store (@lihonTauthbot): ties a Telegram person to the sign-in link the app made, answers a few commands, sends the
notifications about new works, and takes the owner's commands (`/ban A7K-3Q2 7 reason`, `/unban`, `/who`).
Only the owner (MOD_OWNER_ID) may use the owner's commands. Nobody gets another person's data: the bot never says who someone else is.
The bot's token lives in the service's environment (AUTH_BOT_TOKEN), never in the source.
The transport is the Telegram class of modbot.py, injected, so the tests run without a network.
"""
from __future__ import annotations
import threading
import time
from datetime import datetime, timezone
try:
import modbot
except ImportError: # imported as part of a package
from . import modbot
HELP = ("Это бот входа LihonT Store. Откройте приложение Store и нажмите «Войти через Telegram»: оно покажет ссылку на этого бота.\n\n"
"Команды:\n/notify, включить уведомления о новых работах авторов, на которых вы подписаны\n"
"/stop, выключить уведомления\n/delete, удалить аккаунт Store (подписки и вход; ваши работы остаются у автора)")
KINDS = {"frame": "рамку", "bubble": "пузырь"}
def _when(ts: int) -> str:
return datetime.fromtimestamp(ts, timezone.utc).strftime("%d.%m.%Y")
class AuthBot:
def __init__(self, registry, telegram, owner_id, clock=time.time):
self.registry, self.telegram, self.owner = registry, telegram, int(owner_id)
self.accounts = registry.accounts
self.offset = 0
self.clock = clock
self._delete_asked = {}
def say(self, chat_id, text):
self.telegram.call("sendMessage", {"chat_id": chat_id, "text": text})
# -- updates ----------------------------------------------------------------------------------------------------
def handle(self, update):
message = update.get("message") or {}
user = message.get("from") or {}
chat = (message.get("chat") or {}).get("id")
text = (message.get("text") or "").strip()
if not user.get("id") or chat is None or not text.startswith("/") or (message.get("chat") or {}).get("type") != "private":
return
command, _, rest = text.partition(" ")
command = command.split("@")[0].lower()
rest = rest.strip()
if command == "/start":
return self._start(user["id"], chat, rest)
if command in ("/notify", "/stop"):
return self._notify(user["id"], chat, command == "/notify")
if command == "/delete":
return self._delete(user["id"], chat, rest)
if user["id"] == self.owner:
if command == "/ban":
return self._ban(chat, rest)
if command == "/unban":
return self._unban(chat, rest)
if command == "/who":
return self._who(chat, rest)
if command == "/stats":
return self._stats(chat)
self.say(chat, HELP)
def _start(self, tg_id, chat, token):
if not token:
return self.say(chat, HELP)
reply = self.accounts.bot_link(token, tg_id)
if reply["ok"]:
if reply["registered"]:
return self.say(chat, "Готово, вы вошли. Вернитесь в приложение Store.")
return self.say(chat, "Готово. Вернитесь в приложение Store и выберите себе ник.")
if reply["reason"] == "banned":
until = reply.get("banned_until") or 0
tail = "до %s" % _when(until) if until and until < 4_000_000_000 else "бессрочно"
return self.say(chat, "Вход закрыт %s. Причина: %s. Обжалование: t.me/cheb0chik" % (tail, reply.get("ban_reason") or "правила"))
return self.say(chat, "Ссылка устарела или уже использована. Нажмите «Войти через Telegram» в Store ещё раз.")
def _notify(self, tg_id, chat, on):
with self.registry.connect() as db:
changed = db.execute("UPDATE tg_accounts SET notify=? WHERE tg_id=?", (1 if on else 0, tg_id)).rowcount
if not changed:
return self.say(chat, "Сначала войдите через Store.")
self.say(chat, "Уведомления включены." if on else "Уведомления выключены.")
def _delete(self, tg_id, chat, rest):
asked = self._delete_asked.get(tg_id, 0)
if rest.lower() == "yes" and asked > self.clock() - 300:
self._delete_asked.pop(tg_id, None)
self.accounts.delete_tg(tg_id)
return self.say(chat, "Аккаунт удалён.")
self._delete_asked[tg_id] = self.clock()
self.say(chat, "Это удалит вход, подписки и привязку к TikTok. Если уверены, напишите в течение 5 минут: /delete yes")
# -- the owner's commands -----------------------------------------------------------------------------------------
def _ban(self, chat, rest):
parts = rest.split(None, 2)
if len(parts) < 2 or not parts[1].isdigit():
return self.say(chat, "Формат: /ban A7K-3Q2 7 причина (7 дней; 0 = навсегда)")
try:
result = self.accounts.ban(parts[0], int(parts[1]), parts[2] if len(parts) > 2 else "")
except ValueError as error:
return self.say(chat, "Не получилось: %s" % error)
until = "навсегда" if not result["until"] else "до " + _when(result["until"])
self.say(chat, "Забанен %s %s (Telegram: %s, TikTok: %s)." % (result["pid"], until, "да" if result["tg"] else "нет",
"да" if result["tiktok"] else "нет"))
def _unban(self, chat, rest):
try:
result = self.accounts.unban(rest.split()[0] if rest else "")
except ValueError as error:
return self.say(chat, "Не получилось: %s" % error)
self.say(chat, "Бан снят с %s." % result["pid"])
def _who(self, chat, rest):
try:
info = self.accounts.who(rest.split()[0] if rest else "")
except ValueError as error:
return self.say(chat, "Не получилось: %s" % error)
works = ", ".join("%s: %d" % item for item in sorted(info["works"].items())) or "нет"
self.say(chat, "%s\nНик: %s\nTikTok: %s\nРаботы: %s\nПодписчики: %d\nБан: %s" % (
info["pid"], info["handle"] or "нет", info["tiktok"] or "нет", works, info["followers"], "да" if info["banned"] else "нет"))
def _stats(self, chat):
with self.registry.connect() as db:
accounts = db.execute("SELECT COUNT(*) FROM tg_accounts WHERE handle IS NOT NULL").fetchone()[0]
authors = db.execute("SELECT COUNT(*) FROM tg_tiktok").fetchone()[0]
follows = db.execute("SELECT COUNT(*) FROM follows").fetchone()[0]
self.say(chat, "Участников: %d\nАвторов (с TikTok): %d\nПодписок: %d" % (accounts, authors, follows))
# -- notifications --------------------------------------------------------------------------------------------------
def notify_new(self, art):
"""Tells the followers of an author about a work that has just been accepted into the catalog."""
if not art.get("listed"):
return 0
sent = 0
author = self.accounts.handle_of_uid(art["uid"])
text = "Новая %s в Store: «%s»%s\nОткройте LihonT Store, вкладка «Входящие»." % (
"рамка" if art["kind"] == "frame" else "картинка для пузыря" if art["kind"] == "bubble" else "работа", art["name"],
" от @" + author if author else "")
for tg_id in self.accounts.followers_to_notify(art["uid"]):
try:
self.say(tg_id, text)
sent += 1
except RuntimeError as error:
if "blocked" in str(error).lower() or "forbidden" in str(error).lower():
self.accounts.mute(tg_id) # they stopped the bot: do not try again
return sent
# -- the loop ---------------------------------------------------------------------------------------------------------
def poll_once(self, timeout=10):
import json
updates = self.telegram.call("getUpdates", {"offset": self.offset, "timeout": timeout,
"allowed_updates": json.dumps(["message"])}, timeout=timeout + 15) or []
for update in updates:
self.offset = max(self.offset, int(update.get("update_id", 0)) + 1)
try:
self.handle(update)
except Exception:
pass
return len(updates)
def run(self, stop: threading.Event):
while not stop.is_set():
try:
self.poll_once()
except Exception:
stop.wait(5)
def start(registry, token, owner_id):
"""Runs the bot in a background thread; returns (the bot, the stop event)."""
stop = threading.Event()
bot = AuthBot(registry, modbot.Telegram(token), owner_id)
threading.Thread(target=bot.run, args=(stop,), name="lihont-authbot", daemon=True).start()
return bot, stop