Skip to content

Instantly share code, notes, and snippets.

@Soheab
Last active August 3, 2026 15:44
Show Gist options
  • Select an option

  • Save Soheab/cf387b753da32eb02f3228c2e32bb03f to your computer and use it in GitHub Desktop.

Select an option

Save Soheab/cf387b753da32eb02f3228c2e32bb03f to your computer and use it in GitHub Desktop.
Read here how "self.bot" works in a discord.py cog. For a tag called `?tag self.bot` on the dpy server.

What is self.bot and how does it work?

TLDR: it's a custom attribute which you define.

self = class instance
bot = attribute that's usually assigned to the bot instance given in an extension's setup function.

Basically:

class MyCog(Cog):
    # this function is called when we do MyCog()
    # our function takes 2 parameters but self is passed by Python so it has 1 in this case
    # it takes one argument called "bot"
    # just because it's called "bot" it doesn't mean that it's the actual bot instance
    def __init__(self, bot):
        # assign the passed value to the "bot" parameter to a matching variable called "bot"
        bot = bot
        # bot = bot?? That doesn't look right?
        # well it indeed doesn't make sense because "bot" is already defined.. -
        # - but we want to access it OUTSIDE this function.. that's what we can use "self" for
        # since "self" is passed to all functions INSIDE this class, so let's assign it
        self.bot = bot
        # NOW we can access it OUTSIDE this function and INSIDE the class as "self.bot"

    # let's define a function as an example that prints the attribute
    # this function doesn't take any arguments
    def print_bot(self):
        print(self.bot)


# let's define a setup function which is required for an extension
async def setup(bot):
    # notice how this function has 1 parameter called "bot"
    # that's because the library calls this function with one argument which is our bot instance
    # library: await setup(bot)
    # now we can do anything we want inside the function like call "bot".add_cog with the class instance
    # let's assign the class instance to a variable called "cog" and pass the "bot" as required in the "__init__"
    cog = MyCog(bot)
    # notice how we passed the bot to the class like (bot)
    # let's call our custom print_bot function and see what it prints
    cog.print_bot()
    # should've printed something like:
    # <object at 0x........>
    # but what if we pass something else to MyCog like "hello":
    cog = MyCog("hello")
    # and call the method again:
    cog.print_bot()
    # definitely printed:
    # hello
    
    ... # call add_cog like normal
    

Hope you know what self.bot is and how it works now.

Does it have to be called bot?

No, of course not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment