Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
command to sweep for mrbeast
Browse files80 unmodified lines818283848586878879 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921936 unmodified lines200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241330 unmodified lines572573574575576577265 unmodified lines84384484584684784880 unmodified linesIMAGE_SCAN_MAX_TOKENS = 8000 # reasoning tokens count against this, so keep it generousIMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif")image_scan_recent_bans = {} # user_id -> ban time, so a multi-message burst only bans/logs once_bg_tasks = set() # keeps background scan tasks referenced until they finishSCAN_PROMPT = """You are a moderation classifier for the Hugging Face Discord server.The image(s) were all posted together in one message. Judge them as a set.79 unmodified linesreturn Noneasync def scan_message_images(message):try:if not HF_TOKEN or not message.guild or message.author.bot:returnmember = message.author if isinstance(message.author, discord.Member) else message.guild.get_member(message.author.id)if member is None or is_exempt(member):returnurls = _image_urls_from_message(message)if not urls:returnasync with aiohttp.ClientSession() as session:images = [img for img in [await _fetch_image(session, u) for u in urls] if img]if not images:returnverdict = await _classify_images(session, [d for d, _ in images], message.content)if verdict is None:print(f"Image scan: every provider failed for message {message.id}")returnis_mrbeast = verdict.get("mrbeast") is Trueis_scam = verdict.get("scam") is True6 unmodified lineshit = is_scam and confidence >= IMAGE_SCAN_MIN_CONFIDENCE and (is_mrbeast or not IMAGE_SCAN_REQUIRE_MRBEAST)if not hit:return# Discord deletes attachments along with the message, so keep our own copy as evidencefiles = [discord.File(io.BytesIO(jpeg), filename=f"evidence_{i + 1}.jpg") for i, (_, jpeg) in enumerate(images)]jump = f"https://discord.com/channels/{message.guild.id}/{message.channel.id}/{message.id}"details = (f"User: {member.mention} ({member.id}) in {message.channel.mention}\n"f"Verdict: mrbeast={is_mrbeast} scam={is_scam} confidence={confidence:.2f} via `{verdict['model']}`\n"f"Reason: {reason}\n[Jump to message!]({jump})")alert = {"True": "<@&1106995261487710411>", "False": "<@&1108342563628404747>"}.get(os.environ.get("TEST_SERVER"), "")if IMAGE_SCAN_DRY_RUN:await bot.log_channel.send(f"🧪 **[IMAGE SCAN, DRY RUN] would auto-ban**\n{details}", files=files)return# check-and-set with no await in between, so parallel scans of one burst can't double-banif time.time() - image_scan_recent_bans.get(member.id, 0) < 600:returnimage_scan_recent_bans[member.id] = time.time()me = message.guild.meif not (me.guild_permissions.ban_members and member.top_role < me.top_role):await bot.log_channel.send(f"❌ Image-scan ban skipped (missing perms / role hierarchy)\n{details}", files=files)returntry:await member.send(f"You have been automatically banned from **{message.guild.name}** because your account "f"posted scam images (this usually means the account was compromised). Secure your "f"account, then contact @Adam to appeal.")except Exception:passawait member.ban(delete_message_seconds=86400, # wipes their last 24h of messages in every channelreason=f"Auto-ban (image scan): {reason}"[:512])await bot.log_channel.send(f"🚨 **AUTO-BANNED (image scan)**\n{details}\n{alert}", files=files)except Exception as e:print(f"scan_message_images Error: {e}")# stats stuff ---------------------------------------------------------------------------------------------------------------------------------------------------------330 unmodified lines@bot.eventasync def on_member_unban(guild, unbanned_user):try:await asyncio.sleep(5)async for entry in guild.audit_logs(action=discord.AuditLogAction.unban, limit=1):if unbanned_user == entry.target: # verify that unbanned user is in audit log265 unmodified linesawait ctx.send("\n".join(lines)[:1900])80 unmodified lines8182838485868788899091929379 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052066 unmodified lines213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279330 unmodified lines610611612613614615616265 unmodified lines88288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795880 unmodified linesIMAGE_SCAN_MAX_TOKENS = 8000 # reasoning tokens count against this, so keep it generousIMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif")IMAGE_SWEEP_DEFAULT_DAYS = 30 # how far back !scansweep looks by defaultIMAGE_SWEEP_MAX_DAYS = 90IMAGE_SWEEP_CONCURRENCY = 6 # parallel model calls during a sweepimage_scan_banned_ids = set() # users the scanner banned (or found banned), so a burst or a sweep acts once per user_bg_tasks = set() # keeps background scan tasks referenced until they finish_sweep_running = FalseSCAN_PROMPT = """You are a moderation classifier for the Hugging Face Discord server.The image(s) were all posted together in one message. Judge them as a set.79 unmodified linesreturn Noneasync def scan_message_images(message, sweep=False):"""Scan one message's images and act on a hit. Returns "hit", "clean", "failed" or "skipped".sweep=True is used by !scansweep for older messages: the author may have left the server since,and the flagged message is deleted directly because a ban only clears the last 7 days of messages."""try:if not HF_TOKEN or not message.guild or message.author.bot or message.webhook_id:return "skipped"guild = message.guildmember = message.author if isinstance(message.author, discord.Member) else guild.get_member(message.author.id)if member is None and not sweep:return "skipped"if member is not None and is_exempt(member):return "skipped"urls = _image_urls_from_message(message)if not urls:return "skipped"async with aiohttp.ClientSession() as session:images = [img for img in [await _fetch_image(session, u) for u in urls] if img]if not images:return "failed"verdict = await _classify_images(session, [d for d, _ in images], message.content)if verdict is None:print(f"Image scan: every provider failed for message {message.id}")return "failed"is_mrbeast = verdict.get("mrbeast") is Trueis_scam = verdict.get("scam") is True6 unmodified lineshit = is_scam and confidence >= IMAGE_SCAN_MIN_CONFIDENCE and (is_mrbeast or not IMAGE_SCAN_REQUIRE_MRBEAST)if not hit:return "clean"user = member or message.authorlabel = "IMAGE SWEEP" if sweep else "IMAGE SCAN"# Discord deletes attachments along with the message, so keep our own copy as evidencefiles = [discord.File(io.BytesIO(jpeg), filename=f"evidence_{i + 1}.jpg") for i, (_, jpeg) in enumerate(images)]jump = f"https://discord.com/channels/{guild.id}/{message.channel.id}/{message.id}"details = (f"User: {user.mention} ({user.id}) in {message.channel.mention}, "f"posted {convert_to_timezone(message.created_at, zurich_tz)}\n"f"Verdict: mrbeast={is_mrbeast} scam={is_scam} confidence={confidence:.2f} via `{verdict['model']}`\n"f"Reason: {reason}\n[Jump to message!]({jump})")# a sweep can hit many old posts; on_member_ban already pings @alerts once per ban, so don't add a second pingalert = "" if sweep else {"True": "<@&1106995261487710411>", "False": "<@&1108342563628404747>"}.get(os.environ.get("TEST_SERVER"), "")if IMAGE_SCAN_DRY_RUN:action = "delete this post + auto-ban" if sweep else "auto-ban"await bot.log_channel.send(f"🧪 **[{label}, DRY RUN] would {action}**\n{details}", files=files)return "hit"if sweep:# a ban only clears the last 7 days of messages, so remove older scam posts directlytry:await message.delete()except discord.NotFound:passexcept Exception as e:print(f"Image sweep: could not delete message {message.id}: {e}")# claim the user before any await, so parallel scans of one burst (or a sweep) only ban onceif user.id in image_scan_banned_ids:return "hit"image_scan_banned_ids.add(user.id)try:await guild.fetch_ban(user)await bot.log_channel.send(f"🧹 **[{label}] removed scam post from an already-banned user**\n{details}", files=files)return "hit"except discord.NotFound:pass # not banned yetme = guild.meif not (me.guild_permissions.ban_members and (member is None or member.top_role < me.top_role)):image_scan_banned_ids.discard(user.id)await bot.log_channel.send(f"❌ {label} ban skipped (missing perms / role hierarchy)\n{details}", files=files)return "hit"try:await user.send(f"You have been automatically banned from **{guild.name}** because your account "f"posted scam images (this usually means the account was compromised). Secure your "f"account, then contact @Adam to appeal.")except Exception:passawait guild.ban(user,delete_message_seconds=604800 if sweep else 86400, # sweep: max 7 days; live: last 24h, every channelreason=f"Auto-ban ({label.lower()}): {reason}"[:512])await bot.log_channel.send(f"🚨 **AUTO-BANNED ({label.lower()})**\n{details}\n{alert}", files=files)return "hit"except Exception as e:print(f"scan_message_images Error: {e}")return "failed"# stats stuff ---------------------------------------------------------------------------------------------------------------------------------------------------------330 unmodified lines@bot.eventasync def on_member_unban(guild, unbanned_user):try:image_scan_banned_ids.discard(unbanned_user.id) # let the image scanner act again if the account is ever re-hijackedawait asyncio.sleep(5)async for entry in guild.audit_logs(action=discord.AuditLogAction.unban, limit=1):if unbanned_user == entry.target: # verify that unbanned user is in audit log265 unmodified linesawait ctx.send("\n".join(lines)[:1900])# !scansweep [days] scans image posts from the last N days (default 30) in every channel and thread,# with the same rules as the live scanner. Respects IMAGE_SCAN_DRY_RUN. Staff only, one sweep at a time.@bot.command(name="scansweep")async def scansweep(ctx, days: int = IMAGE_SWEEP_DEFAULT_DAYS):global _sweep_runningif not ctx.guild or not is_exempt(ctx.author):returnif not HF_TOKEN:await ctx.send("`HF_TOKEN` isn't set, so the image scanner is off.")returnif _sweep_running:await ctx.send("A sweep is already running.")return_sweep_running = Truetry:days = max(1, min(days, IMAGE_SWEEP_MAX_DAYS))guild = ctx.guildcutoff = discord.utils.utcnow() - timedelta(days=days)mode = "DRY RUN, log only" if IMAGE_SCAN_DRY_RUN else "LIVE, deletes and bans"header = f"🔎 Image sweep, last {days} days ({mode})"status = await ctx.send(f"{header}: collecting channels…")# everywhere messages can live: text channels, voice-channel chats, active threads, threads archived since the cutoffsources = list(guild.text_channels) + list(guild.voice_channels) + list(guild.threads)for parent in list(guild.text_channels) + list(getattr(guild, "forums", [])):try:async for th in parent.archived_threads(limit=None):if th.archive_timestamp and th.archive_timestamp < cutoff:break # newest-archived first, so everything after this is oldersources.append(th)except Exception as e:print(f"Image sweep: can't list archived threads in {parent}: {e}")sources = list({s.id: s for s in sources}.values()) # dedupe, keep ordercounts = {"messages": 0, "hit": 0, "clean": 0, "failed": 0, "skipped": 0}sem = asyncio.Semaphore(IMAGE_SWEEP_CONCURRENCY)async def scan_one(m):async with sem:counts[await scan_message_images(m, sweep=True)] += 1for i, src in enumerate(sources, 1):tasks = []try:async for m in src.history(limit=None, after=cutoff):counts["messages"] += 1if m.attachments or m.embeds or getattr(m, "message_snapshots", None):tasks.append(asyncio.create_task(scan_one(m)))except Exception as e:print(f"Image sweep: can't read {src}: {e}")if tasks:await asyncio.gather(*tasks)if tasks or i % 10 == 0 or i == len(sources):scanned = counts["hit"] + counts["clean"] + counts["failed"]try:await status.edit(content=f"{header}: {i}/{len(sources)} channels · {counts['messages']:,} messages · "f"{scanned:,} image posts scanned · {counts['hit']} scam hits")except Exception:passscanned = counts["hit"] + counts["clean"] + counts["failed"]await ctx.send(f"✅ Sweep done ({mode}): {counts['messages']:,} messages in {len(sources)} channels/threads, "f"{scanned:,} image posts scanned, **{counts['hit']} scam hits**, "f"{counts['failed']} couldn't be scanned. Each hit is logged in admin-logs with its images.")except Exception as e:print(f"scansweep Error: {e}")await ctx.send(f"❌ Sweep stopped with an error: `{e}`")finally:_sweep_running = False
app.py+141-31