Skip to main content
 首页 » 编程设计

python之我无法使用 discord.py 向我的 discord 机器人添加命令

2024年09月07日9jirigala

这是我的代码:

from discord.ext import commands 
import discord 
import config 
 
class Bot(commands.AutoShardedBot): 
 
    def __init__(self): 
        super().__init__(command_prefix="~") 
 
    @commands.command() 
    async def test(self, ctx): 
        await ctx.send("some random text") 
 
    def run(self): 
        super().run(config.TOKEN) 
 
 
if __name__ == "__main__": 
    bot = Bot() 
    bot.run() 

所以现在,当我键入 ~test 时,它应该以 一些随机文本 响应,但相反,此错误消息会在终端中弹出:

Ignoring exception in command None: 
discord.ext.commands.errors.CommandNotFound: Command "test" is not found 

我不明白我做错了什么。

请您参考如下方法:

Discord.py 目前无法自动注册由 @commands.command() 装饰的 Client 子类的命令。但是,您仍然可以在 __init__ 或将要运行的任何地方手动添加它们:

class Bot(commands.AutoShardedBot): 
 
    def __init__(self): 
        super().__init__(command_prefix="~") 
        self.add_command(commands.Command("test", self.test)) 
        # or uglier: 
        self.command()(self.test) 
 
    async def test(self, ctx): 
        await ctx.send("some random text") 

如果你愿意,你仍然可以使用装饰器(我更喜欢这种方式,因为它更简单):

class Bot(commands.AutoShardedBot): 
 
    def __init__(self): 
        super().__init__(command_prefix="~") 
        self.add_command(self.test) 
 
    @commands.command() 
    async def test(self, ctx): 
        await ctx.send("some random text") 

如果您要有很多初始命令并且懒得为每个命令调用 add_command,您可以执行以下操作:

import inspect 
 
class Bot(commands.AutoShardedBot): 
    def __init__(self): 
        super().__init__(command_prefix="~") 
 
        members = inspect.getmembers(self) 
        for name, member in members: 
            if isinstance(member, commands.Command): 
                if member.parent is None: 
                    self.add_command(member) 
 
    @commands.command() 
    async def test(self, ctx): 
        await ctx.send("some random text") 
 
    @commands.command() 
    async def test2(self, ctx): 
        await ctx.send("some random text2") 
 
    @commands.command() 
    async def test3(self, ctx): 
        await ctx.send("some random text3")