#Need help on using a bot class instead of individual functions

1 messages · Page 1 of 1 (latest)

feral stream
#

I wanted to build my first discord bot yesterday and came across this library.
My first steps went pretty well, when I had all the code in one file.
But then I decided to structure it better and use classes for abstraction and organizing my code.
When using a class the library doesn't feel as easy to use anymore and one can't use those very useful decorators anymore.
I also struggled to find any information about using the lib with a class.

Just to put a short example here:

class Bot:
    def __init__(self, token: str):
        self.client = Client(token=token, intents=Intents.GUILDS)
        self.servers = ServerConfigs()

        self._setup_listeners()
        self._setup_commands()

    def _setup_listeners(self):
        self.client.add_listener(Listener(self._on_startup, "startup"))
        self.client.add_listener(Listener(self._on_ready, "ready"))
        self.client.add_listener(Listener(self._on_shutdown, "shutdown"))

For listeners it is not that bad, it gets worse for adding slash commands. Well not "worse", just more boilerplate-ish.

Is my issue understandable?

granite impBOT
#

Hey! Once your issue is solved, press the button below to close this thread!

sonic geyser
#

best way of structuring with this library is probably with extensions

sharp fog
# feral stream I wanted to build my first discord bot yesterday and came across this library. M...

in your main function, you can use:

if __name__ == "__main__":
    bot.load_extension("start_menu")
    bot.start()
``` to load a file called ``start_menu.py``
and then in ``start_menu.py`` you want to have:
```py
import interactions

class start_menu(interactions.Extension):
    def __init__(self, client):
        self.client: interactions.Client = client
        self._setup_listeners()
    
    @interactions.listen()
    async def on_startup(self):
        print("start_menu initialized")

    def _setup_listeners(self):
        self.client.add_listener(Listener(self._on_startup, "startup"))
        self.client.add_listener(Listener(self._on_ready, "ready"))
        self.client.add_listener(Listener(self._on_shutdown, "shutdown"))


def setup(client):
    start_menu(client)
feral stream
sharp fog
#

correct

#

mine looks like this:

import interactions

class start_menu(interactions.Extension):
    def __init__(self, client):
        self.client: interactions.Client = client
    
    @interactions.listen()
    async def on_startup(self):
        print("start_menu initialized")
    
    @interactions.slash_command(name="start")
    @interactions.contexts(guild=True, bot_dm=True, private_channel=True)
    @interactions.integration_types(guild=True, user=True)
    async def start(self, ctx: interactions.SlashContext):
        print(f"start - {ctx.author.id} - {ctx.guild_id} - {ctx.channel_id} ")
        # do stuff

def setup(client):
    start_menu(client)