注意:
以下内容是为较旧的 0.16 版本编写的,该版本没有良好的 cogs 文档。新的 1.0 版本有很好的文档,并且完全改变了 cogs 的结构。如果您使用的是现代版本的discord.py,您应该咨询official documentation。
简介
每个 cog 都有两部分:一个类和一个setup 函数。几乎所有setup 函数看起来都一样:
def setup(bot):
bot.add_cog(Cog(bot))
Cog 是 cog 类。
cog 类包含我们所有的命令和事件作为方法。
主要变化
您需要进行四个主要的转换才能将您的机器人变成一个齿轮:
将bot.command 替换为commands.command(commands 是from discord.ext import commands)
更改函数的签名以在开头包含 self,因为您的所有命令和事件现在都是 cog 类的方法
将所有对bot的引用改为引用self.bot
删除所有 bot.event 装饰器。您的 cog 中的事件侦听器仅在名称上注册
还有一些陷阱:
从 cog 中的任何 on_message 事件中删除 await bot.process_commands(message)。对于任何消息,这应该只等待一次。默认的on_message 已经为您完成了这项工作。
通过 cog 注册事件不会从您的主文件或其他 cog 中删除与该事件相关的其他回调。这意味着您的机器人可以多次响应 on_member_join 事件,例如,如果您在多个位置定义了该事件的行为。
示例
假设您在目录src 中有以下discord.py 机器人bot.py:
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.command(pass_context=True)
@commands.has_role("Mod")
async def acommand(ctx, argument):
await bot.say("Stuff")
@bot.event
async def on_message(message):
print(message.content)
await bot.process_commands(message)
bot.run("token")
然后您将该功能分解为一个 cog src/cogs/maincog.py
from discord.ext import commands
class MainCog:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
@commands.has_role("Mod")
async def acommand(self, ctx, argument):
await self.bot.say("Stuff")
async def on_message(self, message):
print(message.content)
def setup(bot):
bot.add_cog(MainCog(bot))
你的bot.py 文件看起来像
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
bot.load_extension("cogs.maincog")
bot.run("token")
请注意,要在cogs/maincog.py 加载扩展,我们使用load_extension("cogs.maincog")。
其他功能
Cogs 还允许你定义一些特殊的方法。其中大部分仅在discord.py-rewrite 中可用,并记录在here。
__global_check,以前的 __check,在每个命令之前运行,并且必须返回 True 才能继续执行该命令。
__local_check 仅在来自此 cog 的命令之前运行。
__global_check_once 我相信这类似于__global_check,只是它只在子命令的情况下检查一次。我没用过这么多。
__unload 您可以通过卸载扩展程序,然后重新加载它来实时刷新您的机器人,这样您就可以在不让机器人离线的情况下更新您的 cogs。当您卸载扩展程序或当您的机器人停止运行时调用此方法,以防您需要进行清理。
__before_invoke 和 __after_invoke 分别在来自该 cog 的每个命令之前和之后运行。
__error 是来自此 cog 的命令的错误处理程序。