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

Telegram Chatbot with Python from s...
Telegram Chatbot with Python from scratch | Easy Python

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 >>

28 thoughts on “How To Code A Discord Bot in Python (Copy & Paste)”

  1. I found a site where they have two AI wise chat bots you can converse with in a Discord server or right from their site on digitalghost.org in their live web talk. they additionally work with evol.ai which has music, workmanship, pictures, photographs, a wide range of media and a custom and special Discord-based game. you should investigate it its truly flawless

  2. I am not positive the place you are getting your info, but great topic. I needs to spend a while studying more or working out more. Thank you for fantastic info I used to be in search of this information for my mission.

  3. Tomasz Michałowski

    Hi, very great site you have established. I enjoyed reading this posting. I did want to publish a remark to tell you that the design of this site is very aesthetically delightful. I used to be a graphic designer, now I am a copy editor for a firm. I have always enjoyed playing with information processing systems and am attempting to learn computer code in my spare time (which there is never enough of lol).

  4. Portal Edukacyjny

    Completely understand what your stance on this matter. Though I might disagree on a number of the finer details, I think you probably did an awesome job explaining it. Sure beats having to analysis it on my own. Thanks. Anyway, in my language, there arent a lot good supply like this. Have you considered promoting your blog? 🙂

  5. Cheap Proxy Buy

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?

  6. Whitney Mclead

    I need to to thank you for this good read!! I definitely loved every little bit of it. I’ve got you book-marked to look at new things you post…

  7. Tamera Engesser

    Your style is very unique compared to other folks I have read stuff from. Thanks for posting when you have the opportunity, Guess I will just bookmark this blog.

  8. דירות דיסקרטיות בירושלים - israel night club

    You need to be a part of a contest for one of the finest sites online. I am going to recommend this blog!

  9. content generator

    Pretty nice post. I just stumbled upon your weblog and wished to say that I’ve truly loved
    surfing around your blog posts. In any case I’ll be subscribing to
    your rss feed and I am hoping you write again very soon!

  10. Pingback: Discord

  11. Hiya, I am really glad I have found this info. Today bloggers publish just about gossips and net and this is really frustrating. A good site with exciting content, that is what I need. Thanks for keeping this website, I’ll be visiting it. Do you do newsletters? Can not find it.

  12. I get pleasure from, cause I discovered exactly what I was looking for. You have ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  13. Oh my goodness! an amazing article dude. Thanks However I’m experiencing difficulty with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting an identical rss drawback? Anyone who is aware of kindly respond. Thnkx

  14. Hey there! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and fantastic design.

  15. It抯 laborious to search out educated folks on this matter, however you sound like you realize what you抮e talking about! Thanks

  16. I抦 not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back later. All the best

  17. It抯 really a cool and useful piece of information. I am glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  18. It’s appropriate time to make some plans for the longer term and it is time to be happy. I have read this post and if I may I desire to suggest you few interesting things or suggestions. Perhaps you can write next articles regarding this article. I wish to learn even more issues about it!

  19. A further issue is really that video gaming has become one of the all-time most significant forms of fun for people of all ages. Kids participate in video games, and also adults do, too. The particular XBox 360 has become the favorite video games systems for many who love to have hundreds of video games available to them, plus who like to learn live with other individuals all over the world. Thanks for sharing your ideas.

  20. You can certainly see your skills in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  21. Heya i抦 for the first time here. I came across this board and I find It really helpful & it helped me out much. I’m hoping to present one thing again and aid others such as you aided me.

Leave a Comment

Your email address will not be published.