Writing Code for Bot
In this section, we are going to write python code for our discord bot.
Step 1: We are going to create .env file to store the renewal key for our bot we copied above, .env file will protect our credentials when we will host our code somewhere. First, create a .env named file in your project folder and then insert the following code.
TOKEN = ‘<YOUR_KEY>’
Step 2: Importing modules
Create a new python file for main bot code and name it as you want and import necessary modules.
Python3
import discord import os import random from dotenv import load_dotenv |
Step 3: Initializing Variables
Python3
load_dotenv() client = discord.Bot() token = os.getenv( 'TOKEN' ) |
Using load_dotenv() function to import environment variables. Creating discord client to send a request to discord API and last we are getting and initializing our environment variable token.
Step 4: Initializing our Bot
Python3
@client .event async def on_ready(): print ( "Logged in as a bot {0.user}" . format (client)) |
Here we are using on_ready() event provided by discord API once our API client has initialized this event will trigger performing the given operation. Here we are printing the name of our bot.
Step 5: Setting up bot responses
- We are setting appropriate bot responses to user messages. Discord API event on_message which takes an argument as the message is used for this purpose, message argument contains details about the message, author of the message, on which channel the message has been sent .etc
- First extract information about the message such as username, channel, and content of the message.
- The next line plays an important role if the message is sent by the bot itself then don’t respond to it if this condition is not written then the bot will infinitely respond to itself.
- We are going to activate our bot on the channel we create in our server called random, you can also activate the bot in other channels. Writing multiple if-else statements will do work but you can also implement a chatbot using machine learning. Here we implemented a few if-else statements to respond to basic messages such as hi, hello, and bye and implemented a basic statement to tell a joke. You can always add more functionality and make your bot more interactable.
Python3
@client .event async def on_message(message): username = str (message.author).split( "#" )[ 0 ] channel = str (message.channel.name) user_message = str (message.content) print (f 'Message {user_message} by {username} on {channel}' ) if message.author = = client.user: return if channel = = "random" : if user_message.lower() = = "hello" or user_message.lower() = = "hi" : await message.channel.send(f 'Hello {username}' ) return elif user_message.lower() = = "bye" : await message.channel.send(f 'Bye {username}' ) elif user_message.lower() = = "tell me a joke" : jokes = [" Can someone please shed more\ light on how my lamp got stolen?", "Why is she called llene? She\ stands on equal legs.", "What do you call a gazelle in a \ lions territory? Denzel."] await message.channel.send(random.choice(jokes)) |
Step 6: Running bot
We created the API client above which provides a function called to run this function takes the argument auth token as an argument and runs the bot by calling on_ready event.
Python3
client.run(token) |
Output:
Log:
Creating Commands
In the above steps, We saw how to use client.event for commands but for practical uses we generally don’t use that. Discord has provided us another way to create commands and that is by using prefix.
Step 1: Import commands
Import commands from discord.ext which will help us implement commands.
Python3
from discord.ext import commands |
Step 2: Choose a Prefix
Now, choose a prefix from which the bot should be activated and listen to commands. This can be any symbol, alphabet or even a word. For the sake of simplicity, we will choose “!” as our prefix. For this edit the previously defined client:
Python3
client = commands.Bot(command_prefix = "! * ) |
Step 3: Creating Commands
Now, we will create a command. For this, we will use client.command as a decorator.
Python3
@client .command() async def ping(ctx): await ctx.send( 'Pong!' ) |
- ctx: Represents the commands.context class. This argument is mandatory for all normal commands(Not for slash commands). It represents the context in which a command is being invoked under. This argument can give a lot of meta data for ex,: author data, message data etc…
- ctx.send: This is used to send the message back to the channel where the command was invoked. Make sure to use await as this is a coroutine.
Now, run your file again and go the server’s channel where the bot is present.
If you type “!ping”, The bot will reply with “Pong”.
Conclusion
So, this was a basic example to use discord.py library to create a Discord Bot. With the updated version of discord.py even slash commands and Modals can be created.
Creating a Discord Bot in Python
If you are familiar with online communities and if you are a part of one or you own one, you must have heard about discord and in discord, you may have seen bots managing those communities. So in this article, we are going to set up our discord developer portal account and will create a discord bot. A minimal bot with basic functionalities and if you want you can always extend the functionalities of this bot according to your needs.