最近几天,我一直在尝试将用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")
答案 0 :(得分:5)
要注册命令,您应该使用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")
答案 1 :(得分:1)
我遇到了同样的问题,今天找到了这个解决方法。但是我写了另一个代码,没有使用添加命令的方法,更简单的像这样:
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")
这个解决方案对我有用,我希望它可以帮助到这里的人