Create your own Discord bot with Python

Gunnard/ November 16, 2021/ Development, Learning/ 0 comments

What is the best way to develop a Discord bot? You’ve always wondered about this, and we’re here to walk you through the process of creating your own Discord bot. You may make a Discord bot on any platform, including smartphones, tablets, and computers.

We’ll use repl.it to run the bot in this tutorial, but you may also run it locally. With repl.it, your bot will be able to run 24 hours a day, 7 days a week for FREE! This tutorial utilizes Python, but you may also use Javascript/NodeJs.

To begin, we must create a bot on the Discord Developer Portal.

Using the Discord Developer Portal to Create a Bot 1. Log in to the Discord Developer Portal with your Discord account.

  1. Select New Application from the menu bar.

3. Name your application

4. Head to the Bots tab and click on Add A Bot

5. Copy the token as you’re going to need it later on, the token is like the password for your bot, do not share it to anyone you don’t trust or they will be able to hack and log into your bot

Let’s get started building the bot in Repl.it!

  1. Create a free repl.it account.
  2. Create a repl with Python as the language of choice.

Begin by adding import discord to the top of main.py’s first line. Discord.py will be automatically installed when you run the repl.

import discord

Let’s get started planning the events now! When the bot is ready and online, you can use the on ready method to control what it does!

Consider the following scenario:

import discord
client = commands.Bot(command_prefix="%")
@client.event
async def on_ready():
    print('Bot is ready')
print('Bot is ready')

When the bot logs on successfully, this emits “Bot is ready” in the console.

You may use the client function to make configuring your prefixes easier, and it also allows the bot to respond to commands that begin with the prefix!

Commands
Let’s go on to our first command:

from discord.ext import commands @client.command(aliases=[‘hi’]) async def hello(ctx): await ctx.send(“Hi there my friend!”)

If you type %hello or its alias %hi, the bot will reply Hi there my friend! We also need to import commands from discord.ext in order for commands to operate!

How to make the bot work

  1. Return to the previous tab of the Discord Developer Portal.
  2. Go to Bots, copy the Token, and don’t give it to anyone else because they’ll be able to hack into your bot.
  3. Return to your repl and create an environment titled TOKEN in the sidebar, then paste your token into the key. Environments are.env files that prohibit outsiders from viewing and hacking into your token. Anyone can access your code on Repl.it’s free plans, but they can’t see your environment files.
  4. In order to use.env files, we must first import the os module.
import os secret = os.environ['TOKEN']

os.environ finds the .env file, and now your bot is hack-free!

5. In the last line of your code, add this in order for the bot to login

client.run(secret)

6. Now, head to shell, and run the command to install discord on your repl

pip install discord

7. You can now run the bot by clicking the Run button, your code should be something like this, change the token to your bot token

If the console prints Bot is ready, then your code is probably correct!

How to add the bot to your server

1. Head to OAuth2 on the sidebar, select bot, and the required permissions

2. Now copy the generated link and paste it in a new tab

3. Select the server you would like to invite it to

4. Test the bot, make sure it is online in the member list

How to send embed texts

Sending embed texts can be done easily by using the discord.Embed function, here’s an example below!

@client.command()
async def embed(ctx):
    e=discord.Embed(

        color=discord.Color.red(),
        title="Title",
        description="An embed text example"
    )
    await ctx.send(embed=e)

How can I keep the bot online 24 hours a day, 7 days a week?
Your bot will cease operating if you run it in repl.it and then close the tab in which it is executing. You can buy a premium plan on repl.it to keep it running indefinitely, but you can also do it for free. Here’s how:

Every 5 minutes, we’ll use Uptime Robot to ping the bot’s web server on repl.it. The bot will never enter the sleeping state if there are continual pings, and will instead continue to run.

  1. To begin, we must first construct a web server in repl.it. We will use Flask to do so. Create a file called alive.py and paste the following code into it.
from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
    return "I'm alive, and this is my web server!"

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

def alive():
    t = Thread(target=run)
    t.start()

In order to run alive.py from main.py, we need to add the following codes to it:

Add the code below to the top of main.py so it runs the alive function from the file.

from alive import alive

Now, add this code to the second-last line of your code, before your bot runs.

alive()

The full main.py code:

from alive import alive
import discord
import os
from discord.ext import commands
secret = os.environ['TOKEN']
client = commands.Bot(command_prefix="%")
@client.event
async def on_ready():
    print('Bot is ready')

@client.command(aliases=['hi'])
async def hello(ctx):
    await ctx.send("Hi there my friend!")

@client.command()
async def embed(ctx):
    e=discord.Embed(

        color=discord.Color.red(),
        title="Title",
        description="An embed text example"
    )
    await ctx.send(embed=e)
alive()
client.run(secret)

The full alive.py code:

from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
    return "I'm alive, and this is my web server!"

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

def alive():
    t = Thread(target=run)
    t.start()
Share this Post

Leave a Comment

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

*
*