python – 为多个机器人加载cog

栏目: Python · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/49302170/load-cog-for-multiple-bots

使用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()

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))

使用!ping将使client1响应Pong,而使用~ping将使client2响应Pong,这是预期的行为.

但是,只有一个机器人会同时响应!add和~add,计数器会随着任一命令而增加.这似乎取决于哪个机器人最后加载cog.

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

这是因为@ 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)

要么:

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)

为了使两个机器人共享相同的属性.你想要class属性,而不是实例.

翻译自:https://stackoverflow.com/questions/49302170/load-cog-for-multiple-bots


以上所述就是小编给大家介绍的《python – 为多个机器人加载cog》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

若为自由故

若为自由故

[美] Sam Williams / 邓楠、李凡希 / 人民邮电出版社 / 2015-4 / 49

理查德·马修·斯托曼(Richard Matthew Stallman,简称RMS)是自由软件之父,他是自由软件运动的精神领袖、GNU计划以及自由软件基金会的创立者。作为一个著名的黑客,他的主要成就包括Emacs及后来的GNU Emacs、GNU C 编译器及GDB 调试器。他编写的GNU通用公共许可证(GNU GPL)是世上最广为采用的自由软件许可证,为copyleft观念开拓出一条崭新的道路。......一起来看看 《若为自由故》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具