DiscordPHP

Intro

DiscordPHP is a wrapper for the Discord REST, WebSocket and Voice APIs. Built on top of ReactPHP components. This documentation is based off the latest release.

The class reference has moved. You can now access it here.

Requirements

  • PHP 7.4 CLI

    • Will not run on a webserver (FPM, CGI), you must run through CLI. A bot is a long-running process.
  • ext-json for JSON parsing.
  • ext-zlib for gateway packet compression.

Recommended Extensions

  • One of ext-uv, ext-libev or evt-event (in order of preference) for a faster, and more performant event loop.
  • ext-mbstring if you may handle non-english characters.

Voice Requirements

  • x86_64 Windows, Linux or Darwin based OS.

    • If you are running on Windows, you must be using PHP 8.0.
  • ext-sodium for voice encryption.
  • FFmpeg

Development Environment Recommendations

We recommend using an editor with support for the Language Server Protocol. A list of supported editors can be found here. Here are some commonly used editors:

  • Visual Studio Code (built-in LSP support)
  • Vim/Neovim (with the coc.nvim plugin for LSP support)
  • PHPStorm (built-in PHP support)

We recommend installing the PHP Intelephense alongside your LSP-equipped editor for code completion along with many other helpful features. There is no need to pay for the premium features, as the free version will suffice.

Installation

Installation requries Composer.

To install the latest release:

> composer require team-reflex/discord-php

If you would like to run on the latest master branch:

> composer require team-reflex/discord-php dev-master

master can be substituted for any other branch name to install that branch.

Key Tips

As Discord is a real-time application, events come frequently and it is vital that your code does not block the ReactPHP event loop. Most, if not all, functions return promises, therefore it is vital that you understand the concept of asynchronous programming with promises. You can learn more about ReactPHP promises here.

Help

If you need any help, feel free to join the PHP Discorders Discord and someone should be able to give you a hand. We are a small community so please be patient if someone can't help you straight away.

Contributing

All contributions are welcome through pull requests in our GitHub repository. At the moment we would love contributions towards:

  • Unit testing
  • Documentation

FAQ

Class 'X' not found

You most likely haven't imported the class that you are trying to use. Please check the class reference and search for the class that you are trying to use. Add an import statement at the top of the file like shown on the right.

<?php

use Discord\X;

If you don't want to have to import a class every time, you should look into the PHP Intelephense language server (written above) which will do automatic imports for you.

There are less members and/or users than expected

Server members are guarded by a priviliged server intent which must be enabled in the Discord Developer Portal. Note that you will need to verify your bot if you use this intent and pass 100 guilds.

You also need to enable the loadAllMembers option in your code, as shown on the right.

$discord = new Discord([
    'token' => '...',
    'loadAllMembers' => true, // Enable this option
]);

If you are using DiscordPHP Version 6 or greater, you need to enable the GUILD_MEMBERS intent as well as the loadAllMembers option. The shown code will enable all intents minus the GUILD_PRESENCES intent (which is also priviliged).

$discord = new Discord([
    'token' => '...',
    'loadAllMembers' => true,
    'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS // Enable the `GUILD_MEMBERS` intent
])

Basics

First step is to include the Composer autoload file and import any required classes.

<?php

use Discord\Discord;
use Discord\WebSockets\Intents;
use Discord\WebSockets\Event;

include __DIR__.'/vendor/autoload.php';

The Discord instance can be set up with an array of options. All are optional except for token:

$discord = new Discord([

token is your Discord token. Required.

    'token' => 'Your-Token-Here',

intents can be an array of valid intents or an integer representing the intents. Default is all intents minus any privileged intents. At the moment this means all intents minus GUILD_MEMBERS and GUILD_PRESENCES. To enable these intents you must first enable them in your Discord developer portal.

    'intents' => [
        Intents::GUILDS, Intents::GUILD_BANS, // ...
    ],
    // or
    'intents' => 12345,
    // or
    'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, // default intents as well as guild members

loadAllMembers is a boolean whether all members should be fetched and stored on bot start. Loading members takes a while to retrieve from Discord and store, so default is false. This requires the GUILD_MEMBERS intent to be enabled in DiscordPHP. See above for more details.

    'loadAllMembers' => false,

storeMessages is a boolean whether messages received and sent should be stored. Default is false.

    'storeMessages' => false,

retrieveBans is a boolean whether bans should be retrieved on bot load. Default is false.

    'retrieveBans' => false,

pmChannels is a boolean whether PM channels should be stored on bot load. Default is false.

    'pmChannels' => false,

disabledEvents is an array of events that will be disabled. By default all events are enabled.

    'disabledEvents' => [
        Event::MESSAGE_CREATE, Event::MESSAGE_DELETE, // ...
    ],

loop is an instance of a ReactPHP event loop that can be provided to the client rather than creating a new loop. Useful if you want to use other React components. By default, a new loop is created.

    'loop' => \React\EventLoop\Factory::create(),

logger is an instance of a logger that implements LoggerInterface. By default, a new Monolog logger with log level DEBUG is created to print to stdout.

    'logger' => new \Monolog\Logger('New logger'),

The following options should only be used by large bots that require sharding. If you plan to use sharding, read up on how Discord implements it.

shardId is the ID of the bot shard.

    'shardId' => 0,

shardCount is the number of shards that you are using.

    'shardCount' => 5,
]);

