CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-discord-py-interactions

A Feature-rich Discord Bot Framework for Python with comprehensive API coverage and modern interfaces

Pending
Overview
Eval results
Files

client.mddocs/

Client & Bot Management

Manage bot lifecycle, configuration, connection, and core functionality.

Core Client Classes

Client

Main bot client class for Discord applications.

Client(
    *,
    token: str | None = None,
    intents: Union[int, Intents] = Intents.DEFAULT,
    status: Status = Status.ONLINE,
    activity: Union[Activity, str] = None,
    sync_interactions: bool = True,
    sync_ext: bool = True,
    delete_unused_application_cmds: bool = False,
    enforce_interaction_perms: bool = True,
    fetch_members: bool = False,
    send_command_tracebacks: bool = True,
    auto_defer: Absent[Union[AutoDefer, bool]] = MISSING,
    interaction_context: Type[InteractionContext] = InteractionContext,
    component_context: Type[BaseContext] = ComponentContext,
    autocomplete_context: Type[BaseContext] = AutocompleteContext,
    modal_context: Type[BaseContext] = ModalContext,
    slash_context: Type[BaseContext] = SlashContext,
    context_menu_context: Type[BaseContext] = ContextMenuContext,
    owner_ids: Iterable["Snowflake_Type"] = (),
    show_ratelimit_tracebacks: bool = False,
    shard_id: int = 0,
    total_shards: int = 1,
    basic_logging: bool = False,
    logging_level: int = logging.INFO,
    logger: logging.Logger = MISSING,
    debug_scope: Absent["Snowflake_Type"] = MISSING,
    disable_dm_commands: bool = False,
    global_post_run_callback: Absent[Callable[..., Coroutine]] = MISSING,
    global_pre_run_callback: Absent[Callable[..., Coroutine]] = MISSING,
    **kwargs
) -> Client

Core Methods:

  • start() { .api } - Start the bot and connect to Discord
  • login() { .api } - Login to Discord (called automatically by start)
  • stop() { .api } - Stop the bot and disconnect
  • change_presence(status, activity) { .api } - Update bot's status and activity
  • synchronise_interactions() { .api } - Sync application commands with Discord

Extension Methods:

  • load_extension(name: str) { .api } - Load an extension
  • unload_extension(name: str) { .api } - Unload an extension
  • reload_extension(name: str) { .api } - Reload an extension

Guild Methods:

  • get_guild(guild_id: Snowflake) { .api } - Get guild from cache
  • fetch_guild(guild_id: Snowflake) { .api } - Fetch guild from API

Component & Callback Methods:

  • add_component_callback(callback) { .api } - Register component callback
  • add_modal_callback(callback) { .api } - Register modal callback
  • wait_for(event, check=None, timeout=None) { .api } - Wait for specific event
  • wait_for_component(custom_id=None, timeout=None) { .api } - Wait for component interaction
  • wait_for_modal(custom_id=None, timeout=None) { .api } - Wait for modal submission

AutoShardedClient

Automatically sharded version of Client for large bots (2500+ guilds).

AutoShardedClient(
    token: str,
    shard_count: int = None,
    **kwargs
) -> AutoShardedClient

Inherits all Client methods with automatic shard management.

Configuration & Metadata

Version Information

__version__: str  # Library version
__api_version__: int  # Discord API version (10)
__py_version__: str  # Required Python version
__repo_url__: str  # GitHub repository URL

Logging

get_logger(name: str = None) -> logging.Logger  # Get library logger
logger_name: str = "interactions"  # Default logger name

Constants & Limits

# Discord API Limits
ACTION_ROW_MAX_ITEMS: int = 5
SELECTS_MAX_OPTIONS: int = 25
SELECT_MAX_NAME_LENGTH: int = 100
CONTEXT_MENU_NAME_LENGTH: int = 32
SLASH_CMD_NAME_LENGTH: int = 32
SLASH_CMD_MAX_DESC_LENGTH: int = 100
SLASH_CMD_MAX_OPTIONS: int = 25
SLASH_OPTION_NAME_LENGTH: int = 100

# Embed Limits
EMBED_MAX_NAME_LENGTH: int = 256
EMBED_MAX_DESC_LENGTH: int = 4096
EMBED_MAX_FIELDS: int = 25
EMBED_TOTAL_MAX: int = 6000
EMBED_FIELD_VALUE_LENGTH: int = 1024

# Other Constants
DISCORD_EPOCH: int = 1420070400000
PREMIUM_GUILD_LIMITS: dict  # Premium tier limits

Sentinel Values

Missing Values

