反spam: 堵住五个静默绕过 + 新增签到探针层
Browse files这五个问题都是在同源的私有 bot 上、用真实群流量测出来的,公开版同样存在
(探针那层是公开版从来就没有的功能)。都属同一类:消息走到某条路径后,
反spam 静默地根本没跑。
1. @提及/回复bot 绕过 —— 该分支回复完就 return,位置在整条反spam 之前。
spam bot 只要回复一下 bot 自己发的欢迎语就完全免检,而且 bot 还会用 AI
回它一句(等于帮它顶帖)。改为:先过反spam,判定干净了才在函数末尾回答。
新增 sender_ctx 提示提问本身不算违规,避免把正常提问的人误判封号。
管理员仍照常得到回答(公开版对管理员是提前 return,不能顺手跳过回答)。
2. 编辑消息绕过 —— 先发一句无害的、再编辑成广告。两因叠加:allowed_updates
没订阅 edited_message(Telegram 根本不推) + handler 只取 update.message
(编辑事件里是 None)。改为订阅 + 取 message or edited_message;编辑只重判
不重答;私聊 handler 与 CommandHandler 显式加 UpdateType.MESSAGE,否则
编辑一次就重复回答/重复执行命令一次。
3. 判定解析 fail-open —— 非 spam/yes 开头一律当干净,模型多说两个字
(根据以上判断,yes)或被 max_tokens=8 截断在前言里就是免死金牌。
改三态 True/False/None,None 退回词库兜底并记录原始输出;max_tokens 8→32。
4. 新增签到探针层(modules/probe.py) —— 对所有非管理员生效,只标记绝不封人,
窗口内累计到阈值才静默删除。词表刻意只收签到打卡这一族:更宽的版本
(哈+/好+的?/收到/顶/纯emoji/纯标点)实测命中中文群短消息的 59%,
会把真人的哈哈👍删掉,比漏拦更糟。window_start 记窗口起点且命中不刷新,
否则每天发一句水消息的人计数只涨不降,被永久静默删。
5. 命令消息绕过 —— 群 handler 带着 ~filters.COMMAND,命令根本不进反spam;
而发给别的 bot 的命令(/start@某bot)我们的 CommandHandler 也不接
(PTB 会校验 @用户名是否等于自己)。两边都不接 = 没有任何 handler 处理它。
影响面不止 /start:/start@某bot 加我微信一天1000 这类带正文的伪命令同样溜过。
去掉该过滤器(CommandHandler 注册在前,自己的命令行为不变),并把光秃秃的
/start@别的bot 归入探针层(拉流量话术,AI 判不出来)。
验证:py_compile 全过;探针/正则 12/12(含 0 误伤真人短消息、不误伤自己的命令
和别的bot的正常功能调用);同源修复已在私有 bot 的生产环境跑通并经真实
telegram.Update 对象的 PTB 分发对照测试(10/10)与端到端测试(5/5)。
- .env.example +4 -0
- README.md +3 -0
- README_AR.md +3 -0
- README_CN.md +3 -0
- README_ES.md +3 -0
- README_FA.md +3 -0
- README_RU.md +3 -0
- bot.py +121 -56
- config.py +7 -0
- modules/chat.py +58 -15
- modules/database.py +7 -0
- modules/probe.py +120 -0
|
@@ -31,3 +31,7 @@ SPAM_REPEAT_THRESHOLD=3
|
|
| 31 |
SPAM_REPEAT_WINDOW=300
|
| 32 |
# Chinese-slang lexicon hard-hit threshold (prefilter). Higher = stricter.
|
| 33 |
LEXICON_HARD_THRESHOLD=6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
SPAM_REPEAT_WINDOW=300
|
| 32 |
# Chinese-slang lexicon hard-hit threshold (prefilter). Higher = stricter.
|
| 33 |
LEXICON_HARD_THRESHOLD=6
|
| 34 |
+
# Probe ("check-in") filler: silently delete after this many flags. Never bans.
|
| 35 |
+
PROBE_FLAG_DELETE=2
|
| 36 |
+
# Rolling window for those flags (hours); older flags reset the count.
|
| 37 |
+
PROBE_WINDOW_HOURS=24
|
|
@@ -114,6 +114,8 @@ Everything is set via environment variables — see [`.env.example`](.env.exampl
|
|
| 114 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Voice-message model |
|
| 115 |
| `AI_IMAGE_MAX_WIDTH` | `600` | Downscale width before vision calls |
|
| 116 |
| `LEXICON_HARD_THRESHOLD` | `6` | Slang pre-filter strictness (higher = stricter) |
|
|
|
|
|
|
|
| 117 |
|
| 118 |
---
|
| 119 |
|
|
@@ -158,6 +160,7 @@ TelegramGuard/
|
|
| 158 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 159 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 160 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
|
|
|
| 161 |
│ ├── ilang_judge.py I-Lang decision function
|
| 162 |
│ ├── admin.py Group admin
|
| 163 |
│ ├── db.py Shared SQLite + async lock
|
|
|
|
| 114 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Voice-message model |
|
| 115 |
| `AI_IMAGE_MAX_WIDTH` | `600` | Downscale width before vision calls |
|
| 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 |
|
|
|
|
| 160 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 161 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 162 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
| 163 |
+
│ ├── probe.py Check-in filler detection (mark-only, never bans)
|
| 164 |
│ ├── ilang_judge.py I-Lang decision function
|
| 165 |
│ ├── admin.py Group admin
|
| 166 |
│ ├── db.py Shared SQLite + async lock
|
|
@@ -98,6 +98,8 @@ python bot.py
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | نموذج الرسائل الصوتية |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | عرض التصغير قبل استدعاءات الرؤية |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | صرامة المرشّح الأوّلي للعامية (الأعلى = أكثر صرامة) |
|
|
|
|
|
|
|
| 101 |
|
| 102 |
---
|
| 103 |
|
|
@@ -142,6 +144,7 @@ TelegramGuard/
|
|
| 142 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 143 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 144 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
|
|
|
| 145 |
│ ├── ilang_judge.py I-Lang decision function
|
| 146 |
│ ├── admin.py Group admin
|
| 147 |
│ ├── db.py Shared SQLite + async lock
|
|
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | نموذج الرسائل الصوتية |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | عرض التصغير قبل استدعاءات الرؤية |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | صرامة المرشّح الأوّلي للعامية (الأعلى = أكثر صرامة) |
|
| 101 |
+
| `PROBE_FLAG_DELETE` | `2` | عدد علامات رسائل «الحضور» قبل بدء الحذف (لا يحظر أبدًا) |
|
| 102 |
+
| `PROBE_WINDOW_HOURS` | `24` | النافذة المتحركة لتلك العلامات (بالساعات) |
|
| 103 |
|
| 104 |
---
|
| 105 |
|
|
|
|
| 144 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 145 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 146 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
| 147 |
+
│ ├── probe.py كشف رسائل «الحضور» (تعليم فقط، بلا حظر)
|
| 148 |
│ ├── ilang_judge.py I-Lang decision function
|
| 149 |
│ ├── admin.py Group admin
|
| 150 |
│ ├── db.py Shared SQLite + async lock
|
|
@@ -98,6 +98,8 @@ python bot.py
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | 语音模型 |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | 识图前压缩宽度 |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | 黑话预过滤严格度(越高越严) |
|
|
|
|
|
|
|
| 101 |
|
| 102 |
---
|
| 103 |
|
|
@@ -142,6 +144,7 @@ TelegramGuard/
|
|
| 142 |
│ ├── chat.py 提示词编排(加载 .ilang)
|
| 143 |
│ ├── prefilter.py 零成本垃圾预过滤 + 三路分诊
|
| 144 |
│ ├── lexicon.py 黑话/规避归一化 + 打分
|
|
|
|
| 145 |
│ ├── ilang_judge.py I-Lang 判定函数
|
| 146 |
│ ├── admin.py 群管理
|
| 147 |
│ ├── db.py SQLite 共享连接 + 异步锁
|
|
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | 语音模型 |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | 识图前压缩宽度 |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | 黑话预过滤严格度(越高越严) |
|
| 101 |
+
| `PROBE_FLAG_DELETE` | `2` | 签到水消息累计多少次后开始静默删除(绝不封号) |
|
| 102 |
+
| `PROBE_WINDOW_HOURS` | `24` | 上述标记的滚动有效窗口(小时) |
|
| 103 |
|
| 104 |
---
|
| 105 |
|
|
|
|
| 144 |
│ ├── chat.py 提示词编排(加载 .ilang)
|
| 145 |
│ ├── prefilter.py 零成本垃圾预过滤 + 三路分诊
|
| 146 |
│ ├── lexicon.py 黑话/规避归一化 + 打分
|
| 147 |
+
│ ├── probe.py 签到水消息识别(只标记, 绝不封号)
|
| 148 |
│ ├── ilang_judge.py I-Lang 判定函数
|
| 149 |
│ ├── admin.py 群管理
|
| 150 |
│ ├── db.py SQLite 共享连接 + 异步锁
|
|
@@ -98,6 +98,8 @@ Todo se configura mediante variables de entorno — consulta [`.env.example`](.e
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Modelo para mensajes de voz |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | Ancho de reducción antes de las llamadas de visión |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | Rigor del prefiltro de jerga (mayor = más estricto) |
|
|
|
|
|
|
|
| 101 |
|
| 102 |
---
|
| 103 |
|
|
@@ -142,6 +144,7 @@ TelegramGuard/
|
|
| 142 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 143 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 144 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
|
|
|
| 145 |
│ ├── ilang_judge.py I-Lang decision function
|
| 146 |
│ ├── admin.py Group admin
|
| 147 |
│ ├── db.py Shared SQLite + async lock
|
|
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Modelo para mensajes de voz |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | Ancho de reducción antes de las llamadas de visión |
|
| 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 |
|
|
|
|
| 144 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 145 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 146 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
| 147 |
+
│ ├── probe.py Detección de relleno tipo «presente» (solo marca, nunca banea)
|
| 148 |
│ ├── ilang_judge.py I-Lang decision function
|
| 149 |
│ ├── admin.py Group admin
|
| 150 |
│ ├── db.py Shared SQLite + async lock
|
|
@@ -98,6 +98,8 @@ python bot.py
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | مدل پیام صوتی |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | کاهش عرض تصویر پیش از فراخوانیهای بینایی |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | سختگیری پیشفیلتر زبان کوچهبازاری (بالاتر = سختگیرانهتر) |
|
|
|
|
|
|
|
| 101 |
|
| 102 |
---
|
| 103 |
|
|
@@ -142,6 +144,7 @@ TelegramGuard/
|
|
| 142 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 143 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 144 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
|
|
|
| 145 |
│ ├── ilang_judge.py I-Lang decision function
|
| 146 |
│ ├── admin.py Group admin
|
| 147 |
│ ├── db.py Shared SQLite + async lock
|
|
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | مدل پیام صوتی |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | کاهش عرض تصویر پیش از فراخوانیهای بینایی |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | سختگیری پیشفیلتر زبان کوچهبازاری (بالاتر = سختگیرانهتر) |
|
| 101 |
+
| `PROBE_FLAG_DELETE` | `2` | تعداد نشانههای پیام «حضور» پیش از حذف خودکار (هرگز مسدود نمیکند) |
|
| 102 |
+
| `PROBE_WINDOW_HOURS` | `24` | بازهٔ چرخشی برای این نشانهها (ساعت) |
|
| 103 |
|
| 104 |
---
|
| 105 |
|
|
|
|
| 144 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 145 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 146 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
| 147 |
+
│ ├── probe.py تشخیص پیامهای «حضور» (فقط نشانهگذاری، بدون مسدودسازی)
|
| 148 |
│ ├── ilang_judge.py I-Lang decision function
|
| 149 |
│ ├── admin.py Group admin
|
| 150 |
│ ├── db.py Shared SQLite + async lock
|
|
@@ -98,6 +98,8 @@ python bot.py
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Модель для голосовых сообщений |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | Ширина уменьшения изображения перед вызовами зрения |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | Строгость предфильтра сленга (выше = строже) |
|
|
|
|
|
|
|
| 101 |
|
| 102 |
---
|
| 103 |
|
|
@@ -142,6 +144,7 @@ TelegramGuard/
|
|
| 142 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 143 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 144 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
|
|
|
| 145 |
│ ├── ilang_judge.py I-Lang decision function
|
| 146 |
│ ├── admin.py Group admin
|
| 147 |
│ ├── db.py Shared SQLite + async lock
|
|
|
|
| 98 |
| `AI_AUDIO_MODEL` | `Qwen/Qwen3-Omni-30B-A3B-Instruct` | Модель для голосовых сообщений |
|
| 99 |
| `AI_IMAGE_MAX_WIDTH` | `600` | Ширина уменьшения изображения перед вызовами зрения |
|
| 100 |
| `LEXICON_HARD_THRESHOLD` | `6` | Строгость предфильтра сленга (выше = строже) |
|
| 101 |
+
| `PROBE_FLAG_DELETE` | `2` | Сколько меток «отметился» до начала удаления (никогда не банит) |
|
| 102 |
+
| `PROBE_WINDOW_HOURS` | `24` | Скользящее окно для этих меток (часы) |
|
| 103 |
|
| 104 |
---
|
| 105 |
|
|
|
|
| 144 |
│ ├── chat.py Prompt orchestration (loads .ilang)
|
| 145 |
│ ├── prefilter.py Zero-cost spam pre-filter + triage
|
| 146 |
│ ├── lexicon.py Slang / evasion normalization + scoring
|
| 147 |
+
│ ├── probe.py Обнаружение флуда «отметился» (только метки, без банов)
|
| 148 |
│ ├── ilang_judge.py I-Lang decision function
|
| 149 |
│ ├── admin.py Group admin
|
| 150 |
│ ├── db.py Shared SQLite + async lock
|
|
@@ -24,6 +24,7 @@ from modules.chat import (
|
|
| 24 |
)
|
| 25 |
from modules.admin import is_admin, is_bot_admin, register_group
|
| 26 |
from modules.prefilter import prefilter
|
|
|
|
| 27 |
|
| 28 |
logging.basicConfig(
|
| 29 |
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
@@ -137,8 +138,57 @@ async def cmd_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 137 |
|
| 138 |
# ==================== Group ====================
|
| 139 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
if not msg:
|
| 143 |
return
|
| 144 |
chat_id = msg.chat.id
|
|
@@ -151,50 +201,22 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
|
|
| 151 |
|
| 152 |
tos_ok = await check_tos(chat_id)
|
| 153 |
|
| 154 |
-
# @mention or reply to bot
|
|
|
|
| 155 |
is_mention = text and context.bot.username and ("@" + context.bot.username) in text
|
| 156 |
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
|
| 157 |
has_media = bool(msg.photo or msg.video or msg.document)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
reply = "I haven't been enabled yet. Ask an admin to tap the Accept & Enable button above."
|
| 162 |
-
else:
|
| 163 |
-
g_history = context.chat_data.setdefault("group_history", [])
|
| 164 |
-
if msg.photo:
|
| 165 |
-
try:
|
| 166 |
-
f = await context.bot.get_file(msg.photo[-1].file_id)
|
| 167 |
-
img_data = bytes(await f.download_as_bytearray())
|
| 168 |
-
reply = await ai_group_vision(img_data, caption=clean, history=g_history)
|
| 169 |
-
except Exception:
|
| 170 |
-
reply = "Couldn't read that image. Try sending another one?"
|
| 171 |
-
elif msg.video:
|
| 172 |
-
if msg.video.thumbnail:
|
| 173 |
-
try:
|
| 174 |
-
vf = await context.bot.get_file(msg.video.thumbnail.file_id)
|
| 175 |
-
vimg = bytes(await vf.download_as_bytearray())
|
| 176 |
-
reply = await ai_group_vision(vimg, caption=clean, history=g_history)
|
| 177 |
-
except Exception:
|
| 178 |
-
if clean:
|
| 179 |
-
g_history.append({"role": "user", "text": "[video] " + clean})
|
| 180 |
-
reply = await ai_group_reply("[video] " + clean, g_history)
|
| 181 |
-
else:
|
| 182 |
-
reply = "Couldn't read the video thumbnail. What's it about?"
|
| 183 |
-
elif clean:
|
| 184 |
-
g_history.append({"role": "user", "text": "[video] " + clean})
|
| 185 |
-
reply = await ai_group_reply("[video] " + clean, g_history)
|
| 186 |
-
else:
|
| 187 |
-
reply = "Can't process videos directly. What's it about?"
|
| 188 |
-
else:
|
| 189 |
-
g_history.append({"role": "user", "text": clean})
|
| 190 |
-
reply = await ai_group_reply(clean, g_history)
|
| 191 |
-
g_history.append({"role": "assistant", "text": reply})
|
| 192 |
-
if len(g_history) > 20:
|
| 193 |
-
g_history[:] = g_history[-20:]
|
| 194 |
-
await msg.reply_text(reply)
|
| 195 |
-
return
|
| 196 |
|
|
|
|
| 197 |
if not tos_ok:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
return
|
| 199 |
|
| 200 |
# Admin check
|
|
@@ -213,14 +235,39 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
|
|
| 213 |
user_msgs[uid] = []
|
| 214 |
content_hash = _hashlib.md5(text.encode()).hexdigest() if text else ""
|
| 215 |
now = _time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
user_msgs[uid].append((msg.message_id, content_hash, now))
|
| 217 |
if len(user_msgs[uid]) > 20:
|
| 218 |
user_msgs[uid] = user_msgs[uid][-20:]
|
| 219 |
|
| 220 |
-
# Admin bypass
|
| 221 |
if is_admin_user:
|
|
|
|
|
|
|
| 222 |
return
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
# Duplicate message detection
|
| 225 |
spam = False
|
| 226 |
if content_hash:
|
|
@@ -243,30 +290,30 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
|
|
| 243 |
try:
|
| 244 |
f = await context.bot.get_file(msg.photo[-1].file_id)
|
| 245 |
data = bytes(await f.download_as_bytearray())
|
| 246 |
-
spam = await ai_judge_group_image(data, text)
|
| 247 |
except Exception:
|
| 248 |
if text:
|
| 249 |
-
spam = await ai_judge_group_message(text)
|
| 250 |
elif msg.video:
|
| 251 |
if msg.video.thumbnail:
|
| 252 |
try:
|
| 253 |
vf = await context.bot.get_file(msg.video.thumbnail.file_id)
|
| 254 |
vdata = bytes(await vf.download_as_bytearray())
|
| 255 |
-
spam = await ai_judge_group_image(vdata, text)
|
| 256 |
except Exception:
|
| 257 |
if text:
|
| 258 |
-
spam = await ai_judge_group_message(text)
|
| 259 |
elif text:
|
| 260 |
-
spam = await ai_judge_group_message(text)
|
| 261 |
elif msg.forward_date:
|
| 262 |
spam = True
|
| 263 |
elif msg.document or msg.sticker:
|
| 264 |
if text:
|
| 265 |
-
spam = await ai_judge_group_message(text)
|
| 266 |
elif msg.forward_date:
|
| 267 |
spam = True
|
| 268 |
elif text:
|
| 269 |
-
spam = await ai_judge_group_message(text)
|
| 270 |
# verdict == "clean" → skip AI, let it through
|
| 271 |
|
| 272 |
if spam:
|
|
@@ -293,6 +340,11 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
|
|
| 293 |
pass
|
| 294 |
return
|
| 295 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
# ==================== Private ====================
|
| 298 |
|
|
@@ -445,24 +497,32 @@ def main():
|
|
| 445 |
|
| 446 |
app = Application.builder().token(config.BOT_TOKEN).connect_timeout(30).read_timeout(30).write_timeout(30).pool_timeout(30).build()
|
| 447 |
|
|
|
|
|
|
|
|
|
|
| 448 |
for cmd, fn in [
|
| 449 |
("start", cmd_start), ("help", cmd_help), ("ban", cmd_ban),
|
| 450 |
]:
|
| 451 |
-
app.add_handler(CommandHandler(cmd, fn))
|
| 452 |
|
| 453 |
app.add_handler(ChatMemberHandler(handle_my_chat_member, ChatMemberHandler.MY_CHAT_MEMBER))
|
| 454 |
app.add_handler(CallbackQueryHandler(handle_tos_callback, pattern="^tos_"))
|
| 455 |
|
| 456 |
-
# Group
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
app.add_handler(MessageHandler(
|
| 458 |
-
(filters.TEXT | filters.PHOTO | filters.VIDEO | filters.Document.ALL | filters.Sticker.ALL) & filters.ChatType.GROUPS
|
| 459 |
handle_group_message
|
| 460 |
))
|
| 461 |
|
| 462 |
# Private
|
| 463 |
-
app.add_handler(MessageHandler(filters.TEXT & filters.ChatType.PRIVATE & ~filters.COMMAND, handle_private_text))
|
| 464 |
-
app.add_handler(MessageHandler(filters.PHOTO & filters.ChatType.PRIVATE, handle_private_photo))
|
| 465 |
-
app.add_handler(MessageHandler(filters.VOICE & filters.ChatType.PRIVATE, handle_private_voice))
|
| 466 |
|
| 467 |
loop = asyncio.new_event_loop()
|
| 468 |
asyncio.set_event_loop(loop)
|
|
@@ -481,7 +541,10 @@ def main():
|
|
| 481 |
url_path="webhook",
|
| 482 |
webhook_url=webhook_url + "/webhook",
|
| 483 |
drop_pending_updates=True,
|
| 484 |
-
|
|
|
|
|
|
|
|
|
|
| 485 |
)
|
| 486 |
else:
|
| 487 |
# Polling mode: run AI test first, then start
|
|
@@ -503,7 +566,9 @@ def main():
|
|
| 503 |
logger.info("I-Lang Guard starting (polling mode)")
|
| 504 |
app.run_polling(
|
| 505 |
drop_pending_updates=True,
|
| 506 |
-
|
|
|
|
|
|
|
| 507 |
bootstrap_retries=10
|
| 508 |
)
|
| 509 |
|
|
|
|
| 24 |
)
|
| 25 |
from modules.admin import is_admin, is_bot_admin, register_group
|
| 26 |
from modules.prefilter import prefilter
|
| 27 |
+
from modules import probe
|
| 28 |
|
| 29 |
logging.basicConfig(
|
| 30 |
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
|
|
| 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 |
+
|
| 144 |
+
Called only once the message is known to be clean (or from an admin) — it
|
| 145 |
+
used to run at the top of handle_group_message and return, which let any
|
| 146 |
+
spammer skip the entire anti-spam pipeline just by replying to the bot.
|
| 147 |
+
"""
|
| 148 |
+
clean = text.replace("@" + context.bot.username, "").strip() if (text and is_mention) else (text.strip() if text else "")
|
| 149 |
+
g_history = context.chat_data.setdefault("group_history", [])
|
| 150 |
+
if msg.photo:
|
| 151 |
+
try:
|
| 152 |
+
f = await context.bot.get_file(msg.photo[-1].file_id)
|
| 153 |
+
img_data = bytes(await f.download_as_bytearray())
|
| 154 |
+
reply = await ai_group_vision(img_data, caption=clean, history=g_history)
|
| 155 |
+
except Exception:
|
| 156 |
+
reply = "Couldn't read that image. Try sending another one?"
|
| 157 |
+
elif msg.video:
|
| 158 |
+
if msg.video.thumbnail:
|
| 159 |
+
try:
|
| 160 |
+
vf = await context.bot.get_file(msg.video.thumbnail.file_id)
|
| 161 |
+
vimg = bytes(await vf.download_as_bytearray())
|
| 162 |
+
reply = await ai_group_vision(vimg, caption=clean, history=g_history)
|
| 163 |
+
except Exception:
|
| 164 |
+
if clean:
|
| 165 |
+
g_history.append({"role": "user", "text": "[video] " + clean})
|
| 166 |
+
reply = await ai_group_reply("[video] " + clean, g_history)
|
| 167 |
+
else:
|
| 168 |
+
reply = "Couldn't read the video thumbnail. What's it about?"
|
| 169 |
+
elif clean:
|
| 170 |
+
g_history.append({"role": "user", "text": "[video] " + clean})
|
| 171 |
+
reply = await ai_group_reply("[video] " + clean, g_history)
|
| 172 |
+
else:
|
| 173 |
+
reply = "Can't process videos directly. What's it about?"
|
| 174 |
+
else:
|
| 175 |
+
g_history.append({"role": "user", "text": clean})
|
| 176 |
+
reply = await ai_group_reply(clean, g_history)
|
| 177 |
+
g_history.append({"role": "assistant", "text": reply})
|
| 178 |
+
if len(g_history) > 20:
|
| 179 |
+
g_history[:] = g_history[-20:]
|
| 180 |
+
try:
|
| 181 |
+
await msg.reply_text(reply)
|
| 182 |
+
except Exception as e:
|
| 183 |
+
logger.warning("group @mention reply failed: chat=" + str(msg.chat.id) + " err=" + str(e))
|
| 184 |
+
|
| 185 |
+
|
| 186 |
async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 187 |
+
# Edited messages come in too: this used to read update.message only, which
|
| 188 |
+
# is None on an edit event, so the handler returned on its first line and
|
| 189 |
+
# "post something harmless, then edit it into an ad" bypassed everything.
|
| 190 |
+
is_edited = update.message is None and update.edited_message is not None
|
| 191 |
+
msg = update.message or update.edited_message
|
| 192 |
if not msg:
|
| 193 |
return
|
| 194 |
chat_id = msg.chat.id
|
|
|
|
| 201 |
|
| 202 |
tos_ok = await check_tos(chat_id)
|
| 203 |
|
| 204 |
+
# @mention or reply to bot — only detected here, answered at the end of the
|
| 205 |
+
# function once anti-spam has cleared the message.
|
| 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:
|
| 215 |
+
if wants_reply:
|
| 216 |
+
try:
|
| 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
|
|
|
|
| 235 |
user_msgs[uid] = []
|
| 236 |
content_hash = _hashlib.md5(text.encode()).hexdigest() if text else ""
|
| 237 |
now = _time.time()
|
| 238 |
+
# An edit carries the same message_id: replace the existing entry instead of
|
| 239 |
+
# appending a second one, so the bulk-delete list holds no duplicates and
|
| 240 |
+
# editing one message repeatedly doesn't look like flooding.
|
| 241 |
+
user_msgs[uid] = [e for e in user_msgs[uid] if e[0] != msg.message_id]
|
| 242 |
user_msgs[uid].append((msg.message_id, content_hash, now))
|
| 243 |
if len(user_msgs[uid]) > 20:
|
| 244 |
user_msgs[uid] = user_msgs[uid][-20:]
|
| 245 |
|
| 246 |
+
# Admin bypass: no enforcement on admins, but still answer them.
|
| 247 |
if is_admin_user:
|
| 248 |
+
if wants_reply:
|
| 249 |
+
await _answer_mention(msg, context, is_mention, text)
|
| 250 |
return
|
| 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
|
| 262 |
+
# question addressed to it as promotion and bans the person for it.
|
| 263 |
+
sender_ctx = ""
|
| 264 |
+
if wants_reply:
|
| 265 |
+
sender_ctx = (
|
| 266 |
+
"This message is addressed to the bot (a question or a reply to it). "
|
| 267 |
+
"Asking the bot something is not a violation on its own — only call it "
|
| 268 |
+
"spam if the content really is advertising, a scam, or contact harvesting."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
# Duplicate message detection
|
| 272 |
spam = False
|
| 273 |
if content_hash:
|
|
|
|
| 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:
|
|
|
|
| 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.
|
| 345 |
+
if wants_reply:
|
| 346 |
+
await _answer_mention(msg, context, is_mention, text)
|
| 347 |
+
|
| 348 |
|
| 349 |
# ==================== Private ====================
|
| 350 |
|
|
|
|
| 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.
|
| 503 |
for cmd, fn in [
|
| 504 |
("start", cmd_start), ("help", cmd_help), ("ban", cmd_ban),
|
| 505 |
]:
|
| 506 |
+
app.add_handler(CommandHandler(cmd, fn, filters=filters.UpdateType.MESSAGE))
|
| 507 |
|
| 508 |
app.add_handler(ChatMemberHandler(handle_my_chat_member, ChatMemberHandler.MY_CHAT_MEMBER))
|
| 509 |
app.add_handler(CallbackQueryHandler(handle_tos_callback, pattern="^tos_"))
|
| 510 |
|
| 511 |
+
# Group — deliberately no UpdateType filter: edits must be re-judged here.
|
| 512 |
+
# Also deliberately no ~filters.COMMAND. A command addressed to a DIFFERENT bot
|
| 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))
|
| 524 |
+
app.add_handler(MessageHandler(filters.PHOTO & filters.ChatType.PRIVATE & filters.UpdateType.MESSAGE, handle_private_photo))
|
| 525 |
+
app.add_handler(MessageHandler(filters.VOICE & filters.ChatType.PRIVATE & filters.UpdateType.MESSAGE, handle_private_voice))
|
| 526 |
|
| 527 |
loop = asyncio.new_event_loop()
|
| 528 |
asyncio.set_event_loop(loop)
|
|
|
|
| 541 |
url_path="webhook",
|
| 542 |
webhook_url=webhook_url + "/webhook",
|
| 543 |
drop_pending_updates=True,
|
| 544 |
+
# edited_message: without subscribing, Telegram never sends edit
|
| 545 |
+
# events at all and "post something harmless, then edit it into an
|
| 546 |
+
# ad" walks straight past the anti-spam pipeline.
|
| 547 |
+
allowed_updates=["message", "edited_message", "callback_query", "my_chat_member"],
|
| 548 |
)
|
| 549 |
else:
|
| 550 |
# Polling mode: run AI test first, then start
|
|
|
|
| 566 |
logger.info("I-Lang Guard starting (polling mode)")
|
| 567 |
app.run_polling(
|
| 568 |
drop_pending_updates=True,
|
| 569 |
+
# See the webhook branch above — edited_message must be subscribed
|
| 570 |
+
# to or edits bypass anti-spam entirely.
|
| 571 |
+
allowed_updates=["message", "edited_message", "callback_query", "my_chat_member"],
|
| 572 |
bootstrap_retries=10
|
| 573 |
)
|
| 574 |
|
|
@@ -25,5 +25,12 @@ SPAM_REPEAT_WINDOW = int(os.environ.get("SPAM_REPEAT_WINDOW", "300"))
|
|
| 25 |
# Chinese-slang lexicon hard-hit threshold (prefilter Layer 2.5). Higher = stricter.
|
| 26 |
LEXICON_HARD_THRESHOLD = int(os.environ.get("LEXICON_HARD_THRESHOLD", "6"))
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
# Admin user ID (auto-detected from first /start)
|
| 29 |
ADMIN_USER_ID = None
|
|
|
|
| 25 |
# Chinese-slang lexicon hard-hit threshold (prefilter Layer 2.5). Higher = stricter.
|
| 26 |
LEXICON_HARD_THRESHOLD = int(os.environ.get("LEXICON_HARD_THRESHOLD", "6"))
|
| 27 |
|
| 28 |
+
# Probe ("check-in") detection. Mark-only layer: it never bans, it only starts
|
| 29 |
+
# silently deleting once a member has been flagged this many times...
|
| 30 |
+
PROBE_FLAG_DELETE = int(os.environ.get("PROBE_FLAG_DELETE", "2"))
|
| 31 |
+
# ...within this rolling window (hours). Flags older than the window reset to 1,
|
| 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
|
|
@@ -4,6 +4,7 @@ import random
|
|
| 4 |
import os
|
| 5 |
|
| 6 |
from modules import ai_provider
|
|
|
|
| 7 |
import config
|
| 8 |
|
| 9 |
logger = logging.getLogger(__name__)
|
|
@@ -90,10 +91,34 @@ def _deflect():
|
|
| 90 |
|
| 91 |
|
| 92 |
def _is_spam(raw):
|
| 93 |
-
"""Parse a spam-judge reply
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
|
| 99 |
async def ai_text(text, history=None, context_info=""):
|
|
@@ -137,24 +162,42 @@ async def ai_voice(audio_bytes, mime_type="audio/ogg", history=None, context_inf
|
|
| 137 |
return ("chat", "Didn't catch that. Try again or type it out.")
|
| 138 |
|
| 139 |
|
| 140 |
-
async def ai_judge_group_message(text):
|
| 141 |
try:
|
| 142 |
-
prompt = ANTISPAM_TEXT_PROMPT
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
|
| 149 |
-
async def ai_judge_group_image(image_bytes, caption=""):
|
| 150 |
try:
|
| 151 |
prompt = ANTISPAM_TEXT_PROMPT + "\n\nJudge this image. Reply ONLY: spam or ok."
|
|
|
|
|
|
|
| 152 |
if caption:
|
| 153 |
prompt += "\nCaption: " + caption[:500]
|
| 154 |
-
raw = await ai_provider.generate_vision(prompt, image_bytes, max_tokens=
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
|
| 160 |
async def ai_group_vision(image_bytes, caption="", history=None):
|
|
|
|
| 4 |
import os
|
| 5 |
|
| 6 |
from modules import ai_provider
|
| 7 |
+
from modules import lexicon
|
| 8 |
import config
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
|
|
|
| 91 |
|
| 92 |
|
| 93 |
def _is_spam(raw):
|
| 94 |
+
"""Parse a spam-judge reply into True / False / None (couldn't parse it).
|
| 95 |
+
|
| 96 |
+
Fixes the old `"spam" in result` substring bug (a wordy 'not spam' counted as
|
| 97 |
+
spam) and the fail-open that replaced it: anything not starting with spam/yes
|
| 98 |
+
silently meant "clean", so a model that prefixes its answer ("Based on the
|
| 99 |
+
above, yes") or gets truncated inside that preamble was a free pass.
|
| 100 |
+
None means unparseable — callers fall back to the lexicon instead of letting
|
| 101 |
+
the message through.
|
| 102 |
+
"""
|
| 103 |
+
s = (raw or "").strip().lower().lstrip("\"'`*# ")
|
| 104 |
+
if not s:
|
| 105 |
+
return None
|
| 106 |
+
if s.startswith(("spam", "yes", "y,", "违规", "是", "有")) or s == "y":
|
| 107 |
+
return True
|
| 108 |
+
if s.startswith(("ok", "no", "n,", "not ", "clean", "正常", "否", "不是", "无")) or s == "n":
|
| 109 |
+
return False
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _lexicon_fallback(text):
|
| 114 |
+
"""Used when the verdict is unparseable or the API call failed: fall back to
|
| 115 |
+
a lexicon hard hit rather than silently letting the message through."""
|
| 116 |
+
try:
|
| 117 |
+
s, _ = lexicon.score(text or "")
|
| 118 |
+
return s >= getattr(config, "LEXICON_HARD_THRESHOLD", 6)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
logger.warning("lexicon fallback failed: " + str(e))
|
| 121 |
+
return False
|
| 122 |
|
| 123 |
|
| 124 |
async def ai_text(text, history=None, context_info=""):
|
|
|
|
| 162 |
return ("chat", "Didn't catch that. Try again or type it out.")
|
| 163 |
|
| 164 |
|
| 165 |
+
async def ai_judge_group_message(text, sender_context=""):
|
| 166 |
try:
|
| 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.
|
| 174 |
+
raw = await ai_provider.generate_text(prompt, max_tokens=32, temperature=0.0)
|
| 175 |
+
verdict = _is_spam(raw)
|
| 176 |
+
if verdict is None: # unparseable — don't let it through silently
|
| 177 |
+
logger.warning("spam text verdict unparseable: " + repr((raw or "")[:80]) + " — falling back to lexicon")
|
| 178 |
+
return _lexicon_fallback(text)
|
| 179 |
+
return verdict
|
| 180 |
+
except Exception as e:
|
| 181 |
+
logger.warning("spam text judge failed, falling back to lexicon: " + str(e))
|
| 182 |
+
return _lexicon_fallback(text)
|
| 183 |
|
| 184 |
|
| 185 |
+
async def ai_judge_group_image(image_bytes, caption="", sender_context=""):
|
| 186 |
try:
|
| 187 |
prompt = ANTISPAM_TEXT_PROMPT + "\n\nJudge this image. Reply ONLY: spam or ok."
|
| 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
|
| 195 |
+
logger.warning("spam image verdict unparseable: " + repr((raw or "")[:80]) + " — falling back to lexicon")
|
| 196 |
+
return _lexicon_fallback(caption)
|
| 197 |
+
return verdict
|
| 198 |
+
except Exception as e:
|
| 199 |
+
logger.warning("spam image judge failed, falling back to lexicon: " + str(e))
|
| 200 |
+
return _lexicon_fallback(caption)
|
| 201 |
|
| 202 |
|
| 203 |
async def ai_group_vision(image_bytes, caption="", history=None):
|
|
@@ -30,6 +30,13 @@ async def init_db():
|
|
| 30 |
joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 31 |
PRIMARY KEY (chat_id, user_id)
|
| 32 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
CREATE TABLE IF NOT EXISTS tos_consent (
|
| 34 |
chat_id INTEGER PRIMARY KEY,
|
| 35 |
accepted_by INTEGER,
|
|
|
|
| 30 |
joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 31 |
PRIMARY KEY (chat_id, user_id)
|
| 32 |
);
|
| 33 |
+
CREATE TABLE IF NOT EXISTS probe_flags (
|
| 34 |
+
chat_id INTEGER,
|
| 35 |
+
user_id INTEGER,
|
| 36 |
+
flags INTEGER DEFAULT 0,
|
| 37 |
+
window_start TIMESTAMP,
|
| 38 |
+
PRIMARY KEY (chat_id, user_id)
|
| 39 |
+
);
|
| 40 |
CREATE TABLE IF NOT EXISTS tos_consent (
|
| 41 |
chat_id INTEGER PRIMARY KEY,
|
| 42 |
accepted_by INTEGER,
|
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Probe ("check-in") detection.
|
| 3 |
+
|
| 4 |
+
Spam bots warm a group up with harmless filler — 签到 / 打卡 / 冒泡 — to see whether
|
| 5 |
+
anyone is moderating and to build a bit of message history before dropping the
|
| 6 |
+
actual ad. This layer is deliberately the gentlest one in the stack:
|
| 7 |
+
|
| 8 |
+
* every non-admin member is subject to it (not just new joiners)
|
| 9 |
+
* it NEVER bans — the worst it does is silently delete
|
| 10 |
+
* and it only starts deleting after the same member has been flagged
|
| 11 |
+
config.PROBE_FLAG_DELETE times inside a rolling PROBE_WINDOW_HOURS window
|
| 12 |
+
|
| 13 |
+
Everything else keeps going through the lexicon + AI path.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import logging
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
import config
|
| 20 |
+
from modules.db import shared_db
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
# Deliberately narrow — only the check-in family of phrases.
|
| 25 |
+
# A wider pattern (哈+ / 好+的? / 收到 / 顶, plus "pure emoji" and "pure punctuation")
|
| 26 |
+
# was measured against real Chinese group chat: it hit 59% of ordinary short
|
| 27 |
+
# messages. Since this layer applies to every member, that means silently
|
| 28 |
+
# deleting real people's "哈哈" and "👍" — worse than missing a probe.
|
| 29 |
+
PROBE_PATTERNS = re.compile(
|
| 30 |
+
r"^(签到|打卡|报到|新人报道|前来报道|冒泡|水一下|沙发|路过)\s*$"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def looks_like_probe(text):
|
| 35 |
+
"""Pure check-in filler. Single-message check, no history involved."""
|
| 36 |
+
if not text:
|
| 37 |
+
return False
|
| 38 |
+
t = text.strip()
|
| 39 |
+
return len(t) <= 8 and bool(PROBE_PATTERNS.match(t))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# A bare "/start@SomeOtherBot" posted in a group is the classic way to drive
|
| 43 |
+
# traffic to another bot — you start a bot in private, not by announcing it in a
|
| 44 |
+
# group. The AI judge cannot flag it (there is nothing to judge but a command),
|
| 45 |
+
# so it belongs here. Only /start: "/menu@ShopBot" is somebody legitimately
|
| 46 |
+
# using another bot in the group and must not be touched.
|
| 47 |
+
FOREIGN_START = re.compile(r"^/start@([A-Za-z0-9_]{4,32})\s*$", re.I)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def looks_like_foreign_start(text, my_username=""):
|
| 51 |
+
"""True for a bare /start aimed at a bot that is not us."""
|
| 52 |
+
if not text:
|
| 53 |
+
return False
|
| 54 |
+
m = FOREIGN_START.match(text.strip())
|
| 55 |
+
if not m:
|
| 56 |
+
return False
|
| 57 |
+
return m.group(1).lower() != (my_username or "").lower().lstrip("@")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _window_hours():
|
| 61 |
+
try:
|
| 62 |
+
return max(1, int(getattr(config, "PROBE_WINDOW_HOURS", 24)))
|
| 63 |
+
except (TypeError, ValueError):
|
| 64 |
+
return 24
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
async def add_flag(chat_id, user_id):
|
| 68 |
+
"""Add one probe flag for this member and return the running count.
|
| 69 |
+
|
| 70 |
+
UPSERT, not a bare UPDATE: members have no row until their first probe, and
|
| 71 |
+
an UPDATE that matches nothing affects 0 rows and keeps returning 0 — the
|
| 72 |
+
delete threshold would never be reached and this whole layer would be dead.
|
| 73 |
+
|
| 74 |
+
window_start records the START of the current window and is NOT refreshed on
|
| 75 |
+
a hit, so the window genuinely expires. Refreshing it every time would let
|
| 76 |
+
the count of someone who posts one such message a day ratchet up forever
|
| 77 |
+
until they are permanently silenced.
|
| 78 |
+
"""
|
| 79 |
+
window = "-%d hours" % _window_hours()
|
| 80 |
+
async with shared_db() as db:
|
| 81 |
+
await db.execute(
|
| 82 |
+
"INSERT INTO probe_flags (chat_id, user_id, flags, window_start) "
|
| 83 |
+
"VALUES (?, ?, 1, CURRENT_TIMESTAMP) "
|
| 84 |
+
"ON CONFLICT(chat_id, user_id) DO UPDATE SET "
|
| 85 |
+
"flags = CASE WHEN window_start IS NULL OR window_start < datetime('now', ?) "
|
| 86 |
+
" THEN 1 ELSE flags + 1 END, "
|
| 87 |
+
"window_start = CASE WHEN window_start IS NULL OR window_start < datetime('now', ?) "
|
| 88 |
+
" THEN CURRENT_TIMESTAMP ELSE window_start END",
|
| 89 |
+
(chat_id, user_id, window, window)
|
| 90 |
+
)
|
| 91 |
+
await db.commit()
|
| 92 |
+
cur = await db.execute(
|
| 93 |
+
"SELECT flags FROM probe_flags WHERE chat_id=? AND user_id=?",
|
| 94 |
+
(chat_id, user_id)
|
| 95 |
+
)
|
| 96 |
+
row = await cur.fetchone()
|
| 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
|