feature_image

Create a Discord bot with slash commands

Create a simple Discord bot with discord slash command support

by Tim Heidler on Sun Nov 05 2023

Getting started

  • Discord account
  • A coding editor (for example VS Code)
  • Python with pip installed on your PC

Start up your favorite code editor (in this Tutorial, I'll be using VS Code)
and open a folder, where you want to create your Discord bot. Next up, open a
terminal in your folder. In VS Code, press on "Terminal" at the top of
the program and then on "new Terminal".

vs-code-terminal

First, we need to install the discord.py library, which allows python to communicate with discord.

To do so, type the following command in the terminal.

pip3 install discord.py python-dotenv

Now create your main python file, For example “index.py”.

index.py

First, we are going to import the required library os, load_dotenv from dotenv and of course discord

import os
from dotenv import load_dotenv
import discord

Next we load the environment variables

# import eviroment variables
load_dotenv()
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN")
GUILD_ID = os.environ.get("GUILD_ID")

And set the global variables such as client which is the object of the bot. The client object contains multiple given functions like the run() function which is used at the end of the program to start the bot. The tree object is used to add commands to your bot.

# global variables
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)

Next up is the on_ready() function, which is executed when the bot is fully started and connected to discord in this function we will for now sync the command tree (all created commands) with discord (Syncing the command tree on start is not recommended for production). The bot will also display a message in the console when it is ready.

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=GUILD_ID))
       print(f'We have logged in as {client.user}')

Even though the bare structure of the bot now done, it will do nothing if you try to run it because the bot (client) needs to be executed with:

client.run(DISCORD_TOKEN)

The hole index.py at this point:

import os
from dotenv import load_dotenv
import discord

# import eviroment variables
load_dotenv()
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN")
GUILD_ID = os.environ.get("GUILD_ID")

# global variables
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=GUILD_ID))
        print(f'We have logged in as {client.user}')
            
client.run(DISCORD_TOKEN)

Environment variables

Above in the index.py, we are loading environment variables, but we haven’t created these yet. To do so, create a new file called “.env


DISCORD_TOKEN="paste your bot token here"
GUILD_ID="paste your guild ID here"

and paste these lines into it.

Obtaining a discord bot token

To obtain a Discord bot token for your bot, head over to https://discord.com/developers/applications and log in with your Discord account. Click at “new Application” and give your bot a name.

In the settings, go to “bot” and under Token you have your bot token. This token is like a password and should not be shared!

Invite bot to your Discord server

To invite your bot to your discord server, paste your client ID, which can be found at the “General Information” page in the Discord Developer Portal, into this link and open it in your web browser.


https://discord.com/oauth2/authorize?client_id=<Paste your Client id here>&permissions=8&scope=bot

This link will allow you to add your bot to your server, while using admin permissions for production you should adjust the permissions to needs.

Obtaining your guild ID (server ID)

The easiest way to obtain your guild ID is by opening discord web in your browser, https://discord.com/ and going to your server in the URL your guild ID will be the first random string of characters and numbers right behind “/channels/”.

Now add your token and ID into the .env and try running the index.py.


python index.py

If everything is done correctly, the response “We have logged in as Botty#1880” with “Botty#1880” being the name and discriminator of your bot should appear after a while.

Adding a slash command

To add a slash command, we need to add a function to the command tree. First, create an async function called hello like so


async def hello():

Then give and interaction into the functions arguments


async def hello(interaction: discord.Interaction):

Next, you can add the code which is run when the slash command is executed.


async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"Hey {interaction.user.display_name}! This is a slash command!", ephemeral=True)

In this example, it’s a simple answer answering to the user who executed the command with their name. We also added the “ephemeral=True” argument at the end, with makes the answer only visible to the user who executed the command.

Now, to add this function to the command tree, add the following line above your function.


@tree.command(name="hello", description="Tells you that you used a slash command")

This will add the command to discord slash command list with the given name and description.

Finally, run your bot again


python index.py

and see how it can answer your “/hello” command in any channel the bot has access to on your Discord server.

example

The hole source code to this post can be found on GitHub at https://github.com/timplay33/Tutorials/tree/main/simple-discord-bot.

More tutorial like this can be seen at https://theidler.de.

Thanks for reading!