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

discord.py开发Bot时discord.ext命令触发无响应该如何解决?

问题原因和修正方案

核心问题

你的命令不生效不是Discord API更新直接导致的,是代码逻辑存在多处错误,具体问题如下:

  • 运行实例不匹配:你定义了commands.Bot类型的bot实例用来写命令,但最后运行的是自己写的MyClient实例,bot全程没有启动,定义的test命令自然不会生效
  • 命令前缀不匹配:你给bot设置的前缀是$,但你测试的时候用的是.test,前缀对不上不会触发命令
  • 消息意图缺失:discord.py v2.0及以上版本要求显式开启消息内容意图才能读取用户消息,需要同时在代码和Discord开发者后台配置
  • 消息事件拦截:你自定义的on_message事件如果不主动触发命令处理逻辑,所有消息都会被你自己写的逻辑拦截,不会进入命令匹配流程
  • 冗余代码:你导入了没用的discord.ext.bot,还多次初始化无用的client实例,完全可以删除

注意事项

修改代码前需要先去Discord开发者后台,找到你的Bot应用,进入「Bot」选项卡,往下翻找到「Privileged Gateway Intents」,打开「Message Content Intent」的开关,否则Bot无法读取用户消息内容。

修改后的完整代码

import os
import discord
from dotenv import load_dotenv
from discord.ext import commands

# 加载环境变量
load_dotenv()
token = os.getenv("TOKEN")

# 配置意图,开启消息内容权限
intents = discord.Intents.default()
intents.message_content = True

# 初始化Bot,这里统一用.作为命令前缀,你也可以自行修改
bot = commands.Bot(command_prefix='.', intents=intents)

# 你原来的test命令
@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

@bot.event
async def on_ready():
    print('Logged on as {0}!'.format(bot.user))

@bot.event
async def on_message(message):
    # 跳过Bot自己发的消息,避免逻辑冲突
    if message.author == bot.user:
        return

    f = open("muteMsg.txt", "r")
    muteMsg = f.read()
    f.close()

    print('Message from {0.author}: {0.content}'.format(message))

    id = message.author.id
    # 注意这里的id == 0是无效的,需要替换为你实际要屏蔽的用户ID
    if id == 0:
        await message.delete()
        if muteMsg == "1":
            await message.channel.send(f"stfu {message.author.mention}")

    elif message.content.lower().startswith('good bot'):
        await message.channel.send(':)')

    elif message.content.lower().startswith('bad bot'):
        await message.channel.send(':(')

    elif message.content.startswith('.rickroll'):
        await message.channel.send('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

    elif message.content.startswith('.help'):
        await message.channel.send('commands list:\n.help: shows this\n.rickroll: well youll have to try yourself\n.test [内容]: 机器人返回你输入的内容\n.togglemutemsgs: 开关禁言提示')

    elif message.content.startswith('.togglemutemsgs'):
        if muteMsg == "0":
            f = open("muteMsg.txt", "w")
            f.write("1")
            f.close()
            await message.channel.send('mute messages on')
        elif muteMsg == "1":
            f = open("muteMsg.txt", "w")
            f.write("0")
            f.close()
            await message.channel.send('mute messages off')

    # 关键:自定义消息逻辑处理完成后,调用命令处理逻辑
    await bot.process_commands(message)

# 直接运行bot实例即可
bot.run(token)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:36:02