IISHKO: Telegram bot, Mini App and gateway
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 21:51:30 +03:00
co-authored by Claude Opus 5.5
commit 0ee6fb843b
179 changed files with 59173 additions and 0 deletions
+530
View File
@@ -0,0 +1,530 @@
"""Shared daily quests and check-ins for the bot and Mini App.
The ledger/claim is committed in bot.db before money moves. The gateway credit and
its unique payout ref are committed in one gateway.db transaction. A retry checks
that payout ref and completes an interrupted claim instead of paying twice or
returning a false "already". This avoids relying on cross-file WAL atomicity.
"""
from __future__ import annotations
import calendar
from contextlib import closing
import datetime
import logging
import sqlite3
import threading
import time
import econ_guard
log = logging.getLogger("quest-economy")
QUOTA_PER_USD = 500_000
QUEST_BUDGET = 250_000_000
PAYOUT_TYPES = ("quest", "streak:7", "streak:30", "streak:100")
QUESTS = {
0: [("msgs", 10, 100), ("checkin", 1, 100)],
1: [("msgs", 10, 100), ("quiz", 1, 100), ("checkin", 1, 100)],
2: [("msgs", 15, 200), ("quiz", 1, 150), ("checkin", 1, 150)],
3: [("msgs", 20, 300), ("quiz", 1, 250), ("checkin", 1, 250)],
4: [("msgs", 25, 400), ("quiz", 1, 350), ("checkin", 1, 350)],
}
TITLES = {
"msgs": "Сообщения в группе",
"quiz": "Правильный ответ в квизе",
"checkin": "Ежедневный чек-ин",
}
MSK = 3 * 3600
_PREPARED = set()
_PREPARE_LOCK = threading.Lock()
def _now(value=None):
return int(time.time() if value is None else value)
def today(now=None):
return time.strftime("%Y%m%d", time.gmtime(_now(now) + MSK))
def today_iso(now=None):
return time.strftime("%Y-%m-%d", time.gmtime(_now(now) + MSK))
def day_start(now=None):
msk = time.gmtime(_now(now) + MSK)
return calendar.timegm((msk.tm_year, msk.tm_mon, msk.tm_mday, 0, 0, 0)) - MSK
def week_key(now=None):
return time.strftime("%G%V", time.gmtime(_now(now) + MSK))
def week_start(now=None):
msk = datetime.datetime.fromtimestamp(_now(now) + MSK, datetime.timezone.utc)
monday = (msk.replace(hour=0, minute=0, second=0, microsecond=0) -
datetime.timedelta(days=msk.weekday()))
return calendar.timegm(monday.timetuple()) - MSK
def is_today(value, now=None):
if value in (None, "", 0, "0"):
return False
text = str(value)
if len(text) == 8 and text.isdigit():
return text == today(now)
try:
return float(value) >= day_start(now)
except (TypeError, ValueError):
return text.replace("-", "") == today(now)
def _con(path):
con = sqlite3.connect(path, timeout=25)
con.row_factory = sqlite3.Row
con.execute("PRAGMA busy_timeout=25000")
return con
def ensure_schema(bot_db, gw_db):
econ_guard.ensure_schema(bot_db)
with closing(_con(bot_db)) as con:
columns = {row[1] for row in con.execute("PRAGMA table_info(econ_tx)")}
if "wallet_id" not in columns:
try:
con.execute("ALTER TABLE econ_tx ADD COLUMN wallet_id INTEGER")
except sqlite3.OperationalError as exc:
if "duplicate column" not in str(exc).lower():
raise
con.commit()
with closing(_con(gw_db)) as con:
con.execute("""CREATE TABLE IF NOT EXISTS econ_payouts(
ref TEXT PRIMARY KEY, token_id INTEGER NOT NULL,
units INTEGER NOT NULL, created INTEGER NOT NULL)""")
con.commit()
def _migrate_legacy(bot_db, gw_db):
"""Mark pre-upgrade ledger refs as paid exactly once, before any new claim."""
con = _con(gw_db)
try:
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
con.execute("BEGIN IMMEDIATE")
if con.execute("SELECT v FROM ledger.kv WHERE k='quest_credits:v1'").fetchone():
con.commit()
return
rows = con.execute("SELECT ref,units FROM ledger.econ_tx "
"WHERE ref IS NOT NULL AND ref!=''").fetchall()
con.executemany("INSERT OR IGNORE INTO econ_payouts(ref,token_id,units,created) VALUES(?,0,?,0)",
[(row["ref"], int(row["units"])) for row in rows])
con.execute("INSERT INTO ledger.kv(k,v) VALUES('quest_credits:v1','1')")
con.commit()
except Exception:
con.rollback()
raise
finally:
con.close()
def prepare(bot_db, gw_db):
key = (bot_db, gw_db)
if key in _PREPARED:
return
with _PREPARE_LOCK:
if key in _PREPARED:
return
ensure_schema(bot_db, gw_db)
_migrate_legacy(bot_db, gw_db)
_PREPARED.add(key)
def multiplier(bot_db, uid, now=None):
current = _now(now)
with closing(_con(bot_db)) as con:
row = con.execute("SELECT v FROM kv WHERE k=?", ("ec_x2:%d" % int(uid),)).fetchone()
if not row or not row[0]:
return 1
try:
value = str(row[0])
if "|" in value:
until, mult = value.split("|", 1)
return int(mult) if float(until) > current else 1
return 2 if float(value) > current else 1
except (TypeError, ValueError):
return 1
def _progress_con(con, uid, now=None):
user = con.execute("SELECT quiz_last,last_checkin FROM users WHERE tg_id=?", (int(uid),)).fetchone()
msgs = con.execute("SELECT COUNT(*) FROM group_log WHERE uid=? AND ts>=?",
(int(uid), day_start(now))).fetchone()[0]
return {
"msgs": int(msgs or 0),
"quiz": int(is_today(user["quiz_last"] if user else None, now)),
"checkin": int(is_today(user["last_checkin"] if user else None, now)),
}
def progress(bot_db, uid, now=None):
with closing(_con(bot_db)) as con:
return _progress_con(con, uid, now)
def earned_rank(bot_db, uid, badges, rank_refs, ref_new_id_min=9_000_000_000, now=None):
"""Payout rank: formula plus badge_lock floor, without the admin display override."""
current = _now(now)
with closing(_con(bot_db)) as con:
user = con.execute("SELECT rep,created,badge_lock,badge_until FROM users WHERE tg_id=?",
(int(uid),)).fetchone()
refs = con.execute(
"SELECT COALESCE(SUM(CASE WHEN tg_id>=? THEN 0.5 ELSE 1.0 END),0) "
"FROM users WHERE referred_by=? AND ref_awarded=1", (ref_new_id_min, int(uid))).fetchone()[0]
if not user:
return 1
rep, created, badge_lock, badge_until = user
days = max(0, (current - int(created or 0)) // 86400) if created else 0
lvl = 1
for candidate in (2, 3, 4):
rep_req, days_req = badges[candidate][2], badges[candidate][3]
if days >= days_req and (refs >= rank_refs[candidate] or (rep_req and (rep or 0) >= rep_req)):
lvl = candidate
lock = int(badge_lock or 0)
until = int(badge_until or 0)
if lock and (until == 0 or current < until):
lvl = max(lvl, min(4, max(1, lock)))
return lvl
def _credit_once(gw_db, ref, wallet_id, units, bot_db=None, uid=None):
if bot_db is None or uid is None:
return 0, "user"
if int(units) <= 0:
return 0, "error"
con = None
try:
con = _con(gw_db)
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
con.execute("BEGIN IMMEDIATE")
if not econ_guard.account_eligible_con(con, uid, "ledger"):
con.rollback()
return 0, "blocked"
columns = {row[1] for row in con.execute("PRAGMA ledger.table_info(econ_tx)")}
source = "bounty_source" if "bounty_source" in columns else "NULL AS bounty_source"
receipts = con.execute("SELECT dst,units,wallet_id,type,src,%s "
"FROM ledger.econ_tx WHERE ref=? AND type IN (?,?,?,?)" % source,
(ref, *PAYOUT_TYPES)).fetchall()
if (len(receipts) != 1 or int(receipts[0]["dst"]) != int(uid)
or int(receipts[0]["units"]) != int(units)
or receipts[0]["type"] not in PAYOUT_TYPES or receipts[0]["src"] != 0
or bool(receipts[0]["bounty_source"])
or (receipts[0]["wallet_id"] is not None
and int(receipts[0]["wallet_id"]) != int(wallet_id))):
con.rollback()
return 0, "error"
if not econ_guard._wallet_owned_con(con, uid, wallet_id):
con.rollback()
return 0, "wallet"
existing = con.execute("SELECT token_id,units FROM econ_payouts WHERE ref=?", (ref,)).fetchone()
if existing:
token_matches = int(existing["token_id"]) in (0, int(wallet_id))
if not token_matches or int(existing["units"]) != int(units):
con.rollback()
log.error("payout ref conflict ref=%s", ref)
return 0, "error"
con.commit()
return 0, "already"
con.execute("INSERT INTO econ_payouts(ref,token_id,units,created) VALUES(?,?,?,?)",
(ref, int(wallet_id), int(units), int(time.time())))
credited = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
(int(units), int(wallet_id)))
if credited.rowcount != 1:
con.rollback()
return 0, "wallet"
con.commit()
return int(units), "ok"
except sqlite3.Error:
log.exception("gateway payout failed ref=%s", ref)
if con:
con.rollback()
return 0, "error"
finally:
if con:
con.close()
def _credit_ledger_row(bot_db, gw_db, row):
if not econ_guard.account_eligible(bot_db, int(row["dst"])):
return 0, "blocked"
wallet_id = row["wallet_id"]
if wallet_id is None:
wallet = econ_guard.resolve_wallet(gw_db, bot_db, int(row["dst"]))
if not wallet:
return 0, "wallet"
wallet_id = wallet[0]
return _credit_once(gw_db, row["ref"], int(wallet_id), int(row["units"]),
bot_db=bot_db, uid=int(row["dst"]))
def reconcile_pending(bot_db, gw_db, uid=None):
"""Complete this module's two-phase quest/streak claims, never atomic bounty receipts."""
prepare(bot_db, gw_db)
sql = ("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE wallet_id IS NOT NULL "
"AND type IN (?,?,?,?)")
params = list(PAYOUT_TYPES)
if uid is not None:
sql += " AND dst=?"
params.append(int(uid))
with closing(_con(bot_db)) as con:
columns = {row[1] for row in con.execute("PRAGMA table_info(econ_tx)")}
if "bounty_source" in columns:
sql += " AND COALESCE(bounty_source,'')=''"
rows = con.execute(sql, params).fetchall()
with closing(_con(gw_db)) as gw:
paid = {r[0] for r in gw.execute("SELECT ref FROM econ_payouts").fetchall()}
results = {}
for row in rows:
if row["ref"] in paid:
results["already"] = results.get("already", 0) + 1
continue
_, result = _credit_ledger_row(bot_db, gw_db, row)
results[result] = results.get(result, 0) + 1
return results
def _ledger_row(bot_db, type_, ref):
with closing(_con(bot_db)) as con:
return con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type=? AND ref=?",
(type_, ref)).fetchone()
def claim_daily(bot_db, gw_db, uid, qid, lvl, progress_map=None, mult=None, now=None,
allow_checkin=False):
"""Claim once and self-heal interrupted payouts; progress_map is only a caller prefilter."""
uid = int(uid)
current = _now(now)
definition = next((item for item in QUESTS.get(int(lvl), QUESTS[1]) if item[0] == qid), None)
if not definition:
return 0, "unknown_quest"
_, need, reward = definition
prepare(bot_db, gw_db)
if not econ_guard.account_eligible(bot_db, uid):
return 0, "blocked"
if qid == "checkin" and allow_checkin:
checked = record_checkin(bot_db, gw_db, uid, current, source="miniapp")
if not checked.get("ok"):
return 0, checked.get("error", "user")
mult = multiplier(bot_db, uid, current) if mult is None else int(mult)
units = reward * QUOTA_PER_USD * mult
day = today(current)
marker = "ec_q:%d:%s:%s" % (uid, day, qid)
ref = "quest:%d:%s:%s" % (uid, day, qid)
existing = _ledger_row(bot_db, "quest", ref)
wallet = None if existing else econ_guard.resolve_wallet(gw_db, bot_db, uid)
if not existing and not wallet:
return 0, "wallet"
con = _con(bot_db)
try:
con.execute("BEGIN IMMEDIATE")
if not econ_guard.account_eligible_con(con, uid):
con.rollback()
return 0, "blocked"
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type='quest' AND ref=?",
(ref,)).fetchone()
if row is None:
if con.execute("SELECT 1 FROM kv WHERE k=?", (marker,)).fetchone():
con.commit()
return 0, "already"
prog = _progress_con(con, uid, current)
if prog.get(qid, 0) < need:
con.rollback()
return 0, "progress"
spent = int(con.execute("SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE type='quest' AND ts>=?",
(day_start(current),)).fetchone()[0] or 0)
if spent + units > QUEST_BUDGET:
con.rollback()
return 0, "budget"
if not wallet:
con.rollback()
return 0, "wallet"
claimed = con.execute("INSERT OR IGNORE INTO kv(k,v) VALUES (?,'1')", (marker,))
if claimed.rowcount != 1:
con.rollback()
return 0, "already"
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) VALUES (?,?,?,?,?,?,?)",
(0, uid, units, "quest", current, ref, int(wallet[0])))
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type='quest' AND ref=?",
(ref,)).fetchone()
con.commit()
except sqlite3.IntegrityError:
con.rollback()
return 0, "already"
except sqlite3.Error:
log.exception("daily quest ledger failed uid=%s quest=%s", uid, qid)
con.rollback()
return 0, "error"
finally:
con.close()
return _credit_ledger_row(bot_db, gw_db, row)
def _kv_set(con, key, value):
con.execute("INSERT INTO kv(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v",
(key, str(value)))
def _streak_milestone(bot_db, gw_db, uid, days, reward_usd, now):
prepare(bot_db, gw_db)
if not econ_guard.account_eligible(bot_db, uid):
return 0, "blocked"
type_ = "streak:%d" % days
ref = "grant:%d:%d" % (days, int(uid))
units = int(reward_usd) * QUOTA_PER_USD
existing = _ledger_row(bot_db, type_, ref)
wallet = None if existing else econ_guard.resolve_wallet(gw_db, bot_db, uid)
if not existing and not wallet:
return 0, "wallet"
con = _con(bot_db)
try:
con.execute("BEGIN IMMEDIATE")
if not econ_guard.account_eligible_con(con, uid):
con.rollback()
return 0, "blocked"
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type=? AND ref=?",
(type_, ref)).fetchone()
if row is None:
if con.execute("SELECT 1 FROM econ_grants WHERE uid=? AND code=?",
(int(uid), str(days))).fetchone():
con.commit()
return 0, "already"
granted = con.execute("INSERT OR IGNORE INTO econ_grants(uid,code,units,ts) VALUES(?,?,?,?)",
(int(uid), str(days), units, _now(now)))
if granted.rowcount != 1:
con.rollback()
return 0, "already"
if not wallet:
con.rollback()
return 0, "wallet"
con.execute("INSERT INTO econ_tx(src,dst,units,type,ts,ref,wallet_id) VALUES(?,?,?,?,?,?,?)",
(0, int(uid), units, type_, _now(now), ref, int(wallet[0])))
_kv_set(con, "ec_streak_aw:%d:%d" % (int(uid), days), "1")
row = con.execute("SELECT dst,units,type,ref,wallet_id FROM econ_tx WHERE type=? AND ref=?",
(type_, ref)).fetchone()
con.commit()
except sqlite3.Error:
log.exception("streak milestone ledger failed uid=%s days=%s", uid, days)
con.rollback()
return 0, "error"
finally:
con.close()
return _credit_ledger_row(bot_db, gw_db, row)
def record_checkin(bot_db, gw_db, uid, now=None, source="miniapp"):
"""Idempotently apply calendar, streak, weekly and gate effects of one check-in."""
uid = int(uid)
prepare(bot_db, gw_db)
current = _now(now)
day = today_iso(current)
yesterday = time.strftime("%Y-%m-%d", time.gmtime(current - 86400 + MSK))
con = _con(bot_db)
milestone = None
try:
con.execute("BEGIN IMMEDIATE")
user = con.execute("SELECT last_checkin FROM users WHERE tg_id=?", (uid,)).fetchone()
if not user:
con.rollback()
con.close()
return {"ok": False, "error": "user", "streak": 0}
if not econ_guard.account_eligible_con(con, uid):
con.rollback()
con.close()
return {"ok": False, "error": "blocked", "streak": 0}
new_calendar = not is_today(user["last_checkin"], current)
con.execute("UPDATE users SET last_checkin=?,gate_member_ok=NULL,gate_member_ts=0 "
"WHERE tg_id=?", (day, uid))
streak_row = con.execute("SELECT v FROM kv WHERE k=?", ("ec_streak:%d" % uid,)).fetchone()
try:
n, last = str(streak_row[0]).split("|") if streak_row else (0, "")
n = int(n)
except (TypeError, ValueError):
n, last = 0, ""
fx_key = "ec_checkin_fx:%d:%s" % (uid, day)
fresh_fx = con.execute("INSERT OR IGNORE INTO kv(k,v) VALUES(?,'1')", (fx_key,)).rowcount == 1
last_compact = str(last).replace("-", "")
day_compact = day.replace("-", "")
yesterday_compact = yesterday.replace("-", "")
if fresh_fx and last_compact != day_compact:
n = n + 1 if last_compact == yesterday_compact else 1
_kv_set(con, "ec_streak:%d" % uid, "%d|%s" % (n, day))
week = week_key(current)
wk_key = "ec_wcin:%d:%s" % (uid, week)
wk_row = con.execute("SELECT v FROM kv WHERE k=?", (wk_key,)).fetchone()
try:
wcin = int(float(wk_row[0])) if wk_row else 0
except (TypeError, ValueError):
wcin = 0
_kv_set(con, wk_key, wcin + 1)
milestone = n if n in (7, 30, 100) else None
if source == "miniapp":
_kv_set(con, "ec_web_checkin:%d:%s" % (uid, day), "1")
if fresh_fx and last_compact == day_compact:
# A pre-upgrade bot /daily already used its dice; do not offer a second one.
_kv_set(con, "ec_dice:%d:%s" % (uid, day), "1")
con.commit()
except sqlite3.Error:
log.exception("checkin state failed uid=%s", uid)
con.rollback()
con.close()
return {"ok": False, "error": "error", "streak": 0}
else:
con.close()
milestone_result = None
if milestone:
reward = {7: 50, 30: 200, 100: 1000}[milestone]
milestone_result = _streak_milestone(bot_db, gw_db, uid, milestone, reward, current)
return {"ok": True, "new_calendar": new_calendar, "streak": n,
"milestone": milestone, "milestone_result": milestone_result}
def snapshot(bot_db, gw_db, uid, lvl, now=None):
current = _now(now)
prepare(bot_db, gw_db)
day = today(current)
mult = multiplier(bot_db, uid, current)
with closing(_con(bot_db)) as con:
prog = _progress_con(con, uid, current)
spent = int(con.execute("SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE type='quest' AND ts>=?",
(day_start(current),)).fetchone()[0] or 0)
markers = {row[0] for row in con.execute("SELECT k FROM kv WHERE k LIKE ?",
("ec_q:%d:%s:%%" % (int(uid), day),)).fetchall()}
refs = ["quest:%d:%s:%s" % (int(uid), day, qid) for qid, _, _ in QUESTS.get(int(lvl), QUESTS[1])]
ledger = set()
if refs:
ledger = {row[0] for row in con.execute(
"SELECT ref FROM econ_tx WHERE type='quest' AND ref IN (%s)" % ",".join("?" * len(refs)), refs)}
payouts = set()
if ledger:
with closing(_con(gw_db)) as con:
payouts = {row[0] for row in con.execute(
"SELECT ref FROM econ_payouts WHERE ref IN (%s)" % ",".join("?" * len(ledger)), list(ledger))}
quests = []
for qid, need, reward in QUESTS.get(int(lvl), QUESTS[1]):
marker = "ec_q:%d:%s:%s" % (int(uid), day, qid)
ref = "quest:%d:%s:%s" % (int(uid), day, qid)
has_ledger = ref in ledger
pending = has_ledger and ref not in payouts
done = (marker in markers and not has_ledger) or (has_ledger and not pending)
units = reward * QUOTA_PER_USD * mult
complete = qid == "checkin" or prog.get(qid, 0) >= need
quests.append({
"id": qid, "title": TITLES[qid], "target": need,
"progress": prog.get(qid, 0), "done": done, "pending": pending,
"base_reward_usd": reward, "reward_usd": units / QUOTA_PER_USD,
"claimable": not done and complete and (pending or spent + units <= QUEST_BUDGET),
})
return {
"day": day, "rank": int(lvl), "multiplier": mult, "quests": quests,
"budget_usd": QUEST_BUDGET / QUOTA_PER_USD,
"budget_left_usd": max(0, QUEST_BUDGET - spent) / QUOTA_PER_USD,
}