In this blog, I’m going to show you how to build your chatbot in Discord. The reason why you would want to build one for yourself is that it can process all the information it receives and in turn, you can return a response to only certain users or all of them with the same response. We are going to use the discord.py Python library, a free-to-use library designed for retrieving data from the popular text and voice chat service known as Discord. Without further ado, let’s get into building it:

Steps to create Discord bot Python

1. Create Discord Bot python

2. Discord Developer Portal setup

3. Adding the Bot to the server

4. Adding responses

5. Running the Bot

Prerequisites

Python:

To make a word guessing game in python you need to have python installed in our system, you can easily install python in your system by going to https://www.python.org/downloads/ downloading and installing the software.

Discord:

Discord is a popular communication platform that caters to gamers. If you want to talk to your friends while playing games, Discord is the way to do it. Discord provides text and voice chat channels and modern features that you’ll love! Discord is feature-rich, and it’s easy to use. You can easily install discord by going to the following link and then downloading and installing the setup.

https://discord.com/download

Discord.py:

discord.py is a modern, easy-to-use, feature-rich, and async-ready API wrapper for Discord. It is entirely written in Python 3 and is extensively documented. It is a complete rewrite of the popular `discord.py` library, but with a much nicer API.

To install discord.py use the following command in your terminal

pip3 install discord

Step 1: Discord Developer Portal setup

GO to the following link and create a new application 

https://discord.com/developers/applications

  1. Click on the create a new application.
  2. Add the name of the application.
  3. Fill the general information section.

Go to the bot section and select add bot and it will create a bot for you 

Then provide the name and image of the bot for letter convenience and press on save the change, after that copy the project token and save it

Disable the public bot feature and press on save changes 

Go to OAuth2, URL Generator, and checkmark the bot

then scroll down and you will see the lots of bot permission, we are selecting only the text permission here but if you want you can choose the other options as well.

After that it will generate a link for you, just copy-paste that link into a new tab and it will ask you if you want to add this bot to the server. Select the server and authorize the bot.

Now you will see your bot in the discord server is under the offline section. That means we are done with the developer portal let’s get to the code part.

Step 2: Adding the Bot to the server

Import all the dependencies

import discord
import random

Save the token that you copy from the developer portal like this 

TOKEN = 'OTQ2NjU2MDIzMDk4MzA2NTdfkw.Yhh4Hw.A4xI12Af_1aSwHEybrSvyqaXuWQ'

The next thing we have to do is create a client and client event then we defined it as an async function. Then we used the on_ready method, which means once we start the bot this will call this function. In the last block of code, we added the default message using a print statement – let’s try to run our program. 

client = discord.Client()
@client.event
async def on_redy():
    print('We have logged in as {0.user}'.format(client))
client.run(TOKEN)

Output:

We have logged in as first_bot#3182

As you can see that it is showing us that we are successfully logged in as first_bot#30182. Now our bot will be online on the discord server. However, it’s not responding to any of the messages sent its way – so let’s add the responses.

Step 3: Adding responses

To add responses let’s create another client event make this also an async function and added a message as a parameter. Now there are lots of possibilities in terms of what we can do with this message, but for now, we want to echo the message back to the user.

There are a few variables we want to create before we move on to responding to the messages.

1. What first function does is it get the username along with the hash number.

2. With this function we will get messages.

3. With this function we will get the name of the channel, to which the user has sent the messages.

4. The last one is a print statement that will print all the data for us.

We will letter see how important it is to add all the variables. It will give us all of the message data in our command prompt.

@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

Next, we need to build the chatbot in a way that it doesn’t continue asking itself questions and you must set up this system.

    if message.author == client.user:
        return

Now let’s check if the channel is the corresponding channel that we specified so that messages only get responded to that certain channel. After that, we added the following responses

1. If someone sends a hello to the server, the bot will respond with Hello along with their username.

2. If someone sends a bye to the server, then both will respond by seeing you later along with their username.

3. If someone sends! random to the server, then it will respond with a This is your random number: 186388.

    if message.channel.name == 'for-bot':
        # let's add the messages that our bot will respond to
        if user_message.lower() == 'hello':
            await message.channel.send(f'Hello {username}!')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'See you later {username}!')
            return
        elif user_message.lower() == '!random':
            response = f'This is your random number: {random.randrange(1000000)}'
            await message.channel.send(response)

here let’s create a response that will show on the whole discord server. It’s simple if someone sends it! anywhere in the message then both will respond with this can be used anywhere!

    if user_message.lower() == '!anywhere':
        await message.channel.send('This can be used anywhere!')
        return

client.run(TOKEN)

Running the Bot:

After running the code your bot will go online and now you can check if the bot is working properly or not.

As you can see the bot has responded exactly as we specified and now let’s test whether the bot will work on a different server or not.

And you can see the bot is working perfectly on the other server as well. It’s also printing in real-time messages on the command line, with all of its data.

Final Words

This blog has taught you how to create a discord bot in Python. The discord bot is useful for making your discord server more fun. We hope you have a good time using the discord bot.