How to Make a Discord Bot for Free with Python

How to Make a Discord Bot for Free with Python

This tutorial will teach you how to totally build your own Discord bot in the cloud. There is nothing to install on your machine, and to host your bot you do not have to pay anything. We will use some tools such as the Discord API, Python libraries, and the Repl.it cloud computing framework. This written tutorial is also available in film. Following steps for “How to Make a Discord Bot for Free with Python”.

Make a bot account on Discord.

Before we can use the Python library and the Discord API, we need to create a Discord Bot account.

The procedure for building a Discord Bot account is outlined below.

  • Verify that you’re connected to the Discord list.
  • Go to the tab for the application.
  • From the drop-down menu, choose “New Application.”

How to Make a Discord Bot

  • After calling the software, select “Create.”

How to Make a Discord Bot

  • From the drop-down screen, choose “Bot,” then “Add Bot.” To confirm, you must click “Yes, go ahead!”

How to Make a Discord Bot

Keep Public Bot (checked) and Require OAuth2 Code Grant at their default settings (unchecked).

Your bot is now operational. After that, the token must be copied.

How to Make a Discord Bot

This token is your bot’s password, so don’t give it out to anyone. It might allow someone to gain access to your bot and use it for nefarious purposes.

If the token is mistakenly shared, you can regenerate it.

Invite Your Bot to Join a Server

Your Bot User must now be connected to a server. To do so, you’ll need to build an invite URL.

Select “OAuth2” from the drop-down menu. Then, in the “scopes” segment, choose “bot.”

How to Make a Discord Bot

Now you can grant the bot the required permissions. We won’t need many permissions since our bot will primarily communicate through text messages. You’ll need more depending on what you want your bot to do. The “Administrator” authorization should be used with caution.

How to Make a Discord Bot

Select the appropriate permissions and then copy them by clicking the ‘copy‘ button above them. This will create a URL that the bot will use to connect to a server.

To invite the bot to a server, paste the URL into your browser, select a server, and press “Authorize.”

You must have “Manage Server” permissions on your account to add the bot.

We’ll begin writing the bot’s Python code now that you’ve installed the bot user.

How to Code a Basic Discord Bot with the discord.py Library

The bot’s code will be written in Python using the discord.py library. discord.py is a Discord API wrapper that allows creating a Discord bot in Python far easier.

How to Create a Repl and Install disocrd.py

Any code editor can be used to build the bot on your local computer. However, we’ll use Repl.it in this tutorial because it makes it easier for us to follow along. Repl.it is a web-based interactive development environment.

Start by visiting Repl.it. Make a new Repl and set the language to “Python.”

Simply write import discord at the top of main.py to use the discord.py library. When you press the “run” button on Repl.it, it will automatically install this dependency.

Run this command to install discord.py if you prefer to code the bot locally on MacOS:

python3 -m pip install -U discord.py

It’s possible that you’ll have to use pip3 instead of pip.

If you’re using Windows, you can instead use the following line:

py -3 -m pip install -U discord.py

Run the sample code

Replace the token value with the token you saved earlier from your bot.

# Work with Python 3.6
import discord

TOKEN = ‘XXXXXXXXXX’

client = discord.Client()

@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return

if message.content.startswith(‘!hello’):
msg = ‘Hello {0.author.mention}’.format(message)
await client.send_message(message.channel, msg)

@client.event
async def on_ready():
print(‘Logged in as’)
print(client.user.name)
print(client.user.id)
print(‘——‘)

client.run(TOKEN)

How to Add Encouraging Messages to the Bot

We’ll now add a list of motivating messages to which the bot can respond.

After you’ve finished with the sad words list, add the following:

starter_encouragements = [

“Cheer up!”,

“Hang in there.”,

“You are a great person / bot!”

]

Feel free to add more phrases to the list, just as you did before. For the time being, I’m only using three things because we’ll include the potential for users to add more motivating phrases for the bot to use later.

How to Respond to Messages

We’ll need to update our bot now so that it can use the two lists we made. To get the bot to send encouraging messages at random, first import the random module. Add the following line to the top of the file’s import statements: import random.

We’ll now update the on_message() function to look for a word from the sad_words list in all messages. If the bot notices a sad expression, it will send an encouraging message at random.

Here is the updated code:

async def on_message(message):

if message.author == client.user:

return

msg = message.content

if msg.startswith(‘$inspire’):

quote = get_quote()

await message.channel.send(quote)

if any(word in msg for word in sad_words):

await message.channel.send(random.choice(starter_encouragements))

