Discord bots automate community management, add games and utilities, and connect Discord servers to external services. Here's the complete Python guide.
Create Your Bot
- Go to discord.com/developers/applications → New Application
- Bot section → Add Bot → Copy token
- OAuth2 → URL Generator → Select bot + permissions → invite to server
Install discord.py
pip install discord.py
Basic Bot With Prefix Commands
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')
@bot.command()
async def info(ctx, member: discord.Member = None):
member = member or ctx.author
embed = discord.Embed(title=f'Info: {member.name}', color=0x818cf8)
embed.add_field(name='ID', value=member.id)
embed.add_field(name='Joined', value=member.joined_at.strftime('%Y-%m-%d'))
await ctx.send(embed=embed)
bot.run('YOUR_BOT_TOKEN')
Slash Commands (Modern Approach)
@bot.tree.command(name='hello', description='Says hello')
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(f'Hello {interaction.user.mention}!')
# Sync slash commands
@bot.event
async def on_ready():
await bot.tree.sync()
print(f'{bot.user} ready')
Event Handlers
@bot.event
async def on_member_join(member):
channel = member.guild.system_channel
if channel:
await channel.send(f'Welcome {member.mention} to the server! 👋')
@bot.event
async def on_message(message):
if message.author.bot: return
if 'help' in message.content.lower():
await message.add_reaction('✅')
await bot.process_commands(message) # Don't forget this
Deploy to VPS (Systemd)
[Unit]
Description=Discord Bot
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/ubuntu/bot
ExecStart=/usr/bin/python3 bot.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Need a custom Discord bot? Order on Kwork →