Creating A Python Discord Bot – A Complete Step-by-Step Guide

Python Discord Bot Feature Image

Discord is one of the most popular social media platforms of the 21st century and making a discord bot might be one of the coolest python projects out there.

Using python’s discord API and some other modules, we can easily code our own bots for text channels in discord. In this tutorial, we will code a bot that will send us funny messages on discord.

Let’s get started!

Also read: Building a ChatBot in Python Using the spaCy NLP Library

Steps to Add a Bot in Discord

Before we start coding in python, we need to create a discord bot account from the discord developer’s portal. Click here to go to the website directly.

  • Click on “applications” from the left-hand side menu. Then, create a new application by clicking on the “New Application” button.
New Application For Bot
  • Add a name for your bot. For example, since it is our first bot, I will name it Our First Bot and click on “create”.
Bot Name
  • Click on the “bot” option from the left-hand-side menu and you will be able to view the basic details of your newly created bot!
  • Keep the default settings of the bot for now, such as keeping the bot public.

Voila! You have successfully created your very first bot!

Bot Creation
  • Scroll down to the authorization flow section and under “privileged gateway intents” toggle ‘on’ all three boxes.
Intents
  • Once that is done, scroll up to the bot section.
  • Click on “copy” beside the reset token button. This is a very important step as it will help us to connect our code with the bot later.

Note:- Do not share the token with anyone, it can be used to manipulate your bot by anyone without supervision. If you have accidently shared your token, hit “reset token” and then click on copy.

Creating a Discord server

  • If you don’t have an existing server to add the bot to, open discord and click on the “+”(add a server) button from the bottom of the left hand-side menu.
Add A Discord Server
  • Select “create my own”.
Create Discord Server
  • Then select your required purpose for the server.
Choose Discord Purpose
  • Next, name your server and hit create. I have chosen the name “Robot python server” , you can name it whatever you want!
Name Your Server
  • You have now successfully created a new discord server!

Giving permissions to your Discord bot

  • Click on the OAuth2 tab from the menu of the discord development portal and click on the URL generator. Check the “bot” box under scopes and then move on to the “bot permissions” section. This will be used to give your bot various permissions in your server.
  • For example, here we will check all the text permission boxes because we are coding a simple text channel bot but it can be customized according to your use.

Note: You should be careful before assigning administrator privileges’ to the bot.

Discord Bot Permissions

Authorizing your Bot access

  • Now, copy the URL at the very end of the page and open it in a new tab.
Bot Generated URL
  • It will ask for your permission to authorize the bot and ask you to add it to a specific server.
Add Bot To Server
  • Select the required server and click on continue. I have added it to a server named “Robot python server” but you can add it to whatever server you want to.
Authorize Access To Severs
  • Check if all the permissions are correct. Scroll down and click on the “authorize” button.
Bot Authorization

Neat! Now this bot has been added to your respective server and can do specific tasks. When you open your server in discord, You will be able to see that the bot is offline.

Bot Successfully Added

Setting up a cloud-based environment for the bot

  • We will first create a Replit account which is a cloud-based IDE for coding and supports various languages such as python, bash, C, and many others. If you already have a Replit account then you can just use that one. Click here to visit the official site and create a new account.
Replit
  • Sign up or log in with your Google account and you will be then taken to the home dashboard where you need to hit “+create” in order to create a new Repl.
  • After that, choose python from the left drop-down menu and name your repl however you want. I have named it “Ourfirstbot”. Hit “create Repl”.
Ourfirstbot
  • Your new Repl will look something like the one given below.
New Repl

Note: With replit, you don’t need to install anything additional in your computer which makes it easier to write code. When you import modules in replit and hit run, these dependencies are automatically installed and imported.

  • We will write our bot’s code in the main.py file.

Connecting the bot to our very own Repl:

  • Click on “secrets” from the bottom left-hand-side of the menu under tools.
Environment Secrets
  • Write “token” in the key box that will appear on the right-hand side of the panel and paste the token that you earlier copied in the value box below. Hit “add new secret” to add the environment variable.

Note: We could have just pasted the token in the main.py file when using the bot but since Replit is a public platform, our entire repl can be viewed by someone else. Hence, to protect our bot from unwanted and malicious changes, it is very important that we add the key as a secret environment variable that is only visible to us and no one else.

Coding the Discord Bot in Python

  • The code block given below is what we need to write in our main.py file to modify our bot and make it useful. This is the basic code that will help us test if our bot is working properly by sending us a “hello!” message when someone else sends one first.
#importing required modules
import os
import discord
import requests
import json
import random

intents = discord.Intents().all()
client = discord.Client(intents=intents)


#first event :logging in
@client.event
async def on_ready():
  print("successful login as {0.user}".format(client))


#second event: sending message
@client.event
async def on_message(message):
  #check who sent the message
  if message.author == client.user:
    return
  msg = message.content
  if msg.startswith('hello'):
    await message.channel.send("hello!")


#getting the secret token
client.run(os.getenv('token'))

  • After writing the above code hit “run”.
Running The Bot Code
  • In the console beside the editor, you should see something like this:
2022-12-15 07:20:06 INFO     discord.client logging in using static token
2022-12-15 07:20:07 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: ed722695d1f7e5e06167fefa674cc768).
successful login as Our First bot.#5804
Successful Login For Ourfirstbot
  • The above image is how it should look in the repl.
  • Now, if you open your discord application, and go to the server in which the robot was added, in this case :Robot python server, we will observe that the bot is online!
