onboarding: never let a network blip trigger a leave + blocklist
Browse filesSame three fixes as the private tree, plus the two wiring gaps that made them
worse here.
The core problem: has_rights collapsed every exception into "no rights", and at
the 600s slot that answer went straight to leave + blocklist. probe_rights is
now tri-state (True/False/None); only a confirmed False may act. An unreadable
answer requeues the same slot 60s later, up to 3 times, then gives up without
leaving. The nag's send_message no longer treats a timeout as "muted/removed" -
only Forbidden and the chat-is-gone BadRequests do, and that path leaves without
blocklisting. Error-derived cache negatives now live 20s instead of 300s, so a
blip can no longer silence a group for five minutes.
Also here:
- /groups (list + unblock) was private-only, and unblock() was dead code in this
repo. A wrong entry was only undoable by hand-editing bot.db on the VPS.
- ADMIN_USER_ID was claimed by whoever sent the first /start after a restart.
On a public bot that is a stranger, and it re-opened on every deploy. It now
comes from the environment only; unset means nobody holds it. The private tree
removed this a while back and the fix was never ported.
- Blocklist entries expire after 7 days, the no-rights reply is throttled to
once per 10 min per chat, TEXTS lookup moved out of the try, and
restricted -> kicked now cancels pending nags.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
- .env.example +7 -0
- bot.py +66 -11
- config.py +7 -2
- modules/onboarding.py +139 -30
|
@@ -28,6 +28,13 @@ AI_FALLBACK_MODEL=
|
|
| 28 |
# Optional; the fallback text model is reused for images when this is empty.
|
| 29 |
AI_FALLBACK_VISION_MODEL=
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# ── Storage ───────────────────────────────────────────────
|
| 32 |
DB_PATH=/data/bot.db
|
| 33 |
|
|
|
|
| 28 |
# Optional; the fallback text model is reused for images when this is empty.
|
| 29 |
AI_FALLBACK_VISION_MODEL=
|
| 30 |
|
| 31 |
+
# ── Ownership ─────────────────────────────────────────────
|
| 32 |
+
# Your Telegram numeric user ID. Unlocks /groups (view and clear the blocklist
|
| 33 |
+
# of groups the bot left over missing rights). Leave empty and nobody has it —
|
| 34 |
+
# there is deliberately no "first person to /start becomes the admin" fallback.
|
| 35 |
+
# Get yours from @userinfobot.
|
| 36 |
+
ADMIN_USER_ID=
|
| 37 |
+
|
| 38 |
# ── Storage ───────────────────────────────────────────────
|
| 39 |
DB_PATH=/data/bot.db
|
| 40 |
|
|
@@ -116,8 +116,10 @@ async def _group_cmd_allowed(update, context):
|
|
| 116 |
|
| 117 |
|
| 118 |
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
if update.effective_chat.type == "private":
|
| 122 |
context.user_data["history"] = []
|
| 123 |
intent, reply = await ai_text(
|
|
@@ -159,6 +161,47 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 159 |
)
|
| 160 |
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
async def cmd_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 163 |
if update.effective_chat.type == "private" or not update.message.reply_to_message:
|
| 164 |
return
|
|
@@ -397,14 +440,20 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
|
|
| 397 |
# 447 "detected spam but no permission" lines from one unknown group in 24h).
|
| 398 |
# The rights nag runs on a timer in modules/onboarding and gives up at 10 min.
|
| 399 |
if not await onboarding.has_rights(context, chat_id):
|
|
|
|
|
|
|
|
|
|
| 400 |
if wants_reply:
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
|
|
|
|
|
|
|
|
|
| 408 |
return
|
| 409 |
|
| 410 |
# A message posted under a chat's identity (anonymous admin, channel identity)
|
|
@@ -682,6 +731,12 @@ async def handle_my_chat_member(update: Update, context: ContextTypes.DEFAULT_TY
|
|
| 682 |
# This event also fires when our rights are edited, so drop the cache or we
|
| 683 |
# would keep using the stale answer until the TTL expires.
|
| 684 |
onboarding.forget_rights(chat_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
|
| 686 |
if old in ("left", "kicked") and new in ("member", "administrator"):
|
| 687 |
# Channels are not supported: the anti-spam filter is ChatType.GROUPS
|
|
@@ -725,8 +780,7 @@ async def handle_my_chat_member(update: Update, context: ContextTypes.DEFAULT_TY
|
|
| 725 |
[InlineKeyboardButton("Decline", callback_data="tos_decline_" + str(chat_id))]
|
| 726 |
])
|
| 727 |
await context.bot.send_message(chat_id, TOS_TEXT, reply_markup=keyboard)
|
| 728 |
-
elif
|
| 729 |
-
onboarding.cancel(context, chat_id)
|
| 730 |
onboarding.forget_rights(chat_id)
|
| 731 |
await delete_tos(chat_id)
|
| 732 |
|
|
@@ -841,6 +895,7 @@ def main():
|
|
| 841 |
# anywhere else an edit would run the command or the answer a second time.
|
| 842 |
for cmd, fn in [
|
| 843 |
("start", cmd_start), ("help", cmd_help), ("ban", cmd_ban),
|
|
|
|
| 844 |
]:
|
| 845 |
app.add_handler(CommandHandler(cmd, fn, filters=filters.UpdateType.MESSAGE))
|
| 846 |
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 119 |
+
# Deliberately no "first caller becomes super-admin" here. This bot is public,
|
| 120 |
+
# so that grab went to whoever happened to /start first after each restart,
|
| 121 |
+
# and it silently re-opened on every deploy. Set ADMIN_USER_ID explicitly;
|
| 122 |
+
# unset means the super-admin commands are unavailable to everyone.
|
| 123 |
if update.effective_chat.type == "private":
|
| 124 |
context.user_data["history"] = []
|
| 125 |
intent, reply = await ai_text(
|
|
|
|
| 161 |
)
|
| 162 |
|
| 163 |
|
| 164 |
+
async def cmd_groups(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 165 |
+
"""Super-admin: inspect and clear the group blocklist.
|
| 166 |
+
|
| 167 |
+
Entries expire on their own after onboarding.BLOCK_DAYS, but a wrong one
|
| 168 |
+
should not need a week or a hand-edited database to undo.
|
| 169 |
+
/groups — list, /groups unblock <chat_id> — clear one.
|
| 170 |
+
"""
|
| 171 |
+
if not update.effective_user or not is_bot_admin(update.effective_user.id):
|
| 172 |
+
return
|
| 173 |
+
args = context.args or []
|
| 174 |
+
if args and args[0] == "unblock":
|
| 175 |
+
if len(args) < 2:
|
| 176 |
+
await update.message.reply_text("Usage: /groups unblock <chat_id>")
|
| 177 |
+
return
|
| 178 |
+
try:
|
| 179 |
+
cid = int(args[1])
|
| 180 |
+
except ValueError:
|
| 181 |
+
await update.message.reply_text("chat_id must be a number")
|
| 182 |
+
return
|
| 183 |
+
await onboarding.unblock(cid)
|
| 184 |
+
await update.message.reply_text("Unblocked: " + str(cid))
|
| 185 |
+
return
|
| 186 |
+
from modules.db import shared_db
|
| 187 |
+
async with shared_db() as db:
|
| 188 |
+
cur = await db.execute(
|
| 189 |
+
"SELECT chat_id, title, reason, blocked_at FROM group_blocklist "
|
| 190 |
+
"ORDER BY blocked_at DESC LIMIT 20")
|
| 191 |
+
rows = await cur.fetchall()
|
| 192 |
+
if not rows:
|
| 193 |
+
await update.message.reply_text("Blocklist is empty")
|
| 194 |
+
return
|
| 195 |
+
lines = ["Blocked groups (" + str(len(rows)) + ", expire after "
|
| 196 |
+
+ str(onboarding.BLOCK_DAYS) + "d):"]
|
| 197 |
+
for cid, title, reason, at in rows:
|
| 198 |
+
lines.append(str(cid) + " " + (title or "?")[:20] + " " + str(reason)
|
| 199 |
+
+ " " + str(at)[:16])
|
| 200 |
+
lines.append("")
|
| 201 |
+
lines.append("Clear one: /groups unblock <chat_id>")
|
| 202 |
+
await update.message.reply_text("\n".join(lines))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
async def cmd_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 206 |
if update.effective_chat.type == "private" or not update.message.reply_to_message:
|
| 207 |
return
|
|
|
|
| 440 |
# 447 "detected spam but no permission" lines from one unknown group in 24h).
|
| 441 |
# The rights nag runs on a timer in modules/onboarding and gives up at 10 min.
|
| 442 |
if not await onboarding.has_rights(context, chat_id):
|
| 443 |
+
# Say so once in a while so someone fixes it, but not on every mention —
|
| 444 |
+
# "make the bot talk" is the same free drain in miniature, and legacy
|
| 445 |
+
# rights-less groups never go through the nag flow at all.
|
| 446 |
if wants_reply:
|
| 447 |
+
k = "norights_cd_" + str(chat_id)
|
| 448 |
+
if _time.time() - context.bot_data.get(k, 0) >= 600:
|
| 449 |
+
context.bot_data[k] = _time.time()
|
| 450 |
+
try:
|
| 451 |
+
await msg.reply_text(
|
| 452 |
+
"I don't have admin rights yet (Delete Messages + Ban Users), "
|
| 453 |
+
"so I can't do anything here. Ask an admin to grant them."
|
| 454 |
+
)
|
| 455 |
+
except Exception:
|
| 456 |
+
pass
|
| 457 |
return
|
| 458 |
|
| 459 |
# A message posted under a chat's identity (anonymous admin, channel identity)
|
|
|
|
| 731 |
# This event also fires when our rights are edited, so drop the cache or we
|
| 732 |
# would keep using the stale answer until the TTL expires.
|
| 733 |
onboarding.forget_rights(chat_id)
|
| 734 |
+
# Stop nagging the moment we are out, unconditionally. Not inside the branch
|
| 735 |
+
# below: restricted -> kicked does not satisfy its `old` test, which would
|
| 736 |
+
# orphan the nags. They would then keep posting into a chat we already left,
|
| 737 |
+
# fail, and that failure would be read as "we can never speak here".
|
| 738 |
+
if new in ("left", "kicked"):
|
| 739 |
+
onboarding.cancel(context, chat_id)
|
| 740 |
|
| 741 |
if old in ("left", "kicked") and new in ("member", "administrator"):
|
| 742 |
# Channels are not supported: the anti-spam filter is ChatType.GROUPS
|
|
|
|
| 780 |
[InlineKeyboardButton("Decline", callback_data="tos_decline_" + str(chat_id))]
|
| 781 |
])
|
| 782 |
await context.bot.send_message(chat_id, TOS_TEXT, reply_markup=keyboard)
|
| 783 |
+
elif new in ("left", "kicked"):
|
|
|
|
| 784 |
onboarding.forget_rights(chat_id)
|
| 785 |
await delete_tos(chat_id)
|
| 786 |
|
|
|
|
| 895 |
# anywhere else an edit would run the command or the answer a second time.
|
| 896 |
for cmd, fn in [
|
| 897 |
("start", cmd_start), ("help", cmd_help), ("ban", cmd_ban),
|
| 898 |
+
("groups", cmd_groups),
|
| 899 |
]:
|
| 900 |
app.add_handler(CommandHandler(cmd, fn, filters=filters.UpdateType.MESSAGE))
|
| 901 |
|
|
@@ -54,5 +54,10 @@ JUDGE_CAPTION_LIMIT = int(os.environ.get("JUDGE_CAPTION_LIMIT", "900"))
|
|
| 54 |
# only — admins and private chats are never limited.
|
| 55 |
GROUP_CMD_COOLDOWN = int(os.environ.get("GROUP_CMD_COOLDOWN", "60"))
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# only — admins and private chats are never limited.
|
| 55 |
GROUP_CMD_COOLDOWN = int(os.environ.get("GROUP_CMD_COOLDOWN", "60"))
|
| 56 |
|
| 57 |
+
# Super-admin Telegram user ID, for /groups. Must be set explicitly: this used to
|
| 58 |
+
# be claimed by whoever sent the first /start after a restart, which on a public
|
| 59 |
+
# bot means a stranger, re-opened on every deploy. Unset = nobody has it.
|
| 60 |
+
try:
|
| 61 |
+
ADMIN_USER_ID = int(os.environ.get("ADMIN_USER_ID", "") or 0) or None
|
| 62 |
+
except ValueError:
|
| 63 |
+
ADMIN_USER_ID = None
|
|
@@ -13,13 +13,23 @@ Three layers:
|
|
| 13 |
3. Still nothing at 10 minutes: explain, leave, and blocklist the chat, so a
|
| 14 |
re-invite is refused instantly instead of restarting the whole cycle
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
"""
|
| 19 |
|
| 20 |
import logging
|
| 21 |
import time
|
| 22 |
|
|
|
|
|
|
|
| 23 |
from modules.db import shared_db
|
| 24 |
|
| 25 |
logger = logging.getLogger(__name__)
|
|
@@ -28,11 +38,23 @@ logger = logging.getLogger(__name__)
|
|
| 28 |
REMIND_AT = (60, 120, 180, 300, 600)
|
| 29 |
GIVE_UP_AFTER = REMIND_AT[-1]
|
| 30 |
|
| 31 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
# Calling getChatMember per message is expensive, and rights changes arrive via
|
| 33 |
# my_chat_member anyway; the cache only covers the case where that event is
|
| 34 |
# missed, so the TTL can be generous.
|
|
|
|
|
|
|
|
|
|
| 35 |
_RIGHTS_TTL = 300
|
|
|
|
| 36 |
_rights_cache = {}
|
| 37 |
|
| 38 |
|
|
@@ -49,7 +71,11 @@ async def ensure_tables():
|
|
| 49 |
async def is_blocked(chat_id):
|
| 50 |
try:
|
| 51 |
async with shared_db() as db:
|
| 52 |
-
cur = await db.execute(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
return await cur.fetchone() is not None
|
| 54 |
except Exception as e:
|
| 55 |
logger.warning("blocklist lookup failed (allowing): " + str(e))
|
|
@@ -77,26 +103,42 @@ def forget_rights(chat_id):
|
|
| 77 |
_rights_cache.pop(chat_id, None)
|
| 78 |
|
| 79 |
|
| 80 |
-
def note_rights(chat_id, has_rights):
|
| 81 |
-
_rights_cache[chat_id] = (bool(has_rights), time.time())
|
| 82 |
|
| 83 |
|
| 84 |
-
async def
|
| 85 |
-
"""
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
| 90 |
try:
|
| 91 |
me = await context.bot.get_chat_member(chat_id, context.bot.id)
|
| 92 |
-
ok = (me.status == "administrator"
|
| 93 |
-
and bool(getattr(me, "can_delete_messages", False))
|
| 94 |
-
and bool(getattr(me, "can_restrict_members", False)))
|
| 95 |
except Exception as e:
|
| 96 |
-
# Treat an unknown answer as "no rights": better to judge nothing than
|
| 97 |
-
# to burn calls in a chat we were never authorised in.
|
| 98 |
logger.warning("own-rights lookup failed chat=" + str(chat_id) + ": " + str(e))
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
note_rights(chat_id, ok)
|
| 101 |
return ok
|
| 102 |
|
|
@@ -133,6 +175,20 @@ def schedule(context, chat_id, title=""):
|
|
| 133 |
return True
|
| 134 |
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
TEXTS = {
|
| 137 |
60: "I don't have admin rights yet, so I can't delete ads or ban anyone.\n"
|
| 138 |
"Tap the group name -> Administrators -> Add Admin -> pick me -> "
|
|
@@ -141,32 +197,81 @@ TEXTS = {
|
|
| 141 |
180: "Third reminder: still not authorised.",
|
| 142 |
300: "⚠️ Without rights I will leave this group in 5 minutes.",
|
| 143 |
}
|
|
|
|
|
|
|
|
|
|
| 144 |
GOODBYE = ("No admin rights after 10 minutes, so I'm leaving.\n"
|
| 145 |
"Without Delete Messages and Ban Users I can't do anything here, and "
|
| 146 |
"staying would just waste resources.\n\n"
|
| 147 |
"Grant the rights first, then invite me again whenever you like.")
|
| 148 |
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
async def _nag(context):
|
| 151 |
d = context.job.data
|
| 152 |
chat_id, title, at = d["chat_id"], d.get("title", ""), d["at"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
if
|
|
|
|
| 155 |
cancel(context, chat_id)
|
| 156 |
logger.info("rights granted, stopping nags for chat=" + str(chat_id))
|
| 157 |
return
|
| 158 |
|
|
|
|
|
|
|
| 159 |
if at < GIVE_UP_AFTER:
|
|
|
|
| 160 |
try:
|
| 161 |
-
await context.bot.send_message(chat_id,
|
| 162 |
except Exception as e:
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
return
|
| 168 |
|
| 169 |
-
# Final slot: leave and blocklist.
|
| 170 |
try:
|
| 171 |
await context.bot.send_message(chat_id, GOODBYE)
|
| 172 |
except Exception:
|
|
@@ -175,11 +280,15 @@ async def _nag(context):
|
|
| 175 |
await _leave(context, chat_id, title, "no_admin_rights")
|
| 176 |
|
| 177 |
|
| 178 |
-
async def _leave(context, chat_id, title, reason):
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
try:
|
| 184 |
await context.bot.leave_chat(chat_id)
|
| 185 |
logger.info("left unauthorised chat=" + str(chat_id) + " reason=" + reason)
|
|
|
|
| 13 |
3. Still nothing at 10 minutes: explain, leave, and blocklist the chat, so a
|
| 14 |
re-invite is refused instantly instead of restarting the whole cycle
|
| 15 |
|
| 16 |
+
"Couldn't find out" is not "no rights" — that is the central rule here. A
|
| 17 |
+
getChatMember timeout, a Telegram 5xx or a flood-wait all raise, and treating
|
| 18 |
+
every raise as a negative means one network blip can make the bot leave a fully
|
| 19 |
+
authorised group and blocklist it, irreversibly. So probe_rights is tri-state:
|
| 20 |
+
True / False / None, and only a confirmed False may trigger a leave.
|
| 21 |
+
|
| 22 |
+
Blocklist entries expire after BLOCK_DAYS. An attacker has to redo the whole
|
| 23 |
+
setup every week for a payoff of five messages, while an honest mistake heals
|
| 24 |
+
itself without anyone editing the database by hand. A super-admin can also clear
|
| 25 |
+
one instantly with /groups unblock <chat_id>.
|
| 26 |
"""
|
| 27 |
|
| 28 |
import logging
|
| 29 |
import time
|
| 30 |
|
| 31 |
+
from telegram.error import BadRequest, Forbidden
|
| 32 |
+
|
| 33 |
from modules.db import shared_db
|
| 34 |
|
| 35 |
logger = logging.getLogger(__name__)
|
|
|
|
| 38 |
REMIND_AT = (60, 120, 180, 300, 600)
|
| 39 |
GIVE_UP_AFTER = REMIND_AT[-1]
|
| 40 |
|
| 41 |
+
# When the rights lookup itself fails: how long to wait, how many times to retry.
|
| 42 |
+
# No leaving happens while retrying — an unknown answer is not evidence.
|
| 43 |
+
RETRY_AFTER = 60
|
| 44 |
+
MAX_RETRIES = 3
|
| 45 |
+
|
| 46 |
+
# How long a blocklist entry stays in force.
|
| 47 |
+
BLOCK_DAYS = 7
|
| 48 |
+
|
| 49 |
+
# Do we hold enforcement rights in this chat: chat_id -> (has_rights, checked_at, ttl)
|
| 50 |
# Calling getChatMember per message is expensive, and rights changes arrive via
|
| 51 |
# my_chat_member anyway; the cache only covers the case where that event is
|
| 52 |
# missed, so the TTL can be generous.
|
| 53 |
+
# A False derived from a failed lookup is cached only briefly (_UNKNOWN_TTL) —
|
| 54 |
+
# otherwise one blip silences the whole group for five minutes, during which every
|
| 55 |
+
# message skips judging and nothing ever arrives to clear the cache.
|
| 56 |
_RIGHTS_TTL = 300
|
| 57 |
+
_UNKNOWN_TTL = 20
|
| 58 |
_rights_cache = {}
|
| 59 |
|
| 60 |
|
|
|
|
| 71 |
async def is_blocked(chat_id):
|
| 72 |
try:
|
| 73 |
async with shared_db() as db:
|
| 74 |
+
cur = await db.execute(
|
| 75 |
+
"SELECT 1 FROM group_blocklist WHERE chat_id=? "
|
| 76 |
+
"AND blocked_at > datetime('now', ?)",
|
| 77 |
+
(chat_id, "-" + str(BLOCK_DAYS) + " days")
|
| 78 |
+
)
|
| 79 |
return await cur.fetchone() is not None
|
| 80 |
except Exception as e:
|
| 81 |
logger.warning("blocklist lookup failed (allowing): " + str(e))
|
|
|
|
| 103 |
_rights_cache.pop(chat_id, None)
|
| 104 |
|
| 105 |
|
| 106 |
+
def note_rights(chat_id, has_rights, ttl=_RIGHTS_TTL):
|
| 107 |
+
_rights_cache[chat_id] = (bool(has_rights), time.time(), ttl)
|
| 108 |
|
| 109 |
|
| 110 |
+
async def probe_rights(context, chat_id):
|
| 111 |
+
"""Tri-state: True (have them) / False (confirmed not) / None (couldn't tell).
|
| 112 |
+
|
| 113 |
+
None must never collapse into False. Anything irreversible — leaving,
|
| 114 |
+
blocklisting — may only act on a confirmed False. Writes no cache; the caller
|
| 115 |
+
decides how to record the answer.
|
| 116 |
+
"""
|
| 117 |
try:
|
| 118 |
me = await context.bot.get_chat_member(chat_id, context.bot.id)
|
|
|
|
|
|
|
|
|
|
| 119 |
except Exception as e:
|
|
|
|
|
|
|
| 120 |
logger.warning("own-rights lookup failed chat=" + str(chat_id) + ": " + str(e))
|
| 121 |
+
return None
|
| 122 |
+
return (me.status == "administrator"
|
| 123 |
+
and bool(getattr(me, "can_delete_messages", False))
|
| 124 |
+
and bool(getattr(me, "can_restrict_members", False)))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
async def has_rights(context, chat_id, use_cache=True):
|
| 128 |
+
"""Can we delete messages AND ban users here. Both, not either.
|
| 129 |
+
|
| 130 |
+
For the message path: an unknown answer counts as False (better to judge
|
| 131 |
+
nothing than to burn calls in a chat we were never authorised in), but it is
|
| 132 |
+
cached only briefly. Use probe_rights for anything that leads to a leave.
|
| 133 |
+
"""
|
| 134 |
+
if use_cache:
|
| 135 |
+
hit = _rights_cache.get(chat_id)
|
| 136 |
+
if hit and (time.time() - hit[1]) < hit[2]:
|
| 137 |
+
return hit[0]
|
| 138 |
+
ok = await probe_rights(context, chat_id)
|
| 139 |
+
if ok is None:
|
| 140 |
+
note_rights(chat_id, False, _UNKNOWN_TTL)
|
| 141 |
+
return False
|
| 142 |
note_rights(chat_id, ok)
|
| 143 |
return ok
|
| 144 |
|
|
|
|
| 175 |
return True
|
| 176 |
|
| 177 |
|
| 178 |
+
def _requeue(context, chat_id, title, at, tries):
|
| 179 |
+
"""Couldn't read rights for this slot — redo it in a minute, advance nothing."""
|
| 180 |
+
jq = getattr(context, "job_queue", None)
|
| 181 |
+
if not jq:
|
| 182 |
+
return False
|
| 183 |
+
jq.run_once(
|
| 184 |
+
_nag,
|
| 185 |
+
RETRY_AFTER,
|
| 186 |
+
data={"chat_id": chat_id, "title": title, "at": at, "tries": tries},
|
| 187 |
+
name=_job_name(chat_id),
|
| 188 |
+
)
|
| 189 |
+
return True
|
| 190 |
+
|
| 191 |
+
|
| 192 |
TEXTS = {
|
| 193 |
60: "I don't have admin rights yet, so I can't delete ads or ban anyone.\n"
|
| 194 |
"Tap the group name -> Administrators -> Add Admin -> pick me -> "
|
|
|
|
| 197 |
180: "Third reminder: still not authorised.",
|
| 198 |
300: "⚠️ Without rights I will leave this group in 5 minutes.",
|
| 199 |
}
|
| 200 |
+
GENERIC = ("I don't have admin rights yet (Delete Messages + Ban Users), so I "
|
| 201 |
+
"can't do anything here.\nTap the group name -> Administrators -> "
|
| 202 |
+
"Add Admin -> pick me -> enable both.")
|
| 203 |
GOODBYE = ("No admin rights after 10 minutes, so I'm leaving.\n"
|
| 204 |
"Without Delete Messages and Ban Users I can't do anything here, and "
|
| 205 |
"staying would just waste resources.\n\n"
|
| 206 |
"Grant the rights first, then invite me again whenever you like.")
|
| 207 |
|
| 208 |
|
| 209 |
+
def _is_fatal_send_error(e):
|
| 210 |
+
"""Is this "we can never speak here" or "the network hiccuped"?
|
| 211 |
+
|
| 212 |
+
Only the former may lead to a leave. Forbidden means kicked/muted/blocked and
|
| 213 |
+
is definitive; among BadRequests only the chat-is-gone family is. Everything
|
| 214 |
+
else (timeouts, 5xx, flood-wait) is treated as transient so the remaining
|
| 215 |
+
nags still get their chance.
|
| 216 |
+
"""
|
| 217 |
+
if isinstance(e, Forbidden):
|
| 218 |
+
return True
|
| 219 |
+
if isinstance(e, BadRequest):
|
| 220 |
+
t = str(e).lower()
|
| 221 |
+
return ("chat not found" in t or "chat_id is empty" in t
|
| 222 |
+
or "group chat was deactivated" in t or "chat was upgraded" in t)
|
| 223 |
+
return False
|
| 224 |
+
|
| 225 |
+
|
| 226 |
async def _nag(context):
|
| 227 |
d = context.job.data
|
| 228 |
chat_id, title, at = d["chat_id"], d.get("title", ""), d["at"]
|
| 229 |
+
tries = d.get("tries", 0)
|
| 230 |
+
|
| 231 |
+
ok = await probe_rights(context, chat_id)
|
| 232 |
+
|
| 233 |
+
if ok is None:
|
| 234 |
+
# Unknown is not a negative. Never leave on this — retry the same slot.
|
| 235 |
+
if tries < MAX_RETRIES:
|
| 236 |
+
logger.warning("rights lookup failed, retrying in " + str(RETRY_AFTER)
|
| 237 |
+
+ "s chat=" + str(chat_id) + " at=" + str(at)
|
| 238 |
+
+ " tries=" + str(tries + 1))
|
| 239 |
+
_requeue(context, chat_id, title, at, tries + 1)
|
| 240 |
+
else:
|
| 241 |
+
# Repeatedly unanswerable: either a long outage or the chat is gone.
|
| 242 |
+
# Bow out quietly — no leave, no blocklist. A rights-less chat costs
|
| 243 |
+
# nothing on the message path anyway.
|
| 244 |
+
logger.warning("rights lookup failed " + str(MAX_RETRIES)
|
| 245 |
+
+ "x, giving up on nags (not leaving) chat=" + str(chat_id))
|
| 246 |
+
cancel(context, chat_id)
|
| 247 |
+
return
|
| 248 |
|
| 249 |
+
if ok:
|
| 250 |
+
note_rights(chat_id, True)
|
| 251 |
cancel(context, chat_id)
|
| 252 |
logger.info("rights granted, stopping nags for chat=" + str(chat_id))
|
| 253 |
return
|
| 254 |
|
| 255 |
+
note_rights(chat_id, False)
|
| 256 |
+
|
| 257 |
if at < GIVE_UP_AFTER:
|
| 258 |
+
text = TEXTS.get(at, GENERIC)
|
| 259 |
try:
|
| 260 |
+
await context.bot.send_message(chat_id, text)
|
| 261 |
except Exception as e:
|
| 262 |
+
if _is_fatal_send_error(e):
|
| 263 |
+
# We genuinely cannot speak here (kicked/muted) — nagging is moot.
|
| 264 |
+
logger.warning("nag undeliverable chat=" + str(chat_id) + ": "
|
| 265 |
+
+ str(e) + ", leaving")
|
| 266 |
+
cancel(context, chat_id)
|
| 267 |
+
await _leave(context, chat_id, title, "cannot_send", blocklist=False)
|
| 268 |
+
else:
|
| 269 |
+
# Transient — do nothing, the later slots still run.
|
| 270 |
+
logger.warning("nag send failed (transient) chat=" + str(chat_id)
|
| 271 |
+
+ ": " + str(e))
|
| 272 |
return
|
| 273 |
|
| 274 |
+
# Final slot: confirmed no rights, so leave and blocklist.
|
| 275 |
try:
|
| 276 |
await context.bot.send_message(chat_id, GOODBYE)
|
| 277 |
except Exception:
|
|
|
|
| 280 |
await _leave(context, chat_id, title, "no_admin_rights")
|
| 281 |
|
| 282 |
|
| 283 |
+
async def _leave(context, chat_id, title, reason, blocklist=True):
|
| 284 |
+
"""Leave. blocklist=False is for "they kicked or muted us" — that was their
|
| 285 |
+
call, and holding it against the chat would block a re-invite they are
|
| 286 |
+
perfectly entitled to make."""
|
| 287 |
+
if blocklist:
|
| 288 |
+
try:
|
| 289 |
+
await block(chat_id, title, reason)
|
| 290 |
+
except Exception as e:
|
| 291 |
+
logger.warning("blocklist write failed chat=" + str(chat_id) + ": " + str(e))
|
| 292 |
try:
|
| 293 |
await context.bot.leave_chat(chat_id)
|
| 294 |
logger.info("left unauthorised chat=" + str(chat_id) + " reason=" + reason)
|