Author: Kenn Carlo Gutierrez
Last Updated: Wed, Sep 1, 2021Discord is a video, voice, and text communication platform that allows bots to perform automated tasks based on user commands. This article explains how to run a Python-based Discord bot on a Docker application.
Install the Discord API wrapper for Python.
# pip install discord.py
Switch to your home directory.
# cd ~
Create a project folder.
# mkdir discord-bot
Switch to the project folder.
# cd discord-bot
Create a python file named discord_bot.py
.
# nano discord_bot.py
Paste this sample code to your discord_bot.py
file. Replace <YOUR BOT TOKEN>
with the token you saved in section 1.
import discord
TOKEN = '<YOUR BOT TOKEN>'
client = discord.Client()
@client.event
async def on_ready():
print('We have successfully loggged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == 'hello':
await message.channel.send(f'Hello, {message.author.display_name}!')
return
if message.content.lower() == 'bye':
await message.channel.send(f'See you later, {message.author.display_name}!')
return
client.run(TOKEN)
The Discord bot should respond to commands such as hello
, and bye
.
Save and exit the file.
Create a Dockerfile
.
# nano Dockerfile
Paste this to your Dockerfile
.
FROM python:3
FROM gorialis/discord.py
RUN mkdir -p /usr/src/bot
WORKDIR /usr/src/bot
COPY . .
CMD [ "python3", "discord_bot.py" ]
Save and exit the Dockerfile
.
Change to the Discord bot project directory.
# cd ~/discord-bot
Build the docker container for the Discord bot.
# docker build -t discord-bot .
Run the docker container.
# docker run -d discord-bot
Running the bot with -d
flag runs the container in detached mode (it runs in the background).
List all docker processes:
# docker ps
Stop the docker container (discord bot):
# docker stop <CONTAINER ID>
Restart the docker container:
# docker restart <CONTAINER ID>
You can find the <CONTAINER ID>
when you list all the Docker processes.
The Discord bot is now up and running.
To learn more about Discord bots, please see these resources: