Welcome to this workshop! We’re going to build a Discord bot with discord.py and Python. Let’s dive right into it!
Make sure you’re logged on to the Discord website.
Navigate to the application page
Click on the “New Application” button.
Give the application a name and click “Create”.
Create a Bot User by navigating to the “Bot” tab and clicking “Add Bot”.
If you want others to invite your bot, make sure that Public Bot is ticked. Also, make sure that Require OAuth2 Code Grant is unchecked.
Copy the token using the “Copy” button.
Go to the “OAuth2” tab
Tick the “bot” checkbox under “scopes”
Tick the permissions required for your bot to function under “Bot Permissions”
Now the resulting URL can be used to add your bot to a server. Copy and paste the URL into your browser, choose a server to invite the bot to, and click “Authorize”.
Source: https://discordpy.readthedocs.io/en/latest/discord.html
pip3 install -U discord.py
coolio_bot.py
Start off by importing the discord.py library:
import discord
client = discord.Client()
# Add event handlers here
client.run('Your token from Step 1')
Listen to the ready
event
# Event handlers
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
Listen for a new message
:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
import discord
client = discord.Client()
# Event handlers
@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
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('Your token from Step 1')
So now that you’ve got your bot set up, what’s next? Well, of course, start building! Take the next 30 minutes and see what you can come up with. Be ready to share your bot’s commands with others for them to try out what you make!
Let’s say we want to add a new command. Here’s what you would do:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
elif message.content.startswith('$hola'):
await message.channel.send('Hola amigo!')
A simple echo
bot:
@client.event
async def on_message(message):
if message.author == client.user:
return
await message.channel.send(message.content)
When someone sends $pic
, send a link to a random picture from https://picsum.photos/. Note: the ? + randrange()
is just for making discord fetch a new picture everytime you send the same link.
from random import randrange
...
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$pic'):
await message.channel.send('https://picsum.photos/400/400?' + str(randrange(1000)))