You need to enable JavaScript to run this app. discord.py中@client.command功能失效,register命令运行无反应
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中@client.command功能失效,register命令运行无反应

问题根因与修复方案

1. 命令装饰器写法错误

discord.py中的@client.command是装饰器工厂函数,必须加括号调用后才能返回真正的装饰器,当前代码里无括号的写法,根本不会把register函数注册为Bot的可执行命令。
对应错误代码段:

# 错误写法
@client.command
async def register(ctx, arg1, arg2):
    await ctx.send(arg2, arg1)

修正时需要同步解决两个细节问题:

  • 给装饰器补上括号
  • ctx.send()方法仅支持第一个位置参数为待发送的内容字符串,原代码传入两个独立位置参数的写法会触发类型错误,需要将两个参数拼接为字符串后传入
    修正后的代码:
@client.command()
async def register(ctx, arg1, arg2):
    await ctx.send(f"{arg1} {arg2}")

2. 覆写on_message事件后未触发命令解析流程

discord.py默认的on_message内置逻辑,会在收到消息后自动解析命令前缀、匹配已注册的命令并执行。自定义on_message的处理逻辑后,会完全覆盖默认的事件流程,导致所有注册的自定义命令都不会被触发。
需要在on_message函数的末尾,手动补上命令解析的调用:

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith("!instagram"):
        await message.channel.send('https://www.instagram.com')
    if message.content.startswith("!youtube"):
        await message.channel.send("https://www.youtube.com/channel/fsaf!212faf")
    # 新增这行代码,恢复命令解析流程
    await client.process_commands(message)

补充排查点

  • 确认Discord开发者后台已开启Message Content Intent,否则Bot无法读取消息内容,连手写的!instagram这类前缀判断逻辑都无法正常触发
  • 确保调用register命令时的格式符合要求:需要按照!register 参数1 参数2的格式传入两个独立参数,缺参会直接导致命令执行失败且无反馈
  • 冗余代码优化:初始化Bot时无需重复创建intents实例,可以复用之前定义的intents变量:client = commands.Bot(command_prefix='!', intents=intents)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 03:24:07