Now is a good time to put the bot to the test. You now have enough knowledge to create your own bot. However, you’ll then learn how to use the Repl.it database to add more advanced features and store data.

How to Enable User-submitted Messages

Now that the bot works fully, let’s get it updated via Discord directly. If a boot detects a bad term, the user should be able to submit further boosting messages for the bot.

async def on_message(message):

if message.author == client.user:

return

 

msg = message.content

 

if msg.startswith(“$inspire”):

quote = get_quote()

await message.channel.send(quote)

 

options = starter_encouragements

if “encouragements” in db.keys():

options = options + db[“encouragements”]

 

if any(word in msg for word in sad_words):

await message.channel.send(random.choice(options))

 

if msg.startswith(“$new”):

encouraging_message = msg.split(“$new “,1)[1]

update_encouragements(encouraging_message)

await message.channel.send(“New encouraging message added.”)

 

if msg.startswith(“$del”):

encouragements = []

if “encouragements” in db.keys():

index = int(msg.split(“$del”,1)[1])

delete_encouragment(index)

encouragements = db[“encouragements”]

await message.channel.send(encouragements)

The first new piece of code from above is options = starter_encouragements. We’re building a copy of starter encouragements since we’ll add the user-submitted messages to that list before sending the bot a random message.

We look to see if the word “encouragements” already exists in the database keys (meaning that a user has submitted at least one custom message). If this is the case, the user messages will be added to the starting encouragements.

The bot then sends a random message from options, rather than a random message from starter_encouragements.

The next line of code is used to create a new database entry for a user-submitted message. If a Discord message begins with “$new,” the words immediately following “$new” will be used to create a new encouraging message.

The msg.split(“$new “,1)[1] function splits and stores the message from the “$new” command. Take note of the space in “$new” in that line of code. After space, we want everything.

We use the new message to help update, and the bot sends a message to the discord chat indicating that the message has been inserted.

The code above’s third new section decides if a new Discord message starts with “$del.” This command is used to remove an item from the “encouragements” list in the database.

First, an empty array is created for the encouragements variable. This is because if the database does not include a “encouragement” key, this section of code will send an empty array as a message.

The index will be split from the Discord message starting with “$del” if the database has the “encouragement” key. The delete_encouragement() method is then invoked, with the index to be deleted as an argument. Before delivering the most recent list to Discord in a message, the bot inserts the most recent list of encouragements into the encouragements variable.

Final Bot Features

This is an excellent moment to test the bot because it should work. We’ll now finish up with a couple more features.

We’ll add the ability to extract a list of user-submitted messages from Discord directly into the bot, as well as the ability to choose whether or not the bot responds to sad words.

I’ll give you the entire program’s final code, and then we’ll talk about the updates below it.

import discord

import os

import requests

import json

import random

from replit import db

 

client = discord.Client()

 

sad_words = [“sad”, “depressed”, “unhappy”, “angry”, “miserable”]

 

starter_encouragements = [

“Cheer up!”,

“Hang in there.”,

“You are a great person / bot!”

]

 

if “responding” not in db.keys():

db[“responding”] = True

 

def get_quote():