Gateway events should be registered inside the ready event, which is emitted once when the bot first starts and has connected to the gateway.

$discord->on('ready', function (Discord $discord) {

To register an event we use the $discord->on(...) function, which registers a handler. A list of events is available here. They are described in more detail in further sections of the documentation. All events take a callback which is called when the event is triggered, and the callback is called with an object representing the content of the event and an instance of the Discord client.

    $discord->on(Event::MESSAGE_CREATE, function (Message $message, Discord $discord) {
        // ... handle message sent
    });
});

Finally, the event loop needs to be started. Treat this as an infinite loop.

$discord->run();
If you want to stop the bot you can run:
$discord->close();

If you want to stop the bot without stopping the event loop, the close function takes a boolean:

$discord->close(false);

Events

Message Create

Called with a Message object when a message is sent in a guild or private channel. Requires the Intents::GUILD_MESSAGES intent.

$discord->on(Event::MESSAGE_CREATE, function (Message $message, Discord $discord) {
    // ...
});

Message Update

Called with two Message objects when a message is updated in a guild or private channel. The old message may be null if storeMessages is not enabled or the message was sent before the bot was started. Discord does not provide a way to get message update history. Requires the Intents::GUILD_MESSAGES intent.

$discord->on(Event::MESSAGE_UPDATE, function (Message $newMessage, Discord $discord, $oldMessage) {
    // ...
});

Message Delete

Called with a Message object or the raw payload when a message is deleted. The Message object may be the raw payload if storeMessages is not enabled or the message was sent before the bot was started. Discord does not provide a way to get deleted messages. Requires the Intents::GUILD_MESSAGES intent.

$discord->on(Event::MESSAGE_DELETE, function ($message, Discord $discord) {
    if ($message instanceof Message) {
        // Message is present in cache
    }
    // If the message is not present in the cache:
    else {
        // {
        //     "id": "", // deleted message ID,
        //     "channel_id": "", // message channel ID,
        //     "guild_id": "" // channel guild ID
        // }
    }
});

Message Delete Bulk

Called with a Collection of Message objects or the raw payload when bulk messages are deleted. The Message object may be the raw payload if storeMessages is not enabled or the message was sent before the bot was started. Discord does not provide a way to get deleted messages. Requires the Intents::GUILD_MESSAGES intent.

$discord->on(Event::MESSAGE_DELETE_BULK, function (Collection $messages, Discord $discord) {
    foreach ($messages as $message) {
        if ($message instanceof Message) {
            // Message is present in cache
        }
        // If the message is not present in the cache:
        else {
            // {
            //     "id": "", // deleted message ID,
            //     "channel_id": "", // message channel ID,
            //     "guild_id": "" // channel guild ID
            // }
        }
    }
});

Message Reaction Add

Called with a MessageReaction object when a reaction is added to a message. Requires the Intents::GUILD_MESSAGE_REACTIONS intent.

$discord->on(Event::MESSAGE_REACTION_ADD, function (MessageReaction $reaction, Discord $discord) {
    // ...
});

Message Reaction Remove

Called with a MessageReaction object when a reaction is removed from a message. Requires the Intents::GUILD_MESSAGE_REACTIONS intent.

$discord->on(Event::MESSAGE_REACTION_REMOVE, function (MessageReaction $reaction, Discord $discord) {
    // ...
});

Message Reaction Remove All

Called with a MessageReaction object when all reactions are removed from a message. Note that only the fields relating to the message, channel and guild will be filled. Requires the Intents::GUILD_MESSAGE_REACTIONS intent.

$discord->on(Event::MESSAGE_REACTION_REMOVE_ALL, function (MessageReaction $reaction, Discord $discord) {
    // ...
});

Message Reaction Remove Emoji

Called with an object when all reactions of an emoji are removed from a message. This event is still to be implemented. Requires the Intents::GUILD_MESSAGE_REACTIONS intent.

$discord->on(Event::MESSAGE_REACTION_REMOVE_EMOJI, function ($reaction, Discord $discord) {
    // {
    //     "channel_id": "",
    //     "guild_id": "",
    //     "message_id": "",
    //     "emoji": {
    //         "id": "",
    //         "name": ""
    //     }
    // }
});

Channel Create

Called with a Channel object when a channel is created. Requires the Intents::GUILDS intent.

$discord->on(Event::CHANNEL_CREATE, function (Channel $channel, Discord $discord) {
    // ...
});

Channel Update

Called with two Channel objects when a channel is updated. Requires the Intents::GUILDS intent.

$discord->on(Event::CHANNEL_UPDATE, function (Channel $new, Discord $discord, Channel $old) {
    // ...
});

Channel Delete

Called with a Channel object when a channel is deleted. Requires the Intents::GUILDS intent.

$discord->on(Event::CHANNEL_DELETE, function (Channel $channel, Discord $discord) {
    // ...
});

Channel Pins Update

Called with an object when the pinned messages in a channel are updated. This is not sent when a pinned message is deleted. Requires the Intents::GUILDS intent.

$discord->on(Event::CHANNEL_PINS_UPDATE, function ($pins, Discord $discord) {
    // {
    //     "guild_id": "",
    //     "channel_id": "",
    //     "last_pin_timestamp": ""
    // }
});

