Build Your First Discord Bot Using Python

Pinak Last Updated : 07 Sep, 2021
5 min read

This article was published as a part of the Data Science Blogathon

Introduction:

Hello Everyone, in this article, we shall be coding a bot for discord, using just python.

Let us begin and jump into the process without further ado.

A brief about Discord for those who don’t already know

Discord is basically a one-stop voice and text communication platform for gamers.

Players, streamers, students, and developers use Discord to debate games, answer questions, chat while they play, be in a good quality voice call with multiple team members, and far more. It even features a game store, complete with critical reviews and a subscription service. It is basically a hub for gaming communities.

Although there are many things you can build using Discord’s APIs, in this tutorial we will focus on simply how to create a bot using python.

Prerequisites

These are the following prerequisites that you must keep in mind before making this project:

1) You must have a Discord account and your own server.

2)You must have Python installed.

3)You must also have an active internet connection during the process.

That is it.

What are Bots?

A ‘bot’ – short for “robot” – is a software application that performs automated, repetitive, and pre-defined tasks. Bots typically imitate or replace human behaviour. As they are automated, they operate much faster than human users.

Bots are commonly used, as it is very impractical to respond to various queries of the people(members) in the server. The bots act as the human representatives of the various functionalities that we want them to perform. The biggest feature is that it removes the strenuous efforts of manually replying to the needs of the members, as a bot completely automates the process.

Need for Chatbots 

1)Automate the basic answers/replies:  For any domain, there always exists some basic questions that a user may ask. And for these common questions, the same answers are required to be delivered every time the customer makes a similar query. Well, for reducing the strenuous effort. , a chatbot is the best engaging and interacting way to answer these questions.

2)Accelerate the process: Chatbots are not bound by physical limitations, like the way humans are. For example, human agents are capable of handling only limited conversations, whereas chatbots, on the other hand, operate beyond that limit. Employing chatbot solutions to business complement the human task force, boosting efficiency and reducing human labor.

3)Cost and Time efficiency:  with the proper use of a friendly chatbot engaging visitors becomes easy and quick, with a minimal cost, but a great advantage.

Coding a Chatbot

For making this bot, make sure that you have Python installed on your computer. If not, you can download it from this link. You can also use any coding environments that suit you (like PyCharm, VSCode, Sublime, etc.). Now head onto Discord’s website and go under the ‘Developer’s Section’. You can directly attend to the page by clicking here.

Now select the ‘New Application’ option on the top-right corner of the page, and give it a name as you like. As you can see, you can now add custom images to your bot’s avatar. We shall do those later. Go to the ‘Bot’ Section from the categories on the left, and then select ‘Add Bot‘.

Once you have done that, Go to the ‘OAuth2’ category, and under the scope section, check the bot option. And under the ‘Permissions’, permit it that you would like it to perform.

Now open the link that was given above, under the ‘scope’ category, in a new tab. Select the server, in which you want to feature the bot.

Now when that is done, install discord in your system.

In your cmd, run this command:

pip install discord

A Brief about Discord.py:

You can check out their official website by clicking here. Discord.py.

They work on the syntax of async/await API.

After the installation was successful, open your code editor, and mane the file ‘bot.py’.

The main motive of our test bot here is that it must respond to the “Hello” messages entered by the users. You can customize it as per your needs.

Import the necessary dependencies:

import discord
from discord.ext import commands

Naming the client variable ‘client’

client = commands.Bot( command_prefix=" / " )

Do note that you can give any prefix that you want (eg. ‘ > ‘, ‘ . ‘, etc.)

Also remember, that if you want to summon your bot, your calling command should be prefixed by the “command_prefix”.

For example, here in our case, we need to summon the bot by writing “/hello”, instead of “hello” alone.

Now, for knowing the up-status of the bot:

@client.event
async def on_ready( ):
           print("Bot is ready")

This message will be displayed whenever you host your bot online. You will also be able to check the status of the bot from discord itself.

This message will confirm that our Bot is ready and ready to be used on the server.

Now when the bot is ready, we also want to respond to the “Hello”s entered by the server users.

@client.event
async def hello( ):
          await ctx.send("Hi")

This function defines the condition that when the user types “/hello”, the bot will respond by saying “Hi”.

To run the bot, we need the token that will be provided to you in the ‘Bot section’ that you visited while creating the bot.

client.run(" Token ")

Replace the “Token” with your own token. You can find this token, around the avatar logo of the bot. If it is not showing already, click on reveal token. This must do it.

Now after that is done, time to put our bot up live…!!!

Open CMD, and run:

 bot.py

If that does not work, try

python bot.py

If you have followed all the steps correctly, you should be getting a message

Bot is ready

Now head over to your server and check by typing the test query, which in our case was

  '/hello'

We see that our bot successfully replies:

 "Hi".

Thus our bot is performing well.\

Similarly, code to create a bot that welcomes new members would be:

import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has joined Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hello {member.name}!! Welcome to Our Discord Server!'
    )

client.run(TOKEN)

Some problems faced while making a chatbot

Everything might not be as easy it may sound. You should also keep in mind the problems you might face while making a chatbot. I have listed a few below:

  1. Different ways of texting: Different people have different ways of typing a message (short sentences, long sentences, multiple very short sentences in multiple chat bubbles, etc.). So to understand the user’s intention could be a task.
  2. User Emotions:  We people are beings with emotions. Our behavior is controlled by emotions. We feel different at different instances of time and, also, it is not permanent and you change your mood easily, along with the right triggers, and so, does the way you express yourself in messages.
  3. Making a creative and interactive UI: User attention span is very short-timed often distracted. Here is where conversational UI comes into play. It is more about how can we engage them. So how the bot responds to a user’s message is where you grab the user’s attention. The more effectively we do, the more chances are that the bot will be used again. So writing responses to user queries should be taken under heavy consideration.

Ending Notes

This was just the tutorial of the bot creation using python.

You can add your own codes and create bots with awesome features like OCR, etc.

Thanks for reading.

Have a good day!

About the Author:

Hey there, I am Pinak Datta, currently, a second-year student, pursuing Computer Science Engineering from Kalinga Institute of Industrial Technology. I love Web development, Competitive Coding, and a bit of Machine Learning too. Please feel free to connect with me through my socials. I always love to have a chat with similarly minded people.

Linked-in

Instagram

Facebook

Mail

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Hi, I'm Pinak Datta, currently pursuing my B.Tech in Computer Science and Engineering from Kalinga Institute of Industrial Technology. I'm in my third year of study and I've always had a keen interest in technical writing and software development. I love to develop programs and scripts using Python and have worked on several projects in this language.

Apart from my academic pursuits, I've also participated in various hackathons and coding competitions. These experiences have allowed me to showcase my creativity and problem-solving abilities in the field of computer science.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details