为多个机器人加载cog

Ben*_*jin 8 python python-3.x discord discord.py

使用discord.py,我可以从一段代码运行多个机器人,但我正在寻找一种方法将cog或扩展加载到多个机器人.对于一个测试用例,我有bot.py,它处理加载cog并启动bot,cog.py这是一个简单的cog,逐渐增加1到一个计数器

bot.py

from discord.ext import commands
import asyncio

client1 = commands.Bot(command_prefix='!')
client2 = commands.Bot(command_prefix='~')

client1.load_extension('cog')
client2.load_extension('cog')

@client1.event
async def on_ready():
    print('client1 ready')

@client1.command()
async def ping():
    await client1.say('Pong')

@client2.event
async def on_ready():
    print('client2 ready')

@client2.command()
async def ping():
    await client2.say('Pong')

loop = asyncio.get_event_loop()
loop.create_task(client1.start('TOKEN1'))
loop.create_task(client2.start('TOKEN2'))
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)

cog.py

from discord.ext import commands

class TestCog:

    def __init__(self, bot):
        self.bot = bot
        self.counter = 0

    @commands.command()
    async def add(self):
        self.counter += 1
        await self.bot.say('Counter is now %d' % self.counter)


def setup(bot):
    bot.add_cog(TestCog(bot))
Run Code Online (Sandbox Code Playgroud)

使用!pingclient1使用Pong 做出响应,而使用时~ping会对client2Pong 做出响应,这是预期的行为.

但是,只有一个机器人会对这两个机器人做出响应,!add并且~add计数器会随着任何一个命令而增加.这似乎取决于哪个机器人最后加载cog.

有没有办法让正确的机器人响应正确的命令,同时使用任一命令增加计数器?我知道我可以将它分成两个嵌套并将结果保存到文件中,但是可以在不将计数器保存到磁盘的情况下进行吗?

abc*_*ccd 3

这是因为@commands.command()仅加载一次。因此,两个机器人共享同一个Command实例。您需要的是在实例级别添加命令,而不是通过@commands.command()装饰器添加命令。

class TestCog:
    counter = 0

    def __init__(self, bot):
        self.bot = bot
        self.bot.add_command(commands.Command('add', self.add))

    async def add(self):
        TestCog.counter += 1
        await self.bot.say('Counter is now %d' % TestCog.counter)
Run Code Online (Sandbox Code Playgroud)

或者:

class TestCog:
    counter = 0

    def __init__(self, bot):
        self.bot = bot
        self.bot.command()(self.add)

    async def add(self):
        TestCog.counter += 1
        await self.bot.say('Counter is now %d' % TestCog.counter)
Run Code Online (Sandbox Code Playgroud)

为了使两个机器人共享相同的属性。您需要类属性,而不是实例属性。