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

Discord.py编写的机器人无法响应问候关键词问题求助

问题排查与修复方案

问题原因

  • 你定义的on_message消息处理函数没有添加@client.event装饰器,discord.py的事件调度系统无法识别该回调,因此发送匹配关键词的消息时不会触发对应逻辑。
  • 补充装饰器后若不额外添加命令处理逻辑,会覆盖框架默认的消息处理流程,导致你之前编写的_hello前缀命令完全失效。
  • 未添加机器人自身消息过滤逻辑,可能出现机器人自己触发关键词导致死循环的问题。

修复代码

将你的on_message部分代码替换为以下内容即可:

@client.event # 新增事件装饰器
async def on_message(message):
    # 过滤机器人自身发送的消息,避免死循环
    if message.author == client.user:
        return
    msg = message.content.lower()
    if msg in gret_words:
        await message.channel.send("Nice to see you!")
    # 保留命令处理能力,确保hello等前缀命令正常生效
    await client.process_commands(message)

完整可运行代码示例

import discord
from discord.ext import commands

client = commands.Bot(command_prefix='_')

gret_words = ['hi', 'grets', 'greetings', 'mornin', 'hey']

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

@client.command(pass_context=True)
async def hello(ctx):
    author = ctx.message.author
    await ctx.send(f'Hello, {author.mention}! My name is Bot-3P0!')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    msg = message.content.lower()
    if msg in gret_words:
        await message.channel.send("Nice to see you!")
    await client.process_commands(message)

client.run('TOKEN')

注:替换TOKEN为你自己的机器人令牌即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 07:45:04