如何在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
相关产品推荐
相关产品推荐

