Author: Kenn Carlo Gutierrez
Last Updated: Wed, Aug 25, 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 and host it on a Debian 10 cloud server at Vultr.
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)
Save and exit the file.
Your Discord bot stops running when you exit the SSH session. To keep the bot running full-time, use Tmux or PM2.
Create a tmux session.
# tmux new -s DiscordBot
Change to the Discord bot project directory.
# cd ~/discord-bot
Start the bot.
# python3 discord_bot.py
To stop the Discord Bot, press CTRL + C
PM2 is a process manager for Python.
Install npm.
# apt install npm -y
Install PM2.
# npm install -g pm2
Change to the Discord bot project directory.
# cd ~/discord-bot
Start the bot.
# pm2 start discord_bot.py --interpreter=/usr/bin/python3
Make sure you are in the ~/discord-bot
directory, then use these commands to control your bot.
List all PM2 processes:
# pm2 list
Stop the Discord bot:
# pm2 stop discord_bot.py
Restart the Discord bot:
# pm2 restart discord_bot.py
The Discord bot is now up and running.
To learn more about Discord bots, please see these resources: