ilang-ai commited on
Commit
27803aa
·
1 Parent(s): 02538d1

v4.3: pre-filter layer — zero API cost spam defense

Browse files

Three defense lines BEFORE AI:
1. Repeat detection (already had) — same msg 3x in 5min
2. Pre-filter (NEW):
- Keyword/regex: multilingual spam patterns + URL/contact combo
- Forward spam: forwarded msg with link/contact = spam
- New account: no username + no name + has link = spam
3. API rate limiter with token bucket:
- 50 calls/minute budget
- Below 20%: sampling mode (1 in 3 messages)
- Exhausted: rules-only mode, no AI calls
- Graceful degradation, never goes blind

AI only sees messages that pass all pre-filters.
Addresses ACC red team finding #2 (rate limit trap).

Files changed (2) hide show
  1. bot.py +30 -23
  2. modules/prefilter.py +170 -0
bot.py CHANGED
@@ -23,6 +23,7 @@ from modules.chat import (
23
  GROUP_WELCOME
24
  )
25
  from modules.admin import is_admin, is_bot_admin, register_group
 
26
 
27
  logging.basicConfig(
28
  format="%(asctime)s [%(levelname)s] %(message)s",
@@ -231,36 +232,42 @@ async def handle_group_message(update: Update, context: ContextTypes.DEFAULT_TYP
231
  spam = True
232
  logger.info("REPEAT SPAM: user=" + str(uid) + " chat=" + str(chat_id) + " count=" + str(len(recent_same)))
233
 
234
- # AI spam check (skip if already caught)
235
  if not spam:
236
- if msg.photo:
237
- try:
238
- f = await context.bot.get_file(msg.photo[-1].file_id)
239
- data = bytes(await f.download_as_bytearray())
240
- spam = await ai_judge_group_image(data, text)
241
- except Exception:
242
- if text:
243
- spam = await ai_judge_group_message(text)
244
- elif msg.video:
245
- if msg.video.thumbnail:
246
  try:
247
- vf = await context.bot.get_file(msg.video.thumbnail.file_id)
248
- vdata = bytes(await vf.download_as_bytearray())
249
- spam = await ai_judge_group_image(vdata, text)
250
  except Exception:
251
  if text:
252
  spam = await ai_judge_group_message(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  elif text:
254
  spam = await ai_judge_group_message(text)
255
- elif msg.forward_date:
256
- spam = True
257
- elif msg.document or msg.sticker:
258
- if text:
259
- spam = await ai_judge_group_message(text)
260
- elif msg.forward_date:
261
- spam = True
262
- elif text:
263
- spam = await ai_judge_group_message(text)
264
 
265
  if spam:
266
  try:
 
23
  GROUP_WELCOME
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",
 
232
  spam = True
233
  logger.info("REPEAT SPAM: user=" + str(uid) + " chat=" + str(chat_id) + " count=" + str(len(recent_same)))
234
 
235
+ # Pre-filter: keyword/regex/forward/new-account (zero API cost)
236
  if not spam:
237
+ verdict = prefilter(msg, user, text)
238
+ if verdict == "spam":
239
+ spam = True
240
+ elif verdict == "ai":
241
+ # Needs AI analysis (API budget available)
242
+ if msg.photo:
 
 
 
 
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:
273
  try:
modules/prefilter.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pre-filter: catches obvious spam BEFORE burning an AI API call.
3
+ Zero cost. Runs on every message. AI only sees what passes all filters.
4
+ """
5
+
6
+ import re
7
+ import time
8
+ import logging
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Spam keyword patterns (multilingual)
13
+ SPAM_KEYWORDS = re.compile(
14
+ r'加[我微v]|私聊领|免费领|日[赚入]|月入[过百千万]|'
15
+ r'代[开做理]|招[代聘]|兼\s*职|刷\s*单|'
16
+ r'翻[几十百]倍|稳赚|保本|零风险|'
17
+ r'[\U0001F4B0\U0001F4B8\U0001F911]{2,}|' # money emoji spam
18
+ r'click here|earn money|work from home|make \$|'
19
+ r'free crypto|airdrop|whitelist spot|'
20
+ r'join (?:my|our|this) (?:channel|group)|'
21
+ r't\.me/(?:joinchat|[+])',
22
+ re.IGNORECASE
23
+ )
24
+
25
+ # URL patterns
26
+ URL_PATTERN = re.compile(
27
+ r'https?://|t\.me/|bit\.ly|tinyurl|wa\.me|'
28
+ r'@\w+bot\b',
29
+ re.IGNORECASE
30
+ )
31
+
32
+ # Contact info patterns
33
+ CONTACT_PATTERN = re.compile(
34
+ r'[\U0001F4DE\U0001F4F1]|' # phone emojis
35
+ r'(?:whatsapp|telegram|wechat|微信|qq)\s*[::]?\s*\d|'
36
+ r'(?:加|add)\s*(?:我|me)',
37
+ re.IGNORECASE
38
+ )
39
+
40
+
41
+ class APIRateLimiter:
42
+ """Token bucket rate limiter for AI API calls."""
43
+
44
+ def __init__(self, max_calls=50, window=60):
45
+ self.max_calls = max_calls # max calls per window
46
+ self.window = window # window in seconds
47
+ self.calls = [] # timestamps of recent calls
48
+
49
+ def can_call(self):
50
+ """Check if we can make another API call."""
51
+ now = time.time()
52
+ self.calls = [t for t in self.calls if now - t < self.window]
53
+ return len(self.calls) < self.max_calls
54
+
55
+ def record_call(self):
56
+ """Record an API call."""
57
+ self.calls.append(time.time())
58
+
59
+ def remaining(self):
60
+ """How many calls left in current window."""
61
+ now = time.time()
62
+ self.calls = [t for t in self.calls if now - t < self.window]
63
+ return max(0, self.max_calls - len(self.calls))
64
+
65
+ def is_critical(self):
66
+ """Below 20% budget — switch to sampling mode."""
67
+ return self.remaining() < self.max_calls * 0.2
68
+
69
+
70
+ # Global rate limiter: 50 AI calls per minute (adjustable)
71
+ api_limiter = APIRateLimiter(max_calls=50, window=60)
72
+
73
+
74
+ def keyword_spam(text):
75
+ """Fast keyword check. Returns True if obvious spam."""
76
+ if not text:
77
+ return False
78
+ # Keyword match + has URL or contact = almost certainly spam
79
+ has_keywords = bool(SPAM_KEYWORDS.search(text))
80
+ has_url = bool(URL_PATTERN.search(text))
81
+ has_contact = bool(CONTACT_PATTERN.search(text))
82
+
83
+ if has_keywords and (has_url or has_contact):
84
+ return True
85
+
86
+ # Pure contact harvesting: just a contact method, no real conversation
87
+ if has_contact and len(text) < 100 and not any(c in text for c in '??'):
88
+ return True
89
+
90
+ return False
91
+
92
+
93
+ def forward_spam(msg):
94
+ """Forwarded message with link/contact = spam."""
95
+ if not msg.forward_date:
96
+ return False
97
+ text = msg.text or msg.caption or ""
98
+ if URL_PATTERN.search(text) or CONTACT_PATTERN.search(text):
99
+ return True
100
+ # Forwarded media with no caption from non-group member = suspicious
101
+ if not text and (msg.photo or msg.video or msg.document):
102
+ return True
103
+ return False
104
+
105
+
106
+ def new_account_spam(user, text):
107
+ """New/suspicious accounts with links = spam."""
108
+ if not text or not URL_PATTERN.search(text):
109
+ return False
110
+ # No username + no profile photo + has link = high spam probability
111
+ suspicious = 0
112
+ if not user.username:
113
+ suspicious += 1
114
+ if not user.first_name or len(user.first_name) < 2:
115
+ suspicious += 1
116
+ # Name is just emojis or special chars
117
+ if user.first_name and not any(c.isalpha() for c in user.first_name):
118
+ suspicious += 1
119
+ return suspicious >= 2
120
+
121
+
122
+ def should_use_ai(msg):
123
+ """Decide if this message needs AI analysis or if we should skip/sample."""
124
+ if not api_limiter.can_call():
125
+ logger.warning("API rate limit hit — falling back to rules only")
126
+ return False
127
+
128
+ if api_limiter.is_critical():
129
+ # Sampling mode: only check 1 in 3 messages
130
+ import random
131
+ if random.random() > 0.33:
132
+ logger.info("API budget critical — sampling mode, skipping this message")
133
+ return False
134
+
135
+ return True
136
+
137
+
138
+ def prefilter(msg, user, text):
139
+ """
140
+ Run all pre-filters. Returns:
141
+ "spam" — definitely spam, skip AI, nuke immediately
142
+ "clean" — definitely clean, skip AI
143
+ "ai" — unclear, needs AI analysis
144
+ """
145
+ # Layer 1: Forward spam (zero false positive)
146
+ if forward_spam(msg):
147
+ logger.info("PREFILTER forward_spam: user=" + str(user.id))
148
+ return "spam"
149
+
150
+ # Layer 2: Keyword + link/contact (very high accuracy)
151
+ if text and keyword_spam(text):
152
+ logger.info("PREFILTER keyword_spam: user=" + str(user.id) + " text=" + text[:50])
153
+ return "spam"
154
+
155
+ # Layer 3: Suspicious new account + link
156
+ if new_account_spam(user, text):
157
+ logger.info("PREFILTER new_account_spam: user=" + str(user.id))
158
+ return "spam"
159
+
160
+ # Layer 4: No text, no media = nothing to check
161
+ if not text and not msg.photo and not msg.video:
162
+ return "clean"
163
+
164
+ # Layer 5: Rate limiter — can we afford an AI call?
165
+ if not should_use_ai(msg):
166
+ return "clean" # let it through rather than false-positive
167
+
168
+ # Needs AI
169
+ api_limiter.record_call()
170
+ return "ai"