是否可以使用不带齿轮的 discord.py 进行面向对象编程?

Axy*_*yss 7 python python-3.x discord discord.py discord.py-rewrite

最近几天,我一直在尝试将用 discord.py 编写的 discord bot 的结构调整为更面向 OOP 的结构(因为放置函数并不理想)。

但我发现这样多的问题,我可以曾经预计,事情是,我想我的所有命令封装到一个单一的类,但我不知道什么装饰使用和如何,我必须继承哪些类。

到目前为止,我已经实现了一个类似于下面的代码,它运行但在执行命令的那一刻它抛出这样的错误:discord.ext.commands.errors.CommandNotFound:找不到命令“状态”

PD:我使用的是 Python 3.6

from discord.ext import commands


class MyBot(commands.Bot):

    def __init__(self, command_prefix, self_bot):
        commands.Bot.__init__(self, command_prefix=command_prefix, self_bot=self_bot)
        self.message1 = "[INFO]: Bot now online"
        self.message2 = "Bot still online {}"

    async def on_ready(self):
        print(self.message1)

    @commands.command(name="status", pass_context=True)
    async def status(self, ctx):
        print(ctx)
        await ctx.channel.send(self.message2 + ctx.author)


bot = MyBot(command_prefix="!", self_bot=False)
bot.run("token")
Run Code Online (Sandbox Code Playgroud)

小智 11

要注册您应该使用的命令self.add_command(setup),但您不能selfsetup方法中使用参数,因此您可以执行以下操作:

from discord.ext import commands
    
class MyBot(commands.Bot):
    
    def __init__(self, command_prefix, self_bot):
        commands.Bot.__init__(self, command_prefix=command_prefix, self_bot=self_bot)
        self.message1 = "[INFO]: Bot now online"
        self.message2 = "Bot still online"
        self.add_commands()
    
    async def on_ready(self):
        print(self.message1)
    
    def add_commands(self):
        @self.command(name="status", pass_context=True)
        async def status(ctx):
            print(ctx)
            await ctx.channel.send(self.message2, ctx.author.name)
        
        self.add_command(status)
    
bot = MyBot(command_prefix="!", self_bot=False)
bot.run("token")
Run Code Online (Sandbox Code Playgroud)

  • 如果有人发现此内容并收到“discord.ext.commands.errors.CommandRegistrationError:命令状态已经是现有命令或别名。”或“discord.ext.commands.errors.CommandInvokeError:命令引发异常:TypeError: send() 需要 1 到 2 个位置参数,但给出了 3 个错误,请尝试删除 self.add_command(status) 并将发送行更新为 wait ctx.channel.send(f'{self.message2}, { ctx.author.name}')` 这对我有用。 (3认同)