or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

app-commands.mdcommands-framework.mdcore-objects.mdevent-handling.mdindex.mduser-interface.mdutilities.mdvoice-audio.mdwebhooks.md
tile.json

tessl/pypi-discord-py

A modern, feature-rich, and async-ready API wrapper for Discord written in Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/discord.py@2.3.x

To install, run

npx @tessl/cli install tessl/pypi-discord-py@2.3.0

index.mddocs/

Discord.py

A modern, feature-rich, and async-ready API wrapper for Discord written in Python. Discord.py provides a comprehensive interface for building Discord bots and applications with proper rate limiting, optimized performance, and a Pythonic async/await API. The library supports all Discord features including guilds, channels, users, messages, voice connections, slash commands, and UI components.

Package Information

  • Package Name: discord.py
  • Language: Python
  • Installation: pip install discord.py
  • Optional Dependencies:
    • Voice support: pip install discord.py[voice]
    • Speed optimizations: pip install discord.py[speed]

Core Imports

import discord

For bot applications with commands:

from discord.ext import commands

For application commands (slash commands):

from discord import app_commands

For UI components:

from discord import ui

Basic Usage

Simple Bot Example

import discord
from discord.ext import commands

# Create bot with command prefix
bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())

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

@bot.command(name='hello')
async def hello(ctx):
    await ctx.send(f'Hello {ctx.author.mention}!')

# Run the bot
bot.run('YOUR_BOT_TOKEN')

Slash Command Example

import discord
from discord.ext import commands

class MyBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix='!', intents=intents)

    async def setup_hook(self):
        # Sync slash commands
        await self.tree.sync()

bot = MyBot()

@bot.tree.command(name='greet', description='Greet a user')
async def greet(interaction: discord.Interaction, user: discord.Member):
    await interaction.response.send_message(f'Hello {user.mention}!')

bot.run('YOUR_BOT_TOKEN')

Architecture

Discord.py is built around an event-driven architecture with several key components:

  • Client/Bot: Central connection manager handling WebSocket events and HTTP API calls
  • Gateway: WebSocket connection for real-time events (messages, reactions, presence updates)
  • HTTP: REST API client for Discord operations (sending messages, managing guilds, etc.)
  • Commands Framework: Extension providing prefix-based command parsing and execution
  • Application Commands: Built-in slash command and context menu support
  • Cogs: Modular command organization system for scalable bot architecture
  • UI Components: Interactive elements like buttons, select menus, and modals

This design enables both simple script-based bots and complex applications with sophisticated command systems, event handling, and user interactions.

Capabilities

Core Discord Objects

Essential Discord entities including users, guilds, channels, messages, roles, and permissions. These objects provide the foundation for all Discord bot interactions.

class Client:
    def __init__(self, *, intents: Intents): ...
    async def start(self, token: str) -> None: ...
    async def close() -> None: ...

class User:
    id: int
    name: str
    discriminator: str
    avatar: Optional[Asset]

class Guild:
    id: int
    name: str
    owner_id: int
    members: List[Member]
    channels: List[GuildChannel]

class TextChannel:
    id: int
    name: str
    guild: Guild
    async def send(self, content: str = None, **kwargs) -> Message: ...

Core Objects

Commands Framework

Prefix-based command system with argument parsing, checks, cooldowns, and error handling. Supports cogs for modular organization and extensive customization options.

class Bot(commands.Bot):
    def __init__(self, command_prefix: str, **options): ...
    def command(self, name: str = None, **attrs): ...
    def group(self, name: str = None, **attrs): ...

@commands.command()
async def example(ctx: commands.Context, arg: str): ...

@commands.check()
async def custom_check(ctx: commands.Context) -> bool: ...

Commands Framework

Application Commands

Slash commands and context menus with parameter validation, autocomplete, and localization support. Integrates seamlessly with Discord's native UI.

class CommandTree:
    async def sync(self, *, guild: Optional[Guild] = None) -> List[AppCommand]: ...
    def command(self, *, name: str, description: str): ...

@app_commands.command(name="example", description="Example command")
async def example_slash(interaction: Interaction, value: str): ...

@app_commands.describe(user="The user to greet")
async def greet(interaction: Interaction, user: Member): ...

Application Commands

User Interface Components

Interactive UI elements including buttons, select menus, modals, and views. Enables rich user interactions beyond traditional text commands.

class View:
    def __init__(self, *, timeout: Optional[float] = 180.0): ...
    async def on_timeout(self) -> None: ...

class Button(ui.Item):
    def __init__(self, *, style: ButtonStyle, label: str = None): ...
    async def callback(self, interaction: Interaction) -> None: ...

class Modal:
    def __init__(self, *, title: str, timeout: Optional[float] = None): ...
    async def on_submit(self, interaction: Interaction) -> None: ...

User Interface

Voice & Audio

Voice connection management and audio playback with support for various audio sources and real-time voice data processing.

class VoiceClient:
    async def connect(self, *, timeout: float = 60.0) -> None: ...
    async def disconnect(self, *, force: bool = False) -> None: ...
    def play(self, source: AudioSource, *, after: Callable = None) -> None: ...

