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

如何在discord.py的Bot类中添加commands命令?

解决方案

要在你的类结构中使用discord.ext.commands的命令系统,最简洁的方式是让你的Bot类继承commands.Bot而非discord.Client——因为commands.Bot本身就是discord.Client的子类,完全兼容你原来的事件逻辑,同时原生支持命令装饰器。

修改后的完整代码示例:

import discord
from discord.ext import commands

class Bot(commands.Bot):
    def __init__(self, command_prefix, intents):
        # 调用父类构造方法,传入命令前缀和意图
        super().__init__(command_prefix=command_prefix, intents=intents)

    async def on_ready(self):
        debug_channel_id = 123456789  # 替换为你的实际调试频道ID
        debug = self.get_channel(debug_channel_id)
        
        print("Bot ready")
        await debug.send("Bot ready")
        
        # 类内部使用self引用当前Bot实例,替换原来的client
        await self.change_presence(status=discord.Status.online, activity=discord.Game("A game"))

    # 命令方法需将self作为第一个参数(类实例方法要求),之后是ctx和命令参数
    @commands.command()
    async def test(self, ctx, arg):
        await ctx.send(f"test command received: {arg}")

# 初始化并启动Bot
# 注意:必须开启对应意图才能接收消息,这里开启消息内容意图
intents = discord.Intents.default()
intents.message_content = True

bot = Bot(command_prefix="!", intents=intents)
bot.run("你的Bot令牌")

关键说明:

  • 继承commands.Bot后,你可以继续使用所有discord.Client的事件方法(如on_ready、on_message),同时直接用@commands.command()装饰类内部的方法
  • 类中的命令方法必须包含self参数,因为这是类的实例方法,ctx(上下文)作为第二个参数传入
  • 务必配置正确的Discord意图(Intents),当前Discord要求必须开启message_content意图才能接收命令消息
  • 类内部操作Bot实例时,要用self替代原来的全局client变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:22:44