Guild Create

Called with a Guild object in one of the following situations:

  1. When the bot is first starting and the guilds are becoming available.
  2. When a guild was unavailable and is now available due to an outage.
  3. When the bot joins a new guild.

Requires the Intents::GUILDS intent.

$discord->on(Event::GUILD_CREATE, function (Guild $guild, Discord $discord) {
    // ...
});

Guild Update

Called with two Guild object when a guild is updated. Requires the Intents::GUILDS intent.

$discord->on(Event::GUILD_UPDATE, function (Guild $new, Discord $discord, Guild $old) {
    // ...
});

Guild Delete

Called with a Guild object in one of the following situations:

  1. The bot was removed from a guild.
  2. The guild is unavailable due to an outage.

Requires the Intents::GUILDS intent.

$discord->on(Event::GUILD_DELETE, function (Guild $guild, Discord $discord, bool $unavailable) {
    // ...
    if ($unavailable) {
        // the guild is unavailabe due to an outage
    } else {
        // the bot has been kicked from the guild
    }
});

Guild Member Add

Called with a Member object when a member joins a guild. Requires the Intents::GUILD_MEMBERS intent. This intent is a priviliged intent, it must be enabled in your Discord bot developer settings.

$discord->on(Event::GUILD_MEMBER_ADD, function (Member $member, Discord $discord) {
    // ...
});

Guild Member Update

Called with two Member objects when a member is updated in a guild. Note that the old version of the member may be null if loadAllMembers is disabled. Requires the Intents::GUILD_MEMBERS intent. This intent is a priviliged intent, it must be enabled in your Discord bot developer settings.

$discord->on(Event::GUILD_MEMBER_UPDATE, function (Member $new, Discord $discord, $old) {
    // ...
});

Guild Member Remove

Called with a Member object when a member leaves a guild (leave/kick/ban). Note the member object may be null if loadAllMembers is disabled. Requires the Intents::GUILD_MEMBERS intent. This intent is a priviliged intent, it must be enabled in your Discord bot developer settings.

$discord->on(Event::GUILD_MEMBER_REMOVE, function (Member $member, Discord $discord) {
    // ...
});

Guild Role Create

Called with a Role object when a role is created in a guild. Requires the Intents::GUILDS intent.

$discord->on(Event::GUILD_ROLE_CREATE, function (Role $role, Discord $discord) {
    // ...
});

Guild Role Update

Called with two Role objects when a role is updated in a guild. Requires the Intents::GUILDS intent.

$discord->on(Event::GUILD_ROLE_UPDATE, function (Role $new, Discord $discord, Role $old) {
    // ...
});

Guild Role Delete

Called with a Role object when a role is deleted in a guild. Requires the Intents::GUILDS intent.

$discord->on(Event::GUILD_ROLE_DELETE, function (Role $role, Discord $discord) {
    // ...
});

Guild Integrations Update

Called with a Guild object when a guild's integrations are updated. Requires the Intents::GUILD_INTEGRATIONS intent.

$discord->on(Event::GUILD_INTEGRATIONS_UPDATE, function (Guild $guild, Discord $discord) {
    // ...
});

Invite Create

Called with an Invite object when an invite is created. Requires the Intents::GUILD_INVITES intent.

$discord->on(Event::INVITE_CREATE, function (Invite $invite, Discord $discord) {
    // ...
});

Invite Delete

Called with an object when an invite is created. Requires the Intents::GUILD_INVITES intent.

$discord->on(Event::INVITE_DELETE, function ($invite, Discord $discord) {
    // {
    //     "channel_id": "",
    //     "guild_id": "",
    //     "code": "" // the unique invite code
    // }
});

Presence Update

Called with a PresenceUpdate object when a members presence is updated. Requires the Intents::GUILD_PRESENCES intent. This intent is a priviliged intent, it must be enabled in your Discord bot developer settings.

$discord->on(Event::PRESENCE_UPDATE, function (PresenceUpdate $presence, Discord $discord) {
    // ...
});

Typing Start

Called with a TypingStart object when a member starts typing in a channel. Requires the Intents::GUILD_MESSAGE_TYPING intent.

$discord->on(Event::TYPING_START, function (TypingStart $typing, Discord $discord) {
    // ...
});

Voice State Update

Called with a VoiceStateUpdate object when a member joins, leaves or moves between voice channels. Requires the Intents::GUILD_VOICE_STATES intent.

$discord->on(Event::VOICE_STATE_UPDATE, function (VoiceStateUpdate $state, Discord $discord) {
    // ...
});

Repositories

Repositories are containers for parts. They provide the functions to get, save and delete parts from the Discord servers. Different parts have many repositories.

An example is the Channel part. It has 4 repositories: members, messages, overwrites and webhooks. Each of these repositories contain parts that relate to the Channel part, such as messages sent in the channel (messages repository), or if it is a voice channel the members currently in the channel (members repository).

A full list of repositories is provided below in the parts section, per part.

Repositories extend the Collection class. See the documentation on collections for extra methods.

Examples provided below are based on the guilds repository in the Discord client.

Methods

All repositories extend the AbstractRepository class, and share a set of core methods.

Freshening the repository data

Clears the repository and fills it with new data from Discord. It takes no parameters and returns the repository in a promise.

