DiscordPHP Documentation

repository·master·Indexed 22 days ago

https://github.com/discord-php/discordphp

A PHP wrapper for the official Discord REST, Gateway, and Voice APIs. DiscordPHP enables the creation of Discord bots using asynchronous event loops via ReactPHP. It requires PHP 8.1.2 or higher and must be run in a CLI environment. The library supports sharding, gateway event handling, and integration with Laravel via Laracord.

Tokens
62.3K
Snippets
218
Records
264
Agent score
74%

What's inside DiscordPHP

  1. What are DiscordPHP Collections?

    master

    Collections are containers for items that implement standard PHP interfaces, allowing them to behave like arrays. They are built around the concept of 'parts' and can be used for any data type.

    Key behaviors include:

    • Array Access: Use square bracket notation (e.g., $collec[123] = 'asdf';).
    • Iteration: Use foreach loops to iterate over items.
    • Serialization: Supports json_encode(), casting to (array), and casting to (string) (which performs a JSON encoding).
    // square bracket index access
    $collec[123] = 'asdf';
    echo $collec[123]; // asdf
    
    // foreach loops
    foreach ($collec as $item) {
        // ...
    }
    
    // json serialization
    json_encode($collec);
    
    // array serialization
    $collecArray = (array) $collec;
    
    // string serialization
    $jsonCollec = (string) $collec; // same as json_encode($collec)
  2. How to listen to Discord events

    master

    Events are payloads sent over the WebSocket that correspond to real-time occurrences in Discord. To respond to these events in your application, use the event emitter callback mechanism provided by the library along with the Event name constants.

    Note that some events are handled internally by the library and might not trigger a registered listener. These include:

    • Event::READY
    • Event::RESUMED
    • Event::GUILD_MEMBERS_CHUNK

    If you need to intercept these internal events, you must parse the 'raw' dispatch event data directly.

  3. Understand the Member abstraction

    master

    A Member object represents a specific user within a specific guild (server). Because a user can belong to multiple guilds, there will be a unique Member object for every guild-user relationship.

    Note: A Member object can be serialized into a Discord mention string (e.g., <@member_id>) by using it in a string context. However, $message->member may be null if the message is a Direct Message (DM) or if the member object was not cached by the library.

    $discord->on(Event::MESSAGE_CREATE, function (Message $message) {
        // Hello <@member_id>!
        // Note: `$message->member` will be `null` if the message originated from
        // a private message, or if the member object was not cached.
        $message->channel->sendMessage('Hello '.$message->member.'!');
    });
  4. Run DiscordPHP in CLI environments

    master

    DiscordPHP is designed to run in CLI (Command Line Interface) environments only. It cannot be run directly on a webserver (e.g., Apache or Nginx).

    If you need to provide a web interface for your bot, you should integrate react/http and run the entire process through the CLI.

  5. How DiscordPHP Collections work

    master

    Collections in DiscordPHP are specialized containers for items. They are designed around the concept of 'parts' and can be configured to discriminate between items using a specific key (discriminator) or to enforce a specific class type.

    Collections implement standard PHP interfaces, allowing them to be used seamlessly in many contexts:

    • Array access: Use square brackets $collec[key] = $value.
    • Iteration: Use foreach ($collec as $item).
    • Serialization: Supports json_encode($collec), casting to array (array) $collec, and casting to string (string) $collec (which performs JSON serialization).
    // square bracket index access
    $collec[123] = 'asdf';
    
    // foreach loops
    foreach ($collec as $item) {
        // ...
    }
    
    // json serialization
    json_encode($collec);
    
    // array serialization
    $collecArray = (array) $collec;
    
    // string serialization
    $jsonCollec = (string) $collec; // same as json_encode($collec)
  6. Use ActionRow to group buttons

    master

    An ActionRow represents a row of buttons on a message. You cannot attach buttons directly to a message; they must be contained within an ActionRow. Each row can hold up to 5 buttons. Use addComponent($component) to add a button to the row.

    $row = ActionRow::new()
        ->addComponent(Button::new(Button::STYLE_SUCCESS));
  7. Understand Discord 'Parts' in DiscordPHP

    master

    In DiscordPHP, 'Parts' are the data structures representing Discord entities (such as Guild, Channel, Member, Message, and User). All parts share a common set of attributes and methods.

    Parts have a predefined list of 'fillable' fields. If you attempt to set a field that is not in the fillable list, the operation will fail silently without a warning.

  8. Access Guild repositories

    master

    A Guild (Discord server) contains several repositories that allow you to interact with its components. Note that some repositories are not loaded by default and require specific options during the initial guild load to be accessible.

    Available Repositories

    nametypenotes
    rolesRole
    emojisEmoji
    membersMemberMay not contain offline members; use the loadAllMembers option to include them.
    channelsChannel
    stage_instancesStageInstance
    guild_scheduled_eventsScheduledEvent
    stickersSticker
    invitesInviteNot initially loaded.
    bansBanNot initially loaded without the retrieveBans option.
    commandsCommandNot initially loaded.
    templatesGuildTemplateNot initially loaded.
    integrationsIntegrationNot initially loaded.
  9. Understand the Member concept

    master

    A Member object represents a specific user within a specific guild (server). Because a single user can belong to multiple guilds, there will be a unique Member object for every guild-user relationship.

    Important Note: When accessing $message->member, it may be null if the message originated from a private message (DM) or if the member object was not present in the local cache.

    $discord->on(Event::MESSAGE_CREATE, function (Message $message) {
        // Note: `$message->member` will be `null` if the message originated from
        // a private message, or if the member object was not cached.
        // A member object can be serialized into a mention string (e.g., <@member_id>).
        $message->channel->sendMessage('Hello '.$message->member.'!');
    });
  10. Understand Repositories and Parts

    master

    In DiscordPHP, Repositories act as containers for Parts. They provide the interface to get, save, and delete specific data types (Parts) from Discord servers.

    Each Part type has multiple repositories associated with it. For example, the Channel part has four distinct repositories:

    • members: Members currently in a voice channel.
    • messages: Messages sent in the channel.
    • overwrites: Channel permission overwrites.
    • webhooks: Webhooks associated with the channel.

    Repositories extend the Collection class, meaning they inherit all collection-related methods.

  11. Understand the two types of Discord permissions

    master

    DiscordPHP handles permissions through two distinct types of classes: Channel Permissions and Role Permissions. While they represent different scopes of authority, both extend the same abstract permission class.

    • Channel Permissions: Govern what a user can do within specific channel types (Text, Voice, or Stage Instance).
    • Role Permissions: Govern what a user can do within a Guild (Server) based on their assigned roles.
  12. What are Repositories in DiscordPHP

    master

    Repositories act as containers for specific 'parts' of Discord data. They provide the interface to get, save, and delete these parts from Discord servers.

    Each major Discord entity (a 'Part') has multiple repositories associated with it. For example, a Channel part has four repositories:

    • members: Members currently in a voice channel.
    • messages: Messages sent in the channel.
    • overwrites: Permission overwrites for the channel.
    • webhooks: Webhooks associated with the channel.

    All repositories extend the Collection class, meaning they inherit all collection-related methods.