Skip to content
Advertisement

What is the difference between having a main bot class versus no class on discord py?

With discord python bots, I can’t seem to find a great answer on this and the documentation actually uses both examples randomly. What is the main difference between using a bot class in your bot.py versus starting your bot without a class? See below for an example

Example bot with a class:

import discord
from discord.ext import commands

class MyBot(commands.Bot):
    async def on_ready():
        # ready
bot = MyBot(command_prefix='!')
bot.run(token)

Example of a regular bot without the class:

import discord
from discord.ext import commands

if __name__ == "__main__":
    bot = commands.Bot(command_prefix='!')
    async def on_ready():
        # ready
    bot.run(token)

As far as I know, both of these examples work and do the same thing, but like I said I can’t seem to find a great answer to the differences between the two.

Advertisement

Answer

Creating your own class has a couple of advantages.

First, you will be able to import your MyBot class in another file. So if you want to split up your project into multiple files (maybe two people are working on the same project) one person can work on the MyBot class while another can import it.

my_bot.py

import ...

class MyBot(commands.Bot):
    ...

test.py

from my_bot import MyBot

bot = MyBot()

Second, you will be able to more easily change functions inside of MyBot. Right now your async def on_ready(): function doesn’t do anything in the second example, even if there was code in it. If you put it inside of a MyBot class it will be called when your bot is ready. See on_ready()

Compare

class MyBot(commands.Bot):
    async def on_ready():
        print('connected to server!')

bot = MyBot(command_prefix='!')
bot.run(token)

to

if '__name__' == '__main__':
    bot = commands.Bot(command_prefix='!')
    async def on_ready():
        print('connected to server!')
    bot.run(token)

In the second example, it will never say “connected to server!” because that code won’t run. And if you call it with on_ready() that doesn’t really mean you were connected to the server. Turn off your internet connection and you’ll see.

Of course, you might do something more useful than just printing a message of course. Maybe you’ll write connection logs to a file or something.

Advertisement