不带齿轮的discord.py是否可以使用OOP?

问题描述

最近几天,我一直在尝试将用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")

解决方法

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

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)
    
bot = MyBot(command_prefix="!",self_bot=False)
bot.run("token")
,

我遇到了同样的问题,今天找到了这个解决方法。但是我写了另一个代码,没有使用添加命令的方法,更简单的像这样:

from discord.ext import commands

class DiscordBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="!")

        @self.command(name='test')
        async def custom_command(ctx):
            print("Hello world !")

    async def on_ready(self):
        print(f"Bot {self.user.display_name} is connected to server.")

bot = DiscordBot()
bot.run("token")

这个解决方案对我有用,我希望它可以帮助到这里的人

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...