If you want to know how to take your bot to the next level, the first thought would be to have some commands for your bot, right? Your gut reaction would be to use the on_message() event listener and stuff it with switch cases or even if statements. However, this is not ideal since that is not the on_message() function’s intended purpose. It’s to listen for messages from the channel — not to kick off commands.

Luckily, there is a framework that allows us to create specific commands for our lovely bot as well as keep our code super clean because the framework forces us to separate each command into a function.

Assuming you are using discord.py, we can leverage the Commands API provided by it.

In this article, we will be going over how to create a prefix for your bot, as most bots that you have probably interacted with have some form of prefix (e.g. $ or !). After that, we will be covering how to create new commands. Finally, we will be going over the built-in help command for the list of commands that your bot has so that you don’t have to create your own.

1. Creating Your Bot’s Prefix

We are going to be building a bot from scratch, but if you have an existing bot, you are more than welcome to use that file.

So let’s go ahead and add the items that we need to get this bot up and running:

# IMPORT DISCORD.PY. ALLOWS ACCESS TO DISCORD'S API.
import discord

# IMPORT THE OS MODULE.
import os

# IMPORT LOAD_DOTENV FUNCTION FROM DOTENV MODULE.
from dotenv import load_dotenv

# IMPORT COMMANDS FROM THE DISCORD.EXT MODULE.
from discord.ext import commands

# LOADS THE .ENV FILE THAT RESIDES ON THE SAME LEVEL AS THE SCRIPT.
load_dotenv()

# GRAB THE API TOKEN FROM THE .ENV FILE.
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")

# CREATES A NEW BOT OBJECT WITH A SPECIFIED PREFIX. IT CAN BE WHATEVER YOU WANT IT TO BE.
bot = commands.Bot(command_prefix="$")

# EXECUTES THE BOT WITH THE SPECIFIED TOKEN. TOKEN HAS BEEN REMOVED AND USED JUST AS AN EXAMPLE.
bot.run(DISCORD_TOKEN)

This code segment allows us to have a bot that can be started and can hit Discord’s API. We are using the load_dotenv() module so that we don’t have our bot token in plain text.

#programming #python #python3 #discord

How to Make Discord Bot Commands in Python
11.25 GEEK