1
votes

I need to use the same object in multiple extensions (cogs). How to edit my simple bot example to achieve this?

I can initiate SHARED_OBJECT in my main.py or in cog files also. The main point is to use the same object in COG1 and COG2 extensions. It is important to consider that every extension can be reloaded after program start.

I'm using discord.py rewrite lib

main.py

client = Bot(description="Bot", command_prefix="!")
client.run(__token__)    
SHARED_OBJECT = SomeObject()


@client.event
async def on_ready():
    client.dev = True
    print('[Discord] Logged in as {} (ID:{}) | Connected to {}  servers'.format(client.user.name,client.user.id,1))

    client.load_extension('COG1')
    client.load_extension('COG2')

COG1.PY class

class COG1():
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def test(self):
    print()

def setup(bot):
    bot.add_cog(COG1(bot))

COG1.PY class

class COG2():
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def test(self):
    print("test")

def setup(bot):
    bot.add_cog(COG2(bot))
1

1 Answers

0
votes

If your cogs all rely on this shared object, then you should ask yourself if their functionality is really independent enough to be split into different modules.

That said, if you write your own load_extension, then you can write setup methods that take this shared object and pass it to the class __init__. I cribbed the below off the actual implementation, removing some of the validations for brevity.

cog1.py: (same changes to cog2)

class COG1():
    def __init__(self, bot, sharedobj):
        self.bot = bot
        self.sharedobj = sharedobj

    @commands.command()
    async def test(self):
        print()

def setup(bot, sharedobj):
    bot.add_cog(COG1(bot, sharedobj))

main.py

import importlib

def load_extension(name, bot, sharedobj):
    if name in self.extensions:
        return
    lib = importlib.import_module(name)
    lib.setup(bot, sharedobj)
    bot.extensions[name] = lib

SHARED_OBJECT = SomeObject()

load_extension('COG1', SHARED_OBJECT)
load_extension('COG2', SHARED_OBJECT)