You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py实现垃圾账号softban后如何在提示中展示被封禁用户

修改后实现带用户标识的封禁提示方案

核心调整逻辑

  • 事件触发时已经天然持有被判定为垃圾账号的用户对象message.author,不需要额外发起API查询就能拿到完整的用户身份信息,直接把固定提示文本替换成动态拼接的用户相关内容即可。
  • 同步新增本地持久化操作日志,解决softban清理消息后无法追溯操作记录、用户身份的问题。

完整修改后代码

import asyncio
import datetime

@bot.event
async def on_message(message):
    # 过滤机器人自身消息,避免自触发误判
    if message.author.bot:
        return
    counter = 0
    # 提前把目标用户对象存入变量,避免后续上下文变动丢失引用
    target_user = message.author
    with open("spam_detect.txt", "r+", encoding="utf-8") as file:
        for lines in file:
            if lines.strip("\n") == str(target_user.id):
                counter += 1
        # 追加当前用户ID到计数文件
        file.writelines(f"{str(target_user.id)}\n")

        if counter > 5:
            await message.guild.ban(
                target_user,
                reason="Spammer",
                delete_message_days=1
            )
            await asyncio.sleep(5)
            await message.guild.unban(target_user)
            # 动态拼接带用户信息的提示文本
            notify_content = f"{target_user.mention}(用户名:{target_user.name},ID:{target_user.id})因spam被封禁"
            await message.channel.send(notify_content)
            # 写入本地操作日志,实现操作可追溯
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            with open("spam_operation_log.txt", "a", encoding="utf-8") as log_handle:
                log_handle.write(f"[{current_time}] 对用户 {target_user.name}(ID:{target_user.id}) 执行软封禁操作,原因:Spammer\n")
            print(f"已封禁用户 {target_user.name},操作时间:{current_time}")

关键改动说明

  • 替换原固定提示逻辑:把原来硬编码的"Banned for spam"替换为包含用户@提及、用户名、用户ID的动态文本,频道内用户可以直接识别被处理的对象。
  • 新增独立日志文件spam_operation_log.txt,每次软封禁操作发生时,自动把操作时间、用户身份、操作原因写入本地文件,就算softban把频道内的所有相关消息都清理掉,本地留存的日志也能完整追溯操作记录。
  • 新增机器人自身消息过滤逻辑,避免机器人发出的消息被误纳入垃圾计数,触发不必要的封禁流程。

内容的提问来源于stack exchange,提问作者Mihai Cristian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 22:27:07