response = requests.get(“https://zenquotes.io/api/random”)

json_data = json.loads(response.text)

quote = json_data[0][“q”] + ” -” + json_data[0][“a”]

return(quote)

 

def update_encouragements(encouraging_message):

if “encouragements” in db.keys():

encouragements = db[“encouragements”]

encouragements.append(encouraging_message)

db[“encouragements”] = encouragements

else:

db[“encouragements”] = [encouraging_message]

 

def delete_encouragment(index):

encouragements = db[“encouragements”]

if len(encouragements) > index:

del encouragements[index]

db[“encouragements”] = encouragements

 

@client.event

async def on_ready():

print(“We have logged in as {0.user}”.format(client))

 

@client.event

async def on_message(message):

if message.author == client.user:

return

 

msg = message.content

 

if msg.startswith(“$inspire”):

quote = get_quote()

await message.channel.send(quote)

 

if db[“responding”]:

options = starter_encouragements

if “encouragements” in db.keys():

options = options + db[“encouragements”]

 

if any(word in msg for word in sad_words):

await message.channel.send(random.choice(options))

 

if msg.startswith(“$new”):

encouraging_message = msg.split(“$new “,1)[1]

update_encouragements(encouraging_message)

await message.channel.send(“New encouraging message added.”)

 

if msg.startswith(“$del”):

encouragements = []

if “encouragements” in db.keys():

index = int(msg.split(“$del”,1)[1])

delete_encouragment(index)

encouragements = db[“encouragements”]

await message.channel.send(encouragements)

 

if msg.startswith(“$list”):

encouragements = []

if “encouragements” in db.keys():

encouragements = db[“encouragements”]

await message.channel.send(encouragements)

 

if msg.startswith(“$responding”):

value = msg.split(“$responding “,1)[1]

if value.lower() == “true”:

db[“responding”] = True

await message.channel.send(“Responding is on.”)

else:

db[“responding”] = False

await message.channel.send(“Responding is off.”)

 

client.run(os.getenv(“TOKEN”))

Under the starter_encouragements list, the first part was added to the code.:

if “responding” not in db.keys():

db[“responding”] = True

A new key called “responding” can be added in the database and set to “True.” This is used to analyze if the bot should answer sad words or not. We only generate a new key if it doesn’t already exist, because the database is saved even after the program has stopped operating.

The component of the code that replies to sad phrases is now included within this if statement: if db[“responding”]:. The bot will only respond to sad words if db[“responding”] = True. After this section, you’ll be able to edit this value.

Following the code that allows the bot to respond to the “$del” command, there is a new code that allows the bot to respond to the “$list” command when submitted as a Discord message.

Create an empty list called encouragements to begin this section. If there are already encouragements in the database, they will take the place of the newly formed empty list.

Finally, the bot sends a Discord message containing the list of affirmations.

Following that is the final new section. This code will be used by the bot to answer the command “$responding.” This command has two inputs: “true” or “false.” An example of how to use it is “$responding true.”

The code first extracts the parameter with value = msg.split(“$responding “,1)[1] (notice the space in “$responding “, as mentioned previously). Then there’s an if/else line that correctly sets the database’s “responding” key and sends a Discord notification message. If the option isn’t “true,” the code defaults to “false.”

The bot’s programming is now complete! You can now test the bot by running it. But there’s one more crucial step that we’ll go over next.

Set Up the Bot to Run Continuously

If you execute it in repl.it and then exit the tab in which it is running, your bot will cease functioning.

However, there are two ways to maintain your bot even after you close your web browser.

The first and easiest method is to join the paid schedule of Repl.it. The Hacker Package is your most affordable and is comprised of five replenishments always available.

This connection (limited to the first 1000 people) will get you three months free: https://repl.it/claim?code=tryalwayson2103

When you have subscribed to this contract, open your Repl and press the top name. Then, from the option down, select “Always On.”

Read More:- HOW TO FIX DISCORD “YOU ARE BEING RATE LIMITED” ERROR

Create a Web Server in repl.it

It’s easier than you might think to set up a web server.

Make a new file called keep_alive.py in your project to accomplish this.

Then paste the following code into the box:

from flask import Flask

from threading import Thread

app = Flask(”)

@app.route(‘/’)

def home():

return “Hello. I am alive!”

def run():

app.run(host=’0.0.0.0′,port=8080)

def keep_alive():

t = Thread(target=run)

t.start()

Flask is used to start a web server in this code. The server provides a response “Hello. I am alive.” to everybody who comes to see it Our bot will execute on a separate thread from the server. We won’t go over everything here because the rest is unrelated to our bot.

Now, all we need is for the bot to execute the webserver.

To import the server, add the following line to the start of main.py.

from keep_alive import keep_alive

Add the following line as the second-to-last line, right before the bot runs, to start the webserver when main.py is executed.

keep_alive()

A new web server window will pop up when you run the bot on repl.it after inserting this code. A URL for the webserver is displayed. Make a note of the URL so you can reference it in the next stage.

How to Set Up Uptime Robot

Uptime Robot must now be configured to ping the webserver every five minutes. This will make the bot operate indefinitely.

Create a free account on https://uptimerobot.com/.

Click “Add New Monitor” once you’ve logged in to your account.

Select “HTTP(s)” as the Monitor Type for the new monitor and give it whatever name you like. Then, from repl.it, paste in the URL of your web server. Finally, select “Create Monitor” from the drop-down menu.

We’ve completed our task! The bot will now operate indefinitely, allowing users to interact with it on Repl.it at any time.

Conclusion

Congratulations on your achievement! You’ve now learned how to create a Python Discord bot. You can construct bots to communicate with members of guilds you form, as well as bots that other users can invite to interact with their communities. Messages, commands, and a variety of other events will be able to be responded to by your bots.

Read their detailed documentation to learn more about the powerful discord.py library and how to take your bots to the next level. You also have a better basis for constructing various types of Discord applications now that you’re familiar with Discord APIs in general.

Leave a Reply

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

Back to top
%d bloggers like this: