discord.py-self Documentation

repository·master·Indexed 22 days ago

https://github.com/dolfies/discord.py-self

An async-ready Python API wrapper for Discord's user API designed for the automation of user accounts. It provides features for session management, relationship handling, interaction support, and CAPTCHA challenge handling via the Client class. The library includes utilities for managing presence, voice states, and retrieving cached or fetched data for guilds, users, and channels.

Tokens
62.3K
Snippets
91
Records
408
Agent score
73%

What's inside discord.py-self

  1. Use the discord.ext.commands framework for bot command management

    master
    The discord.ext.commands extension provides a high-level framework for building extensible, flexible, and powerful bot command systems. While the core discord.py library handles low-level Discord interactions, discord.ext.commands is designed to abstract the repetitive tasks involved in creating a command structure, allowing you to focus on the logic of your bot's commands.
  2. Use discord.ext.tasks for background loops

    master

    The discord.ext.tasks extension provides asyncio.Task helpers to run background loops at specified intervals. It abstracts common concerns like handling asyncio.CancelledError, connection interruptions, and sleep intervals. You can define a loop using the @tasks.loop decorator and control its lifecycle using methods like .start() and .cancel().

    from discord.ext import tasks, commands
    
    class MyCog(commands.Cog):
        def __init__(self):
            self.index = 0
            self.printer.start()
    
        def cog_unload(self):
            self.printer.cancel()
    
        @tasks.loop(seconds=5.0)
        async def printer(self):
            print(self.index)
            self.index += 1
  3. How events work in discord.py-self

    master

    The library is built around the concept of events. An event is something you listen for and then respond to (e.g., receiving a message or the client becoming ready). You typically handle events by overriding methods in a class that inherits from discord.Client.

    Common event methods include:

    • on_ready: Triggered when the client has successfully logged on.
    • on_message: Triggered when a new message is received.
    import discord
    
    class MyClient(discord.Client):
        async def on_ready(self):
            print(f'Logged on as {self.user}!')
    
        async def on_message(self, message):
            print(f'Message from {message.author}: {message.content}')
    
    client = MyClient()
    client.run('token')
  4. Understand Guild Subscriptions

    master

    Guild subscriptions allow a client to limit the volume of events received from a guild. By default, discord.py-self subscribes to as much as possible at startup, which is optimized for traditional clients rather than bots.

    Default Behavior:

    • Automatic Subscription: The client automatically subscribes to all guilds with fewer than 75,000 members upon connection.
    • Non-subscribed Guilds: You will not receive non-stateful events (e.g., on_message, on_message_edit, on_message_delete) for guilds you are not subscribed to. Voice states and channel unreads are updated passively rather than in real-time.
    • Automatic User Subscriptions: For guilds with < 75,000 members, the client automatically subscribes to all friends, implicit relationships, and members with whom the user has open DMs.
    • Self-Action Events: Events for actions the client performs (e.g., changing a nickname, kicking/banning a user) are always received, regardless of subscription status.

    Limitations:

    • There is no way to reliably retrieve the entire member list of a guild.
    • You cannot subscribe to presence updates for all members in a guild; you can only subscribe to specific members or thread member lists.
  5. How AuditLogChanges work

    master

    An AuditLogChanges object represents the state of an audit log entry before and after an action occurred. It contains two primary attributes, before and after, both of which are AuditLogDiff objects. The content of these attributes depends on the AuditLogActionCategory of the entry:

    • create category: before attributes are all None; after attributes contain the created values.
    • delete category: before attributes contain the values before deletion; after attributes are all None.
    • update category: before attributes contain the old values; after attributes contain the new values.
    • None category: No attributes are set in either.
  6. How to use Discord Models

    master

    Discord Models are classes representing data received from Discord.

    Important Constraints:

    • Read-Only: You should not modify model instances yourself.
    • Do Not Instantiate: You should not create your own instances of these classes (e.g., do not call User() to create a new user).
    • Accessing Models: To obtain model instances, use the library's cache or retrieve them from attributes of objects received via Discord API events.
    • Dynamic Attributes: Most model classes use __slots__, meaning you cannot add arbitrary new attributes to them at runtime.
  7. How VoiceChannel and Message.channel behavior changed in v2.0

    master

    To support 'text in voice' functionality, the following changes were implemented:

    • VoiceChannel now implements abc.Messageable, allowing messages to be sent and received within voice channels.
    • Message.channel can now return instances of VoiceChannel or StageChannel in addition to standard text channels.
  8. Use positional parameters in commands

    master

    Positional parameters are the most basic way to accept arguments. The library maps user input directly to the function's arguments.

    Note on multi-word input: If a user wants to pass a single argument containing spaces, they must wrap the input in quotes (e.g., $foo "hello world"). If they omit quotes, the library will only capture the first word as the argument.

    @bot.command()
    async def test(ctx, arg1, arg2):
        await ctx.send(f'You passed {arg1} and {arg2}')
  9. Compare Application Membership and Verification States

    master

    Several application-related state classes (ApplicationMembershipState, ApplicationVerificationState, StoreApplicationState, RPCApplicationState, ApplicationDiscoverabilityState) support comparison operations. This allows you to check the progression or equality of states using standard Python comparison operators:

    • x == y: Checks if two states are equal.
    • x != y: Checks if two states are not equal.
    • x > y: Checks if one state is higher than another.
    • x < y: Checks if one state is lower than another.
    • x >= y: Checks if one state is higher or equal to another.
    • x <= y: Checks if one state is lower or equal to another.
  10. Understand versioning and breaking change guarantees

    master

    The library follows Semantic Versioning (SemVer). Major version updates are reserved for incompatible API changes.

    Key Guarantees:

    • Public API Scope: Breaking change guarantees apply only to publicly documented functions and classes. Attributes starting with an underscore (_) or undocumented functions are considered internal and may change without notice.
    • Patch Releases: Guaranteed to not introduce breaking changes.
    • Minor Releases: May introduce minor breaking changes due to the dynamic nature of Python and the Discord API.
    • Major Releases: Reserved for significant breaking changes.
  11. Use discord.abc Abstract Base Classes for type checking

    master

    The library uses Abstract Base Classes (ABCs) that inherit from typing.Protocol. These classes are intended for use with isinstance() and issubclass() to verify object behavior rather than for direct instantiation.

    Key ABCs include:

    • Snowflake: For objects with a snowflake ID.
    • User: For user objects.
    • PrivateChannel: For direct message channels.
    • GuildChannel: For channels within a guild.
    • Messageable: For objects that can receive messages (supports async with context manager).
    • Connectable: For objects that can be connected to (e.g., voice).
    • ApplicationCommand: For application command objects.
  12. Understand AuditLogDiff for channel and guild changes

    master

    When an AuditLogAction occurs, the AuditLogDiff object contains the specific changes made.

    For guild_update, AuditLogDiff may contain:

    • afk_channel, system_channel, afk_timeout, default_notifications, explicit_content_filter, mfa_level, name, owner, splash, discovery_splash, icon, banner, vanity_url_code, description, preferred_locale, prune_delete_days, public_updates_channel, rules_channel, verification_level, widget_channel, widget_enabled, premium_progress_bar_enabled, system_channel_flags.

    For channel_create or channel_update, AuditLogDiff may contain:

    • name, type, position, overwrites, topic, bitrate, rtc_region, video_quality_mode, default_auto_archive_duration, nsfw, slowmode_delay, user_limit.

    For overwrite_create, overwrite_update, or overwrite_delete, AuditLogDiff may contain:

    • deny, allow, id, type.