class AudioSource:
    def read(self) -> bytes: ...
    def cleanup(self) -> None: ...

Voice & Audio

Event Handling

Comprehensive event system for responding to Discord activities like messages, reactions, member changes, and guild updates.

@client.event
async def on_ready(): ...

@client.event  
async def on_message(message: Message): ...

@client.event
async def on_member_join(member: Member): ...

@client.event
async def on_reaction_add(reaction: Reaction, user: User): ...

Event Handling

Webhooks

Both synchronous and asynchronous webhook clients for sending messages without a bot presence, supporting embeds, files, and thread management.

class Webhook:
    @classmethod
    async def from_url(cls, url: str, *, session: ClientSession = None) -> Webhook: ...
    async def send(self, content: str = None, **kwargs) -> WebhookMessage: ...
    async def edit_message(self, message_id: int, **kwargs) -> WebhookMessage: ...

Webhooks

Utilities & Helpers

Helper functions and utilities for common Discord operations including OAuth URLs, snowflake handling, markdown processing, and time formatting.

def oauth_url(client_id: int, *, permissions: Permissions = None) -> str: ...
def snowflake_time(id: int) -> datetime: ...
def utcnow() -> datetime: ...
def escape_markdown(text: str) -> str: ...

Utilities

Enums & Constants

Essential Discord enums for channels, messages, status types, and other Discord-specific values that provide type safety and clear API semantics.

class Status(Enum):
    online = 'online'
    offline = 'offline'
    idle = 'idle'
    dnd = 'dnd'
    do_not_disturb = 'dnd'
    invisible = 'invisible'

class ChannelType(Enum):
    text = 0
    private = 1
    voice = 2
    group = 3
    category = 4
    news = 5
    news_thread = 10
    public_thread = 11
    private_thread = 12
    stage_voice = 13
    forum = 15

class MessageType(Enum):
    default = 0
    recipient_add = 1
    recipient_remove = 2
    call = 3
    channel_name_change = 4
    channel_icon_change = 5
    pins_add = 6
    guild_member_join = 7

class ActivityType(Enum):
    playing = 0
    streaming = 1
    listening = 2
    watching = 3
    custom = 4
    competing = 5

Types

# Core Types
Snowflake = int

# Intent Types
class Intents:
    """Gateway intent flags controlling which events Discord sends to your bot."""
    def __init__(self, **kwargs): ...
    
    @classmethod
    def all(cls) -> Intents:
        """Create Intents with all flags enabled."""
    
    @classmethod
    def none(cls) -> Intents:
        """Create Intents with no flags enabled."""
    
    @classmethod
    def default(cls) -> Intents:
        """Create Intents with Discord's default flags."""
    
    # Core Intent Flags
    guilds: bool  # Guild events (recommended to keep enabled)
    members: bool  # Member events (requires privileged intent)
    moderation: bool  # Ban/unban events
    emojis_and_stickers: bool  # Emoji and sticker events
    integrations: bool  # Integration events
    webhooks: bool  # Webhook events
    invites: bool  # Invite events
    voice_states: bool  # Voice state events
    presences: bool  # Presence events (requires privileged intent)
    messages: bool  # Message events
    reactions: bool  # Reaction events
    typing: bool  # Typing indicator events
    message_content: bool  # Message content access (privileged)

# Permission Types  
class Permissions:
    def __init__(self, permissions: int = 0): ...
    @classmethod
    def all(cls) -> Permissions: ...
    @classmethod  
    def none(cls) -> Permissions: ...

# Color Types
class Colour:
    def __init__(self, value: int): ...
    @classmethod
    def red(cls) -> Colour: ...
    @classmethod
    def blue(cls) -> Colour: ...

# Message Types
class Embed:
    def __init__(self, **kwargs): ...
    def add_field(self, *, name: str, value: str, inline: bool = True) -> None: ...
    def set_footer(self, *, text: str, icon_url: str = None) -> None: ...

class AllowedMentions:
    def __init__(self, *, everyone: bool = True, users: bool = True, roles: bool = True): ...

# File Types
class File:
    def __init__(self, fp: Union[str, bytes, os.PathLike], filename: str = None): ...

Exceptions

# Base Exceptions
class DiscordException(Exception):
    """Base exception class for discord.py. Catch this to handle any discord.py exception."""

class ClientException(DiscordException):
    """Exception raised when a Client operation fails due to user input."""

class HTTPException(DiscordException):
    """Exception raised when an HTTP request fails."""
    status: int  # HTTP status code
    code: int  # Discord error code
    text: str  # Error message

# Specific HTTP Exceptions
class Forbidden(HTTPException):
    """Exception raised when a 403 Forbidden response is received."""

class NotFound(HTTPException):
    """Exception raised when a 404 Not Found response is received."""

class RateLimited(DiscordException):
    """Exception raised when being rate limited by Discord."""
    retry_after: float  # Seconds until retry is allowed

# Connection Exceptions
class ConnectionClosed(ClientException):
    """Exception raised when the gateway connection is closed unexpectedly."""

class LoginFailure(ClientException):
    """Exception raised when login fails due to invalid credentials."""

class PrivilegedIntentsRequired(ClientException):
    """Exception raised when privileged intents are required but not enabled."""