問題描述
最近幾天,我一直在嘗試將用 discord.py 編寫的不和諧機器人的結構調整為更面向 OOP 的結構(因為周圍有功能并不理想).
These last few days, I've been trying to adapt the structure of a discord bot written in discord.py to a more OOP one (because having functions lying around isn't ideal).
但我發現的問題比我想象的要多得多.問題是我想將所有命令封裝到一個單個類中,但我不知道要使用哪些裝飾器以及我必須繼承哪些類以及如何繼承.
But I have found way more problems that I could have ever expected. The thing is that I want to encapsulate all my commands into a single class, but I don't know what decorators to use and how and which classes I must inherit.
到目前為止,我所取得的成果是類似于下面的代碼片段.它會運行,但在執行命令時會拋出類似
What I've achieved so far is code like the snippet down below. It runs, but at the moment of executing a command it throws errors like
discord.ext.commands.errors.CommandNotFound:命令狀態"沒找到
discord.ext.commands.errors.CommandNotFound: Command "status" is not found
我使用的是 Python 3.6.
I'm using 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
方法中的/code> 參數,因此您可以執行以下操作:
To register the command you should use self.add_command(setup)
, but you can't have the self
argument in the setup
method, so you could do something like this:
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")
這篇關于使用不帶 cogs 的 discord.py 是否可以實現 OOP?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!