[Discord Bot] 01. Creating a Basic Bot
Creating a basic Discord chat bot using Python3
Just for fun, let’s write something I haven’t written before.
Lately, I’ve been active on Discord, so I’ve decided to create a Discord ChatBot.
Adding a Discord Application
Go to Discord Developers Applications and log in to your Discord account.
Click on New Application
, name it, and then click Create
. You can change the name later.
Navigate to Bot
on the left and click on Add Bot
.
Click on the OAuth2
tab on the left.
- In
SCOPES
, selectbot
. - Under
Bot Permissions
, chooseAdministrator
.
The link for inviting the bot to your server is shown below.
Installing pip and Discord.py
Use the following command to install the Discord.py
library.
python3 -m pip install -U discord.py
Bot Code
We’ve just created a bot and added it to our server. The next step is to start the bot and make it do something.
As an example, let’s write the simplest bot and see how it performs.
roll_dice.py
# Import the Discord.py library
import discord
# Obtain the Discord client object for operations
client = discord.Client()
# Invoke the event library
@client.event
# When the bot is ready, display a message in the terminal
async def on_ready():
print(f'Logged in as {client.user}')
# Invoke the event library
@client.event
# When a message is received
async def on_message(message):
# Exclude messages sent by the bot itself to avoid an infinite loop
if message.author == client.user:
return
# If we say "Who is the bot," the bot will respond with "Who called me?"
if message.content == 'Who is the bot':
await message.channel.send('Who called me?')
client.run('MY APP TOKEN')
The explanation is provided in the example. The only thing to explain is where to get the token.
No more talking, let’s see the image!
You can obtain the TOKEN on the BOT
page in Discord Developer.
It won’t be directly displayed on the screen; just click Copy
.
If you insist on viewing it, click Click to Reveal Token
, and it will be displayed.
If you think the TOKEN is compromised, you can use Regenerate
to generate a new one.
Starting the Bot
Open your terminal and run the Python file you just created.
python roll_dice.py
Now, test whether the command triggers the bot.
Looks like it was successfully called!