How to Make a Discord Bot
On Discord, people collaborate to share ideas, discuss projects, and chat about life and hobbies in general. But Discord bots can make your chat rooms more fun in addition to automating tasks. These can be anything from telling random jokes to playing specific music and more.
Nonetheless, there are some essential steps you must follow while learning how to make a Discord bot. We’ll explore them in this article.
Let’s get started.
1. Create Your Discord Server
Before you create a Discord bot, you have to start by creating a server, as this is the bot’s place of assignment.
A Discord server or chat room is a space where you manage channels and communications on the platform.
To create a Discord server, head over to the Discord website and log in to your Discord dashboard. Or create an account if you don’t already have one.
Once in your Dashboard, follow these steps to make a Discord server:
- Click the addition (+) icon on the left sidebar.
- Select the Create My Own option.
- Choose a purpose for creating your server.
- Customize your server with a profile picture and a name. Then click Create.
You’ve now created a Discord server and are ready to make a bot for controlling certain activities on it.
2. Set Up and Create Your Discord Bot
Next, you want to create a Discord bot inside a Discord application by going to the Discord Developer Portal. Or you can type the following URL in your browser address field instead:
https://discord.com/developers/applications
Once in the developer console:
- Click New Application at the top-left.
- Provide a name for your application in the given field. Then click Create.
- Look to the left sidebar, and select Bot.
- Click Add Bot at the extreme right.
- From the next prompt, choose Yes, do it!
- Click Copy to copy your bot token. Create a text file inside your project root and paste it there. You can name the file secret.txt. Make sure that you don’t reveal the copied token.
- Scroll down and toggle on the switch under PRESENCE INTENT. Also, switch on the toggle under SERVER MEMBERS INTENT.
- Next, click OAuth2 on the left bar to add authentication priorities to your Discord bot.
- Select URL Generator to generate a bot invitation URL for the server you created earlier.
- From the options, under SCOPES, select bot.
- Scroll down to the BOT PERMISSION section and select roles for your Discord bot. In this case, we’ll give it the Administrator role.
- Scroll to the bottom and click COPY to copy the generated URL to your clipboard.
Now to link your server to the bot.
Link a Server to Your Discord Bot
As we mentioned, a bot works primarily inside the server. Hence, after creating a Discord bot as we did, you’ll have to assign it to a server where you want it to work.
So once you copy the generated URL, follow these next steps to link your chat room to the Discord bot:
- Paste the copied URL in your browser’s address field and log on to it.
- From the prompt, click Select a server and choose the one you created earlier.
- Click Continue to proceed.
- You’ll see a new menu with a list of permissions you set earlier. Select Authorize.
- Solve the CAPTCHA to complete authorizing your Discord bot.
You’ve now created a Discord bot. Go back to your server dashboard, and you’ll see the robot on the right sidebar. But as you can see, it’s currently offline. So it doesn’t work yet until you program it to do so.
To make your bot work, you need to write a script in any programming language that works best for you.
3. Program Your Discord Bot Using Python
For this tutorial, we’ll use Python and host the Discord bot on the local machine. You can host yours on cloud services like Heroku if you want once everything is set up. Let’s dive in.
Set up Python and Libraries
To program your Discord bot with Python, you’ll use the discord.py module, which only works with Python 3.5.3 or later.
If you’ve not done so already or have an earlier version, go to python.org to download the latest Python version.
You can check the Python version installed on your PC by entering the following command in your terminal:
python --version
If Python is up to date, open the terminal to your project root. Then activate a Python virtual environment.
Also, you’ll have to install discord.py and a voice support package called discord.py[voice].
With the virtual environment active, run the following command in your terminal to install these packages:
pip install -U discord.py discord.py[voice]
Send a Message With Your Discord Bot
Here, you’ll program your Discord bot to reply with a custom message when you send a text in a channel.
But first, type the following code at the top of your script to initialize your Discord bot:
import discord
# Import the commands module:
from discord.ext import commands
# Initialize the bot instance and use a blank prefix:
bot = commands.Bot(command_prefix="")
#Read your bot token from the txt file in your project root:
Secret = open("secret.txt", 'r')
Secret = Secret.read()
#Run the bot in an event loop:
bot.run(Secret)
The bot variable invokes custom commands from the command class. And the command_prefix in the parenthesis lets you specify a character that precedes it. Characters like the dollar sign ($), exclamation (!), ampersand (&), and more are common prefixes that precede bot commands.
But we’ve blanked the prefix in our case. So you don’t need one while instructing the Discord bot.
Using the @bot.command() decorator, let’s make a custom command, Hi, and provide a reply text for the Discord bot when it sees it.
Note that custom commands are Python functions:
import discord
# Import the commands module:
from discord.ext import commands
# Initialize the bot instance:
bot = commands.Bot(command_prefix="")
@bot.command()
async def Hi(ctx):
await ctx.send("Hi, welcome to our server")
Secret = open("secret.txt", 'r')
Secret = Secret.read()
bot.run(Secret)
Now run the Python script in your terminal. Then go to Discord and send “Hi” to see the magic unfold.
Looking closely, you’ll see that we’ve used the async await method to serve the function. This is essential, as it’s the only way for the module to communicate with Discord.
The ctx instance is a context, and it has many functions. But in this case, it allows your Discord bot to send a message.
Welcome New Channel Members With Your Bot
In this example, you’ll see how to use events to trigger a greeting when someone joins your server. You’ll also learn how to display the username of a new member and the server they’ve joined in the greeting message.
We’ll use @bot.event here instead. Here’s how that works:
@bot.event
async def on_member_join(member):
guild = member.guild
if guild.system_channel is not None:
detailMessage = 'We welcome {0.mention} to the {1.name}!'.format(member, guild)
await guild.system_channel.send(detailMessage)
The on_member_join function is a type of event. There are many others, though. The on_ready method, for instance, is a widely used event for checking if a bot is ready or not.
Further, the condition that follows the if statement checks if the connected server (guild or chat room) exists or not. If it does, it uses the Python string format method to output the new member’s username and the server they’ve joined.
Now ask a friend to join your server to see what happens. You might want to try this first with a dummy Discord account, though, to ensure that it works.
Ask Discord Bot to Join or Leave an Audio Channel
Now let’s expand the code. And this time, you’ll tell your bot to join or leave an audio channel when it receives a particular command.
In the example code below, the Discord bot joins you in an audio channel when you type “enter”:
@bot.command()
async def enter(ctx):
if ctx.author.voice:
await ctx.message.author.voice.channel.connect()
The condition within the if statement checks if you’ve joined an audio channel already. If so, the await keyword connects your Discord bot with it.
It means you must’ve joined an audio channel before the command will work.
Note: Ensure that you stop and restart your Python script after each update. It lets Python sync your changes.
Once you re-execute your Python script, open Discord, and type enter—you’ll now see that your Discord bot has joined the audio channel.
Asking your bot to leave the channel is as easy as adding it.
The following code tells it to leave the channel when you type the appropriate command. We’ll use the word “leave” in this case:
@bot.command()
async def leave(ctx):
if ctx.voice_client:
await ctx.guild.voice_client.disconnect()
Stop and execute your script again. The Discord bot should now leave the audio channel when you send the “leave” command.
Keep Improving Your Discord Bot
That’s it! You’ve made yourself a functional Discord bot. Put the example blocks of code together and keep adding features to your Discord bot. For instance, you can tell it to play music from your PC or a streaming platform as soon as it joins an audio channel.
Discord bots are fun to use. If you don’t yet automate tasks with them in your chat rooms, you’re missing out on some serious efficiency.