$discord->guilds->freshen()->done(function (GuildRepository $guilds) {
    // ...
});

Creating a part

Creates a repository part from an array of attributes and returns the part. Does not create the part in Discord servers, you must use the ->save() function later.

name type description
attributes array Array of attributes to fill in the part. Optional
$guild = $discord->guilds->create([
    'name' => 'My new guild name',
]);
// to save
$discord->guilds->save($guild)->done(...);

Saving a part

Creates or updates a repository part in the Discord servers. Takes a part and returns the same part in a promise.

name type description
part Part The part to create or update
$discord->guilds->save($guild)->done(function (Guild $guild) {
    // ...
});

Deleting a part

Deletes a repository part from the Discord servers. Takes a part and returns the old part in a promise.

name type description
part Part The part to delete
$discord->guilds->delete($guild)->done(function (Guild $guild) {
    // ...
});

Fetch a part

Fetches/freshens a part from the repository. If the part is present in the cache, it returns the cached version, otherwise it retrieves the part from Discord servers. Takes a part ID and returns the part in a promise.

name type description
id string Part ID
fresh bool Forces the method to skip checking the cache. Default is false
$discord->guilds->fetch('guild_id')->done(function (Guild $guild) {
    // ...
});
// or, if you don't want to check the cache
$discord->guilds->fetch('guild_id', true)->done(function (Guild $guild) {
    // ...
});

Parts

Parts is the term used for the data structures inside Discord. All parts share a common set of attributes and methods.

Parts have a set list of fillable fields. If you attempt to set a field that is not accessible, it will not warn you.

To create a part object, you can use the new syntax or the factory method. For example, creating a Message part:

$message = new Message($discord);
// or
$message = $discord->factory->create(Message::class);

Part attributes can be accessed similar to an object or like an array:

$message->content = 'hello!';
// or
$message['content'] = 'hello!';

echo $message->content;
// or
echo $message['content'];

Filling a part with data

The ->fill(array $attributes) function takes an array of attributes to fill the part. If a field is found that is not 'fillable', it is skipped.

$message->fill([
    'content' => 'hello!',
]);

Getting the raw attributes of a part

The ->getRawAttributes() function returns the array representation of the part.

$attributes = $message->getRawAttributes();
/**
 * [
 *     "id" => "",
 *     "content" => "",
 *     // ...
 * ]
 */

Guild

Guilds represent Discord 'servers'.

Repositories

name type notes
channels Channel
members Member May not contain offline members, see the loadAllMembers option.
roles Role
bans Ban
invites Invite
emojis Emoji

Creating a role

Shortcut for $guild->roles->save($role);. Takes an array of parameters for a role and returns a role part in a promise.

Parameters

name type description default
name string Role name new role
color integer RGB color value 0
permissions string Bitwise value of permissions @everyone permissions
hoist bool Hoisted role? false
mentionable bool Mentionable role? false
$guild->createRole([
    'name' => 'New Role',
    // ...
])->done(function (Role $role) {
    // ...
});

Transferring ownership of guild

Transfers the ownership of the guild to another member. The bot must own the guild to be able to transfer ownership. Takes a member object or a member ID and returns nothing in a promise.

Parameters

name type description
member Member or member ID The member to get ownership
$guild->transferOwnership($member)->done(...);
// or
$guild->transferOwnership('member_id')->done(...);

Unbanning a member with a User or user ID

Unbans a member when passed a User object or a user ID. If you have the ban object, you can do $guild->bans->delete($ban);. Returns nothing in a promise.

Parameters

name type description
user_id User or user ID The user to unban
$guild->unban($user)->done(...);
// or
$guild->unban('user_id')->done(...);

Querying the Guild audit log

Takes an array of parameters to query the audit log for the guild. Returns an Audit Log object inside a promise.

Parameters

name type description
user_id string, int, Member, User Filters audit log by who performed the action
action_type Entry constants Filters audit log by the type of action
before string, int, Entry Retrieves audit logs before the given audit log object
limit int between 1 and 100 Limits the amount of audit log entries to return
$guild->getAuditLog([
    'user_id' => '123456',
    'action_type' => Entry::CHANNEL_CREATE,
    'before' => $anotherEntry,
    'limit' => 12,
])->done(function (AuditLog $auditLog) {
    foreach ($auditLog->audit_log_entries as $entry) {
        // $entry->...
    }
});

Channel

Channels represent a Discord channel, whether it be a direct message channel, group channel, voice channel, text channel etc.

Properties

name type description
id string id of the channel
name string name of the channel
type int type of the channel, see Channel constants
topic string topic of the channel
guild_id string or null id of the guild the channel belongs to, null if direct message
guild Guild or null guild the channel belongs to, null if direct message
position int position of the channel in the Discord client
is_private bool whether the message is a private direct message channel
lastmessageid string id of the last message sent in the channel
bitrate int bitrate of the voice channel
recipient User recipient of the direct message, only for direct message channel
recipients Collection of Users recipients of the group direct message, only for group dm channels
nsfw bool whether the channel is set as NSFW
user_limit int user limit of the channel for voice channels
ratelimitper_user int amount of time in seconds a user has to wait between messages
icon string channel icon hash
owner_id string owner of the group DM
application_id string id of the group dm creator if it was via an oauth application
parent_id string id of the parent of the channel if it is in a group
lastpintimestamp Carbon timestamp when the last message was pinned in the channel

