为多个机器人程序加载cog

2024-05-21 01:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

使用discord.py,我可以从一段代码运行多个bot,但是我正在寻找一种方法将cog或扩展加载到多个bot中。对于一个测试用例,我有bot.py,它负责加载cog并启动bot,而{}是一个简单的cog,它递增地向计数器添加1

机器人.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()

齿轮副

^{pr2}$

使用!ping将使client1响应Pong,而使用~ping将使{}响应Pong,这是预期的行为。在

但是,只有一个bot将同时响应!add~add,并且计数器会随任意一个命令而增加。这似乎取决于哪个机器人最后加载齿轮。在

有没有办法让正确的机器人响应正确的命令,同时让计数器增加任何一个命令?我知道我可以把它分成两个齿轮,然后把结果保存到一个文件中,但是有没有可能不把计数器保存到磁盘上呢?在


Tags: pyloopasyncdefbot计数器机器人ping
1条回答
网友
1楼 · 发布于 2024-05-21 01:47:24

这是因为@commands.command()只加载了一次。因此,两个bot共享相同的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)

或者:

^{pr2}$

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

相关问题 更多 >