Intermediate

Discord is a popular collaboration platform that initially was targeted at gamers that has more than 300million users. Within Discord, there’s an ability to create ‘bots’. These are computer users that have code behind them to respond to interactions with them but they can be very useful to do some other tasks as well.

What can you do with a discord bot?

You have control of your bot and what it can do so the ideas are endless. Some popular ideas for bots includes:

  1. Welcome bot – when you join a channel there are welcome messages and instructions for your attendees
  2. Quiz bot – a bot that can generate a quiz to test your members with trivia as a means to engage them
  3. Poll bots – a bot that can survey your members on a particular area
  4. Meme bots – these pull images from the web in reaction to your commands

There are many more ideas you can create with a discord bot. You will be able to recognise a bot with the “BOT” tag in Discord.

How the Discord bot works

A discord bot works by creating an “application” configuration in discord, assigning it to a discord user called a “bot user”, and then running a python program in our case that controls this bot user.

The architecture is as follows where you create the bot independently, then assign it to a given server with your python code running outside of Discord to provide the logic for your bot. You will need to ensure you have a place to run your code (either a server or run it in the background). Whenever your code is not running, your bot will be offline.

So the overall steps will be:

  • Step 1: Setting up your account on Discord and creating your Discord server
  • Step 2: Configuring the bot
  • Step 3: Configuring security and adding your bot to your server
  • Step 4: Writing and then running your python code for your bot logic
  • Step 5: Getting your bot to interact with messages
  • Step 6: Getting your bot show a weather forecast

Step 1: Setting up your account on Discord

First and foremost you will need to create a discord account if you haven’t already at discord.com/register

Once you’ve entered your logon details, you will need to chose a type of server. Server’s are not referring necessarily to a computer server but are more referring to a space on discord for your community. There are different styles of servers and you can select a template which best suits your intent. For this demo we’ll create a simple one:

You can then chose if it is to be a large server (“lead a community”) or intended to be a smaller server (“for friends and family”). Finally you can name the server so that people can find it,

Once you’re done, you will be taken to your own discord server! Please make sure you verify your account through your email. An activation link would have been sent to your email that you used to register.

Now with your space already set up, you’re ready to go.

Step 2: Configuring the bot

Each bot is referred to as an “application” which will need to be registered in the developer portal. This will help Discord know which bots they will allow to be embedded to a given server. You will create an “application” first, and then this will give you the authentication tokens for you to use later in your python code.

Make sure you are logged in, and then go to https://discord.com/developers/applications . In case you go to the chat window, enter the URL. You should see the following:

Click on “New Application” and then you can specify the application – in this case “Weather Forecast” bot.

You can then add further details such as icon, search tags:

You can then “Save changes”.

Finally, on the left hand menu, click on “Bot” and then “Add Bot”. This will help to assign your application as a bot and make the bot look like a user in the chat screens.

In the bot screen, you will need to click on Reset Token to get a new security token. You will need to copy this token to use in your python code. This is the security token you will use to connect to your bot. In case you lost this security token or it was leaked, you can generate a new one in this same screen:

Your Discord Bot Security Token

Step 3: Configuring Authentication and Adding Your Bot to Your Server

On the left menu list, click on OAuth. This is where permissions will be configured so that your remote python code can acccess the Discord bot.

Chose the option “bot”, and then scroll down and select all the “Text messages”. At the bottom of the screen a generated URL be created. Copy this as this will be your URL to connect to the server.

Paste the copied link into a new tab, select your server and hit continue.

Chose the server that your bot is intended to connect to – in this case “PythonHowToProgram”:

Next confirm the access rights (already pre-selected before) and click on Authorize at bottom of the screen:

Finally there will be a captcha to confirm you are a real person.

That’s it, configuration is done.

When you go to your main chat window, you should be able to see the bot in the users that are connected to your server:

The reason it shows as offline is because there’s no python code generated yet.

Step 4: Getting the bot online

So at this point, you will be able to see your bot in the server members tab but it will be offline. So here is where the coding part begins!

The engine of the bot will be a event based where you specify events to

Let’s install the discords files first.

pip install discord

Now we will import the discord files and add a token that will be used as an ID for the BOT. Remember to add the token code which you have copied from Step 1 and use that otherwise it won’t work. The following code will help to get the bot online. Please note the print statement will only show on your console and not anywhere else.

import discord

TOKEN = '<Your Discord Bot Security Token>'
client = discord.Client()

@client.event
async def on_ready():
	print('We have logged in successfully')

if __name__ == '__main__':
	client.run(TOKEN)

When you run this code – you’ll notice the code will run forever as it is waiting to process the next event:

