CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-cord

A modern, async-ready Python API wrapper for Discord with comprehensive bot development features

Overall
score

93%

Overview
Eval results
Files

core-clients.mddocs/

Core Client Functionality

The foundation of py-cord's Discord integration, providing client classes for connecting to Discord, managing bot instances, handling events, and auto-sharding for large applications.

Capabilities

Base Client Classes

Core client classes that handle the connection to Discord's gateway and provide the foundation for all Discord interactions.

class Client:
    """
    Represents a client connection to Discord.
    
    Parameters:
    - loop: Optional[asyncio.AbstractEventLoop] - Event loop to use (default None uses current loop)
    - **options: Any - Additional options including:
        - intents: Intents - The intents to use for the client
        - max_messages: Optional[int] - Maximum messages in cache (default 1000, None disables)
        - heartbeat_timeout: float - Gateway heartbeat timeout seconds (default 60.0)
        - guild_ready_timeout: float - Guild ready timeout seconds (default 2.0)
        - assume_unsync_clock: bool - Assume unsync clock (default True)
        - enable_debug_events: bool - Enable debug gateway events (default False)
        - shard_id: Optional[int] - Shard ID for this client
        - shard_count: Optional[int] - Total number of shards
        - connector: Optional[aiohttp.BaseConnector] - HTTP connector
        - proxy: Optional[str] - Proxy URL
        - proxy_auth: Optional[aiohttp.BasicAuth] - Proxy authentication
    """
    
    def __init__(
        self, 
        *, 
        loop: Optional[asyncio.AbstractEventLoop] = None,
        **options: Any
    ): ...
    
    async def start(self, token: str) -> None:
        """Start the client with the given bot token."""
    
    async def close(self) -> None:
        """Close the client connection."""
    
    def run(self, token: str, *, reconnect: bool = True) -> None:
        """Run the client. This is a blocking call that starts the event loop."""
    
    def event(self, coro) -> Callable:
        """Decorator that registers an event handler."""
    
    async def login(self, token: str) -> None:
        """Login to Discord with the given token."""
    
    async def connect(self, *, reconnect: bool = True) -> None:
        """Connect to the Discord gateway."""
    
    def is_ready(self) -> bool:
        """Return True if the client is ready."""
    
    def is_closed(self) -> bool:
        """Return True if the client connection is closed."""
    
    @property
    def latency(self) -> float:
        """The latency between a HEARTBEAT and HEARTBEAT_ACK in seconds."""
    
    @property
    def user(self) -> Optional[ClientUser]:
        """The client user (bot account)."""
    
    @property
    def guilds(self) -> List[Guild]:
        """A list of guilds the client can see."""
    
    @property
    def users(self) -> List[User]:
        """A list of users the client can see."""
    
    def get_guild(self, id: int) -> Optional[Guild]:
        """Get a guild by ID."""
    
    def get_user(self, id: int) -> Optional[User]:
        """Get a user by ID."""
    
    def get_channel(self, id: int) -> Optional[Union[GuildChannel, PrivateChannel]]:
        """Get a channel by ID."""
    
    async def fetch_guild(self, guild_id: int, *, with_counts: bool = True) -> Guild:
        """Fetch a guild from the API."""
    
    async def fetch_user(self, user_id: int) -> User:
        """Fetch a user from the API."""
    
    async def fetch_channel(self, channel_id: int) -> Union[GuildChannel, PrivateChannel]:
        """Fetch a channel from the API."""

class ClientUser(User):
    """
    Represents the client user (the bot itself).
    """
    
    async def edit(self, *, username: str = None, avatar: bytes = None) -> ClientUser:
        """
        Edit the client user.
        
        Parameters:
        - username: str - New username
        - avatar: bytes - New avatar image data
        """

class AutoShardedClient(Client):
    """
    A client that automatically shards the bot across multiple shards.
    
    Parameters:
    - shard_count: Optional[int] - Number of shards to use (None for automatic)
    - shard_ids: Optional[List[int]] - Specific shard IDs to use
    """
    
    def __init__(
        self,
        *,
        shard_count: Optional[int] = None,
        shard_ids: Optional[List[int]] = None,
        **options
    ): ...
    
    @property
    def shard_count(self) -> Optional[int]:
        """The number of shards this client is using."""
    
    @property
    def shards(self) -> Dict[int, ShardInfo]:
        """A mapping of shard IDs to their info."""

Bot Classes for Application Commands

Enhanced client classes specifically designed for building bots with application command support (slash commands, user commands, message commands).

