Hosting a Python Discord Bot using AWS & Redis

Setting up a Python Discord Bot on an AWS virtual server and saving your Authentication Token using Redis

E.T. Deubner
Jul 17, 2020 · 7 min read
Image for post
Image for post
Photo by Halacious on Unsplash

We’re going to set up a Discord Bot using Python. We’ll use AWS to host and Redis to save our Authentication Token. We’ll need to do 4 things.

  1. Set up an AWS Virtual Server
  2. Set up a bot in Discord
  3. Use Redis to hold and retrieve our Discord Authentication Token
  4. Write code using Python that controls our bot

Set up an AWS Virtual Server

The first thing we’re going to do is set up a virtual server using AWS. This is where we’ll host our Discord Bot. You can set up a free tier account with 12 months of access very easily. You will need a credit/debit card so they can verify your identity. You’ll also need a phone for security verification.

AWS (Amazon Web Services) offers a wide range of services that are worth checking out. All we need it for is a virtual server running Ubuntu 18.04. If you’re a Windows user there is an option for that too. At this time I’ll only be covering Ubuntu. We’ll see how this goes and I might make a Windows add-on.

Image for post
Image for post
Launch a virtual machine

Go to aws.amazon.com and create a new account. Choose Launch a virtual machine with EC2. I’ll be using Ubuntu 18.04 which is near the bottom of the list of available servers.

Once you get to the key pair screen select “Create a new key pair.” Type in a name, I used aws-discord, then it will have you save a private key file. You’ll need this when logging into the virtual server so take note of where you store it. After you download the private key, your server will start booting up.

Image for post
Image for post
Running instances

Eventually you’ll see the Instance State change to running. Now that our Linux Server is up we can login. Open a terminal window. Your virtual servers public DNS (IPv4) is located under the instance of your server. Copy the public DNS. ubuntu is the default username for Ubuntu servers. You’ll have to put the path of your private key file in as well. Replace the .pem file and DNS with your own and type the following.

$ ssh -i aws-discord.pem ubuntu@ec2–3–15–32–133.us-east-2.compute.amazonaws.com

You should get the following message. Type yes and hit enter.

The authenticity of host 'ec2-198-51-100-1.compute-1.amazonaws.com (10.254.142.33)'
can't be established.
RSA key fingerprint is 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f.
Are you sure you want to continue connecting (yes/no)?

You should see a command prompt that says something like ubuntu@ip-172.89.23.2. If you run into an error dealing with security and your .pem file try this.

$ sudo chmod 600 aws-discord.pem 

Now that we’re actually in our new virtual server we need to start redecorating. Update first.

sudo apt-get update

Then use apt to install python-pip, python-env, redis-server and vim. (I use vim and I’ll have a very cool guide that makes it a solid Python IDE at the bottom. If you have another favorite editor then by all means go ahead.)

Image for post
Image for post
Vim

Now we’re going to make a virtual environment to install our bot in. Make a new directory called DiscordBot. Change to that directory and make a virtual environment by running the following command.

$~/DiscordBot/python3 -m venv env 

Then type the following to activate the virtual environment you just created.

$~/DiscordBot/source env/bin/activate 

You should see (env) before your command prompt. Which means you are now in your virtual environment on your virtual server. Meta!

Everything is ready to begin coding. However, we still need to create a bot in Discord and we need to get our Authentication Token.

Set up a bot in Discord

You’ll need to have an active Discord account as well as a live server in Discord. Go to https://discord.com/developers/applications

Image for post
Image for post
Creating a Discord Bot

Click on New Application and name it whatever you want. Now click Bot on the left. Then click Add Bot.

Scroll down to Bot Permissions. For now we’ll make it an Administrator but you can change that later.

Now click on OAuth2. Scroll down to Scopes and select Bot. This will open another list of permissions right below it. Choose Administrator again. Now copy the link that is between Scopes and Bot Permissions. Paste it in a browser and hit enter.

Image for post
Image for post

You should be looking at a drop down list of any and all servers you have running. It’s asking where you want to place your bot. Select a server and hit Authorize. Within seconds you’ll have an offline bot occupying space in that server.

Image for post
Image for post

Use Redis to save our Authentication Token

We have the bot ready in Discord. We have a virtual environment set up on our virtual server which is being hosted using AWS. We’re almost ready to code. We just need to save our Discord Authentication Token using Redis.

