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

discord.py开发机器人时on_message事件导致命令失效如何解决

故障根因

你重复定义了两次on_message事件,后定义的敏感词检测on_message会覆盖前一个。且第二个on_message未调用await client.process_commands(message),discord.py不会将消息转发给自定义命令处理器,因此所有@client.command装饰的命令都会失效。

修复步骤
  • 合并两个on_message的逻辑,不要分开多次定义同一事件
  • 敏感词检测执行完成后补充命令处理调用,保证合法消息可以触发对应命令
  • 修正命令回调的参数定义,discord.py的命令回调第一个参数默认是上下文对象ctx,原代码中写为message属于参数错误
修复后完整代码
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    general_channel = client.get_channel(874180398475804695)
    await general_channel.send('I am ready',delete_after=10)

@client.event
async def on_message(message):
    # 过滤机器人自身发送的消息
    if message.author == client.user:
        return
    # 敏感词检测逻辑
    if any(word in message.content for word in rude_word):
        await message.reply('Hey man, that word is not allowed here .',delete_after=2)
        await message.delete()
        # 敏感消息不需要触发后续命令,直接返回
        return
    # 转发合法消息给命令处理器
    await client.process_commands(message)

@client.command(name='ping')
async def ping(ctx):
    await ctx.reply('pong')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:27:00