Bot Online In Discord
  • Now, if you send a “hello” message, the bot will send one back as shown below.
First Hello Bot Messages

Give yourself a pat on the back because your bot successfully responds now!

Modifying the Discord Bot to Be Funny (Jokes API)

  • Now, we have to modify the bot so that it can send funny texts whenever a user asks for a joke.
  • The following is how we will go about modifying the original code by adding a function called “joke” which will retrieve random jokes from the official jokes api.
#importing required modules
import os
import discord
import requests
import json
import random

intents = discord.Intents().all()
client = discord.Client(intents=intents)


#creating a function to retrieve jokes from the official joke api
def joke(j):

  data = requests.get(j)
  tt = json.loads(data.text)
  return tt


j = r"https://official-joke-api.appspot.com/random_ten"
a = joke(j)

#formatting to only get the setup and punchline of joke
for i in (a):
  Setup = (i["setup"])
  Punchline = (i["punchline"])


#first event :logging in
@client.event
async def on_ready():
  print("successful login as {0.user}".format(client))


#second event: sending message
@client.event
async def on_message(message):
  #check who sent the message
  if message.author == client.user:
    return
  #retrieving message to look for keywords
  msg = message.content
  #to check if above message has required keywords
  if 'joke' in msg.lower() or 'funny' in msg.lower() or 'laugh' in msg.lower():
    await message.channel.send(Setup)
    await message.channel.send(Punchline)


#getting the secret token
client.run(os.getenv('token'))

  • Modify the code as shown above in the main.py file and hit “run”.
  • Now, if you send a message in the general text channel of the server like “make me laugh!” or “say something funny”, the bot will respond with a joke to those messages.
Discord Bot Being Funny

Hooray! You have now successfully created your very own funny bot!

Note: The bot will only be online as long as you are running the code in your repl via your browser. As soon as you close the browser or hit “stop” in your repl, the bot will go back to being offline.

Hence, the last step would be to host your bot in a server so that it stays online even when you close your browser.

Hosting your Bot:

We have to set up a web server for the discord bot which can be done by creating a web server on Replit and uptime robot, a free monitoring website used to ping our robot so that even when our browser is closed, it will send regular pings to our discord bot to keep it running.

  • Click on “new file” and name it “keep_up”.py
Keeping The Bot Up
  • Now, we have to write the following functions to keep our bot awake for as long as we want.
#importing required modules
from flask import Flask
from threading import Thread

app = Flask('')


@app.route('/')
def home():
  return "Hello. I am awake!"


def run():
  app.run(host='0.0.0.0', port=8080)

#function to keep the bot awake
def keep_awake():
  t = Thread(target=run)
  t.start()

  • Now, you need to go back to the main.py file and modify the code by adding two additional lines:-
#imprting required modules
import os
import discord
import requests
import json
import random
#importing the keep_awake function from the newly created file
from Keep_up import keep_awake

intents = discord.Intents().all()
client = discord.Client(intents=intents)


#creating a function to retrieve jokes from the official joke api
def joke(j):

  data = requests.get(j)
  tt = json.loads(data.text)
  return tt


j = r"https://official-joke-api.appspot.com/random_ten"
a = joke(j)

#formatting to only get the setup and punchline of joke
for i in (a):
  Setup = (i["setup"])
  Punchline = (i["punchline"])


#first event :logging in
@client.event
async def on_ready():
  print("successful login as {0.user}".format(client))


#second event: sending message
@client.event
async def on_message(message):
  #check who sent the message
  if message.author == client.user:
    return
  #retrieving message to look for keywords
  msg = message.content
  #to check if above message has required keywords
  if 'joke' in msg.lower() or 'funny' in msg.lower() or 'laugh' in msg.lower():
    await message.channel.send(Setup)
    await message.channel.send(Punchline)


#calling the awake function
keep_awake()
#getting the secret token
client.run(os.getenv('token'))

  • Now when you run the main.py file, you will be able to see a webpage displayed right above the console on the right-hand side panel in the repl as shown below. The “Hello, I am awake!” message will also be displayed on the webpage.
Keeping The Bot Awake
  • Next, we will set up the Uptime Robot.
  • Login to your Uptime robot account if you already have one or register for free using your Google account.
  • Verify your email and then you will be redirected to a window as shown below, and then hit “add new monitor.”
Uptime Robot Dashboard
  • Select the monitor type as “HTTPS”. And then add whatever name you would like to give to your monitor. I have named it “Ourfirstbot”.
  • Next copy the URL of your bot repl where you have written and saved all the code and paste it in the URL section.
  • Set the monitoring interval to “5 mins” and leave the rest as is.
Setting Up The Monitor
  • Scroll down and hit “create monitor.”
Create Monitor
  • Great! you have created your very first uptime robot monitor.

Note: If an orange button appears after clicking on “create monitor”, hit that orange button once and your monitor will be created.

  • You can now view your newly created monitor on the left-hand side of the dashboard.
Monitor Setup Successful
  • Now, even if you close your replit tab from your browser, your bot will still appear online in discord!
Bot Appears Online

Try it yourself!

Summary

This tutorial is about how to set up a basic text bot in discord, for more information on how to make discord bots using python, visit the official site.