very-cool-group

if-name-main

This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__ special variable is automatically set to the string '__main__'. Conversely, when you import that same module into a different one, and run that, __name__ is instead set to the filename of your module minus the .py extension.

Example

# foo.py

print('spam')

if __name__ == '__main__':
    print('eggs')
If you run the above module foo.py directly, both 'spam'and 'eggs' will be printed. Now consider this next example:
# bar.py

import foo
If you run this module named bar.py, it will execute the code in foo.py. First it will print 'spam', and then the if statement will fail, because __name__ will now be the string 'foo'.

Why would I do this?

  • Your module is a library, but also has a special case where it can be run directly
  • Your module is a library and you want to safeguard it against people running it directly (like what pip does)
  • Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test
on-message-event

Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.

Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:

@bot.listen()
async def on_message(message):
    ...  # do stuff here

# Or...

@bot.listen('on_message')
async def message_listener(message):
    ...  # do stuff here
You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.

If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.