class Bot(Client):
    """
    A subclass of Client that provides application command support.
    
    Parameters:
    - description: Optional[str] - Bot description (default None)
    - **options: Any - Additional options including all Client options plus:
        - debug_guilds: Optional[List[int]] - Guild IDs for debugging commands
        - owner_id: Optional[int] - Bot owner user ID
        - owner_ids: Optional[Set[int]] - Set of bot owner user IDs
        - auto_sync_commands: bool - Whether to automatically sync commands (default True)
        - default_command_contexts: Collection[InteractionContextType] - Default command contexts
        - default_command_integration_types: Collection[IntegrationType] - Default integration types
    """
    
    def __init__(
        self,
        description: Optional[str] = None,
        *,
        **options: Any
    ): ...
    
    def slash_command(
        self,
        *,
        name: str = None,
        description: str = None,
        guild_ids: List[int] = None,
        **kwargs
    ) -> Callable:
        """
        Decorator for creating slash commands.
        
        Parameters:
        - name: str - Command name (defaults to function name)
        - description: str - Command description
        - guild_ids: List[int] - Guilds where this command is available
        """
    
    def user_command(
        self,
        *,
        name: str = None,
        guild_ids: List[int] = None,
        **kwargs
    ) -> Callable:
        """
        Decorator for creating user context menu commands.
        
        Parameters:
        - name: str - Command name (defaults to function name)
        - guild_ids: List[int] - Guilds where this command is available
        """
    
    def message_command(
        self,
        *,
        name: str = None,
        guild_ids: List[int] = None,
        **kwargs
    ) -> Callable:
        """
        Decorator for creating message context menu commands.
        
        Parameters:
        - name: str - Command name (defaults to function name)
        - guild_ids: List[int] - Guilds where this command is available
        """
    
    async def sync_commands(
        self,
        *,
        commands: List[ApplicationCommand] = None,
        guild_ids: List[int] = None,
        register_guild_commands: bool = True,
        check_guilds: List[int] = None,
        delete_existing: bool = True,
        force: bool = False
    ) -> None:
        """
        Sync application commands with Discord.
        
        Parameters:
        - commands: List[ApplicationCommand] - Specific commands to sync
        - guild_ids: List[int] - Specific guilds to sync to
        - register_guild_commands: bool - Whether to register guild commands
        - check_guilds: List[int] - Guilds to check for existing commands
        - delete_existing: bool - Whether to delete existing commands not in the list
        - force: bool - Force sync even if commands haven't changed
        """
    
    @property
    def pending_application_commands(self) -> List[ApplicationCommand]:
        """List of application commands pending sync."""
    
    def get_application_command(
        self,
        name: str,
        *,
        guild_id: int = None,
        type: ApplicationCommandType = None
    ) -> Optional[ApplicationCommand]:
        """Get an application command by name."""
    
    async def is_owner(self, user: Union[User, Member]) -> bool:
        """Check if a user is the bot owner."""

class AutoShardedBot(Bot, AutoShardedClient):
    """
    A Bot that automatically shards across multiple processes.
    """
    pass

Connection Management and Events

Event system for handling Discord gateway events and managing the bot's lifecycle.

# Event Decorators and Registration
def event(coro) -> Callable:
    """
    Decorator that registers a coroutine as an event handler.
    
    Example:
    @bot.event
    async def on_ready():
        print(f'{bot.user} is ready!')
    """

def listen(name: str = None) -> Callable:
    """
    Decorator that registers a listener for a specific event.
    
    Parameters:
    - name: str - Event name to listen for
    """

# Core Events
async def on_ready() -> None:
    """Called when the client has successfully connected and is ready."""

async def on_resumed() -> None:
    """Called when the client has resumed a session."""

async def on_connect() -> None:
    """Called when the client has successfully connected to Discord."""

async def on_disconnect() -> None:
    """Called when the client has disconnected from Discord."""

async def on_shard_connect(shard_id: int) -> None:
    """Called when a shard connects."""

async def on_shard_disconnect(shard_id: int) -> None:
    """Called when a shard disconnects."""

async def on_shard_ready(shard_id: int) -> None:
    """Called when a shard is ready."""

async def on_shard_resumed(shard_id: int) -> None:
    """Called when a shard resumes."""

# Guild Events
async def on_guild_join(guild: Guild) -> None:
    """Called when the bot joins a guild."""

async def on_guild_remove(guild: Guild) -> None:
    """Called when the bot is removed from a guild."""

async def on_guild_update(before: Guild, after: Guild) -> None:
    """Called when a guild is updated."""

async def on_guild_available(guild: Guild) -> None:
    """Called when a guild becomes available."""

async def on_guild_unavailable(guild: Guild) -> None:
    """Called when a guild becomes unavailable."""

# Message Events  
async def on_message(message: Message) -> None:
    """Called when a message is created."""

async def on_message_edit(before: Message, after: Message) -> None:
    """Called when a message is edited."""

async def on_message_delete(message: Message) -> None:
    """Called when a message is deleted."""

async def on_raw_message_edit(payload: RawMessageUpdateEvent) -> None:
    """Called when a message is edited (raw payload)."""

async def on_raw_message_delete(payload: RawMessageDeleteEvent) -> None:
    """Called when a message is deleted (raw payload)."""

# Member Events
async def on_member_join(member: Member) -> None:
    """Called when a member joins a guild."""

async def on_member_remove(member: Member) -> None:
    """Called when a member leaves a guild."""

