ilang-ai commited on
Commit
e4cf54e
·
1 Parent(s): da5659b

反spam: 同步私有姊妹版的入口完整性审计成果

Browse files

同源的私有 bot 在真实群流量上跑出了这批问题,公开版逐条同样存在。
仍是同一个模式:消息走到某条路径后,反spam 静默地根本没跑。

1. 崩溃: msg.forward_date 在 PTB 22.8 已不存在(Bot API 7.0 换成 forward_origin,
读取直接 AttributeError)。三处在读它 —— bot.py 两处判定链 + prefilter.forward_spam,
于是任何无 caption 的贴纸/文件/GIF 进群就崩,不判定不删除不记录。
而且全仓库零个错误处理器,崩了只在日志留 traceback。已全部改 forward_origin
并注册 add_error_handler。

2. 命令抢占: CommandHandler 注册在群 handler 之前且同在 group 0,PTB 每个 group
只跑第一个匹配的;而 PTB 允许命令携带任意后缀正文 —— /<任意命令> <广告> 被命令
handler 吃掉后静默 return,广告全程无人过问。群 handler 移到 group=-1 先跑,
真正处置(删/封)后 raise ApplicationHandlerStop 掐断。连带:命令消息不再算作
@提问,否则 /start@自己 会被 AI 回一遍、命令再回一遍。

3. 类型覆盖: 过滤器白名单只有 TEXT/PHOTO/VIDEO/Document/Sticker,语音、音频、
圆视频、投票、快拍等匹配不到任何 handler。改为收群里的一切、只排掉入群退群
系统消息。名片不再排除 —— 本仓库没有独立的名片 handler,排掉等于复刻同一个洞。