Repositories

name type notes
members VoiceStateUpdate Only for voice channels. Contains voice members.
messages Message
overwrites Overwrite Contains permissioon overwrites.
webhooks Webhook

Set permissions of a member or role

Sets the permissions of a member or role. Takes two arrays of permissions - one for allow and one for deny. See Channel Permissions for a valid list of permissions. Returns nothing in a promise.

Parameters

name type description default
part Member or Role The part to apply the permissions to required
allow array Array of permissions to allow the part []
deny array Array of permissions to deny the part []
// Member can send messages and attach files,
// but can't add reactions to message.
$channel->setPermissions($member, [
    'send_messages',
    'attach_files',
], [
    'add_reactions',
])->done(function () {
    // ...
});

Set permissions of a member or role with an Overwrite

Sets the permissions of a member or role, but takes an Overwrite part instead of two arrays. Returns nothing in a promise.

Parameters

name type description default
part Member or Role The part to apply the permissions to required
overwrite Overwrite part The overwrite to apply required
$allow = new ChannelPermission($discord, [
    'send_messages' => true,
    'attach_files' => true,
]);

$deny = new ChannelPermission($discord, [
    'add_reactions' => true,
]);

$overwrite = $channel->overwrites->create([
    'allow' => $allow,
    'deny' => $deny,
]);

// Member can send messages and attach files,
// but can't add reactions to message.
$channel->setOverwrite($member, $overwrite)->done(function () {
    // ...
});

Move member to voice channel

Moves a member to a voice channel if the member is already in one. Takes a Member object or member ID and returns nothing in a promise.

Parameters

name type description default
member Member or string The member to move required
$channel->moveMember($member)->done(function () {
    // ...
});

// or

$channel->moveMember('123213123123213')->done(function () {
    // ...
});

Muting and unmuting member in voice channel

Mutes or unmutes a member in the voice channel. Takes a Member object or member ID and returns nothing in a promise.

Parameters

name type description default
member Member or string The member to mute/unmute required
// muting a member with a member object
$channel->muteMember($member)->done(function () {
    // ...
});

// unmuting a member with a member ID
$channel->unmuteMember('123213123123213')->done(function () {
    // ...
});

Creating an invite

Creates an invite for a channel. Takes an array of options and returns the new invite in a promise.

Parameters

Parameters are in an array.

name type description default
max_age int Maximum age of the invite in seconds 24 hours
max_uses int Maximum uses of the invite unlimited
temporary bool Whether the invite grants temporary membership false
unique bool Whether the invite should be unique false
$channel->createInvite([
    'max_age' => 60, // 1 minute
    'max_uses' => 5, // 5 uses
])->done(function (Invite $invite) {
    // ...
});

Bulk deleting messages

Deletes many messages at once. Takes an array of messages and/or message IDs and returns nothing in a promise.

Parameters

name type description default
messages array or collection of messages and/or message IDs The messages to delete default
$channel->deleteMessages([
    $message1,
    $message2,
    $message3,
    'my_message4_id',
    'my_message5_id',
])->done(function () {
    // ...
});

Getting message history

Retrieves message history with an array of options. Returns a collection of messages in a promise.

Parameters

name type description default
before Message or message ID Get messages before this message
after Message or message ID Get messages after this message
around Message or message ID Get messages around this message
limit int Number of messages to get, between 1 and 100 100
$channel->getMessageHistory([
    'limit' => 5,
])->done(function (Collection $messages) {
    foreach ($messages as $message) {
        // ...
    }
});

Limit delete messages

Deletes a number of messages, in order from the last one sent. Takes an integer of messages to delete and returns an empty promise.

Parameters

name type description default
value int number of messages to delete, in the range 1-100 required
// deletes the last 15 messages
$channel->limitDelete(15)->done(function () {
    // ...
});

Pin or unpin a message

Pins or unpins a message from the channel pinboard. Takes a message object and returns the same message in a promise.

Parameters

name type description default
message Message The message to pin/unpin required
// to pin
$channel->pinMessage($message)->done(function (Message $message) {
    // ...
});

// to unpin
$channel->unpinMessage($message)->done(function (Message $message) {
    // ...
});

Get invites

Gets the channels invites. Returns a collection of invites in a promise.

$channel->getInvites()->done(function (Collection $invites) {
    foreach ($invites as $invite) {
        // ...
    }
});

Send a message

Sends a message to the channel. Takes a string of content, whether the message is TTS and an embed. Returns the message in a promise.

Parameters

name type description default
text string Message content required
tts bool Whether the message is TTS false
embed Embed or embed array The embed for the message none
$channel->sendMessage('Hello, world!', false, $embed)->done(function (Message $message) {
    // ...
});

Send an embed

Sends an embed to the channel. Takes an embed and returns the sent message in a promise.

Parameters

name type description default
embed Embed The embed to send required
$channel->sendEmbed($embed)->done(function (Message $message) {
    // ...
});

Send a file

Sends a file to the channel. Takes a filepath, filename, message content and tts value. Returns a message in a promise.

Parameters

