discord.py

repository·master·Indexed 11 days ago

https://github.com/rapptz/discord.py

A modern, feature-rich, and async-ready Python wrapper for the Discord API. It provides a Pythonic interface using async/await and includes the discord.ext.commands extension for creating command-based bots with support for Cogs, hybrid commands, and application command trees.

Tokens
85.5K
Snippets
247
Records
451
Agent score
95%

What's inside discord.py

  1. Use the discord.ui Bot UI Kit

    master

    The discord.ui package provides a suite of helpers for building component-based user interfaces. It includes classes for managing views, layouts, modals, and individual UI elements like buttons, select menus, and text inputs.

    Key components include:

    • Views: View and LayoutView for managing groups of components.
    • Modals: Modal for pop-up forms.
    • Items: Button, Select (and specialized versions like UserSelect, RoleSelect, etc.), TextInput, and ActionRow.
    • Advanced Layouts (v2.6+): Container, Section, Separator, TextDisplay, Thumbnail, MediaGallery, File, Label, FileUpload, RadioGroup, and CheckboxGroup.
  2. Use discord.ext.commands for bot command frameworks

    master

    While discord.py provides low-level interaction with the Discord API, discord.ext.commands is a high-level extension designed specifically for building extensible, flexible, and powerful bot command frameworks. Instead of manually handling message parsing and command routing, you should use this extension to manage bot commands efficiently.

    import discord
    from discord.ext import commands
    
    # Typical setup involves using commands.Bot instead of discord.Client
    bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
  3. Handle changes to read-only sequences (Client and Guild attributes)

    master

    To improve performance, several attributes that previously returned a list now return a read-only sequence. This is transparent for reading, but will raise errors if you attempt to modify them directly (e.g., using .append()).

    To convert a sequence back into a list, wrap it in the list() constructor.

    Affected attributes:

    • Client.guilds
    • Client.emojis
    • Client.private_channels
    • Guild.roles
    • Guild.channels
    • Guild.members
    # If you need to modify the sequence, convert it to a list first
    my_list = list(guild.roles)
    my_list.append(new_role)
  4. Manage shards with AutoShardedClient

    master

    The AutoShardedClient has been redesigned for better multi-process cluster support. Key capabilities include:

    • Shard Information: Use AutoShardedClient.get_shard or the shards attribute to access ShardInfo objects.
    • Shard Control: ShardInfo allows you to manually reconnect or disconnect specific shards.
    • Lifecycle Hooks: Use Client.before_identify_hook to execute logic before the IDENTIFY payload is sent.
    • Shard Events: New events are available for monitoring shard status: on_shard_connect, on_shard_disconnect, and on_shard_resumed.
  5. How to use Discord Models

    master

    Discord Models (e.g., User, Message, Guild, Member) are classes representing data received from the Discord API.

    Important Constraints:

    • Read-Only: You should not attempt to modify model instances directly.
    • Do Not Instantiate: You should not create your own instances of these classes (e.g., do not call User() to create a user).
    • Accessing Models: To obtain a model instance, you should retrieve it from the library's cache or via attributes provided in Discord API events. A common way to find a specific model is using the utils.find function.
    • Slots: Most model classes use __slots__, meaning you cannot add dynamic attributes to them.
  6. Understand Abstract Base Classes (ABCs) in discord.py

    master

    The library uses Abstract Base Classes (ABCs) to define common behaviors and interfaces.

    Important: You should not instantiate these classes directly. They are designed to be used with isinstance() and issubclass() to check if an object implements a specific interface (e.g., checking if a channel is Messageable).

    All ABCs in this library are subclasses of typing.Protocol, allowing for structural subtyping.

  7. Use Webhooks with discord.py

    master

    discord.py provides support for managing and interacting with Discord webhooks via the Webhook and SyncWebhook classes.

    • Webhook: Used for asynchronous webhook operations. It works with WebhookMessage objects.
    • SyncWebhook: Used for synchronous webhook operations (blocking), which is useful in environments where an event loop is not available or preferred. It works with SyncWebhookMessage objects.
    # Note: Specific method calls are not provided in this segment, but the classes are:
    # from discord import Webhook, SyncWebhook
  8. Handle command-specific events

    master

    The command extension provides custom events that trigger during the command lifecycle. These are distinct from standard Discord API events:

    • on_command(ctx): Called when a command is found and is about to be invoked. This triggers regardless of whether the command succeeds or fails.
    • on_command_completion(ctx): Called only when a command successfully completes (all checks passed and user input was correct).
    • on_command_error(ctx, error): An error handler called when an error is raised inside a command (e.g., user input error, check failure, or code error). You can define a global handler using Bot.on_command_error or specific command error handlers using Command.error().
  9. Register and implement event handlers

    master

    You can register events in discord.py using two primary methods:

    1. Using Client.event: Register a function as a listener for a specific event.
    2. Subclassing Client: Override specific event methods (e.g., on_message) within a custom class.

    Important Requirements:

    • All event handlers must be coroutines (defined using async def).
    • If an event handler raises an exception, on_error is called by default, which logs the traceback and ignores the exception.

    To prevent your bot from responding to itself, check the message.author against self.user within the handler.

    import discord
    
    class MyClient(discord.Client):
        async def on_message(self, message):
            # Don't respond to ourselves
            if message.author == self.user:
                return
    
            if message.content.startswith('$hello'):
                await message.channel.send('Hello World!')
  10. Use Converters to transform command arguments

    master

    Converters are used in discord.ext.commands to automatically transform command arguments into specific Discord objects. When a command parameter is type-hinted with a converter class, the command framework attempts to resolve the user's input (e.g., a mention, an ID, or a string) into the corresponding object. If conversion fails, a CommandError is raised.

    Commonly used converters include:

    • Users/Members: UserConverter, MemberConverter (resolves users or guild members).
    • Channels: GuildChannelConverter, TextChannelConverter, VoiceChannelConverter, StageChannelConverter, CategoryChannelConverter, ForumChannelConverter.
    • Messages: MessageConverter, PartialMessageConverter.
    • Guild/Roles: GuildConverter, RoleConverter.
    • Media/Visuals: EmojiConverter, PartialEmojiConverter, GuildStickerConverter, ColourConverter.
    • Other: InviteConverter, ThreadConverter, ScheduledEventConverter, SoundboardSoundConverter, GameConverter.

    You can also use Greedy for optional arguments that consume all remaining input, or Range to constrain numeric inputs.

    from discord.ext import commands
    
    @bot.command()
    async def ban(ctx, member: commands.Member, reason: str):
        # 'member' is automatically converted from a mention or ID
        await member.ban(reason=reason)
  11. Understand custom bool() implementation for Flag classes

    master

    Flag classes now have a custom __bool__ implementation. Evaluating them in a boolean context (e.g., if obj:) will only return True if at least one flag is enabled. If no flags are set, they will evaluate to False.

    # The following classes follow this behavior:
    # Intents, MemberCacheFlags, MessageFlags, Permissions,
    # PublicUserFlags, SystemChannelFlags
    
    # If no intents are enabled, this will be False:
    if intents:  # might be False even if the object exists
        ...