2 min read

Python Discord Bot Guide

This guide demonstrates how to create a Discord bot using the discord.py library. It covers setting up the bot, handling events, and creating commands.

Modules Used:

  • discord.py: The API wrapper for Discord.
  • python-dotenv: To securely manage the bot token.

Prerequisites

  1. Create an application in the Discord Developer Portal.
  2. Create a Bot user within the application.
  3. Copy the Token.
  4. Enable Message Content Intent in the Bot settings (required for reading command arguments).
  5. Invite the bot to your server using the OAuth2 URL generator (Scopes: bot, Permissions: Send Messages, Read Message History).

Installation

pip install discord.py python-dotenv

Setup

Create a .env file in your project directory to store your token:

DISCORD_TOKEN=your_actual_token_here

The Code

Save this as bot.py. This example uses the commands extension, which is the standard way to build bots.

import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

# 1. Load environment variables
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

# 2. Setup Intents
# Intents allow the bot to subscribe to specific buckets of events
intents = discord.Intents.default()
intents.message_content = True # Required to read message content

# 3. Create Bot Instance
# command_prefix is what triggers the bot (e.g., !ping)
bot = commands.Bot(command_prefix='!', intents=intents)

# --- Events ---

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

@bot.event
async def on_message(message):
    # Prevent bot from replying to itself
    if message.author == bot.user:
        return

    # Process commands (required if overriding on_message)
    await bot.process_commands(message)

# --- Commands ---

@bot.command(name='ping', help='Responds with Pong!')
async def ping(ctx):
    await ctx.send('Pong!')

@bot.command(name='echo', help='Repeats what you say')
async def echo(ctx, *, content):
    await ctx.send(content)

# Error Handling for Commands
@echo.error
async def echo_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('You need to tell me what to echo! Usage: !echo <text>')

# 4. Run the Bot
if TOKEN:
    bot.run(TOKEN)
else:
    print("Error: DISCORD_TOKEN not found in .env")

Usage

  1. Run the script:
    python bot.py
  2. In your Discord server, type !ping.

programming/python/python