name type description default
filepath string Path to the file to send required
filename string The filename to send the file as same as filepath
content string Message content to send with the file
tts bool Whether the message content is TTS false
$channel->sendFile('/home/user/my_cool_pic.png', 'new_filename.png', 'content', false)
->done(function (Message $message) {
    // ...
});

Broadcast typing

Broadcasts to the channel that the bot is typing. Genreally, bots should not use this route, but if a bot takes a while to process a request it could be useful. Returns nothing in a promise.

$channel->broadcastTyping()->done(function () {
    // ...
});

Create a message collector

Creates a message collector, which calls a filter function on each message received and inserts it into a collection if the function returns true. The collector is resolved after a specified time or limit, whichever is given or whichever happens first. Takes a callback, an array of options and returns a collection of messages in a promise.

Parameters

name type description default
filter callable The callback to call on every message required
options array Array of options []
// Collects 5 messages containing hello
$channel->createMessageCollector(fn ($message) => strpos($message->content, 'hello') !== false, [
    'limit' => 5,
])->done(function (Collection $messages) {
    foreach ($messages as $message) {
        // ...
    }
});

Options

One of time or limit is required, or the collector will not resolve.

name type description
time int The time after which the collector will resolve, in milliseconds
limit int The number of messages to be collected

Get pinned messages

Returns the messages pinned in the channel. Only applicable for text channels. Returns a collection of messages in a promise.

$channel->getPinnedMessages()->done(function (Collection $messages) {
    foreach ($messages as $message) {
        // $message->...
    }
});

Member

Members represent a user in a guild. There is a member object for every guild-user relationship, meaning that there will be multiple member objects in the Discord client with the same user ID, but they will belong to different guilds.

A member object can also be serialised into a mention string. For example:

$discord->on(Event::MESSAGE_CREATE, function (Message $message) {
    // Hello <@member_id>!
    $message->channel->sendMessage('Hello '.$message->author.'!');
});

Properties

name type description
id string the user ID of the member
username string the username of the member
discriminator string the four digit discriminator of the member
user User the user part of the member
roles Collection of Roles roles the member is a part of
deaf bool whether the member is deafened
mute bool whether the member is muted
joined_at Carbon timestamp when the member joined the guild
guild Guild the guild the member is a part of
guild_id string the id of the guild the member is a part of
string status the status of the member
game Activity the current activity of the member
nick string the nickname of the member
premium_since Carbon timestamp when the member started boosting the guild
activities Collection of Activities the current activities of the member

Ban the member

Bans the member from the guild. Returns a Ban part in a promise.

Parameters

name type description
daysToDelete int number of days back to delete messages, default none
reason string reason for the ban
$member->ban(5, 'bad person')->done(function (Ban $ban) {
    // ...
});

Set the nickname of the member

Sets the nickname of the member. Requires the MANAGE_NICKNAMES permission. Returns nothing in a promise.

Parameters

name type description
nick string nickname of the member, null to clear, default null
$member->setNickname('newnick')->done(function () {
    // ...
});

Move member to channel

Moves the member to another voice channel. Member must already be in a voice channel. Takes a channel or channel ID and returns nothing in a promise.

Parameters

name type description
channel Channel or string the channel to move the member to
$member->moveMember($channel)->done(function () {
    // ...
});

// or

$member->moveMember('123451231231')->done(function () {
    // ...
});

Add member to role

Adds the member to a role. Takes a role or role ID and returns nothing in a promise.

Parameters

name type description
role Role or string the role to add the member to
$member->addRole($role)->done(function () {
    // ...
});

// or

$member->addRole('1231231231')->done(function () {
    // ...
});

Remove member from role

Removes the member from a role. Takes a role or role ID and returns nothing in a promise.

Parameters

name type description
role Role or string the role to remove the member from
$member->removeRole($role)->done(function () {
    // ...
});

// or

$member->removeRole('1231231231')->done(function () {
    // ...
});

Get permissions of member

Gets the effective permissions of the member:

  • When given a channel, returns the effective permissions of a member in a channel.
  • Otherwise, returns the effective permissions of a member in a guild.

Returns a role permission in a promise.

Parameters

name type description
channel Channel or null the channel to get the effective permissions for
$member->getPermissions($channel)->done(function (RolePermission $permission) {
    // ...
});

// or

$member->getPermissions()->done(function (RolePermission $permission) {
    // ...
});

Message

Messages are present in channels and can be anything from a cross post to a reply and a regular message.

Properties

name type description
id string id of the message
channel_id string id of the channel the message was sent in
channel Channel channel the message was sent in
content string content of the message
type int, Message constants type of the message
mentions Collection of Users users mentioned in the message
author Member or User the author of the message, a member object in a guild channel and a user object in a private channel
user_id string id of the user that sent the message
mention_everyone bool whether @everyone was mentioned
timestamp Carbon timestamp the time the message was sent
edited_timestamp Carbon timestamp or null the time the message was edited or null if it hasn't been edited
tts bool whether text to speech was set when the message was sent
attachments array array of attachments
embeds Collection of Embeds embeds contained in the message
nonce string randomly generated string for client
mention_roles Collection of Roles any roles that were mentioned in the message
mention_channels Collection of Channels any channels that were mentioned in the message
pinned bool whether the message is pinned
reactions reaction repository any reactions on the message
webhook_id string id of the webhook that sent the message
activity object current message activity, requires rich present
application object application of the message, requires rich presence
message_reference object message that is referenced by the message
flags int message flags, see below 5 properties
crossposted bool whether the message has been crossposted
is_crosspost bool whetehr the message is a crosspost
suppress_emeds bool whether embeds have been supressed
sourcemessagedeleted bool whether the source message has been deleted e.g. crosspost
urgent bool whetehr message is urgent

