How To Code A Discord Bot in Python (Copy & Paste)

This tutorial will show you how to create a Discord bot using Python.

A Discord bot is a program that can act as a user/person on Discord and interact with other users/persons, post in a channel, automate admin permissions, etc.

Table of Contents

Requirements

This tutorial will assume that you have some background with Python but does not assume any experience working with Discord or bot-writing in general.

It also assumes that you have a working Python 3 environment and access to a command line and text editor.

Registration

To create a bot, you must first register an account on Discord’s Developer Portal. If you already have a Discord account, you can skip this step.

After registering your account (by clicking the register button under the sign-in dialog), you will need to verify your email address.

Now that your account is functional, the first step in creating a Discord bot is to create an Application.

An Application will allow you to access Discord’s API (Application Programming Interface) and begin writing your bot.

To create an Application, navigate to the Applications tab in the Developer Portal and select the New Application button.

Make sure to give the Application a unique name. You should now see a screen that displays information (such as the id and public key) about your Application.

Next, you need to create the bot user itself. To do so, navigate to the Bot tab under the page for the Application that you just created. Click Add Bot and confirm your decision.

You should see a new bot user appear. By default, it will have the same username as its parent Application. Give the bot a new name and click Save Changes. Now you have a bot!

For your bot to talk to users, however, you will need to create a server for it to inhabit. Navigate back to your home page and click the + button to add a new server.

Click Create My Own and then For me and my friends to initialize some settings for your new server, then give it a name that you will remember. You should now see this server appear in the Discord interface along with its current channels and users.

Now it is time to add your bot to your server. Return to the Developer Portal and select your Application again.

Then select the OAuth2 tab on the left. You should see a section called OAuth2 URL Generator. Under Scopes select bot and then under Bot Permissions select Administrator.

While giving the bot administrator permissions is the easiest for this tutorial, it may be dangerous to do so in production. Instead, more specific and detailed permissions should be used.

Now, copy the generated URL by clicking copy to the right of the URL that should appear under the Scopes section. Navigate to this URL using your web browser. You may have to log into Discord again.

Under Add to Server select the server that you just created and then click Continue. Then click Authorize to grant your bot access. You may have to complete a reCAPTCHA after clicking Authorize to confirm your identity.

Coding The Discord Bot with Python

At this point, you have created the Discord resources that you will need to create your bot. Now, you just have to write the code for the bot itself in Python.

To do so, we are going to use the library discord.py. First, install it by running…

python3 -m pip install -U discord.py[voice] 

Now that we have this library, we can finally begin to write our bot. As you follow along, I would suggest adding these lines of code to a Python file. That way, when you are done, your bot will be ready to run.

First, let’s import the libraries that we are going to need…

import os
import discord

Note that discord is the discord.py library that we just installed. Next, we need to load the token that authenticates our bot to connect to Discord.

TOKEN = os.getenv('DISCORD_TOKEN') 

As you can see, this assumes that the token will be stored in the environment variable DISCORD_TOKEN.

To do anything with Discord’s API, we need to create a Client object. This object will connect to Discord and allow us to interact with messages, channels, users, etc. We can create a Client object like this

client = discord.Client() 

Discord’s API is structured around the notion of events. An event occurs anytime something happens in the Discord server.

For example, a client connecting or disconnecting, a user sending a message, or a user joining a group are all examples of events.

For a complete list of the events that discord.py supports, check out the relevant documentation.

In order for our bot to do anything, we need to register a handler for the appropriate event with our Client object. We can do so using the @client.event decorator and Python async/await syntax.

Let’s see what this looks like for a basic event handler that prints a message when our bot logs into Discord:

@client.event
async def on_ready():
    print(f'Logged in as {client.user}') 

As you can see, the handler definition is preceded by an @client.event decorator.

Additionally, it is not a normal Python function (like what is created by def) but is actually a coroutine (created by async def). Normal Python code is executed in a synchronous manner.

This means that after each statement runs the next will be executed immediately.

Coroutines, such as the one we just defined, run in an asynchronous fashion. This means that execution can be suspended and resumed. This sounds confusing but is actually fairly simple.

If you are familiar with Python’s generators, it is a similar concept.

Basically, a coroutine can call another coroutine and wait for it to return its result (using the await syntax).

Unlike in a normal function call, program execution does not stop while we wait for the result to be ready. Instead, Python can go run other code and will return execution to the coroutine when the called coroutine is ready to return a result.

To use discord.py, it is not essential to have an in-depth knowledge of Python coroutines.

You just need to make sure that your event handlers are defined using async def, not just def, and that when you call another coroutine you prefix it with await (we’ll see an example of this soon).

It is, however, valuable to know what coroutines are and have a basic idea of how they function.

Now that we have seen how a very basic event handler works, let’s look at a more complex one. The following is an event handler that will respond to any message that reads “Hi bot” with “Hello human!”.

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content == 'Hi bot':
        await message.channel.send('Hello human!')

The definition of an event handler using the @client.event decorator and async syntax should be familiar by now. The on_message handler will be called every time a message is sent.

One difference should be immediately apparent, however. This event handler takes an argument, called message. This argument will be discord.message object representing the message that has been sent.

For more documentation about these objects and their methods, check out the relevant documentation.

First, we compare message.author to our own username, client.user, to see if the message was sent by us, the bot. If so, we return, since we don’t want to have the bot reply to itself!

Next, we check to see if the message’s content is “Hi bot”. If so, we send the message “Hello human!” in the same channel as the message that we received. Note that this call to message.channel.send is prefixed with an await.

As I discussed before, this is because we are calling a coroutine, not a normal function.

Now that we have programmed the functionality of our bot, we need to run it.

In order to run a client, we call its client.run() method with the token that will give our bot permissions to function. In our code, we will pass the token to the bot as an environment variable.

Assuming that the environment variable will be called DISCORD_TOKEN, this looks like

TOKEN = os.getenv('DISCORD_TOKEN')

Now that we have the token, we can start the client, like so…

client.run(TOKEN)

Now that we have all of the code, we can finally run our bot.

Enter the following into your shell, making sure to replace YOUR_TOKEN with your bot’s token and YOUR_BOT_FILE with the name of the file in which you entered the code for the bot.

DISCORD_TOKEN=YOUR_TOKEN python3 YOUR_BOT_FILE.py

You can find your bot’s token by navigating to the Bot tab in your Application’s page in the Discord Developer Portal and clicking the Copy button under the Token section for your bot.

Once you have run your bot, navigate back to Discord and enter the server that you have just created. In the shell where you ran the bot, you should see that the bot is logged in.

Now, try sending “Hi bot” as a message in Discord. You should see that the bot replies “Hello human!”.

Conclusion

Congratulations! You now have a functional, albeit simple, Discord bot.

There are many ways you may want to develop your bot further. Maybe you want it to greet new people that join your server? Perhaps it could provide answers to commonly asked questions?

Whatever your goals may be, you should be able to achieve them with the basic setup described in this tutorial and the features provided by the discord.py library.

For more information on using discord.py in ways not described here, check out the complete API documentation.

Happy coding!

To explore the next generation of Discord Bot creation; check out this post on the new Nextcord.py library.

Get Full Discord Bot Code Here >>

Leave a Comment

Your email address will not be published. Required fields are marked *