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

discord.py违规词过滤功能失效如何修复?机器人上线后不删除敏感词

问题原因排查

    1. delete是异步方法,你代码里漏写了调用括号,await msg.delete 实际没有执行删除操作,正确写法是await msg.delete()
    1. client.process_commands(msg) 缩进层级错误,目前只有触发敏感词的消息才会执行命令处理,正常消息的命令会全部失效,且该逻辑不需要放在敏感词判断分支内
    1. 缺少基础过滤逻辑,比如没有排除机器人自身发送的消息,可能触发误删逻辑
    1. 当前敏感词匹配是大小写敏感的,用户发送大写、大小写混合的违规词会绕过检测

修正后的完整代码

import os
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions, is_owner

# 开启消息内容意图,discord.py v2.0+ 必须开启才能读取消息内容,同时要在discord开发者后台开启对应权限
intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='/', intents=intents, status=discord.Status.idle)

@client.command()
async def ban(ctx, member: discord.Member, reason=None):
    await member.ban(reason=reason)
    await ctx.send(f"{member} was banned by {ctx.author.name} for reason {reason}")
    
@client.command()
async def kick(ctx, member: discord.Member,reason=None):
  await member.kick(reason=reason)
  await ctx.send(f"{member} was kicked by {ctx.author.name} for reason {reason}")

@client.command(aliases=['m'])
async def mute(ctx,member : discord.Member):
  muted_role = ctx.guild.get_role(905765835791036477)
  await member.add_roles(muted_role)
  await ctx.send(member.mention + "has been muted")

# 填入实际的违规敏感词
filtered_words = ["填你实际要过滤的N词、NSFW词等"]
# 转成小写做大小写不敏感匹配
filtered_words = [w.lower() for w in filtered_words]

@client.event
async def on_message(msg):
  # 跳过机器人自身发的消息
  if msg.author.bot:
    return
  # 转成小写匹配
  msg_content = msg.content.lower()
  for word in filtered_words:
    if word in msg_content:
      # 加括号调用delete方法
      await msg.delete()
      # 可以加个发送提示,需要的话就取消注释
      # await msg.channel.send(f"{msg.author.mention} 请勿发送违规内容", delete_after=3)
      # 已经删除违规消息,不需要再处理对应命令,直接返回
      return
  # 所有正常消息都要执行命令处理,放在最外层
  await client.process_commands(msg)

@client.event
async def on_ready():
 print('we have logged in as {0.user}'.format(client))

my_secret = os.environ['Token']
client.run(my_secret)

额外注意事项

  • 你使用的如果是discord.py 2.0及以上版本,必须在Discord开发者后台的对应机器人设置页,开启Message Content Intent权限,否则机器人无法读取用户消息内容,自然无法检测敏感词
  • 请确保机器人在服务器中拥有管理消息权限,否则无法执行删除消息的操作

内容的提问来源于stack exchange,提问作者Mixu lol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:57:03