Redis is a NoSQL Database that can be used in many different ways. You can use it as an alternative to Environment Variables and even SQL itself.

We need our Authentication Token first though. Go back to the Discord website and click on Bots. In the middle of that page it’ll say ‘Click to reveal token’. Click it and copy what you see.

Back in our virtual server we need to access the Redis client. First type this.

$ redis-server

If it’s already running you’ll get an error message saying the port is already in use. If it’s not running then you just started Redis. Now type this.

$ redis-cli
Image for post
Image for post

As you can see, once you’re in Redis it will show up as your local IP loop back address with 6379 as the port. You can change these things in the config file. Use set followed by a variable name and then your token. Use single quotes around both of them.

$ set ‘AUTH_TOKEN’ ‘TOKEN HERE WITH SINGLE QUOTES SURROUNDING’

Now we can access AUTH_TOKEN using Redis inside our code.

Use Python to program our bot

It’s finally time to start coding. Here is a basic starter bot. I’ve named the file bot.py.

import discord
import redis
redis_server = redis.Redis() # Create access to Redisclient = discord.Client() # starts the discord client.AUTH_TOKEN = str(redis_server.get(‘AUTH_KEY’).decode(‘utf-8’))@client.event
async def on_ready():
print(f’Successful Launch!!! {client.user}’)
@client.event
async def on_message(message): # event that happens per any message.
print(f”{message.channel}: {message.author}: {message.author.name}: {message.content}”)@client.event
async def on_message(message):
if message.content.upper() == ‘PURPLE’:
await message.channel.send(‘Start wearing purple’)
client.run(AUTH_TOKEN) # Pull Auth Token from above

We import discord and redis then make a Redis object. Next we make a client object which is our direct line of communication with Discord. Then we define a variable called AUTH_TOKEN by pulling data from our Redis object.

Redis always returns byte code so we have to decode it using ‘utf-8’ then convert it into a string.

AUTH_TOKEN = str(redis_server.get(‘AUTH_TOKEN’).decode(‘utf-8’))

The first event only tells us that our Bot has started. It doesn’t have to do anything. But this is a good way of making sure that the Bot actually started successfully.

@client.event 
async def on_ready():
print(f’Successful Launch!!! {client.user}’)

This event waits for a message. Any message. When it receives that message it spits out information about the author, the channel and the message itself.

@client.event
async def on_message(message): # event that happens per any message.
print(f”{message.channel}: {message.author}: {message.author.name}: {message.content}”)

This is another on_message event. This time we take the message and only act when the message content is the word purple. If it is purple then we use await message.channel.send to send a message directly to the channel itself.

@client.event
async def on_message(message):
if message.content.upper() == ‘PURPLE’:
await message.channel.send(‘Start wearing purple’)

Finally we have client.run using AUTH_TOKEN which is the variable we created by converting the contents of results from our Redis object into a string.

client.run(AUTH_TOKEN) # Pull Auth Token from above

Exit out of your editor and run your bot.

$ python3 bot.py

Your offline bot will switch to online. Try typing purple in your Discord Server to see if it’s working correctly. If it responds with ‘Start wearing purple’ then our bot is up and running.

I suggest setting up a kill command as well. Inside your code put this at the bottom right before client.run

@client.event
async def on_message(message):
if message.content == 'kill':
await client.logout()

Now you can kill your bot easily. Although you’ll want to set up some sort of security so not everyone can do this. What I’ve done in the past is create an admin bot channel that only I have access to. Then you can have the on_message event check to see if you’re in that channel and it will only run if you are. You can do the same thing with your username as well. I like having the bot channel for testing as well.

Well, that’s the basics of putting together a Discord Bot using Python. I highly recommend checking out how cogs work and what else you can do with Redis. Check out the documentation for discord.py and if you continue using vim definitely check out how to optimize it for Python. Thanks so much for reading and best of luck to you.

Discord.py documentation

Setting up Vim for Python

Python & Redis

Python & Cogs

Python In Plain English

New Python + Programming articles every day.

E.T. Deubner

Written by

I write about my experiences as a Software Engineer — If anyone has any questions or comments, please reach out. I love feedback — both positive and negative.

Python In Plain English

New Python + Programming articles every day.

E.T. Deubner

Written by

I write about my experiences as a Software Engineer — If anyone has any questions or comments, please reach out. I love feedback — both positive and negative.

Python In Plain English

New Python + Programming articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store