async def on_member_update(before: Member, after: Member) -> None:
    """Called when a member is updated."""

# Application Command Events
async def on_application_command_error(ctx: ApplicationContext, error: Exception) -> None:
    """Called when an application command raises an error."""

async def on_application_command(ctx: ApplicationContext) -> None:
    """Called when an application command is invoked."""

Intents and Permissions

Gateway intents control what events your bot receives, optimizing performance and respecting Discord's requirements.

class Intents:
    """
    Represents Discord gateway intents.
    
    Intents control which events your bot receives from Discord.
    Some intents are privileged and require approval for verified bots.
    """
    
    def __init__(self, **kwargs) -> None: ...
    
    @classmethod
    def all(cls) -> Intents:
        """Create an Intents object with all intents enabled."""
    
    @classmethod
    def none(cls) -> Intents:
        """Create an Intents object with no intents enabled."""
    
    @classmethod
    def default(cls) -> Intents:
        """Create an Intents object with default intents enabled."""
    
    # Privileged Intents (require approval for verified bots)
    @property
    def message_content(self) -> bool:
        """Access to message content in guild messages."""
    
    @property
    def members(self) -> bool:
        """Access to guild member events and member list."""
    
    @property
    def presences(self) -> bool:
        """Access to user presence updates."""
    
    # Standard Intents
    @property
    def guilds(self) -> bool:
        """Guild and channel create/update/delete events."""
    
    @property
    def guild_messages(self) -> bool:
        """Guild message events."""
    
    @property
    def guild_reactions(self) -> bool:
        """Guild message reaction events."""
    
    @property
    def guild_typing(self) -> bool:
        """Guild typing indicator events."""
    
    @property
    def dm_messages(self) -> bool:
        """Direct message events."""
    
    @property
    def dm_reactions(self) -> bool:
        """Direct message reaction events."""
    
    @property
    def dm_typing(self) -> bool:
        """Direct message typing events."""
    
    @property
    def guild_integrations(self) -> bool:
        """Guild integration update events."""
    
    @property
    def webhooks(self) -> bool:
        """Guild webhook update events."""
    
    @property
    def invites(self) -> bool:
        """Guild invite create/delete events."""
    
    @property
    def voice_states(self) -> bool:
        """Voice state update events."""
    
    @property
    def guild_scheduled_events(self) -> bool:
        """Scheduled event create/update/delete events."""
    
    @property
    def auto_moderation_configuration(self) -> bool:
        """Auto-moderation rule create/update/delete events."""
    
    @property
    def auto_moderation_execution(self) -> bool:
        """Auto-moderation action execution events."""
    
    @property
    def value(self) -> int:
        """The raw integer value of the intents."""

class MemberCacheFlags:
    """
    Controls which members are cached by the client.
    """
    
    def __init__(self, **kwargs) -> None: ...
    
    @classmethod
    def all(cls) -> MemberCacheFlags:
        """Cache all members."""
    
    @classmethod
    def none(cls) -> MemberCacheFlags:
        """Cache no members."""
    
    @classmethod
    def from_intents(cls, intents: Intents) -> MemberCacheFlags:
        """Create cache flags based on intents."""
    
    @property
    def voice(self) -> bool:
        """Cache members in voice channels."""
    
    @property
    def joined(self) -> bool:
        """Cache members when they join."""
    
    @property
    def online(self) -> bool:
        """Cache online members."""

WebSocket and Connection Details

Low-level connection management classes for advanced use cases.

class DiscordWebSocket:
    """
    The Discord WebSocket connection handler.
    """
    
    @property
    def latency(self) -> float:
        """The latency between heartbeat and heartbeat ack."""
    
    async def send_heartbeat(self) -> None:
        """Send a heartbeat to Discord."""
    
    async def close(self, code: int = 1000) -> None:
        """Close the WebSocket connection."""

class ShardInfo:
    """
    Information about a shard.
    """
    
    def __init__(self, shard_id: int, shard_count: int) -> None: ...
    
    @property
    def id(self) -> int:
        """The shard ID."""
    
    @property
    def shard_count(self) -> int:
        """Total number of shards."""
    
    def is_ws_ratelimited(self) -> bool:
        """Check if the shard is WebSocket rate limited."""

class ConnectionClosed(Exception):
    """
    Exception raised when the gateway connection is closed.
    """
    
    def __init__(self, original: Exception, shard_id: Optional[int] = None) -> None: ...
    
    @property
    def code(self) -> int:
        """The close code."""
    
    @property
    def reason(self) -> str:
        """The close reason."""

The core client functionality provides the foundation for all Discord bot development with py-cord, handling connection management, event processing, application command registration, and the essential infrastructure needed for Discord integration.

Install with Tessl CLI

npx tessl i tessl/pypi-py-cord

docs

commands-interactions.md

core-clients.md

discord-objects.md

error-handling.md

extensions.md

index.md

ui-components.md

utilities-helpers.md

tile.json