4. 判定链死分支 + 看不见的文本: 贴纸/无caption文件/GIF 以前只判 caption,
没 caption 就恒判为干净。现在走缩略图识图(image/* 文件直接用本体),
并新增 _poll_text / _media_meta / _hidden_text 与 judge_text ——
text_link 超链接的真实 URL 存在 entities 里不在 text 里,转发来源频道名、
发送者昵称、via_bot 同理,全都读者可见而判定层以前看不见。
三者都喂给词库、名片检测和 AI,不是只喂其中一层。

5. 处置静默失败: gather(return_exceptions=True) 把权限不足和限流变成返回值而非
异常,"我没权限"的提醒分支因此是永远进不去的死代码,而日志照打成功。
改为分别核对删除与封禁结果,全失败时提醒(每群每小时一次)并记录真实错误。

6. sender_chat 身份: 以某个 chat 的身份发言时 from 里是全局共用的假用户,
真身在 sender_chat。后果是 ban_chat_member 对频道身份永远无效、
每用户消息桶把不相关的发送者混在一起。新增 actor_id 与 _ban_actor(),
外部频道走 ban_chat_sender_chat;正确豁免匿名管理员与关联频道自动转发。

7. 判定截断: 长消息只送前一段给模型,前面塞长文、广告放末尾即可绕过。
改为掐头去尾。

8. 群内公开命令限流: bot 用 reply_text 回复会把触发消息顶到最新,
等于替刷屏者反复顶他自己的广告。非管理员每群 60 秒一次,管理员与私聊不限。

9. 加进频道不再假装启用: 过滤器不含 CHANNEL、也没订阅 channel_post,
结构上永远看不到任何帖子,以前却照样走完 ToS 回一个绿勾。改为说明并退出。

10. 词库: 补伪造货币品类、汉字形近字归一(叚→假 幣→币)、词中分隔符剥离(叚*币)、
以及规避加成 —— 会做规避写法本身就是意图证据。冥币(祭祀用品)不收,
练功券只给 4 分(银行点钞券是合法商品)。

11. /start@别的bot 改为首次即删: 它归在探针层但不该走累计阈值 ——
实测是两个一次性小号各发一次,阈值 2 会让它们一个都逃掉。签到水消息保持
首次免罚(真人可能无意发一次),宣传别的 bot 不会是无意的。

验证: py_compile 全过; PTB 22.8 真实 Update 对象分发 20/20;
针对本仓库实际代码的端到端 25/25; 词库回归 15/15 且旧样本零漂移;
本次交叉核对 21/21。

.env.example CHANGED
@@ -35,3 +35,9 @@ LEXICON_HARD_THRESHOLD=6
35
  PROBE_FLAG_DELETE=2
36
  # Rolling window for those flags (hours); older flags reset the count.
37
  PROBE_WINDOW_HOURS=24
 
 
 
 
 
 
 
35
  PROBE_FLAG_DELETE=2
36
  # Rolling window for those flags (hours); older flags reset the count.
37
  PROBE_WINDOW_HOURS=24
38
+ # How much of a long message the judge sees (clipped head + tail, not head only).
39
+ JUDGE_TEXT_LIMIT=1800
40
+ JUDGE_CAPTION_LIMIT=900
41
+ # Cooldown (seconds) on public group commands for non-admins, so the bot cannot
42
+ # be used as a megaphone to bump someone's message. Admins are never limited.
43
+ GROUP_CMD_COOLDOWN=60
README.md CHANGED
@@ -116,6 +116,9 @@ Everything is set via environment variables — see [`.env.example`](.env.exampl
116
  | `LEXICON_HARD_THRESHOLD` | `6` | Slang pre-filter strictness (higher = stricter) |
117
  | `PROBE_FLAG_DELETE` | `2` | Check-in filler flags before it starts deleting (never bans) |
118
  | `PROBE_WINDOW_HOURS` | `24` | Rolling window for those flags |
 
 
 
119
 
120
  ---
121
 
 
116
  | `LEXICON_HARD_THRESHOLD` | `6` | Slang pre-filter strictness (higher = stricter) |
117
  | `PROBE_FLAG_DELETE` | `2` | Check-in filler flags before it starts deleting (never bans) |
118
  | `PROBE_WINDOW_HOURS` | `24` | Rolling window for those flags |
119
+ | `JUDGE_TEXT_LIMIT` | `1800` | Chars of a long message the judge sees (head + tail) |
120
+ | `JUDGE_CAPTION_LIMIT` | `900` | Same, for image captions |
121
+ | `GROUP_CMD_COOLDOWN` | `60` | Cooldown (s) on public group commands for non-admins |
122
 
123
  ---
124
 
README_AR.md CHANGED
@@ -100,6 +100,9 @@ python bot.py
100
  | `LEXICON_HARD_THRESHOLD` | `6` | صرامة المرشّح الأوّلي للعامية (الأعلى = أكثر صرامة) |
101
  | `PROBE_FLAG_DELETE` | `2` | عدد علامات رسائل «الحضور» قبل بدء الحذف (لا يحظر أبدًا) |
102
  | `PROBE_WINDOW_HOURS` | `24` | النافذة المتحركة لتلك العلامات (بالساعات) |
 
 
 
103
 
104
  ---
105
 
 
100
  | `LEXICON_HARD_THRESHOLD` | `6` | صرامة المرشّح الأوّلي للعامية (الأعلى = أكثر صرامة) |
101
  | `PROBE_FLAG_DELETE` | `2` | عدد علامات رسائل «الحضور» قبل بدء الحذف (لا يحظر أبدًا) |
102
  | `PROBE_WINDOW_HOURS` | `24` | النافذة المتحركة لتلك العلامات (بالساعات) |
103
+ | `JUDGE_TEXT_LIMIT` | `1800` | عدد أحرف الرسالة الطويلة التي يراها التحليل (البداية + النهاية) |
104
+ | `JUDGE_CAPTION_LIMIT` | `900` | المثل نفسه لتعليقات الصور |
105
+ | `GROUP_CMD_COOLDOWN` | `60` | مهلة (ثانية) لأوامر المجموعة العامة لغير المشرفين |
106
 
107
  ---
108
 
README_CN.md CHANGED
@@ -100,6 +100,9 @@ python bot.py
100
  | `LEXICON_HARD_THRESHOLD` | `6` | 黑话预过滤严格度(越高越严) |
101
  | `PROBE_FLAG_DELETE` | `2` | 签到水消息累计多少次后开始静默删除(绝不封号) |
102
  | `PROBE_WINDOW_HOURS` | `24` | 上述标记的滚动有效窗口(小时) |
 
 
 
103
 
104
  ---
105
 
 
100
  | `LEXICON_HARD_THRESHOLD` | `6` | 黑话预过滤严格度(越高越严) |
101
  | `PROBE_FLAG_DELETE` | `2` | 签到水消息累计多少次后开始静默删除(绝不封号) |
102
  | `PROBE_WINDOW_HOURS` | `24` | 上述标记的滚动有效窗口(小时) |
103
+ | `JUDGE_TEXT_LIMIT` | `1800` | 长消息送judge的字数(掐头去尾各一半) |
104
+ | `JUDGE_CAPTION_LIMIT` | `900` | 同上,图片附带文字 |
105
+ | `GROUP_CMD_COOLDOWN` | `60` | 群内公开命令对非管理员的冷却(秒) |
106
 
107
  ---
108
 
README_ES.md CHANGED
@@ -100,6 +100,9 @@ Todo se configura mediante variables de entorno — consulta [`.env.example`](.e
100
  | `LEXICON_HARD_THRESHOLD` | `6` | Rigor del prefiltro de jerga (mayor = más estricto) |
101
  | `PROBE_FLAG_DELETE` | `2` | Marcas de relleno tipo «presente» antes de borrar (nunca banea) |
102
  | `PROBE_WINDOW_HOURS` | `24` | Ventana móvil para esas marcas (horas) |
 
 
 
103
 
104
  ---
105
 
 
100
  | `LEXICON_HARD_THRESHOLD` | `6` | Rigor del prefiltro de jerga (mayor = más estricto) |
101
  | `PROBE_FLAG_DELETE` | `2` | Marcas de relleno tipo «presente» antes de borrar (nunca banea) |
102
  | `PROBE_WINDOW_HOURS` | `24` | Ventana móvil para esas marcas (horas) |
103
+ | `JUDGE_TEXT_LIMIT` | `1800` | Caracteres de un mensaje largo que ve el análisis (inicio + final) |
104
+ | `JUDGE_CAPTION_LIMIT` | `900` | Lo mismo, para los pies de foto |
105
+ | `GROUP_CMD_COOLDOWN` | `60` | Espera (s) en comandos públicos de grupo para no administradores |
106
 
107
  ---
108
 
README_FA.md CHANGED
@@ -100,6 +100,9 @@ python bot.py
100
  | `LEXICON_HARD_THRESHOLD` | `6` | سخت‌گیری پیش‌فیلتر زبان کوچه‌بازاری (بالاتر = سخت‌گیرانه‌تر) |
101
  | `PROBE_FLAG_DELETE` | `2` | تعداد نشانه‌های پیام «حضور» پیش از حذف خودکار (هرگز مسدود نمی‌کند) |
102
  | `PROBE_WINDOW_HOURS` | `24` | بازهٔ چرخشی برای این نشانه‌ها (ساعت) |
 
 
 
103
 
104
  ---
105
 
 
100
  | `LEXICON_HARD_THRESHOLD` | `6` | سخت‌گیری پیش‌فیلتر زبان کوچه‌بازاری (بالاتر = سخت‌گیرانه‌تر) |
101
  | `PROBE_FLAG_DELETE` | `2` | تعداد نشانه‌های پیام «حضور» پیش از حذف خودکار (هرگز مسدود نمی‌کند) |
102
  | `PROBE_WINDOW_HOURS` | `24` | بازهٔ چرخشی برای این نشانه‌ها (ساعت) |
103
+ | `JUDGE_TEXT_LIMIT` | `1800` | تعداد نویسه‌های پیام بلند که تحلیل می‌بیند (ابتدا + انتها) |
104
+ | `JUDGE_CAPTION_LIMIT` | `900` | همان مورد برای زیرنویس تصاویر |
105
+ | `GROUP_CMD_COOLDOWN` | `60` | مهلت (ثانیه) برای فرمان‌های عمومی گروه برای غیرمدیران |
106
 
107
  ---
108
 
README_RU.md CHANGED
@@ -100,6 +100,9 @@ python bot.py
100
  | `LEXICON_HARD_THRESHOLD` | `6` | Строгость предфильтра сленга (выше = строже) |
101
  | `PROBE_FLAG_DELETE` | `2` | Сколько меток «отметился» до начала удаления (никогда не банит) |
102
  | `PROBE_WINDOW_HOURS` | `24` | Скользящее окно для этих меток (часы) |
 
 
 
103
 
104
  ---
105
 
 
100
  | `LEXICON_HARD_THRESHOLD` | `6` | Строгость предфильтра сленга (выше = строже) |
101
  | `PROBE_FLAG_DELETE` | `2` | Сколько меток «отметился» до начала удаления (никогда не банит) |
102
  | `PROBE_WINDOW_HOURS` | `24` | Скользящее окно для этих меток (часы) |
103
+ | `JUDGE_TEXT_LIMIT` | `1800` | Сколько символов длинного сообщения видит анализатор (начало + конец) |
104
+ | `JUDGE_CAPTION_LIMIT` | `900` | То же для подписей к изображениям |
105
+ | `GROUP_CMD_COOLDOWN` | `60` | Задержка (с) публичных групповых команд для не-админов |
106
 
107
  ---
108
 
bot.py CHANGED
@@ -12,7 +12,8 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
12
  from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
13
  from telegram.ext import (
14
  Application, CommandHandler, MessageHandler,
15
- CallbackQueryHandler, ChatMemberHandler, filters, ContextTypes
 
16
  )
17
  import config
18
  from modules.db import db_exec
@@ -85,6 +86,30 @@ async def _handle_ai_result(intent, reply, msg, user_id, context):
85
 
86
  # ==================== Commands ====================
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
89
  if not config.ADMIN_USER_ID:
90
  config.ADMIN_USER_ID = update.effective_user.id
@@ -100,6 +125,10 @@ async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
100
  else:
101
  chat_id = update.effective_chat.id
102
  await register_group(chat_id, update.effective_chat.title)
 
 
 
 
103
  if not await check_tos(chat_id):
104
  keyboard = InlineKeyboardMarkup([
105
  [InlineKeyboardButton("Accept & Enable", callback_data="tos_accept_" + str(chat_id))],
@@ -118,6 +147,8 @@ async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
118
  "Anything else → Just chat"
119
  )
120
  else:
 
 
121
  await update.message.reply_text(
122
  "I work automatically in groups. No config needed.\n\nAdmin commands:\n/ban — Reply to a message to ban the user"
123
  )
@@ -138,6 +169,125 @@ async def cmd_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
138
 
139
  # ==================== Group ====================
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  async def _answer_mention(msg, context, is_mention, text):
142
  """Reply to someone who @mentioned the bot or replied to it.
143
 
@@ -196,6 +346,12 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
196
  if not user:
197
  return
198
  text = msg.text or msg.caption or ""
 
 
 
 
 
 
199
 
200
  await register_group(chat_id, msg.chat.title)
201
 
@@ -206,9 +362,17 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
206
  is_mention = text and context.bot.username and ("@" + context.bot.username) in text
207
  is_reply_to_bot = msg.reply_to_message and msg.reply_to_message.from_user and msg.reply_to_message.from_user.id == context.bot.id
208
  has_media = bool(msg.photo or msg.video or msg.document)
 
 
 
 
 
 
 
209
  # An edited message is re-judged for spam but never re-answered, otherwise
210
  # the bot replies again every time the user tweaks their message.
211
- wants_reply = bool((text or has_media) and (is_mention or is_reply_to_bot) and not is_edited)
 
212
 
213
  # ToS not accepted: guidance only. Without admin consent we take no action.
214
  if not tos_ok:
@@ -217,20 +381,41 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
217
  await msg.reply_text("I haven't been enabled yet. Ask an admin to tap the Accept & Enable button above.")
218
  except Exception as e:
219
  logger.warning("group @mention reply failed: chat=" + str(chat_id) + " err=" + str(e))
 
 
 
220
  return
221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  # Admin check
223
- is_admin_user = False
224
- try:
225
- member = await context.bot.get_chat_member(chat_id, user.id)
226
- if member.status in ("administrator", "creator"):
227
- is_admin_user = True
228
- except Exception:
229
- pass
 
230
 
231
  # Track recent messages: (msg_id, content_hash, timestamp)
232
  user_msgs = context.chat_data.setdefault("user_recent_msgs", {})
233
- uid = user.id
234
  if uid not in user_msgs:
235
  user_msgs[uid] = []
236
  content_hash = _hashlib.md5(text.encode()).hexdigest() if text else ""
@@ -251,11 +436,17 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
251
 
252
  # Probe ("check-in") filler: mark only, never ban. Runs before the duplicate
253
  # check so repeated check-ins can't escalate into a ban.
 
254
  try:
255
- if await probe.check(msg, chat_id, uid, context.bot.username):
256
- return
257
  except Exception as e:
258
  logger.warning("probe check failed: " + str(e))
 
 
 
 
 
 
259
 
260
  # @mention / reply-to-bot now goes through anti-spam as well. Asking the bot
261
  # a question is not an offence though — without this hint the judge reads a
@@ -279,9 +470,12 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
279
  spam = True
280
  logger.info("REPEAT SPAM: user=" + str(uid) + " chat=" + str(chat_id) + " count=" + str(len(recent_same)))
281
 
282
- # Pre-filter: keyword/regex/forward/new-account (zero API cost)
 
 
 
283
  if not spam:
284
- verdict = prefilter(msg, user, text)
285
  if verdict == "spam":
286
  spam = True
287
  elif verdict == "ai":
@@ -290,30 +484,77 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
290
  try:
291
  f = await context.bot.get_file(msg.photo[-1].file_id)
292
  data = bytes(await f.download_as_bytearray())
293
- spam = await ai_judge_group_image(data, text, sender_context=sender_ctx)
294
  except Exception:
295
- if text:
296
- spam = await ai_judge_group_message(text, sender_context=sender_ctx)
297
  elif msg.video:
298
  if msg.video.thumbnail:
299
  try:
300
  vf = await context.bot.get_file(msg.video.thumbnail.file_id)
301
  vdata = bytes(await vf.download_as_bytearray())
302
- spam = await ai_judge_group_image(vdata, text, sender_context=sender_ctx)
303
  except Exception:
304
- if text:
305
- spam = await ai_judge_group_message(text, sender_context=sender_ctx)
306
- elif text:
307
- spam = await ai_judge_group_message(text, sender_context=sender_ctx)
308
- elif msg.forward_date:
309
- spam = True
310
- elif msg.document or msg.sticker:
311
- if text:
312
- spam = await ai_judge_group_message(text, sender_context=sender_ctx)
313
- elif msg.forward_date:
314
  spam = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  elif text:
316
- spam = await ai_judge_group_message(text, sender_context=sender_ctx)
 
 
 
 
 
 
317
  # verdict == "clean" → skip AI, let it through
318
 
319
  if spam:
@@ -322,23 +563,36 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
322
  for entry in user_msgs.get(uid, []):
323
  mid = entry[0] if isinstance(entry, tuple) else entry
324
  tasks.append(context.bot.delete_message(chat_id, mid))
325
- tasks.append(context.bot.ban_chat_member(chat_id, uid))
 
326
  results = await asyncio.gather(*tasks, return_exceptions=True)
 
 
 
 
 
 
 
 
 
327
  user_msgs.pop(uid, None)
328
- logger.info("SPAM nuked: user=" + str(uid) + " chat=" + str(chat_id) + " tasks=" + str(len(tasks)))
 
 
 
 
 
 
 
 
 
329
  except Exception as e:
330
  logger.warning("Anti-spam action failed: " + str(e))
331
- last_remind = context.bot_data.get("perm_remind_" + str(chat_id), 0)
332
- if _time.time() - last_remind > 3600:
333
- context.bot_data["perm_remind_" + str(chat_id)] = _time.time()
334
- try:
335
- await msg.reply_text(
336
- "\u26a0\ufe0f Detected spam but I don't have permissions to act.\n\n"
337
- "Tap group name → Admins → Add Admin → Find me → Enable Delete Messages and Ban Users → Done"
338
- )
339
- except Exception:
340
- pass
341
- return
342
 
343
  # Clean message (spam was handled and returned above). Only now do we answer
344
  # someone who was talking to the bot.
@@ -406,6 +660,27 @@ async def handle_my_chat_member(update: Update, context: ContextTypes.DEFAULT_TY
406
  new = result.new_chat_member.status if result.new_chat_member else "left"
407
 
408
  if old in ("left", "kicked") and new in ("member", "administrator"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
  await delete_tos(chat_id)
410
  await register_group(chat_id, result.chat.title)
411
  keyboard = InlineKeyboardMarkup([
@@ -497,6 +772,13 @@ def main():
497
 
498
  app = Application.builder().token(config.BOT_TOKEN).connect_timeout(30).read_timeout(30).write_timeout(30).pool_timeout(30).build()
499
 
 
 
 
 
 
 
 
500
  # UpdateType.MESSAGE everywhere below: once edited_message is subscribed to,
501
  # every handler sees edit events too. Only the group handler wants them —
502
  # anywhere else an edit would run the command or the answer a second time.
@@ -513,11 +795,28 @@ def main():
513
  # ("/start@OtherBot buy followers cheap") is refused by our own CommandHandlers —
514
  # PTB checks the @username against this bot and returns None on a mismatch — so
515
  # excluding commands here left those messages handled by nothing at all.
516
- # The CommandHandlers above are registered first, so our own commands still win.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  app.add_handler(MessageHandler(
518
- (filters.TEXT | filters.PHOTO | filters.VIDEO | filters.Document.ALL | filters.Sticker.ALL) & filters.ChatType.GROUPS,
519
  handle_group_message
520
- ))
521
 
522
  # Private
523
  app.add_handler(MessageHandler(filters.TEXT & filters.ChatType.PRIVATE & ~filters.COMMAND & filters.UpdateType.MESSAGE, handle_private_text))
 
12
  from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
13
  from telegram.ext import (
14
  Application, CommandHandler, MessageHandler,
15
+ CallbackQueryHandler, ChatMemberHandler, filters, ContextTypes,
16
+ ApplicationHandlerStop
17
  )
18
  import config
19
  from modules.db import db_exec
 
86
 
87
  # ==================== Commands ====================
88
 
89
+ async def _group_cmd_allowed(update, context):
90
+ """Rate-limit publicly callable commands inside a group.
91
+
92
+ The bot answers with reply_text, which bumps the triggering message back to
93
+ the top of the chat — so anyone can spam /help and have the bot repeatedly
94
+ bump their own ad for them, and a loop of /start makes it reprint the whole
95
+ ToS block. One call per chat per GROUP_CMD_COOLDOWN seconds for non-admins;
96
+ admins and private chats are never limited.
97
+ """
98
+ if update.effective_chat.type == "private":
99
+ return True
100
+ try:
101
+ if await is_admin(update, context):
102
+ return True
103
+ except Exception:
104
+ pass
105
+ key = "cmd_cd_" + str(update.effective_chat.id)
106
+ last = context.bot_data.get(key, 0)
107
+ if _time.time() - last < getattr(config, "GROUP_CMD_COOLDOWN", 60):
108
+ return False
109
+ context.bot_data[key] = _time.time()
110
+ return True
111
+
112
+
113
  async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
114
  if not config.ADMIN_USER_ID:
115
  config.ADMIN_USER_ID = update.effective_user.id
 
125
  else:
126
  chat_id = update.effective_chat.id
127
  await register_group(chat_id, update.effective_chat.title)
128
+ # Rate-limited: the ToS text is a large block, and without this anyone
129
+ # can loop /start to make the bot flood the group with it.
130
+ if not await _group_cmd_allowed(update, context):
131
+ return
132
  if not await check_tos(chat_id):
133
  keyboard = InlineKeyboardMarkup([
134
  [InlineKeyboardButton("Accept & Enable", callback_data="tos_accept_" + str(chat_id))],
 
147
  "Anything else → Just chat"
148
  )
149
  else:
150
+ if not await _group_cmd_allowed(update, context):
151
+ return
152
  await update.message.reply_text(
153
  "I work automatically in groups. No config needed.\n\nAdmin commands:\n/ban — Reply to a message to ban the user"
154
  )
 
169
 
170
  # ==================== Group ====================
171
 
172
+ async def _ban_actor(context, chat_id, sender_chat, user_id):
173
+ """Ban whoever is actually responsible for the message.
174
+
175
+ A message posted under a chat's identity carries a globally shared stand-in
176
+ user in `from` (Channel_Bot / GroupAnonymousBot); ban_chat_member on that id
177
+ is a permanent no-op, so a spammer wearing a channel identity could post
178
+ forever. The real identity is in sender_chat and needs ban_chat_sender_chat.
179
+ """
180
+ if sender_chat is not None and sender_chat.id != chat_id:
181
+ return await context.bot.ban_chat_sender_chat(chat_id, sender_chat.id)
182
+ return await context.bot.ban_chat_member(chat_id, user_id)
183
+
184
+
185
+ async def _remind_no_permission(msg, context, chat_id):
186
+ """Tell admins we found spam but cannot act on it. Once per chat per hour."""
187
+ last = context.bot_data.get("perm_remind_" + str(chat_id), 0)
188
+ if _time.time() - last <= 3600:
189
+ return
190
+ context.bot_data["perm_remind_" + str(chat_id)] = _time.time()
191
+ try:
192
+ await msg.reply_text(
193
+ "⚠️ Detected spam but I don't have permissions to act.\n\n"
194
+ "Tap group name → Admins → Add Admin → Find me → Enable Delete Messages and Ban Users → Done"
195
+ )
196
+ except Exception:
197
+ pass
198
+
199
+
200
+ def _poll_text(msg):
201
+ """A poll's visible text: the question plus every option.
202
+
203
+ A poll is prime real estate — 300 characters of question and up to 12 options
204
+ of 100 characters each, all sender-controlled — and none of it appears in
205
+ msg.text, so it used to be judged by nobody.
206
+ """
207
+ p = getattr(msg, "poll", None)
208
+ if not p:
209
+ return ""
210
+ parts = [p.question or ""]
211
+ for o in (p.options or []):
212
+ parts.append(getattr(o, "text", "") or "")
213
+ return " ".join(x for x in parts if x)
214
+
215
+
216
+ def _media_meta(msg):
217
+ """Text a reader can see on a media message but that msg.text/caption lacks.
218
+
219
+ Ads live here routinely: the file name spells out a contact handle, the audio
220
+ title is used as ad space, the sticker set name points at a landing page, a
221
+ shared contact card is a phone number and a display name and nothing else.
222
+ """
223
+ out = []
224
+ for obj, attrs in (
225
+ (getattr(msg, "document", None), ("file_name",)),
226
+ (getattr(msg, "audio", None), ("title", "performer", "file_name")),
227
+ (getattr(msg, "video", None), ("file_name",)),
228
+ (getattr(msg, "animation", None), ("file_name",)),
229
+ (getattr(msg, "sticker", None), ("emoji", "set_name")),
230
+ (getattr(msg, "venue", None), ("title", "address")),
231
+ (getattr(msg, "game", None), ("title", "description")),
232
+ (getattr(msg, "invoice", None), ("title", "description")),
233
+ # No dedicated contact handler exists, so contact cards come through the
234
+ # normal pipeline and this is the only text they carry.
235
+ (getattr(msg, "contact", None), ("first_name", "last_name", "phone_number")),
236
+ ):
237
+ if obj is None:
238
+ continue
239
+ for a in attrs:
240
+ v = getattr(obj, a, None)
241
+ if v:
242
+ out.append(str(v))
243
+ return " ".join(out)
244
+
245
+
246
+ def _hidden_text(msg, user):
247
+ """Attack-surface text that readers can see or tap but msg.text does not hold.
248
+
249
+ 1. The URL behind a hyperlink: a text_link entity keeps its url in entities,
250
+ never in msg.text. "[hello everyone](spam-link)" reached the judge as two
251
+ harmless words.
252
+ 2. The forward origin's title: a spammer's own channel name IS the ad, and it
253
+ is rendered above the message and is tappable.
254
+ 3. The sender's display name: set first_name to an ad and every innocuous
255
+ message they post is advertising on their behalf.
256
+ """
257
+ out = []
258
+ for e in list(getattr(msg, "entities", None) or []) + list(getattr(msg, "caption_entities", None) or []):
259
+ u = getattr(e, "url", None)
260
+ if u:
261
+ out.append(u)
262
+ eu = getattr(e, "user", None) # text_mention: a user rendered as a link
263
+ if eu is not None:
264
+ for a in ("first_name", "last_name", "username"):
265
+ v = getattr(eu, a, None)
266
+ if v:
267
+ out.append(str(v))
268
+ fo = getattr(msg, "forward_origin", None)
269
+ if fo is not None:
270
+ for holder in (getattr(fo, "chat", None), getattr(fo, "sender_chat", None), getattr(fo, "sender_user", None)):
271
+ if holder is None:
272
+ continue
273
+ for a in ("title", "username", "first_name"):
274
+ v = getattr(holder, a, None)
275
+ if v:
276
+ out.append(str(v))
277
+ v = getattr(fo, "sender_user_name", None)
278
+ if v:
279
+ out.append(str(v))
280
+ vb = getattr(msg, "via_bot", None)
281
+ if vb is not None and getattr(vb, "username", None):
282
+ out.append(str(vb.username))
283
+ if user is not None:
284
+ for a in ("first_name", "last_name", "username"):
285
+ v = getattr(user, a, None)
286
+ if v:
287
+ out.append(str(v))
288
+ return " ".join(out)
289
+
290
+
291
  async def _answer_mention(msg, context, is_mention, text):
292
  """Reply to someone who @mentioned the bot or replied to it.
293
 
 
346
  if not user:
347
  return
348
  text = msg.text or msg.caption or ""
349
+ # The string the judges see = the visible body plus everything a reader can
350
+ # see or tap that is NOT in text (link targets, forward origin, display name).
351
+ # Only the judging layers get it; text itself stays untouched because it is
352
+ # still used for @mention parsing, the probe layer and logging.
353
+ _hidden = _hidden_text(msg, user)
354
+ judge_text = (text + " " + _hidden).strip() if _hidden else text
355
 
356
  await register_group(chat_id, msg.chat.title)
357
 
 
362
  is_mention = text and context.bot.username and ("@" + context.bot.username) in text
363
  is_reply_to_bot = msg.reply_to_message and msg.reply_to_message.from_user and msg.reply_to_message.from_user.id == context.bot.id
364
  has_media = bool(msg.photo or msg.video or msg.document)
365
+ # Is this message a command? This handler now runs in group=-1, ahead of the
366
+ # CommandHandlers, so command messages reach it too. They must be excluded:
367
+ # "/start@ourbot" contains "@ourbotusername", so the mention check above fires
368
+ # and the bot would answer it with AI here while cmd_start answers it again
369
+ # in group 0 — one command, two replies.
370
+ ents = getattr(msg, "entities", None) or ()
371
+ is_command = bool(ents) and ents[0].type == "bot_command" and ents[0].offset == 0
372
  # An edited message is re-judged for spam but never re-answered, otherwise
373
  # the bot replies again every time the user tweaks their message.
374
+ wants_reply = bool((text or has_media) and (is_mention or is_reply_to_bot)
375
+ and not is_edited and not is_command)
376
 
377
  # ToS not accepted: guidance only. Without admin consent we take no action.
378
  if not tos_ok:
 
381
  await msg.reply_text("I haven't been enabled yet. Ask an admin to tap the Accept & Enable button above.")
382
  except Exception as e:
383
  logger.warning("group @mention reply failed: chat=" + str(chat_id) + " err=" + str(e))
384
+ # Plain return, never ApplicationHandlerStop: the group-0 CommandHandlers
385
+ # still have to run, otherwise /start can never be used to accept the ToS
386
+ # and the bot could never be enabled at all.
387
  return
388
 
389
+ # A message posted under a chat's identity (anonymous admin, channel identity)
390
+ # gets a globally shared stand-in user in `from` — GroupAnonymousBot
391
+ # (1087968824) or Channel_Bot (136817688) — with the real identity in
392
+ # sender_chat. Never reading sender_chat had two consequences:
393
+ # 1. banning called ban_chat_member on the stand-in id, which does nothing,
394
+ # so a channel identity could post ads indefinitely
395
+ # 2. the per-user message bucket was keyed on that shared id, pooling every
396
+ # channel-identity sender together, so a cleanup deleted other people's
397
+ # messages
398
+ sender_chat = getattr(msg, "sender_chat", None)
399
+ # sender_chat == this group means an admin posting anonymously — an admin.
400
+ is_anon_admin = sender_chat is not None and sender_chat.id == chat_id
401
+ # An automatic forward from the linked channel is the owner's own content.
402
+ is_auto_forward = bool(getattr(msg, "is_automatic_forward", False))
403
+ # The party held responsible: bookkeeping, judging and banning all key on it.
404
+ actor_id = sender_chat.id if sender_chat is not None else user.id
405
+
406
  # Admin check
407
+ is_admin_user = is_anon_admin or is_auto_forward
408
+ if not is_admin_user:
409
+ try:
410
+ member = await context.bot.get_chat_member(chat_id, user.id)
411
+ if member.status in ("administrator", "creator"):
412
+ is_admin_user = True
413
+ except Exception:
414
+ pass
415
 
416
  # Track recent messages: (msg_id, content_hash, timestamp)
417
  user_msgs = context.chat_data.setdefault("user_recent_msgs", {})
418
+ uid = actor_id
419
  if uid not in user_msgs:
420
  user_msgs[uid] = []
421
  content_hash = _hashlib.md5(text.encode()).hexdigest() if text else ""
 
436
 
437
  # Probe ("check-in") filler: mark only, never ban. Runs before the duplicate
438
  # check so repeated check-ins can't escalate into a ban.
439
+ probe_result = None
440
  try:
441
+ probe_result = await probe.check(msg, chat_id, uid, context.bot.username)
 
442
  except Exception as e:
443
  logger.warning("probe check failed: " + str(e))
444
+ # ApplicationHandlerStop is raised outside the try above on purpose — it is
445
+ # an Exception subclass, so `except Exception` would swallow it.
446
+ if probe_result == probe.DELETED:
447
+ raise ApplicationHandlerStop
448
+ if probe_result:
449
+ return
450
 
451
  # @mention / reply-to-bot now goes through anti-spam as well. Asking the bot
452
  # a question is not an offence though — without this hint the judge reads a
 
470
  spam = True
471
  logger.info("REPEAT SPAM: user=" + str(uid) + " chat=" + str(chat_id) + " count=" + str(len(recent_same)))
472
 
473
+ # Pre-filter: keyword/regex/forward/new-account (zero API cost).
474
+ # judge_text, not text: the keyword, contact and lexicon layers have to see
475
+ # the hidden text too, otherwise a bare "hello everyone" hyperlinked to a spam
476
+ # URL passes every one of them.
477
  if not spam:
478
+ verdict = prefilter(msg, user, judge_text)
479
  if verdict == "spam":
480
  spam = True
481
  elif verdict == "ai":
 
484
  try:
485
  f = await context.bot.get_file(msg.photo[-1].file_id)
486
  data = bytes(await f.download_as_bytearray())
487
+ spam = await ai_judge_group_image(data, judge_text, sender_context=sender_ctx)
488
  except Exception:
489
+ if judge_text:
490
+ spam = await ai_judge_group_message(judge_text, sender_context=sender_ctx)
491
  elif msg.video:
492
  if msg.video.thumbnail:
493
  try:
494
  vf = await context.bot.get_file(msg.video.thumbnail.file_id)
495
  vdata = bytes(await vf.download_as_bytearray())
496
+ spam = await ai_judge_group_image(vdata, judge_text, sender_context=sender_ctx)
497
  except Exception:
498
+ if judge_text:
499
+ spam = await ai_judge_group_message(judge_text, sender_context=sender_ctx)
500
+ elif judge_text:
501
+ spam = await ai_judge_group_message(judge_text, sender_context=sender_ctx)
502
+ elif msg.forward_origin:
 
 
 
 
 
503
  spam = True
504
+ elif msg.document or msg.sticker or msg.animation or msg.video_note:
505
+ # This branch used to judge the caption and nothing else, falling
506
+ # back to msg.forward_date — an attribute PTB no longer has, so a
507
+ # caption-less sticker/document/GIF raised AttributeError right
508
+ # here and the message was never judged, deleted or logged.
509
+ # And these ads are usually IN the picture, not in the caption:
510
+ # the sticker image is the ad, "send as file" dodges the vision
511
+ # judge, the file name spells out a contact handle.
512
+ # Now: judge the thumbnail if there is one, otherwise at least
513
+ # judge the metadata text.
514
+ thumb = None
515
+ if msg.sticker:
516
+ # A plain .webp sticker can go to the vision judge as-is;
517
+ # animated/video stickers only via their thumbnail.
518
+ thumb = msg.sticker.thumbnail
519
+ if not thumb and not msg.sticker.is_animated and not msg.sticker.is_video:
520
+ thumb = msg.sticker
521
+ elif msg.animation:
522
+ thumb = msg.animation.thumbnail
523
+ elif msg.video_note:
524
+ thumb = msg.video_note.thumbnail
525
+ elif msg.document:
526
+ thumb = msg.document.thumbnail
527
+ if not thumb and (msg.document.mime_type or "").startswith("image/"):
528
+ thumb = msg.document # an image "sent as a file": judge it directly
529
+ # Combined, not "judge_text or metadata": judge_text is never
530
+ # empty (it always carries the sender's display name), so an
531
+ # `or` would silently discard the file name / sticker set name
532
+ # on every single message.
533
+ meta = (judge_text + " " + _media_meta(msg)).strip()
534
+ judged = False
535
+ if thumb is not None:
536
+ try:
537
+ tf = await context.bot.get_file(thumb.file_id)
538
+ tdata = bytes(await tf.download_as_bytearray())
539
+ spam = await ai_judge_group_image(tdata, meta, sender_context=sender_ctx)
540
+ judged = True
541
+ except Exception as e:
542
+ logger.warning("media thumb judge failed: " + str(e))
543
+ if not judged:
544
+ if meta:
545
+ spam = await ai_judge_group_message(meta, sender_context=sender_ctx)
546
+ elif msg.forward_origin:
547
+ spam = True
548
+ elif msg.poll:
549
+ spam = await ai_judge_group_message((_poll_text(msg) + " " + _hidden).strip(), sender_context=sender_ctx)
550
  elif text:
551
+ spam = await ai_judge_group_message(judge_text, sender_context=sender_ctx)
552
+ else:
553
+ # Everything else that carries sender-controlled text but no body:
554
+ # a shared contact card, a venue, an audio track.
555
+ meta = (_media_meta(msg) + " " + _hidden).strip()
556
+ if meta:
557
+ spam = await ai_judge_group_message(meta, sender_context=sender_ctx)
558
  # verdict == "clean" → skip AI, let it through
559
 
560
  if spam:
 
563
  for entry in user_msgs.get(uid, []):
564
  mid = entry[0] if isinstance(entry, tuple) else entry
565
  tasks.append(context.bot.delete_message(chat_id, mid))
566
+ n_del = len(tasks)
567
+ tasks.append(_ban_actor(context, chat_id, sender_chat, user.id))
568
  results = await asyncio.gather(*tasks, return_exceptions=True)
569
+ # gather(return_exceptions=True) never raises: a permission error
570
+ # (Forbidden) or a rate limit (RetryAfter) comes back as a VALUE in
571
+ # results. The old code threw the results away, so a bot without the
572
+ # rights logged "SPAM nuked" while the ad sat untouched in the group
573
+ # and the reminder branch below was unreachable dead code.
574
+ deleted_ok = sum(1 for r in results[:n_del]
575
+ if not isinstance(r, Exception) and r is not False)
576
+ ban_ok = not isinstance(results[n_del], Exception)
577
+ errs = [r for r in results if isinstance(r, Exception)]
578
  user_msgs.pop(uid, None)
579
+ if errs and (deleted_ok == 0 or not ban_ok):
580
+ logger.warning(
581
+ "SPAM action PARTIAL/FAILED: user=" + str(uid) + " chat=" + str(chat_id) +
582
+ " deleted=" + str(deleted_ok) + "/" + str(n_del) + " ban_ok=" + str(ban_ok) +
583
+ " errs=" + str([type(e).__name__ + ":" + str(e)[:60] for e in errs[:3]])
584
+ )
585
+ await _remind_no_permission(msg, context, chat_id)
586
+ else:
587
+ logger.info("SPAM nuked: user=" + str(uid) + " chat=" + str(chat_id) +
588
+ " deleted=" + str(deleted_ok) + "/" + str(n_del) + " (banned)")
589
  except Exception as e:
590
  logger.warning("Anti-spam action failed: " + str(e))
591
+ await _remind_no_permission(msg, context, chat_id)
592
+ # The message is gone: stop the chain so the group-0 CommandHandlers do
593
+ # not reply to a deleted message. A command may carry arbitrary trailing
594
+ # text, so "/help <ad text>" reaches this handler AND cmd_help.
595
+ raise ApplicationHandlerStop
 
 
 
 
 
 
596
 
597
  # Clean message (spam was handled and returned above). Only now do we answer
598
  # someone who was talking to the bot.
 
660
  new = result.new_chat_member.status if result.new_chat_member else "left"
661
 
662
  if old in ("left", "kicked") and new in ("member", "administrator"):
663
+ # Channels are not supported: the anti-spam filter is ChatType.GROUPS
664
+ # (which excludes CHANNEL) and allowed_updates does not subscribe to
665
+ # channel_post, so structurally we can never see a single post here.
666
+ # Running the whole ToS flow and answering with a green "enabled" tick
667
+ # was an empty promise — the owner would think the product works. Say so
668
+ # and leave instead.
669
+ if result.chat.type not in ("group", "supergroup"):
670
+ try:
671
+ await context.bot.send_message(
672
+ chat_id,
673
+ "I only support groups and supergroups — not channels. "
674
+ "I can't see any content here, so keeping me around wouldn't do "
675
+ "anything. Leaving now."
676
+ )
677
+ except Exception:
678
+ pass
679
+ try:
680
+ await context.bot.leave_chat(chat_id)
681
+ except Exception as e:
682
+ logger.warning("leave non-group chat failed: " + str(e))
683
+ return
684
  await delete_tos(chat_id)
685
  await register_group(chat_id, result.chat.title)
686
  keyboard = InlineKeyboardMarkup([
 
772
 
773
  app = Application.builder().token(config.BOT_TOKEN).connect_timeout(30).read_timeout(30).write_timeout(30).pool_timeout(30).build()
774
 
775
+ async def _on_error(update, context):
776
+ # There was no error handler at all, so an exception inside a handler
777
+ # left nothing but a traceback in the log: a crash halfway through the
778
+ # judging chain looked exactly like a clean message.
779
+ logger.exception("handler error: " + str(context.error))
780
+ app.add_error_handler(_on_error)
781
+
782
  # UpdateType.MESSAGE everywhere below: once edited_message is subscribed to,
783
  # every handler sees edit events too. Only the group handler wants them —
784
  # anywhere else an edit would run the command or the answer a second time.
 
795
  # ("/start@OtherBot buy followers cheap") is refused by our own CommandHandlers —
796
  # PTB checks the @username against this bot and returns None on a mismatch — so
797
  # excluding commands here left those messages handled by nothing at all.
798
+ #
799
+ # group=-1, and it has to be. PTB runs only the FIRST matching handler per
800
+ # group, and CommandHandler accepts arbitrary trailing text (everything after
801
+ # /help goes into args), so with the CommandHandlers registered first in
802
+ # group 0 a message like "/help buy followers cheap 加V abc" was swallowed by
803
+ # cmd_help and never judged at all. Running first fixes that; the handler
804
+ # raises ApplicationHandlerStop once it has actually deleted something, so
805
+ # clean messages still fall through to the group-0 command handlers.
806
+ #
807
+ # The type whitelist is gone too. TEXT|PHOTO|VIDEO|Document|Sticker meant
808
+ # audio, voice, video notes, polls, stories, venues, locations and dice
809
+ # matched no handler anywhere — an mp3 with an ad caption, or a poll whose
810
+ # question IS the ad, was visible to the whole group and checked by nobody.
811
+ # Everything in a group is now accepted, minus join/leave/pin system events.
812
+ # CONTACT is deliberately NOT excluded (unlike the private bot this was
813
+ # ported from, which has a dedicated contact handler): here nothing else
814
+ # would pick a shared contact card up, and a contact card is a display name
815
+ # plus a phone number, which is exactly what a contact-harvesting ad is.
816
  app.add_handler(MessageHandler(
817
+ filters.ChatType.GROUPS & ~filters.StatusUpdate.ALL,
818
  handle_group_message
819
+ ), group=-1)
820
 
821
  # Private
822
  app.add_handler(MessageHandler(filters.TEXT & filters.ChatType.PRIVATE & ~filters.COMMAND & filters.UpdateType.MESSAGE, handle_private_text))
config.py CHANGED
@@ -32,5 +32,17 @@ PROBE_FLAG_DELETE = int(os.environ.get("PROBE_FLAG_DELETE", "2"))
32
  # so a real person posting one such message a day is never permanently silenced.
33
  PROBE_WINDOW_HOURS = int(os.environ.get("PROBE_WINDOW_HOURS", "24"))
34
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # Admin user ID (auto-detected from first /start)
36
  ADMIN_USER_ID = None
 
32
  # so a real person posting one such message a day is never permanently silenced.
33
  PROBE_WINDOW_HOURS = int(os.environ.get("PROBE_WINDOW_HOURS", "24"))
34
 
35
+ # How much of an over-long message the spam judge sees. The text is clipped
36
+ # head + tail (never head only), so an ad appended to the end of a long paste
37
+ # still lands inside the judged range.
38
+ JUDGE_TEXT_LIMIT = int(os.environ.get("JUDGE_TEXT_LIMIT", "1800"))
39
+ JUDGE_CAPTION_LIMIT = int(os.environ.get("JUDGE_CAPTION_LIMIT", "900"))
40
+
41
+ # Public group commands reply with reply_text, which bumps the triggering
42
+ # message to the top of the chat. Without a cooldown anyone can spam a command
43
+ # and have the bot repeatedly bump their own ad. Seconds, per chat, non-admins
44
+ # only — admins and private chats are never limited.
45
+ GROUP_CMD_COOLDOWN = int(os.environ.get("GROUP_CMD_COOLDOWN", "60"))
46
+
47
  # Admin user ID (auto-detected from first /start)
48
  ADMIN_USER_ID = None
modules/chat.py CHANGED
@@ -90,6 +90,22 @@ def _deflect():
90
  return random.choice(lines)
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  def _is_spam(raw):
94
  """Parse a spam-judge reply into True / False / None (couldn't parse it).
95
 
@@ -167,7 +183,7 @@ async def ai_judge_group_message(text, sender_context=""):
167
  prompt = ANTISPAM_TEXT_PROMPT
168
  if sender_context:
169
  prompt += "\n\nSender context: " + sender_context
170
- prompt += "\n\nMessage content: " + text[:1000]
171
  # max_tokens 32, not 8: eight tokens is enough to truncate the answer
172
  # inside a preamble ("Based on the above,"), which leaves nothing to
173
  # parse and drops the judgement down to the lexicon for no reason.
@@ -188,7 +204,7 @@ async def ai_judge_group_image(image_bytes, caption="", sender_context=""):
188
  if sender_context:
189
  prompt += "\nSender context: " + sender_context
190
  if caption:
191
- prompt += "\nCaption: " + caption[:500]
192
  raw = await ai_provider.generate_vision(prompt, image_bytes, max_tokens=32, temperature=0.0)
193
  verdict = _is_spam(raw)
194
  if verdict is None: # same as above — no silent pass
 
90
  return random.choice(lines)
91
 
92
 
93
+ def _clip(text, limit):
94
+ """Keep the head AND the tail of an over-long message, not just the head.
95
+
96
+ The old text[:1000] / caption[:500] cut the message before the judge ever saw
97
+ it, while Telegram allows 4096 characters in one message — so pasting a news
98
+ article in front and appending the payload at the end hid the payload
99
+ completely. Taking half from each end guarantees an ad tacked onto the tail
100
+ lands inside the judged range.
101
+ """
102
+ t = text or ""
103
+ if len(t) <= limit:
104
+ return t
105
+ half = limit // 2
106
+ return t[:half] + "\n…(middle omitted)…\n" + t[-half:]
107
+
108
+
109
  def _is_spam(raw):
110
  """Parse a spam-judge reply into True / False / None (couldn't parse it).
111
 
 
183
  prompt = ANTISPAM_TEXT_PROMPT
184
  if sender_context:
185
  prompt += "\n\nSender context: " + sender_context
186
+ prompt += "\n\nMessage content: " + _clip(text, getattr(config, "JUDGE_TEXT_LIMIT", 1800))
187
  # max_tokens 32, not 8: eight tokens is enough to truncate the answer
188
  # inside a preamble ("Based on the above,"), which leaves nothing to
189
  # parse and drops the judgement down to the lexicon for no reason.
 
204
  if sender_context:
205
  prompt += "\nSender context: " + sender_context
206
  if caption:
207
+ prompt += "\nCaption: " + _clip(caption, getattr(config, "JUDGE_CAPTION_LIMIT", 900))
208
  raw = await ai_provider.generate_vision(prompt, image_bytes, max_tokens=32, temperature=0.0)
209
  verdict = _is_spam(raw)
210
  if verdict is None: # same as above — no silent pass
modules/lexicon.py CHANGED
@@ -1,54 +1,118 @@
1
  """
2
- 中文黑话/擦边词库层(功能4)。
3
 
4
- 解决通用模型判不出"收米""上车""日结"这类抖音直播式规避话术的问题。
5
- 两步:
6
- 1. normalize() 先把文本归一化 —— 全角转半角、去零宽字符、同形字(西里尔/希腊字母伪装)还原、转小写,
7
- 破掉 spam 常用的 Unicode 花招。
8
- 2. score() 在归一化后的文本上匹配词库打分,并对"搞钱词 + 联系方式规避词"同时出现做组合加成。
9
 
10
- 用法(在 bot.py 判定前调用):
 
 
 
 
 
 
 
 
 
11
  s, terms = lexicon.score(text)
12
- if s >= config.LEXICON_HARD_THRESHOLD: # 硬命中,直接判 spam,省一次 AI 调用
13
  ...
14
- else: # 软命中,把 terms 作为线索喂给 AI
15
  ...
16
 
17
- 词库可通过 config.LEXICON_EXTRA 扩展,群主不用改代码就能加词。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  """
19
 
 
20
  import unicodedata
21
 
22
  import config
23
 
24
- # 零宽字符 / 方向控制符(spam 常插进词里破坏关键词匹配)
 
25
  _ZERO_WIDTH = dict.fromkeys(
26
  map(ord, "​‌‍‎‏‪‫‬⁠"), None
27
  )
28
 
29
- # 常见同形字:西里尔 / 希腊字母拉丁(伪装成英文字母的花招)
30
  _HOMOGLYPH = {
31
  "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "х": "x", "у": "y",
32
  "ѕ": "s", "і": "i", "ј": "j", "к": "k", "н": "h", "в": "b", "м": "m", "т": "t",
33
  "ο": "o", "ρ": "p", "α": "a", "ν": "v", "τ": "t", "ϲ": "c",
34
  }
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  def normalize(text):
 
38
  if not text:
39
  return ""
40
- t = unicodedata.normalize("NFKC", text) # 全角半角
41
- t = t.translate(_ZERO_WIDTH) # 去零宽/方向符
42
- t = "".join(_HOMOGLYPH.get(ch, ch) for ch in t) # 同形字还原
 
43
  return t.lower()
44
 
45
 
46
- # 词库:term -> (含义, 权重, 类别)
47
- # 类别 money=搞钱/招募 contact=联系方式规避 pay=支付/加密货 scam=诈骗盘
48
- # 权重越高越可疑;单个词一般不足以直接判 spam(见 LEXICON_HARD_THRESHOLD),
49
- # 靠组合 + 阈值控制误伤(例如"收米"在直播打赏语境是正常词)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  SLANG = {
51
- # ---- 搞钱 / 招募 ----
52
  "收米": ("收钱", 3, "money"),
53
  "上车": ("入局/加入项目", 2, "money"),
54
  "车头": ("项目发起人", 2, "money"),
@@ -68,7 +132,24 @@ SLANG = {
68
  "躺赚": ("虚假收益", 2, "scam"),
69
  "内部消息": ("荐股诈骗", 2, "scam"),
70
  "带你飞": ("带单诱导", 2, "money"),
71
- # ---- 联系方式规避 ----
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  "薇": ("微信", 2, "contact"),
73
  "威": ("微信", 2, "contact"),
74
  "维": ("微信", 2, "contact"),
@@ -81,12 +162,19 @@ SLANG = {
81
  "扣v": ("加QQ/微信", 2, "contact"),
82
  "纸飞机": ("Telegram", 2, "contact"),
83
  "电报": ("Telegram", 1, "contact"),
 
 
 
 
 
 
 
84
  "蝙蝠": ("BatChat 加密聊天", 2, "contact"),
85
  "皮皮虾": ("加密聊天软件", 2, "contact"),
86
  "私我": ("私聊引流", 1, "contact"),
87
  "详聊": ("私下详谈引流", 1, "contact"),
88
  "加我": ("引流加好友", 1, "contact"),
89
- # ---- 支付 / 加密货币 ----
90
  "usdt": ("USDT 加密货币支付", 2, "pay"),
91
  "泰达": ("USDT", 2, "pay"),
92
  "承兑": ("加密货币承兑洗钱", 3, "pay"),
@@ -94,12 +182,29 @@ SLANG = {
94
  "四方": ("四方支付(灰产收款)", 3, "pay"),
95
  }
96
 
 
 
 
 
 
 
97
 
98
  def score(text):
99
- """返回 (总分, 命中词列表'=含义')。文本先归一化再匹配。"""
100
- t = normalize(text)
101
- if not t:
 
 
 
 
 
102
  return 0, []
 
 
 
 
 
 
103
  table = dict(SLANG)
104
  extra = getattr(config, "LEXICON_EXTRA", None) or {}
105
  table.update(extra)
@@ -109,20 +214,30 @@ def score(text):
109
  cats = set()
110
  for term, meta in table.items():
111
  meaning, weight, cat = meta
112
- if term in t:
113
- total += weight
114
- cats.add(cat)
 
 
 
115
  matched.append(term + "=" + meaning)
116
-
117
- # 组合加成:搞钱/诈骗词 + 联系方式规避词 同时出现强烈可疑
118
- if cats & {"money", "scam", "pay"} and "contact" in cats:
 
 
 
 
 
 
119
  total += 3
120
 
121
  return total, matched
122
 
123
 
124
  def is_hard_spam(text):
125
- """归一化打分 >= 硬阈值(config.LEXICON_HARD_THRESHOLD, 默认6) → 直接判 spam。
126
- prefilter 用:黑话硬命中直接判、省一次 AI 调用,且破全角/同形字/零宽规避。"""
 
127
  s, _ = score(text)
128
  return s >= getattr(config, "LEXICON_HARD_THRESHOLD", 6)
 
1
  """
2
+ Chinese slang / evasion lexicon layer.
3
 
4
+ General-purpose models do not recognise livestream-style slang like 收米 / 上车 /
5
+ 日结, so this layer scores it with a plain word table. Three steps:
 
 
 
6
 
7
+ 1. normalize() folds the text — fullwidth to halfwidth, zero-width characters
8
+ stripped, homoglyphs restored (Cyrillic / Greek / lookalike Han characters),
9
+ traditional to simplified, lowercased.
10
+ 2. strip_separators() additionally removes in-word separators, which breaks the
11
+ "split the word up" trick (叚*币 / 假-币 / 假 币).
12
+ 3. score() matches the table on all three tracks and adds two bonuses:
13
+ - combo bonus: a money/scam term AND a contact-evasion term in one message
14
+ - evasion bonus: the term only matches AFTER normalizing / de-separating
15
+
16
+ Usage (called before the judge in bot.py):
17
  s, terms = lexicon.score(text)
18
+ if s >= config.LEXICON_HARD_THRESHOLD: # hard hit — spam, no AI call needed
19
  ...
20
+ else: # soft hit — feed terms to the AI
21
  ...
22
 
23
+ The table is extensible through config.LEXICON_EXTRA, so an operator can add
24
+ terms without touching code.
25
+
26
+ Why the evasion bonus exists
27
+ ----------------------------
28
+ **Deliberate obfuscation is itself evidence of intent.** Somebody discussing or
29
+ complaining about counterfeit money has no reason to write 假 as 叚. Making that
30
+ substitution means the sender knows the word gets blocked — which is an
31
+ admission that what they are posting is the thing that gets blocked.
32
+
33
+ So the same word carries a completely different risk depending on how it was
34
+ written:
35
+ "假币" → could be news, a complaint, a question → weight 4, under the
36
+ hard threshold, goes to the AI for context
37
+ "叚*币" → 4 + evasion bonus 3 = 7 → over the threshold, deleted at once
38
+
39
+ This does not depend on enumerating every lookalike character: swap in any rare
40
+ character or insert any separator and, as long as the folded text spells the
41
+ term, the bonus applies automatically.
42
  """
43
 
44
+ import re
45
  import unicodedata
46
 
47
  import config
48
 
49
+ # Zero-width / directional control characters (spam inserts these mid-word to
50
+ # break keyword matching).
51
  _ZERO_WIDTH = dict.fromkeys(
52
  map(ord, "​‌‍‎‏‪‫‬⁠"), None
53
  )
54
 
55
+ # Common homoglyphs: Cyrillic / GreekLatin (letters disguised as English).
56
  _HOMOGLYPH = {
57
  "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "х": "x", "у": "y",
58
  "ѕ": "s", "і": "i", "ј": "j", "к": "k", "н": "h", "в": "b", "м": "m", "т": "t",
59
  "ο": "o", "ρ": "p", "α": "a", "ν": "v", "τ": "t", "ϲ": "c",
60
  }
61
 
62
+ # Lookalike Han characters / traditional / Japanese shinjitai → simplified.
63
+ # NFKC does **nothing** for these: it handles fullwidth and compatibility forms,
64
+ # not distinct characters that merely look alike, and it does no traditional →
65
+ # simplified conversion. 叚 (U+53DA) and 假 (U+5047) are two separate characters.
66
+ _CJK_HOMOGLYPH = {
67
+ # Lookalike substitutions actually observed in spam
68
+ "叚": "假", "仮": "假", "葭": "假",
69
+ "帀": "币", "巿": "币",
70
+ # Traditional / variant → simplified (outside NFKC's remit)
71
+ "幣": "币", "鈔": "钞", "偽": "伪", "僞": "伪", "貨": "货", "錢": "钱",
72
+ "髙": "高", "證": "证", "護": "护",
73
+ "銀": "银", "帳": "账", "號": "号", "軟": "软", "體": "体",
74
+ "電": "电", "報": "报", "聯": "联", "係": "系", "繫": "系",
75
+ "點": "点", "擊": "击", "賣": "卖", "買": "买", "貸": "贷",
76
+ }
77
+
78
+ # Characters commonly pushed into the middle of a word as separators (the * in
79
+ # 叚*币). Stripping zero-width characters is not enough — these are visible
80
+ # characters and NFKC leaves them alone.
81
+ _SEPARATORS = re.compile(r"[\*\-_\.·・~||/\\\s、,,。::;;'\"“”‘’()()\[\]【】<>《》!!??##]+")
82
+
83
 
84
  def normalize(text):
85
+ """Fullwidth → halfwidth, drop zero-width, restore homoglyphs, lowercase."""
86
  if not text:
87
  return ""
88
+ t = unicodedata.normalize("NFKC", text) # fullwidthhalfwidth
89
+ t = t.translate(_ZERO_WIDTH) # drop zero-width/marks
90
+ t = "".join(_HOMOGLYPH.get(ch, ch) for ch in t) # Cyrillic/Greek → Latin
91
+ t = "".join(_CJK_HOMOGLYPH.get(ch, ch) for ch in t) # lookalike Han → simplified
92
  return t.lower()
93
 
94
 
95
+ def strip_separators(text):
96
+ """Remove in-word separators, defeating 叚*币 / 假-币 / style splitting.
97
+
98
+ This crosses legitimate punctuation boundaries ("美国币安" → "美国币安"), so
99
+ it is used **only as an auxiliary match track and every hit on it carries the
100
+ evasion bonus** — it is never a verdict on its own.
101
+ """
102
+ return _SEPARATORS.sub("", text or "")
103
+
104
+
105
+ # Table: term -> (meaning, weight, category)
106
+ # Categories: money=earning/recruiting contact=contact-detail evasion
107
+ # pay=payment/crypto scam=fraud scheme
108
+ # fake=counterfeit currency/documents (serious, and the ad format is
109
+ # "the account itself is the contact detail")
110
+ # Higher weight = more suspicious. A single term is usually not enough to call
111
+ # something spam on its own (see LEXICON_HARD_THRESHOLD) — combinations and the
112
+ # threshold keep false positives down (收米, for example, is an ordinary word in a
113
+ # livestream-tipping context).
114
  SLANG = {
115
+ # ---- Earning / recruiting ----
116
  "收米": ("收钱", 3, "money"),
117
  "上车": ("入局/加入项目", 2, "money"),
118
  "车头": ("项目发起人", 2, "money"),
 
132
  "躺赚": ("虚假收益", 2, "scam"),
133
  "内部消息": ("荐股诈骗", 2, "scam"),
134
  "带你飞": ("带单诱导", 2, "money"),
135
+ # ---- Counterfeit currency ----
136
+ # Serious offence, but the plain spelling gets weight 4 (under the hard
137
+ # threshold) so context still goes to the AI; obfuscated it picks up the
138
+ # evasion bonus and hard-hits on its own.
139
+ # Note 冥币 (joss paper, a funeral good) is deliberately NOT in this table.
140
+ "假币": ("伪造货币", 4, "fake"),
141
+ "假钞": ("伪造钞票", 4, "fake"),
142
+ "伪钞": ("伪造钞票", 4, "fake"),
143
+ "假钱": ("伪造货币", 3, "fake"),
144
+ # These are pure trade jargon — they do not turn up in ordinary conversation,
145
+ # so one occurrence is enough. Weight 6 clears the threshold by itself.
146
+ "高仿钞": ("高仿伪钞", 6, "fake"),
147
+ "仿真钞": ("仿真伪钞", 6, "fake"),
148
+ "1:1真钞": ("伪钞话术", 6, "fake"),
149
+ # 练功券 is a bank note-counting practice pad — a legal product — so it only
150
+ # gets 4 and the AI decides from context.
151
+ "练功券": ("点钞练习券(常被用作伪钞幌子)", 4, "fake"),
152
+ # ---- Contact-detail evasion ----
153
  "薇": ("微信", 2, "contact"),
154
  "威": ("微信", 2, "contact"),
155
  "维": ("微信", 2, "contact"),
 
162
  "扣v": ("加QQ/微信", 2, "contact"),
163
  "纸飞机": ("Telegram", 2, "contact"),
164
  "电报": ("Telegram", 1, "contact"),
165
+ # A bare 飞机 cannot go in — "我坐飞机去北京" would be a false positive. Only
166
+ # the multi-character forms that unambiguously mean a contact handle.
167
+ "飞机号": ("Telegram 账号", 2, "contact"),
168
+ "联系飞机": ("Telegram 联系", 2, "contact"),
169
+ "飞机搜": ("Telegram 搜索", 2, "contact"),
170
+ "tg号": ("Telegram 账号", 2, "contact"),
171
+ "电报号": ("Telegram 账号", 2, "contact"),
172
  "蝙蝠": ("BatChat 加密聊天", 2, "contact"),
173
  "皮皮虾": ("加密聊天软件", 2, "contact"),
174
  "私我": ("私聊引流", 1, "contact"),
175
  "详聊": ("私下详谈引流", 1, "contact"),
176
  "加我": ("引流加好友", 1, "contact"),
177
+ # ---- Payment / crypto ----
178
  "usdt": ("USDT 加密货币支付", 2, "pay"),
179
  "泰达": ("USDT", 2, "pay"),
180
  "承兑": ("加密货币承兑洗钱", 3, "pay"),
 
182
  "四方": ("四方支付(灰产收款)", 3, "pay"),
183
  }
184
 
185
+ # Evasion bonus: added when a term only matches after normalizing / removing
186
+ # separators. 3 is chosen so a single obfuscated fake-currency term (weight 4)
187
+ # clears the default hard threshold of 6, while the same term spelled plainly
188
+ # stays at 4 and still goes to the AI.
189
+ _EVASION_BONUS = 3
190
+
191
 
192
  def score(text):
193
+ """Return (total, ['term=meaning', ...]). Each term scores at most once.
194
+
195
+ Three match tracks:
196
+ raw the original text, lowercased only — direct hit, no bonus
197
+ norm after normalize() — needed folding = evasion
198
+ strip after normalize() + strip_separators() — same
199
+ """
200
+ if not text:
201
  return 0, []
202
+ raw = text.lower()
203
+ norm = normalize(text)
204
+ strip = strip_separators(norm)
205
+ if not norm:
206
+ return 0, []
207
+
208
  table = dict(SLANG)
209
  extra = getattr(config, "LEXICON_EXTRA", None) or {}
210
  table.update(extra)
 
214
  cats = set()
215
  for term, meta in table.items():
216
  meaning, weight, cat = meta
217
+ hit_raw = term in raw
218
+ if not (hit_raw or term in norm or term in strip):
219
+ continue
220
+ total += weight
221
+ cats.add(cat)
222
+ if hit_raw:
223
  matched.append(term + "=" + meaning)
224
+ else:
225
+ # Only matched after foldingthe sender obfuscated it on purpose,
226
+ # which is evidence of intent in itself.
227
+ total += _EVASION_BONUS
228
+ matched.append(term + "=" + meaning + " (obfuscated)")
229
+
230
+ # Combo bonus: an earning/scam/counterfeit term together with a
231
+ # contact-evasion term is strongly suspicious.
232
+ if cats & {"money", "scam", "pay", "fake"} and "contact" in cats:
233
  total += 3
234
 
235
  return total, matched
236
 
237
 
238
  def is_hard_spam(text):
239
+ """Normalized score >= the hard threshold (config.LEXICON_HARD_THRESHOLD,
240
+ default 6) → spam outright. Used by the prefilter: a hard slang hit saves an
241
+ AI call and defeats fullwidth / lookalike / zero-width / split-word evasion."""
242
  s, _ = score(text)
243
  return s >= getattr(config, "LEXICON_HARD_THRESHOLD", 6)
modules/prefilter.py CHANGED
@@ -94,7 +94,10 @@ def keyword_spam(text):
94
 
95
  def forward_spam(msg):
96
  """Forwarded message with link/contact = spam."""
97
- if not msg.forward_date:
 
 
 
98
  return False
99
  text = msg.text or msg.caption or ""
100
  if URL_PATTERN.search(text) or CONTACT_PATTERN.search(text):
@@ -121,6 +124,27 @@ def new_account_spam(user, text):
121
  return suspicious >= 2
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def should_use_ai(msg):
125
  """Decide if this message needs AI analysis or if we should skip/sample."""
126
  if not api_limiter.can_call():
@@ -166,8 +190,14 @@ def prefilter(msg, user, text):
166
  logger.info("PREFILTER new_account_spam: user=" + str(user.id))
167
  return "spam"
168
 
169
- # Layer 4: No text, no media = nothing to check
170
- if not text and not msg.photo and not msg.video:
 
 
 
 
 
 
171
  return "clean"
172
 
173
  # Layer 5: Rate limiter — can we afford an AI call?
 
94
 
95
  def forward_spam(msg):
96
  """Forwarded message with link/contact = spam."""
97
+ # forward_origin, not forward_date: Bot API 7.0 replaced the flat forward_*
98
+ # fields and PTB dropped the attribute entirely, so reading msg.forward_date
99
+ # raises AttributeError — which crashed this filter on every message.
100
+ if not getattr(msg, "forward_origin", None):
101
  return False
102
  text = msg.text or msg.caption or ""
103
  if URL_PATTERN.search(text) or CONTACT_PATTERN.search(text):
 
124
  return suspicious >= 2
125
 
126
 
127
+ def has_judgeable_media(msg):
128
+ """True when the message carries something a judge can actually look at.
129
+
130
+ Used to decide whether a caption-less message is worth an AI call. It is not
131
+ just photo/video: a sticker, a GIF, a round video and a document all have a
132
+ thumbnail the vision judge can read, and a poll, a shared contact, a venue or
133
+ an audio file all carry sender-controlled text (question and options, name
134
+ and phone number, file name, track title) that the text judge can read.
135
+
136
+ Voice notes, locations and dice are deliberately absent — there is no text
137
+ and no image on them, so an AI call would be judging the sender's display
138
+ name and nothing else.
139
+ """
140
+ return bool(
141
+ msg.photo or msg.video or msg.document or msg.sticker or
142
+ msg.animation or msg.video_note or msg.audio or
143
+ msg.poll or msg.contact or msg.venue or
144
+ getattr(msg, "game", None) or getattr(msg, "invoice", None)
145
+ )
146
+
147
+
148
  def should_use_ai(msg):
149
  """Decide if this message needs AI analysis or if we should skip/sample."""
150
  if not api_limiter.can_call():
 
190
  logger.info("PREFILTER new_account_spam: user=" + str(user.id))
191
  return "spam"
192
 
193
+ # Layer 4: nothing to check at all.
194
+ # Tested against msg, not the text argument: the caller passes a judge string
195
+ # that also carries hidden text (link targets, forward origin, display name),
196
+ # so it is practically never empty and this layer would never fire. It also
197
+ # used to list only photo/video, which meant every caption-less sticker,
198
+ # document, GIF or poll was declared clean here and the judging branches for
199
+ # them downstream could never run.
200
+ if not (msg.text or msg.caption) and not has_judgeable_media(msg):
201
  return "clean"
202
 
203
  # Layer 5: Rate limiter — can we afford an AI call?
modules/probe.py CHANGED
@@ -97,24 +97,39 @@ async def add_flag(chat_id, user_id):
97
  return row[0] if row else 0
98
 
99
 
 
 
 
 
 
 
 
 
100
  async def check(msg, chat_id, user_id, my_username=""):
101
- """Flag a probe message. Returns True if this message was one (caller stops).
102
 
103
  Judges msg.text only, never captions: a caption hit would delete the photo
104
  along with it, which is a visible accident. Admins never reach this — the
105
  caller returns for them before calling in.
106
  """
107
  if not msg.text:
108
- return False
109
- if not (looks_like_probe(msg.text) or looks_like_foreign_start(msg.text, my_username)):
110
- return False
 
111
  flags = await add_flag(chat_id, user_id)
112
  logger.info("PROBE flag: user=" + str(user_id) + " chat=" + str(chat_id) +
113
  " flags=" + str(flags) + " text=" + msg.text[:20])
114
- if flags >= getattr(config, "PROBE_FLAG_DELETE", 2):
 
 
 
 
 
115
  # Mark-only layer: delete quietly, never ban, never warn.
116
  try:
117
  await msg.delete()
 
118
  except Exception as e:
119
  logger.warning("PROBE delete failed: " + str(e))
120
- return True
 
97
  return row[0] if row else 0
98
 
99
 
100
+ # check() return values. Both are truthy, so "was this a probe?" stays a plain
101
+ # boolean test; the caller only needs to tell them apart to decide whether the
102
+ # message still exists (DELETED means the rest of the handler chain must not try
103
+ # to reply to it).
104
+ FLAGGED = "flagged"
105
+ DELETED = "deleted"
106
+
107
+
108
  async def check(msg, chat_id, user_id, my_username=""):
109
+ """Flag a probe message. Returns FLAGGED / DELETED, or None if not a probe.
110
 
111
  Judges msg.text only, never captions: a caption hit would delete the photo
112
  along with it, which is a visible accident. Admins never reach this — the
113
  caller returns for them before calling in.
114
  """
115
  if not msg.text:
116
+ return None
117
+ is_foreign_start = looks_like_foreign_start(msg.text, my_username)
118
+ if not (looks_like_probe(msg.text) or is_foreign_start):
119
+ return None
120
  flags = await add_flag(chat_id, user_id)
121
  logger.info("PROBE flag: user=" + str(user_id) + " chat=" + str(chat_id) +
122
  " flags=" + str(flags) + " text=" + msg.text[:20])
123
+ # A foreign /start goes on the first hit, not on the threshold. Check-in
124
+ # filler earns a free pass because a real member may post it once without
125
+ # meaning anything by it; announcing another bot in a group does not happen
126
+ # by accident. Observed in the wild: two throwaway accounts posting it once
127
+ # each — under a threshold of 2 neither would ever have been touched.
128
+ if is_foreign_start or flags >= getattr(config, "PROBE_FLAG_DELETE", 2):
129
  # Mark-only layer: delete quietly, never ban, never warn.
130
  try:
131
  await msg.delete()
132
+ return DELETED
133
  except Exception as e:
134
  logger.warning("PROBE delete failed: " + str(e))
135
+ return FLAGGED
prompts_demo/antispam.ilang CHANGED
@@ -23,6 +23,13 @@
23
  ::IMMUNE{UNICODE_VARIANT, DETECT}
24
  # Fullwidth chars, Cyrillic lookalikes, special spaces
25
 
 
 
 
 
 
 
 
26
  ::IMMUNE{EMOJI_STUFFING, DETECT}
27
  # Text broken up by emojis to avoid keyword filters
28
 
@@ -35,6 +42,9 @@
35
  ::IMMUNE{TRANSLITERATION, DETECT}
36
  # Pinyin, romanization, phonetic spelling to dodge filters
37
 
 
 
 
38
  # ============================================================
39
  # TEXT SPAM JUDGE
40
  # ============================================================
@@ -50,10 +60,24 @@ Step 3 — VERDICT based on these patterns:
50
  - Crypto/airdrop/token + link = crypto scam
51
  - Sexual services / hookup = sexual spam
52
  - Gambling / betting / lottery = gambling spam
 
 
53
  - Normal conversation / question / complaint / emoji / reply = OK
54
  - Key insight: spam often disguises as normal content. Product codes may be hidden contact info. "Discount" may mean stolen goods.
55
  - Key insight: normal members rarely forward product info with contact details
56
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  Reply ONLY: spam or ok. No explanation.
58
 
59
  # ============================================================
 
23
  ::IMMUNE{UNICODE_VARIANT, DETECT}
24
  # Fullwidth chars, Cyrillic lookalikes, special spaces
25
 
26
+ ::IMMUNE{CJK_LOOKALIKE, DETECT}
27
+ # Look-alike Han characters swapped in: 叚 for 假, 幣 for 币, 仮 for 假.
28
+ # The stealthiest variant — the word reads normally to a human, matches nothing.
29
+
30
+ ::IMMUNE{INWORD_SEPARATOR, DETECT}
31
+ # A separator pushed into the middle of a word: 叚*币, 假-币, 假 币
32
+
33
  ::IMMUNE{EMOJI_STUFFING, DETECT}
34
  # Text broken up by emojis to avoid keyword filters
35
 
 
42
  ::IMMUNE{TRANSLITERATION, DETECT}
43
  # Pinyin, romanization, phonetic spelling to dodge filters
44
 
45
+ ::IMMUNE{OBFUSCATION_IS_INTENT, WEIGH}
46
+ # Obfuscation is not just a filter to see through — it is evidence in itself.
47
+
48
  # ============================================================
49
  # TEXT SPAM JUDGE
50
  # ============================================================
 
60
  - Crypto/airdrop/token + link = crypto scam
61
  - Sexual services / hookup = sexual spam
62
  - Gambling / betting / lottery = gambling spam
63
+ - Contraband trade — counterfeit currency (假币 / 假钞 / 高仿钞), forged documents,
64
+ trafficked ID cards and bank cards, weapons, drugs = spam
65
  - Normal conversation / question / complaint / emoji / reply = OK
66
  - Key insight: spam often disguises as normal content. Product codes may be hidden contact info. "Discount" may mean stolen goods.
67
  - Key insight: normal members rarely forward product info with contact details
68
 
69
+ Key test — deliberate obfuscation is itself evidence of intent:
70
+ Someone discussing, complaining about, or asking for help identifying a sensitive
71
+ topic has no reason to write the word with look-alike characters or a separator
72
+ wedged into it. Doing so means the sender knows the word gets blocked — an
73
+ admission that what they are posting is the thing that gets blocked.
74
+ So the same word can go either way depending on how it was written:
75
+ "the bank seized a batch of 假币" (news, plain spelling) → ok
76
+ "叚*币" (three characters, no context) → spam. This is not a truncated ad, it
77
+ IS the complete ad — the contact detail is the poster's own profile, anyone
78
+ who sees it taps through and messages them privately. Leaving out the contact
79
+ detail is only there to dodge the filter.
80
+
81
  Reply ONLY: spam or ok. No explanation.
82
 
83
  # ============================================================