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

discord.py中第二个@client.event无法生效,求原因及解决方法

解决Discord.py中多个on_message事件覆盖导致功能失效的问题

你遇到的问题是因为重复定义了on_message事件,discord.py中同一个事件的装饰器只能绑定一个处理函数,后面定义的on_message会直接覆盖前面的,所以第一个处理@提及的逻辑根本不会被执行。

解决方法很简单,把两个on_message的逻辑合并到同一个函数里即可,注意处理顺序:先排除机器人自身的消息,再依次处理不同的触发条件。

修改后的代码如下:

import discord
import random

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

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

@client.event
async def on_message(message):
    # 先排除机器人自己发的消息,避免循环触发
    if message.author == client.user:
        return
    
    # 处理@提及机器人的情况
    if client.user.mentioned_in(message):
        await message.channel.send("hi!")
    
    # 处理$ask命令
    if message.content.startswith('$ask'):
        possible_responses = [
            'It is certain.',
            'It is decidedly so.',
            'Without a doubt.',
            'Yes - definitely.',
            'You may rely on it.',
            'As I see it, yes.',
            'Most likely.',
            'Outlook good.',
            'Yes.',
            'Signs point to yes.',
            'Reply hazy, try again.',
            'Ask again later.',
            'Better not tell you now.',
            'Cannot predict now.',
            'Concentrate and ask again.',
            'Don\'t count on it.',
            'My reply is no.',
            'My sources say no.',
            'Outlook not so good.',
            'Very doubtful.',
        ]
        await message.channel.send(random.choice(possible_responses))

# 替换为你的机器人token
client.run("YOUR_BOT_TOKEN")

另外可以清理掉代码中未使用的导入(from discord.ext import commands、from random import choice),让代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:53:29