MISSING  # Sentinel for missing values
Missing  # Missing type class
Absent[T]  # Union[T, Missing] type

Scopes

GLOBAL_SCOPE  # Global command scope instance
GlobalScope  # Global scope class
MENTION_PREFIX  # Mention prefix instance
MentionPrefix  # Mention prefix class

Utility Types

Sentinel  # Base sentinel class
Singleton  # Singleton metaclass
T  # Generic type variable
T_co  # Covariant type variable

Client Lifecycle

Basic Setup

import interactions
from interactions import listen, events

# Basic bot
bot = interactions.Client(token="TOKEN")

@listen()
async def on_ready(event: events.Ready):
    print(f"Bot is ready! Logged in as {event.user}")

bot.start()

Advanced Configuration

import interactions
from interactions import Intents, Status, Activity, ActivityType

bot = interactions.Client(
    token="TOKEN",
    intents=Intents.ALL,
    status=Status.DND,
    activity=Activity(
        name="Custom Game",
        type=ActivityType.PLAYING
    ),
    sync_interactions=True,
    delete_unused_application_cmds=True,
    auto_defer=interactions.AutoDefer(enabled=True, time_until_defer=2.0)
)

Sharded Bot

import interactions

# For large bots (2500+ guilds)
bot = interactions.AutoShardedClient(
    token="TOKEN",
    shard_count=4  # Optional, auto-calculated if not provided
)

Event Handling

Event Listeners

@listen()
async def on_ready(event: events.Ready):
    """Called when bot is ready"""
    pass

@listen()  
async def on_guild_join(event: events.GuildJoin):
    """Called when bot joins a guild"""
    guild = event.guild

Listener Decorators

@listen()
async def on_message_create(event):
    """Listen to message create events"""
    message = event.message
    print(f"Message from {message.author}: {message.content}")

@listen(interactions.events.GuildJoin)
async def on_guild_join(event):
    """Listen to guild join events"""
    guild = event.guild
    print(f"Joined guild: {guild.name}")

Status & Presence

Change Status

from interactions import Status, Activity, ActivityType

# Change status
await bot.change_presence(status=Status.IDLE)

# Set activity
activity = Activity(name="Custom Game", type=ActivityType.PLAYING)
await bot.change_presence(activity=activity)

# Combine both
await bot.change_presence(
    status=Status.DND,
    activity=Activity(name="Maintenance", type=ActivityType.WATCHING)
)

Activity Types

from interactions import ActivityType

ActivityType.PLAYING    # "Playing {name}"
ActivityType.STREAMING  # "Streaming {name}"  
ActivityType.LISTENING  # "Listening to {name}"
ActivityType.WATCHING   # "Watching {name}"
ActivityType.COMPETING  # "Competing in {name}"

Error Handling

Built-in Exceptions

from interactions import errors

# Common exceptions
errors.BotException          # Base bot exception
errors.InteractionMissingAccess  # Missing interaction permissions
errors.ExtensionLoadException    # Extension loading failed
errors.ExtensionNotFound         # Extension not found
errors.HTTPException            # HTTP request failed
errors.Forbidden               # 403 Forbidden
errors.NotFound               # 404 Not Found

Error Event Handling

@listen(interactions.events.Error)
async def on_error(event):
    """Handle general errors"""
    print(f"Error occurred: {event.error}")

@listen(interactions.events.CommandError) 
async def on_command_error(event):
    """Handle command errors"""
    print(f"Command error in {event.ctx.command}: {event.error}")

Extensions Management

Load Extensions

# Load extension
bot.load_extension("extensions.moderation")

# Load multiple extensions
extensions = ["extensions.moderation", "extensions.fun", "extensions.admin"]
for ext in extensions:
    bot.load_extension(ext)

Extension Events

@listen(interactions.events.ExtensionLoad)
async def on_extension_load(event):
    print(f"Extension loaded: {event.extension}")

@listen(interactions.events.ExtensionUnload) 
async def on_extension_unload(event):
    print(f"Extension unloaded: {event.extension}")

Cache & Utilities

Cache Access

# Access cached objects
guild = bot.get_guild(guild_id)
user = bot.get_user(user_id)
channel = bot.get_channel(channel_id)

# Cache properties
bot.guilds       # List of cached guilds
bot.users        # List of cached users  
bot.channels     # List of cached channels

Utility Modules

from interactions import utils, smart_cache

# Utility functions in bot.utils
# Smart caching system in bot.smart_cache

Install with Tessl CLI

npx tessl i tessl/pypi-discord-py-interactions

docs

client.md

commands.md

components.md

discord-models.md

events.md

extensions.md

index.md

tile.json