python - 使用不带 cogs 的 discord.py 是否可以实现 OOP?
问题描述
最近几天,我一直在尝试将用 discord.py 编写的不和谐机器人的结构调整为更面向 OOP 的结构(因为周围存在功能并不理想)。
但是我发现了更多我可以预料到的问题。问题是我想将所有命令封装到一个类中,但我不知道要使用哪些装饰器以及我必须继承哪些类以及如何继承。
到目前为止,我所取得的成果是下面的代码片段。它运行,但在执行命令的那一刻,它会抛出错误,如
discord.ext.commands.errors.CommandNotFound:找不到命令“状态”
我正在使用 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)
self.add_command(status)
bot = MyBot(command_prefix="!", self_bot=False)
bot.run("token")
推荐阅读
- css - 如何从 material-ui AppBar 的一小部分上删除高程(框阴影)?
- javascript - Discord.js - 存储每个人的响应
- c - 以 argv[0] 为 NULL 调用 C 程序
- javascript - 使用 Ratchet 和 CakePHP 创建一个 Web Socket 服务器
- node.js - 从 Lambda 函数运行时从 Mailchimp Transactional 获取超时
- java - DatabaseReference setValue 像在循环中一样工作
- javascript - 尝试为类别或标签构建模板页面时,我在 gatsby-node 中误解了什么?
- keras - TypeError:检查模型时出错:数据应该是 Numpy 数组,或 Numpy 数组的列表/字典
- javascript - 更改嵌入文本的颜色
- javascript - 即使extendedProp存在,Fullcalendar 5外部事件下降到资源时间线也会返回未定义