Reply to a message

Sends a "reply" to the message. Returns the new message in a promise.

Parameters

name type description
text string text to send in the message
$message->reply('hello!')->done(function (Message $message) {
    // ...
});

Crosspost a message

Crossposts a message to any channels that are following the channel the message was sent in. Returns the crossposted message in a promise.

$message->crosspost()->done(function (Message $message) {
    // ...
});

Reply to a message after a delay

Similar to replying to a message, also takes a delay parameter in which the reply will be sent after. Returns the new message in a promise.

Parameters

name type description
text string text to send in the message
delay int time in milliseconds to delay before sending the message
// <@message_author_id>, hello! after 1.5 seconds
$message->delayedReply('hello!', 1500)->done(function (Message $message) {
    // ...
});

React to a message

Adds a reaction to a message. Takes an Emoji object, a custom emoji string or a unicode emoji. Returns nothing in a promise.

Parameters

name type description
emoticon Emoji or string the emoji to react with
$message->react($emoji)->done(function () {
    // ...
});

// or

$message->react(':michael:251127796439449631')->done(function () {
    // ...
});

// or

$message->react('😀')->done(function () {
    // ...
});

Delete reaction(s) from a message

Deletes reaction(s) from a message. Has four methods of operation, described below. Returns nothing in a promise.

Parameters

name type description
type int type of deletion, one of Message::REACT_DELETE_ALL, Message::REACT_DELETE_ME, Message:REACT_DELETE_ID, Message::REACT_DELETE_EMOJI
emoticon Emoji, string, null emoji to delete, require if using DELETE_ID, DELETE_ME or DELETE_EMOJI
id string, null id of the user to delete reactions for, required by DELETE_ID

Delete all reactions

$message->deleteReaction(Message::REACT_DELETE_ALL)->done(function () {
    // ...
});

Delete reaction by current user

$message->deleteReaction(Message::REACT_DELETE_ME, $emoji)->done(function () {
    // ...
});

Delete reaction by another user

$message->deleteReaction(Message::REACT_DELETE_ID, $emoji, 'member_id')->done(function () {
    // ...
});

Delete all reactions of one emoji

$message->deleteReaction(Message::REACT_DELETE_EMOJI, $emoji)->done(function () {
    // ...
});

Delete the message

Deletes the message. Returns nothing in a promise.

$message->delete()->done(function () {
    // ...
});

Create reaction collector

Creates a reaction collector. Works similar to Channel's reaction collector. Takes a callback and an array of options. Returns a collection of reactions in a promise.

Options

At least one of time or limit must be specified.

name type description
time int or false time in milliseconds until the collector finishes
limit int or false amount of reactions to be collected until the collector finishes
$message->createReactionCollector(function (MessageReaction $reaction) {
    // return true or false depending on whether you want the reaction to be collected.
    return $reaction->user_id == '123123123123';
}, [
    // will resolve after 1.5 seconds or 2 reactions
    'time' => 1500,
    'limit' => 2,
])->done(function (Collection $reactions) {
    foreach ($reactions as $reaction) {
        // ...
    }
});

Add embed to message

Adds an embed to a message. Takes an embed object. Will overwrite the old embed (if there is one). Returns the updated message in a promise.

Parameters

name type description
embed Embed the embed to add
$message->addEmbed($embed)->done(function (Message $message) {
    // ...
});

User

User represents a user of Discord. The bot can "see" any users that to a guild that they also belong to.

Properties

name type description
id string id of the user
username string username of the user
avatar string avatar URL of the user
avatar_hash string avatar hash of the user
discriminator string four-digit discriminator of the user
bot bool whether the user is a bot
system bool whetehr the user is a system user e.g. Clyde
mfa_enabled bool whether the user has multifactor authentication enabled
locale string locale of the user
verified bool whether the user is verified
email string email of the user
flags int user flags, see the User classes constants. use bit masks to compare
premium_type int type of nitro, see the User classes constants
public_flags int see flags above

Get private channel for user

Gets the private direct message channel for the user. Returns a Channel in a promise.

$user->getPrivateChannel()->done(function (Channel $channel) {
    // ...
});

Send user a message

Sends a private direct message to the user. Note that your bot account can be suspended for doing this, consult Discord documentation for more information. Returns the message in a promise.

Parameters

name type description
message string content to send
tts bool whether to send the message as text to speech
embed Embed embed to send in the message
$user->sendMessage('Hello, world!', false, $embed)->done(function (Message $message) {
    // ...
});

Get avatar URL

Gets the avatar URL for the user. Only call this function if you need to change the format or size of the image, otherwise use $user->avatar. Returns a string.

Parameters

name type description
format string format of the image, one of png, jpg or webp, default jpg
size int size of the image, default 1024
$url = $user->getAvatarAttribute('png', 2048);
echo $url; // https://cdn.discordapp.com/avatars/:user_id/:avatar_hash.png?size=2048