On your Discord server you’ll now see your bot is online – it’s green!

However, right now your bot cannot do anything and cannot respond to any messages since we have yet to write that logic in there.

Step 5: How To Read Write Messages from a Discord Bot

Now the Bot is online, but it doesn’t talk or interact so in this step we are going to make the bot read user messages and store them.

The event you need to manage is “on_message”. With this event, you will intercept every message that is being entered on your server. The object that is passed is a Message object that has some interesting properties. with the argument below of message representing the Message object you can access some useful fields:

  • message.channel.name – the name of the channel where the message was sent
  • message.author.name – name of the user
  • message.content – actual content of the message

The following code will add a direct response of the message posted in the channel was ‘hello’ or ‘bye’:

#Read message
@client.event
async def on_message(message):
	print(f'({message.channel.name}):{message.author.name}:{message.content}')
	if message.content.lower() =='hello':
		await message.channel.send(f'Hello There {message.author.name}')
		return
	elif message.content.lower() == 'bye':
		await message.channel.send(f'bye bye {message.author.name}!')
		return

You can see the bot responding in Discord server below:

The code is fairly easy to understand as it just checks to see the user typed “hello” or “bye” and if so then returns a message to the same channel through the message.channel.send() function call.

There are the async and await commands that are there. These prevent the code to block if the response is not fast enough since there might be more messages that might come through at the same time. You can see an explanation here:

Now that we know how to have a bot registered that can respond, let’s create a slightly more interesting example.

Step 6: See the 5 day weather forecast from your bot

For the final section, let’s create a response from your bot, that if you ask for the current weather and provide a location, you’ll get a 7 day weather forecast as an image.

For this to work you can use the python library weatherchart

pip install weatherchart

In order to get the weather chart for a given location you need to arrange two things:

  1. Token to call a weather API from OpenWeatherMap. You can create your API key from your profile “My API Keys”
  2. The timezone name (e.g. EST or Asia/Hong_Kong) to use for the 7 day forecast. Full list on Wiki

To test the API, try the following:

from weatherchart import WeatherChart

wchart = WeatherChart('<your open weather map API token>', 'Asia/Hong_Kong')
print( wchart.get_forecast_chart_image_by_loc('Tokyo, Japan'  ) )

When you run this you’ll get the URL of your particular 7-day forecast:

You can then combine this to your discord bot fairly easily by responding to a chat. If a user types in weather <location>, then the <location> will be sent to the get_forecast_chart_image_by_loc() and a URL be returned.

wchart = WeatherChart('<your OpenWeatherMap token>', 'Asia/Hong_Kong')
space_index = message.content.find(' ')
await message.channel.send(f"{ wchart.get_forecast_chart_image_by_loc( message.content[ space_index+1:] )  }")

Hence the full code will look like this:

import discord

from weatherchart import WeatherChart
TOKEN = '<your discord bot token>'

client = discord.Client()


@client.event
async def on_ready():
	print('We have logged in successfully')

#Read message
@client.event
async def on_message(message):
	print(f'({message.channel.name}):{message.author.name}:{message.content}')
	if message.content.lower() =='hello':
		await message.channel.send(f'Hello There {message.author.name}')
		return
	elif message.content.lower() == 'bye':
		await message.channel.send(f'bye bye {message.author.name}!')
		return
	elif message.content.split(' ')[0] == 'weather':
		wchart = WeatherChart('<your OpenWeatherMap API token>', 'Asia/Hong_Kong')
		space_index = message.content.find(' ')
		await message.channel.send(f"{ wchart.get_forecast_chart_image_by_loc( message.content[space_index+1:] )  }")

if __name__ == '__main__':
	client.run(TOKEN)

With the above code, if you type in for example weather Seattle then what happens in the background is that first the location is converted to a Lat/Long, then sent to OpenWeatherMap to get the 7 day weather forecast, and finally this is converted to a chart image using quickcharts.io. A URL is in fact returned and this URL, which is an image file, when sent to the bot will be automatically be shown as that image!

Conclusion

That’s a good start on your Discord bot. We just only scratched the surface. You can do many more things such as trigger an event when a new person joins the chatroom, you could do some ‘onboarding’ for them, you could schedule a job to send reminders, you could also have some automatic moderation as well! You can refer to the official Discord developer documentation or also look into the PyPi discord library which has a range of sample code as well.

Comments? Feedback? Email us at admin@pythonHowToProgram.com

Join the Python Insiders Group and get FREE tips in your inbox
Also, when you subscribe, we will send you a list of the most useful python one liners which will help you save time, make your code more readable, and which you can use immediately in your code! Subscribe to our email list and get the list now!