Collection

Collections are exactly what they sound like - collections of items. In DiscordPHP collections are based around the idea of parts, but they can be used for any type of item.

Collections implement interfaces allowing them to be accessed like arrays, such as:
// 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)

Creating a collection

name type description
items array Array of items for the collection. Default is empty collection
discrim string or null The discriminator used to discriminate between parts. Default 'id'
class string or null The type of class contained in the collection. Default null
// Creates an empty collection with discriminator of 'id' and no class type.
// Any item can be inserted into this collection.
$collec = new Collection();

// Creates an empty collection with no discriminator and no class type.
// Similar to a laravel collection.
$collec = new Collection([], null, null);

Getting an item

Gets an item from the collection, with a key and value.

name type description
key any The key to search with
value any The value that the key should match
// Collection with 3 items, discriminator is 'id', no class type
$collec = new Collection([
    [
        'id' => 1,
        'text' => 'My ID is 1.'
    ],
    [
        'id' => 2,
        'text' => 'My ID is 2.'
    ],
    [
        'id' => 3,
        'text' => 'My ID is 3.'
    ]
]);

// [
//     'id' => 1,
//     'text' => 'My ID is 1.'
// ]
$item = $collec->get('id', 1);

// [
//     'id' => 1,
//     'text' => 'My ID is 1.'
// ]
$item = $collec->get('text', 'My ID is 1.');

Adding an item

Adds an item to the collection. Note that if class is set in the constructor and the class of the item inserted is not the same, it will not insert.

name type description
$item any The item to insert
// empty, no discrim, no class
$collec = new Collection([], null, null);

$collec->push(1);
$collec->push('asdf');
$collec->push(true);

// ---

class X
{
    public $y;

    public function __construct($y)
    {
        $this->y = $y;
    }
}

// empty, discrim 'y', class X
$collec = new Collection([], 'y', X::class);
$collec->push(new X(123));
$collec->push(123); // won't insert

// new X(123)
$collec->get('y', 123);

Pulling an item

Removes an item from the collection and returns it.

name type description
key any The key to look for
default any Default if key is not found. Default null
$collec = new Collection([], null, null);
$collec->push(1);
$collec->push(2);
$collec->push(3);

$collec->pull(1); // returns at 1 index - which is actually 2
$collec->pull(100); // returns null
$collec->pull(100, 123); // returns 123

Filling the collection

Fills the collection with an array of items.

$collec = new Collection([], null, null);
$collec->fill([
    1, 2, 3, 4,
]);

Number of items

Returns the number of items in the collection.

$collec = new Collection([
    1, 2, 3
], null, null);

echo $collec->count(); // 3

Getting the first item

Gets the first item of the collection.

$collec = new Collection([
    1, 2, 3
], null, null);

echo $collec->first(); // 1

Filtering a collection

Filters the collection with a given callback function. The callback function is called for every item and is called with the item. If the callback returns true, the item is added to the new collection. Returns a new collection.

name type description
callback callable The callback called on every item
$collec = new Collection([
    1, 2, 3, 100, 101, 102
], null, null);

// [ 101, 102 ]
$newCollec = $collec->filter(function ($item) {
    return $item > 100;
});

Clearing a collection

Clears the collection.

$collec->clear(); // $collec = []

Mapping a collection

A given callback function is called on each item in the collection, and the result is inserted into a new collection.

name type description
callback callable The callback called on every item
$collec = new Collection([
    1, 2, 3, 100, 101, 102
], null, null);

// [ 100, 200, 300, 10000, 10100, 10200 ]
$newCollec = $collec->map(function ($item) {
    return $item * 100;
});

Converting to array

Converts a collection to an array.

$arr = $collec->toArray();

Permissions

There are two types of permissions - channel permissions and role permissions. They are represented by their individual classes, but both extend the same abstract permission class.

Properties

name type description
bitwise int bitwise representation
create_instant_invite bool
manage_channels bool
view_channel bool
manage_roles bool
manage_webhooks bool

The rest of the properties are listed under each permission type, all are type of bool.

Methods

Get all valid permissions

Returns a list of valid permissions, in key value form. Static method.

var_dump(ChannelPermission::getPermissions());
// [
//     'priority_speaker' => 0x123,
//     // ...
// ]

Channel Permission

Represents permissions for voice and text channels.

Voice Channel Permissions

  • create_instant_invite
  • manage_channels
  • view_channel
  • manage_roles
  • manage_webhooks
  • priority_speaker
  • stream
  • connect
  • speak
  • mute_members
  • deafen_members
  • move_members
  • use_vad

Text Channel Permissions

  • create_instant_invite
  • manage_channels
  • view_channel
  • manage_roles
  • manage_webhooks
  • add_reactions
  • send_messages
  • send_tts_messages
  • manage_messages
  • embed_links
  • attach_files
  • read_message_history
  • mention_everyone
  • use_external_emojis

Role Permissions

Represents permissions for roles.

Permissions

  • create_instant_invite
  • manage_channels
  • view_channel
  • manage_roles
  • manage_webhooks
  • kick_members
  • ban_members
  • administrator
  • manage_guild
  • view_audit_log
  • view_guild_insights
  • change_nicknames
  • manage_nicknames
  • manage_emojis