### Install Dependencies and Develop Locally Source: https://github.com/discord-php/discordphp/blob/master/docs/README.md Navigate to the docs directory, install dependencies using Yarn, and start the development server. ```bash cd ./docs yarn install yarn develop ``` -------------------------------- ### Install DiscordPHP (Latest Release) Source: https://github.com/discord-php/discordphp/blob/master/guide/index.rst Use Composer to install the latest stable release of the DiscordPHP library. ```bash $ composer require team-reflex/discord-php ``` -------------------------------- ### Install DiscordPHP (Master Branch) Source: https://github.com/discord-php/discordphp/blob/master/guide/index.rst Use Composer to install the latest development version from the master branch of DiscordPHP. ```bash $ composer require team-reflex/discord-php dev-master ``` -------------------------------- ### Install Latest Release with Composer Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/00_intro.md Use this command to install the latest stable release of DiscordPHP. ```shell composer require team-reflex/discord-php ``` -------------------------------- ### Install Latest Master Branch with Composer Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/00_intro.md Use this command to install the latest code from the master branch. Replace 'master' with any other branch name to install that specific branch. ```shell composer require team-reflex/discord-php dev-master ``` -------------------------------- ### Install DiscordPHP (Master Branch) Source: https://github.com/discord-php/discordphp/wiki/Intro Install the latest development version from the master branch using Composer. You can substitute 'master' with any other branch name. ```shell > composer require team-reflex/discord-php dev-master ``` -------------------------------- ### Install DiscordPHP (Latest Release) Source: https://github.com/discord-php/discordphp/wiki/Intro Use this command to install the latest stable release of DiscordPHP via Composer. ```shell > composer require team-reflex/discord-php ``` -------------------------------- ### Button Listener Setup Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/09_components.md How to set up a listener for button interactions to handle clicks and respond accordingly. ```APIDOC ### Adding a button listener If you add a button you probably want to listen for when it is clicked. This is done through the `setListener(callable $listener, Discord $discord)` function. The `callable $listener` will be a function which is called with the `Interaction` object that triggered the button press. You must also pass the function the `$discord` client. If the interaction is not responded to after the function is called, the interaction will be automatically acknowledged with no response. If you are going to acknowledge the interaction after a delay (e.g. HTTP request, arbitrary timeout) you should return a promise from the listener to prevent the automatic acknowledgement: ### Request Example ```php // Basic listener $button->setListener(function (Interaction $interaction) { $interaction->respondWithMessage(MessageBuilder::new() ->setContent('why\'d u push me?')); }, $discord); // Listener returning a promise $button->setListener(function (Interaction $interaction) use ($discord) { return someFunctionWhichWillReturnAPromise()->then(function ($returnValueFromFunction) use ($interaction) { $interaction->respondWithMessage(MessageBuilder::new() ->setContent($returnValueFromFunction)); }); }, $discord); ``` ``` -------------------------------- ### Start the Event Loop Source: https://github.com/discord-php/discordphp/wiki/Basics Start the Discord client's event loop to begin processing events. This is typically an infinite loop. ```php $discord->run(); ``` -------------------------------- ### Install DiscordPHP with Composer Source: https://github.com/discord-php/discordphp/blob/master/README.md Use Composer to install the latest stable release of DiscordPHP. For the development branch, use 'dev-master'. ```bash composer require team-reflex/discord-php ``` ```bash composer require team-reflex/discord-php dev-master ``` -------------------------------- ### Typing Start Event Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/03_events/08_presences.md Handles events when a user starts typing in a channel. Requires the Guild Message Typing intent. ```APIDOC ## Typing Start ### Description Called with a `TypingStart` object when a user starts typing in a channel. ### Method Event Listener ### Endpoint N/A (Event-driven) ### Parameters #### Query Parameters - **Intents** (Intents::GUILD_MESSAGE_TYPING) - Required - This intent must be enabled. ### Request Example ```php // use Discord\Parts\WebSockets\TypingStart; $discord->on(Event::TYPING_START, function (TypingStart $typing, Discord $discord) { // ... }); ``` ### Response #### Success Response (Event Triggered) - **TypingStart** (object) - An object containing typing start information. - **Discord** (object) - The Discord client instance. #### Response Example (Callback function receives the TypingStart object) ``` -------------------------------- ### Import MessageBuilder Class Source: https://github.com/discord-php/discordphp/wiki/MessageBuilder Import the MessageBuilder class to start composing messages. ```php use Discord\Builders\MessageBuilder; ``` -------------------------------- ### Discord Run Method Source: https://github.com/discord-php/discordphp/wiki/Discord Starts the Bot client and runs the ReactPHP event loop, keeping the bot online and responsive. ```APIDOC ## POST /api/discord/run ### Description Run the Bot client, starts the ReactPHP event loop. ### Method POST ### Endpoint /api/discord/run ### Response #### Success Response (204) No content is returned as this method typically runs indefinitely until the bot is stopped. ### Notes This method should generally be the last one called in your bot's script execution flow. ``` -------------------------------- ### Adding a Component to an ActionRow Source: https://github.com/discord-php/discordphp/wiki/ActionRow Example of how to add a component to an ActionRow. ```APIDOC ## Add a Component to an ActionRow To add a component to an ActionRow, you first need to have a `Component` object. ### Method POST (conceptual, as this is a builder pattern) ### Endpoint N/A (This is a builder method) ### Parameters #### Request Body - **component** (Component) - Required - The component object to add. ### Request Example ```php use Discord\Builders\Components\ActionRow; use Discord\Builders\Components\Button; // Example component // Assuming $component is a valid Discord $component = new Button(['label' => 'Click Me']); $action = ActionRow::new()->addComponent($component); ``` ### Response This method returns the modified ActionRow object for chaining. ``` -------------------------------- ### Import CommandBuilder in PHP Source: https://github.com/discord-php/discordphp/wiki/CommandBuilder Import the CommandBuilder class to start creating commands. This is a foundational step for command creation. ```php use Discord\Builders\CommandBuilder; ``` -------------------------------- ### Create a Message with a Button Source: https://github.com/discord-php/discordphp/wiki/Button Example of how to create a message with a primary style button that responds to clicks. ```APIDOC ## Create a message with a button For this it is mandatory to use the [ActionRow](https://discord-php.github.io/DiscordPHP/classes/Discord-Builders-Components-ActionRow.html) class. To send a [Message](https://github.com/discord-php/DiscordPHP/wiki/Message) you must have the [Channel](https://github.com/discord-php/DiscordPHP/wiki/Channel) object! Create a button with a text ```php // REMEMBER THIS -> Discord\Builders\Components\ActionRow // First we create a MessageBuilder $builder = MessageBuilder::new(); // Now we create an actionRow instance $action = ActionRow::new() // Let's create the button $button = Button::new(Button::STYLE_PRIMARY)->setLabel('Click me!')->setListener(function (Interaction $interaction) { // CODE... $interaction->respondWithMessage(MessageBuilder::new()->setContent("{$interaction->user} You clicked the button!")); }, $discord); $channel->sendMessage($builder->addComponent($action->addComponent($button)))->then(function (Message $message) { echo "Message sent in the channel {$message->channel->id}"; }); ``` ``` -------------------------------- ### Slash Command with User Option Source: https://github.com/discord-php/discordphp/wiki/Option_commands Example of creating a slash command that accepts a user as an option. ```APIDOC ## POST /discord/commands ### Description Creates a new slash command with a user option. ### Method POST ### Endpoint /discord/commands ### Parameters #### Request Body - **name** (string) - Required - The name of the command. - **description** (string) - Required - The description of the command. - **options** (array) - Optional - An array of options for the command. - **name** (string) - Required - The name of the option. - **description** (string) - Required - The description of the option. - **type** (integer) - Required - The type of the option (e.g., Option::USER). - **required** (boolean) - Optional - Whether the option is required. ### Request Example ```php use Discord\Builders\CommandBuilder; use Discord\Parts\Interactions\Command\Option; // Assuming $discord is an initialized Discord instance $discord->application->commands->save($discord->application->commands->create(CommandBuilder::new() ->setName('greet') ->setDescriptions('Greet an user') ->addOption((new Option($discord)) ->setName('user') ->setDescription('User to greet') ->setType(Option::USER) ->setRequired(true) ) ->toArray() )); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Command created successfully" } ``` ``` -------------------------------- ### Handling Slash Command with User Option Source: https://github.com/discord-php/discordphp/wiki/Option_commands Example of how to listen for and handle a slash command that includes a user option. ```APIDOC ## POST /discord/listenCommand/{commandName} ### Description Listens for a specific slash command and processes its interaction, retrieving a user option. ### Method POST ### Endpoint /discord/listenCommand/{commandName} ### Parameters #### Path Parameters - **commandName** (string) - Required - The name of the command to listen for. #### Request Body - **callback** (callable) - Required - The function to execute when the command is invoked. - **interaction** (Interaction) - The interaction object containing command data. ### Request Example ```php // Assuming $discord is an initialized Discord instance $discord->listenCommand('greet', function (Interaction $interaction) { $user = $interaction->data->resolved->users->first(); $interaction->respondWithMessage(MessageBuilder::new()->setContent("Hello, {$user}")); }); ``` ``` -------------------------------- ### Slash Command with String Option Source: https://github.com/discord-php/discordphp/wiki/Option_commands Example of creating a slash command that accepts a string as an option. ```APIDOC ## POST /discord/commands ### Description Creates a new slash command with a string option. ### Method POST ### Endpoint /discord/commands ### Parameters #### Request Body - **name** (string) - Required - The name of the command. - **description** (string) - Required - The description of the command. - **options** (array) - Optional - An array of options for the command. - **name** (string) - Required - The name of the option. - **description** (string) - Required - The description of the option. - **type** (integer) - Required - The type of the option (e.g., Option::STRING). - **required** (boolean) - Optional - Whether the option is required. ### Request Example ```php use Discord\Builders\CommandBuilder; use Discord\Parts\Interactions\Command\Option; // Assuming $discord is an initialized Discord instance $discord->application->commands->save($discord->application->commands->create(CommandBuilder::new() ->setName('say') ->setDescriptions('Say a phrase') ->addOption((new Option($discord)) ->setName('text') ->setDescription('Phrase') ->setType(Option::STRING) ->setRequired(true) ) ->toArray() )); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Command created successfully" } ``` ``` -------------------------------- ### Create New MessageBuilder Source: https://github.com/discord-php/discordphp/wiki/Message-Builder Instantiate a new MessageBuilder object. This is the starting point for constructing a message. ```php $builder = MessageBuilder::new(); ``` -------------------------------- ### Create and Send Embed Source: https://github.com/discord-php/discordphp/wiki/Embed Example of creating an embed object and sending it within a message to a channel. ```APIDOC ## Create an embed and send in a channel To send a [Message](https://github.com/discord-php/DiscordPHP/wiki/Message) you must have the [Channel](https://github.com/discord-php/DiscordPHP/wiki/Channel) object! ```php use Discord\Parts\Embed\Embed; use Discord\Builders\Messages\MessageBuilder; // Assuming $discord and $channel objects are already available $embed = $discord->factory(Embed::class); $embed->setTitle('Hello') ->setDescription('My name is DiscordPHP'); $channel->sendMessage(MessageBuilder::new()->setEmbed($embed)); ``` ``` -------------------------------- ### Handling Slash Command with String Option Source: https://github.com/discord-php/discordphp/wiki/Option_commands Example of how to listen for and handle a slash command that includes a string option. ```APIDOC ## POST /discord/listenCommand/{commandName} ### Description Listens for a specific slash command and processes its interaction, retrieving a string option. ### Method POST ### Endpoint /discord/listenCommand/{commandName} ### Parameters #### Path Parameters - **commandName** (string) - Required - The name of the command to listen for. #### Request Body - **callback** (callable) - Required - The function to execute when the command is invoked. - **interaction** (Interaction) - The interaction object containing command data. ### Request Example ```php // Assuming $discord is an initialized Discord instance $discord->listenCommand('say', function (Interaction $interaction) { $content = $interaction->data->options->offsetGet('text')->value; $interaction->respondWithMessage(MessageBuilder::new()->setContent($content)); }); ``` ``` -------------------------------- ### Get Cache Prefix Source: https://github.com/discord-php/discordphp/wiki/Cache-Interface Retrieves the cache prefix for a given repository. For example, the 'users' repository typically returns 'User.'. ```php $discord->users->cache->getPrefix() ``` -------------------------------- ### Basic Discord Bot Setup Source: https://github.com/discord-php/discordphp/blob/master/README.md This snippet shows how to initialize a Discord bot, log in with a token, and set up an event listener for incoming messages. Ensure you have the MESSAGE_CONTENT intent enabled if your bot needs to read message content when not mentioned or in DMs. ```php 'bot-token', 'intents' => Intents::getDefaultIntents() // | Intents::MESSAGE_CONTENT, // Note: MESSAGE_CONTENT is privileged, see https://dis.gd/mcfaq ]); $discord->on('ready', function (Discord $discord) { $discord->logger->info("Bot is ready!"); // Listen for messages. $discord->on(Event::MESSAGE_CREATE, function (Message $message, Discord $discord) { // Note: MESSAGE_CONTENT intent must be enabled to get the content if the bot is not mentioned/DMed. $discord->logger->info("{$message->author->username}: {$message->content}"); }); }); $discord->run(); ``` -------------------------------- ### Initialize Discord Instance with Options Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/02_basics.md Instantiate the Discord class with an array of configuration options. The 'token' option is mandatory. ```php $discord = new Discord([ ``` ```php 'token' => 'Your-Token-Here', ``` ```php 'intents' => [ Intents::GUILDS, Intents::GUILD_BANS, // ... ], // or 'intents' => 12345, // or 'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, // default intents as well as guild members ``` ```php 'loadAllMembers' => false, ``` ```php 'storeMessages' => false, ``` ```php 'retrieveBans' => false, ``` ```php 'disabledEvents' => [ Event::MESSAGE_CREATE, Event::MESSAGE_DELETE, // ... ], ``` ```php 'loop' => \React\EventLoop\Factory::create(), ``` ```php 'logger' => new \Monolog\Logger('New logger'), ``` ```php 'dnsConfig' => '1.1.1.1', ``` ```php 'shardId' => 0, ``` ```php 'shardCount' => 5, ``` ```php ]); ``` -------------------------------- ### Create a TextInput for a Modal Source: https://github.com/discord-php/discordphp/wiki/Components Initializes a TextInput component for use within Discord modals. This example creates a short-text input that is required. ```php $textInput = TextInput::new('Label', TextInput::TYPE_SHORT, 'custom id') ->setRequired(true); ``` -------------------------------- ### Initialize Discord Instance with Token Source: https://github.com/discord-php/discordphp/wiki/Basics Instantiate the Discord client, providing your bot's token. This is the only required option. ```php $discord = new Discord([ 'token' => 'Your-Token-Here', ``` -------------------------------- ### Initialize Filesystem Cache Source: https://github.com/discord-php/discordphp/wiki/Cache-Interface Sets up a filesystem cache using ReactPHP's Filesystem component. Note: This implementation does not work on Windows. ```php use React\EventLoop\Loop; use React\Filesystem\Filesystem as ReactFilesystem; use WyriHaximus\React\Cache\Filesystem; $loop = Loop::get(); $filesystem = ReactFilesystem::create($loop); $cache = new Filesystem($filesystem, '/tmp/cache/dphp/'); $discord = new Discord([ 'token' => 'bot token', 'loop' => $loop, // note the same loop 'cache' => $cache, ]); ``` -------------------------------- ### Configure Discord Instance (PHP) Source: https://github.com/discord-php/discordphp/blob/master/guide/basics.rst Initialize the Discord instance with an array of options. The 'token' is required. Other options include 'intents', 'loadAllMembers', 'storeMessages', 'retrieveBans', 'pmChannels', 'disabledEvents', 'loop', 'logger', 'dnsConfig', 'shardId', and 'shardCount'. ```php $discord = new Discord([ 'token' => 'Your-Token-Here', 'intents' => [ Intents::GUILDS, Intents::GUILD_BANS, // ... ], // or 'intents' => 12345, // or 'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, // default intents as well as guild members 'loadAllMembers' => false, 'storeMessages' => false, 'retrieveBans' => false, 'pmChannels' => false, 'disabledEvents' => [ Event::MESSAGE_CREATE, Event::MESSAGE_DELETE, // ... ], 'loop' => \React\EventLoop\Factory::create(), 'logger' => new \Monolog\Logger('New logger'), 'dnsConfig' => '1.1.1.1', 'shardId' => 0, 'shardCount' => 5, ]); ``` -------------------------------- ### Get Logger Instance Source: https://github.com/discord-php/discordphp/wiki/Discord Gets the PSR-3 compliant logger instance used by the bot client for logging messages. ```php $logger = $discord->getLogger(); $logger->info('This information goes to log!'); ``` -------------------------------- ### Initialize Discord Bot Client Source: https://github.com/discord-php/discordphp/wiki/Discord Instantiate the Discord Bot client with your bot token. Ensure the token is kept secure. ```php use Discord\Discord; $discord = new Discord([ 'token' => 'bot-token', ]); ``` -------------------------------- ### Initialize MemcachedAdapter and Discord with Cache Source: https://github.com/discord-php/discordphp/wiki/Cache-Interface This snippet shows how to set up a MemcachedAdapter, wrap it in a Psr16Cache, and then use it to configure the Discord client. Ensure Memcached PECL is installed and a Memcached server is running on localhost:11211. ```php use Symfony\Component\Cache\Adapter\MemcachedAdapter; $memcached = new \Memcached(); $memcached->addServer('localhost', 11211); $psr6Cache = new MemcachedAdapter($memcached, 'dphp', 0); // prefix is "dphp:" $cache = new \Symfony\Component\Cache\Psr16Cache($psr6Cache); $discord = new Discord([ 'token' => 'bot token', 'cache' => $cache, ]); ``` -------------------------------- ### GET /users/{user_id}/private-channel Source: https://github.com/discord-php/discordphp/blob/master/guide/parts/user.rst Gets the private direct message channel for the user. Returns a `Channel` object in a promise. ```APIDOC ## GET /users/{user_id}/private-channel ### Description Gets the private direct message channel for the user. Returns a `Channel` object in a promise. ### Method GET ### Endpoint `/users/{user_id}/private-channel` ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to get the private channel for. ### Response #### Success Response (200) - **Channel** (object) - The private channel object. ### Request Example ```php $user->getPrivateChannel()->then(function (Channel $channel) { // ... }); ``` ``` -------------------------------- ### Create an Invite Source: https://github.com/discord-php/discordphp/wiki/Parts/Invite Creates an invite for a channel with specified expiry and usage limits. Ensure your bot has the 'create_instant_invite' permission. ```php $channel->createInvite([ // All options are optional 'max_age' => 60, // 1 minute 'max_uses' => 5, // 5 uses // more options in Docs ])->then(function (Invite $invite) { echo "Here is the invite link: {$invite->invite_url}"; })->done(); ``` -------------------------------- ### Get Private Channel for User Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/05_user.md Gets the private direct message channel for the user. Returns a [Channel](#channel) in a promise. ```APIDOC ## GET /users/{user_id}/channels ### Description Gets the private direct message channel for the user. Returns a [Channel](#channel) in a promise. ### Method GET ### Endpoint `/users/{user_id}/channels` ### Response #### Success Response (200) - **channel** (Channel) - The private channel object. ### Response Example ```json { "id": "1234567890", "type": 1, "recipients": [ { "id": "0987654321", "username": "testuser", "discriminator": "1234", "avatar": "a_avatar_hash" } ] } ``` ``` -------------------------------- ### Handle 'greet' Slash Command Source: https://github.com/discord-php/discordphp/wiki/Option_commands Listens for the 'greet' slash command and responds with a greeting message to the mentioned user. It retrieves the user from the resolved data. ```php use Discord\Interactions\Interaction; use Discord\Builders\MessageBuilder; //... $discord->listenCommand('greet', function (Interaction $interaction) { $user = $interaction->data->resolved->users->first(); $interaction->respondWithMessage(MessageBuilder::new()->setContent("Hello, {$user}")); }); ``` -------------------------------- ### Create a SelectMenu with Options Source: https://github.com/discord-php/discordphp/wiki/Components Instantiates a new SelectMenu and adds two options to it. Select menus can have up to 25 options, each with a unique value. ```php $select = SelectMenu::new() ->addOption(Option::new('me?')) ->addOption(Option::new('or me?')); ``` -------------------------------- ### Create a Repository Part Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/04_repositories.md Creates a repository part from an array of attributes. Does not create the part in Discord servers; use `->save()` later. Requires an array of attributes. ```php $guild = $discord->guilds->create([ 'name' => 'My new guild name', ]); // to save $discord->guilds->save($guild)->then(...); ``` -------------------------------- ### Get Channel Source: https://github.com/discord-php/discordphp/wiki/Parts/Channel Retrieves a specific channel either from the cache or by fetching it from Discord. You can use the Discord instance or the Guild object to get a channel. ```APIDOC ## GET /channels/{channel.id} ### Description Retrieves a specific channel. ### Method GET ### Endpoint `/channels/{channel.id}` ### Parameters #### Path Parameters - **channel.id** (string) - Required - The ID of the channel to retrieve. ### Request Example (Using Discord Instance) ```php $channel = $discord->getChannel('123123123123123123'); ``` ### Request Example (Using Guild Object - Cached) ```php $channel = $guild->channels->get('id', '123123123123123123'); ``` ### Request Example (Using Guild Object - Fetching) ```php $guild->channels->fetch('123123123123123123')->then(function (Channel $channel) { // ... })->done(); ``` ### Response #### Success Response (200) - **id** (string) - The ID of the channel. - **name** (string) - The name of the channel. - **type** (integer) - The type of the channel. #### Response Example ```json { "id": "123123123123123123", "name": "general", "type": 0 } ``` ``` -------------------------------- ### Create an Empty Collection Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/06_collection.md Initializes a new Collection. The first example creates a general-purpose collection, while the second creates one similar to a Laravel collection. ```php $collec = new Collection(); // Creates an empty collection with no discriminator and no class type. // Similar to a laravel collection. $collec = new Collection([], null, null); ``` -------------------------------- ### Get Member Permissions Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/03_member.md Retrieves the effective permissions of a member. Provide a channel to get permissions within that specific channel, otherwise, it returns guild-wide permissions. ```php $permissions = $member->getPermissions($channel); ``` ```php $permissions = $member->getPermissions(); ``` -------------------------------- ### Get User Avatar URL Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/05_user.md 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. ```APIDOC ## GET /users/{user_id}/avatars/{avatar_hash} ### Description 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. ### Method GET ### Endpoint `/users/{user_id}/avatars/{avatar_hash}` ### Parameters #### Query Parameters - **format** (string) - Optional - format of the image, one of png, jpg or webp, default webp or gif if animated - **size** (int) - Optional - size of the image, default 1024 ### Response #### Success Response (200) - **url** (string) - The avatar URL. ### Response Example ``` https://cdn.discordapp.com/avatars/:user_id/:avatar_hash.png?size=2048 ``` ``` -------------------------------- ### Get User Banner URL Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/05_user.md Gets the banner URL for the user. Only call this function if you need to change the format or size of the image, otherwise use `$user->banner`. Returns a string or `null` if user has no banner image set. ```APIDOC ## GET /users/{user_id}/banners/{banner_hash} ### Description Gets the banner URL for the user. Only call this function if you need to change the format or size of the image, otherwise use `$user->banner`. Returns a string or `null` if user has no banner image set. ### Method GET ### Endpoint `/users/{user_id}/banners/{banner_hash}` ### Parameters #### Query Parameters - **format** (string) - Optional - format of the image, one of png, jpg or webp, default png or gif if animated - **size** (int) - Optional - size of the image, default 600 ### Response #### Success Response (200) - **url** (string) - The banner URL. ### Response Example ``` https://cdn.discordapp.com/banners/:user_id/:banner_hash.png?size=1024 ``` ``` -------------------------------- ### Discord Constructor Source: https://github.com/discord-php/discordphp/wiki/Discord Initializes a new Discord Bot client instance. Options can be provided to configure the client. ```APIDOC ## POST /api/discord ### Description Creates a Discord Bot client instance. ### Method POST ### Endpoint /api/discord ### Parameters #### Request Body - **options** (array) - Optional - An array of options to configure the client. ### Request Example ```json { "options": { "token": "bot-token" } } ``` ### Response #### Success Response (200) - **Discord** (Discord) - The Bot client object. #### Response Example ```json { "discord": "Discord object" } ``` ``` -------------------------------- ### Guild::createdTimestamp() Source: https://github.com/discord-php/discordphp/wiki/Parts/Guild Gets the timestamp of when the guild was created. ```APIDOC ## Guild::createdTimestamp() ### Description Returns the timestamp of when the guild was created. ### Method Instance Method ### Endpoint N/A ### Parameters None ### Request Example ```php echo $guild->createdTimestamp(); ``` ### Response #### Success Response (200) - **timestamp** (float) - The timestamp of when the guild was created. #### Response Example ```php 1678886400.0 ``` ``` -------------------------------- ### Select Menu Listener Source: https://github.com/discord-php/discordphp/blob/master/guide/components.rst How to set up a listener for select menu interactions. The callback receives the Interaction object and a collection of selected Options. ```APIDOC ## Select Menu Listener ### Description Sets a listener for select menu interactions. The callback function is invoked with the `Interaction` object and a collection of selected `Option` objects. ### Method `setListener(callable $listener, Discord $discord)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $select->setListener(function (Interaction $interaction, Collection $options) { foreach ($options as $option) { echo $option->getValue().PHP_EOL; } $interaction->respondWithMessage(MessageBuilder::new()->setContent('thanks!')); }, $discord); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Channel Invites Source: https://github.com/discord-php/discordphp/blob/master/guide/parts/channel.rst Retrieves all of the invites for a given channel. ```APIDOC ## GET /api/channels/{channel.id}/invites ### Description Gets the channels invites. Returns a collection of invites. ### Method GET ### Endpoint /api/channels/{channel.id}/invites ### Parameters None ### Request Example ```php $channel->getInvites()->then(function (Collection $invites) { foreach ($invites as $invite) { // ... } }); ``` ### Response #### Success Response (200) - **invites** (Collection) - A collection of invite objects. #### Response Example ```json [ { "code": "invite_code_1", "guild": { "id": "guild_id_1", "name": "Example Guild" }, "channel": { "id": "channel_id" } }, { "code": "invite_code_2", "guild": { "id": "guild_id_2", "name": "Another Guild" }, "channel": { "id": "channel_id" } } ] ``` ``` -------------------------------- ### Get Guild Source: https://github.com/discord-php/discordphp/wiki/Parts/Guild Retrieves a guild from cache or fetches it if not found. ```APIDOC ## Get Guild ### Description Retrieves a guild from cache or fetches it if not found. Your BOT must be a member of the guild. ### Cached Retrieval ```php // By ID $guild = $discord->guilds->get('id', '123123123123123123'); // Or using offsetGet $guild = $discord->guilds['123123123123123123']; ``` ### Fetching Guild (Asynchronous) If the guild is not in cache, you may need to fetch it. ```php $discord->guilds->fetch('123123123123123123')->then(function (Guild $guild) { // ... })->done(); ``` ``` -------------------------------- ### Create a Repository Part Source: https://github.com/discord-php/discordphp/wiki/Repositories Creates a repository part from an array of attributes. This does not create the part in Discord servers; you must use `->save()` later. ```php $guild = $discord->guilds->create([ 'name' => 'My new guild name', ]); ``` -------------------------------- ### Import Invite Class Source: https://github.com/discord-php/discordphp/wiki/Parts/Invite Imports the Invite class for use in your project. ```php use Discord\Parts\Channel\Invite; ``` -------------------------------- ### Sending Ephemeral Messages Source: https://github.com/discord-php/discordphp/wiki/Option_commands Example of responding to an interaction with an ephemeral message. ```APIDOC ## POST /discord/listenCommand/{commandName} ### Description Responds to a slash command interaction with an ephemeral message. ### Method POST ### Endpoint /discord/listenCommand/{commandName} ### Parameters #### Path Parameters - **commandName** (string) - Required - The name of the command to listen for. #### Request Body - **callback** (callable) - Required - The function to execute when the command is invoked. - **interaction** (Interaction) - The interaction object containing command data. ### Request Example ```php // Assuming $discord is an initialized Discord instance $discord->listenCommand('mycommand', function (Interaction $interaction) { // ... other logic $interaction->respondWithMessage(MessageBuilder::new()->setContent($content), true); }); ``` ``` -------------------------------- ### Initialize DiscordPHP Slash Client Source: https://github.com/discord-php/discordphp/blob/master/V7_CONVERSION.md Instantiate the Slash Client with options. In standard DiscordPHP, all options are provided when constructing the main Discord object. ```php $client = new Client([ /* options */ ]); ``` -------------------------------- ### Getting the First Item of a Collection Source: https://github.com/discord-php/discordphp/wiki/Collection Retrieve the very first item present in the collection. ```php $collec = new Collection([ 1, 2, 3 ], null, null); echo $collec->first(); // 1 ``` -------------------------------- ### Create a reaction collector Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/04_message.md Sets up a collector to gather reactions on a message. It can be configured with a time limit or a reaction limit. The collector resolves with a collection of reactions. ```php $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, ])->then(function (Collection $reactions) { foreach ($reactions as $reaction) { // ... } }); ``` -------------------------------- ### Basic Discord Command Client Usage Source: https://github.com/discord-php/discordphp/wiki/Command-Client Initialize the command client with a token and register a simple 'ping' command that responds with 'pong!'. The client automatically runs and listens for commands. ```php 'your-token', //'discordOptions' => [ // other options from Discord() here, example: //'intents' => Intents::getDefaultIntents(), //'loadAllMembers' => false, //], ]); $discord->registerCommand('ping', function ($message) { return 'pong!'; }, [ 'description' => 'pong!', ]); $discord->run(); ``` -------------------------------- ### Create a message with an embed Source: https://github.com/discord-php/discordphp/wiki/MessageBuilder Example of how to create a message with an embed using MessageBuilder. ```PHP use Discord\Builders\MessageBuilder; use Discord\Parts\Embed; // Assuming $discord and $channel are already initialized $embed = $discord->factory(Embed::class)->setDescription('oh no an embed!'); $channel->sendMessage(MessageBuilder::new()->addEmbed($embed)); ``` -------------------------------- ### Configure Load All Members Option Source: https://github.com/discord-php/discordphp/wiki/Basics Set 'loadAllMembers' to true if you need to fetch and store all guild members on bot startup. This requires the GUILD_MEMBERS intent. ```php 'loadAllMembers' => false, ``` -------------------------------- ### Get Invites Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/02_channel.md Retrieves all active invites for a given channel. Returns a collection of invites. ```APIDOC ## GET /channels/{channel.id}/invites ### Description Gets the channels invites. Returns a collection of invites in a promise. ### Method GET ### Endpoint /channels/{channel.id}/invites ### Parameters #### Path Parameters - **channel.id** (string) - Required - The ID of the channel. ### Response #### Success Response (200 OK) - **invites** (Collection) - A collection of invite objects. ``` -------------------------------- ### Get Original Interaction Response Source: https://github.com/discord-php/discordphp/blob/master/guide/interactions.rst Retrieves the initial message that was sent as a response to the interaction. ```php getOriginalResponse() ``` -------------------------------- ### Get a Specific Reaction Source: https://github.com/discord-php/discordphp/wiki/Parts/Reaction Retrieves reaction information for a message, either from cache or by fetching. ```APIDOC ## Get a Specific Reaction ### Description Retrieves reaction information for a message. Can be fetched from cache or asynchronously. ### Method GET (implied by library function) ### Endpoint (Not directly specified, operates on Message object's reactions collection) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example #### Cached, synchronous: ```php $reaction = $message->reactions->get('id', '😀'); ``` #### Fetch (Promise, asynchronous): ```php $message->reactions->fetch('😀')->then(function (Reaction $reactions) { // ... })->done(); ``` ### Response #### Success Response (200) - **Reaction** (object) - Represents the reaction details. #### Response Example ```json { "example": "Reaction object details" } ``` ``` -------------------------------- ### Handle Channel Create Event Source: https://github.com/discord-php/discordphp/wiki/Events/Channels Listen for the CHANNEL_CREATE event to react when a new channel is created. Requires the Intents::GUILDS intent. ```php $discord->on(Event::CHANNEL_CREATE, function (Channel $channel, Discord $discord) { // ... }); ``` -------------------------------- ### Get Channel Invites Source: https://github.com/discord-php/discordphp/wiki/Parts/Invite Retrieves all invites for a given channel. Requires the Channel object. ```php $channel->getInvites()->then(function (Collection $invites) { foreach ($invites as $invite) { // ... } })->done(); ``` -------------------------------- ### Get Channel Invites Source: https://github.com/discord-php/discordphp/blob/master/guide/parts/channel.rst Retrieves all invites for a given channel. Returns a collection of invite objects. ```php $channel->getInvites()->then(function (Collection $invites) { foreach ($invites as $invite) { // ... } }); ``` -------------------------------- ### Get Message History API Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/02_channel.md Retrieves the message history of a channel with various filtering options. ```APIDOC ## GET /channels/{channel.id}/messages ### Description Retrieves message history with an array of options. Returns a collection of messages in a promise. ### Method GET ### Endpoint /channels/{channel.id}/messages ### Parameters #### Query Parameters - **before** (string) - Optional - Get messages before this message ID. - **after** (string) - Optional - Get messages after this message ID. - **around** (string) - Optional - Get messages around this message ID. - **limit** (int) - Optional - Number of messages to get, between 1 and 100. Defaults to 100. ### Request Example ```php $channel->getMessageHistory([ 'limit' => 5, ])->then(function (Collection $messages) { foreach ($messages as $message) { // ... } }); ``` ### Response #### Success Response (200) - **messages** (Collection) - A collection of message objects. #### Response Example ```json [ { "id": "message_id_1", "content": "Hello!", "author": { "id": "user_id_1", "username": "User1" }, "timestamp": "2023-10-27T10:00:00.000Z" }, { "id": "message_id_2", "content": "Hi there!", "author": { "id": "user_id_2", "username": "User2" }, "timestamp": "2023-10-27T10:01:00.000Z" } ] ``` ``` -------------------------------- ### Handle 'ready' Event Source: https://github.com/discord-php/discordphp/wiki/Discord This event is emitted once when the Discord BOT is ready. Gateway event listeners should be registered inside this event. Ensure any other event listeners are placed within this callback. ```php $discord->on('ready', function (Discord $discord) { echo "Bot is ready.", PHP_EOL; // place any $discord->on(Event::x, function () {}) here }); ``` -------------------------------- ### Get Avatar URL Source: https://github.com/discord-php/discordphp/blob/master/guide/parts/user.rst Retrieves the avatar URL for a user, allowing customization of format and size. ```APIDOC ## Get Avatar URL ### Description 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. ### Method GET (Implicit) ### Endpoint User Avatar URL ### Parameters #### Query Parameters - **format** (string) - Optional - Format of the image, one of png, jpg or webp, default webp or gif if animated. - **size** (int) - Optional - Size of the image, default 1024. ### Request Example ```php $url = $user->getAvatarAttribute('png', 2048); echo $url; ``` ### Response #### Success Response (200) - **url** (string) - The URL of the user's avatar. #### Response Example ```json { "url": "https://cdn.discordapp.com/avatars/:user_id/:avatar_hash.png?size=2048" } ``` ``` -------------------------------- ### Get Guild by ID (Cached) Source: https://github.com/discord-php/discordphp/wiki/Parts/Guild Retrieves a guild from the cache using its ID. This is a synchronous operation. ```php $guild = $discord->guilds->get('id', '123123123123123123'); // Or using offsetGet $guild = $discord->guilds['123123123123123123']; ``` -------------------------------- ### Configure DNS Settings Source: https://github.com/discord-php/discordphp/wiki/Basics Set DNS configuration, typically for the VoiceClient. Accepts a string of a name server address or a Config instance. ```php 'dnsConfig' => '1.1.1.1', ``` -------------------------------- ### Get a Specific Message Source: https://github.com/discord-php/discordphp/wiki/Parts/Message Retrieves a specific message from a channel, either from cache or by fetching it asynchronously. ```APIDOC ## Get a Specific Message You must first get the [Channel](Channel) object to use the code below. Change `123123123123123123` below with the Message ID you want to retrieve Cached, synchrounous: ```php $message = $channel->messages->get('id', '123123123123123123'); ``` Message can be also retrieved from related objects: * [Message](Message) `$reply = $message->referenced_message;` reply referenced to the message * [Reaction](Reaction) `$message = $reaction->message;` message where the reaction is part of If the code above returns `null`, you may need to fetch it first (Promise, asynchrounous): ```php $channel->messages->fetch('123123123123123123')->then(function (Message $message) { // ... })->done(); ``` https://discord.com/developers/docs/resources/channel#get-channel-message ``` -------------------------------- ### Array-like Access for Collections Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/06_collection.md Demonstrates how Collections can be accessed and manipulated using array-like syntax, including assignment, iteration, and serialization to JSON or arrays. ```php 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) ``` -------------------------------- ### Discord Get Logger Method Source: https://github.com/discord-php/discordphp/wiki/Discord Retrieves the PSR-3 logger instance used by the Bot client. ```APIDOC ## GET /api/discord/logger ### Description Gets the PSR-3 logger being used by the Bot client. ### Method GET ### Endpoint /api/discord/logger ### Response #### Success Response (200) - **logger** (LoggerInterface) - The Logger interface instance. #### Response Example ```json { "logger": "LoggerInterface object" } ``` ``` -------------------------------- ### Create a Message with a Button Source: https://github.com/discord-php/discordphp/wiki/Button This example demonstrates how to create a message with a primary style button that responds to interactions. Ensure you have a Channel object and have imported ActionRow and MessageBuilder. ```php // REMEMBER THIS -> Discord\Builders\Components\ActionRow // First we create a MessageBuilder $builder = MessageBuilder::new(); // Now we create an actionRow instance $action = ActionRow::new() // Let's create the button $button = Button::new(Button::STYLE_PRIMARY)->setLabel('Click me!')->setListener(function (Interaction $interaction) { // CODE... $interaction->respondWithMessage(MessageBuilder::new()->setContent("{$interaction->user} You clicked the button!")); }, $discord); $channel->sendMessage($builder->addComponent($action->addComponent($button)))->then(function (Message $message) { echo "Message sent in the channel {$message->channel->id}"; }); ``` -------------------------------- ### Initialize DiscordPHP with Event Loop Source: https://github.com/discord-php/discordphp/wiki/Home Initializes the DiscordPHP client and registers event listeners before starting the event loop. The `$discord->run()` method blocks execution. ```php $discord = new Discord([ 'token' => '...', 'loop' => Loop::get() // set the Event Loop ]); // Register event listeners before the run() $discord->on('ready', function (Discord $discord) { // Code run during event loops }); echo 'Bot started!'; // Must be placed at the bottom $discord->run(); // This code blocks here // Any code below here will NOT be executed until the loop is stopped. echo 'Bot stopped!'; ``` -------------------------------- ### Register Command with Aliases and Options Source: https://github.com/discord-php/discordphp/wiki/Command-Client Register a command with multiple aliases and options, such as a description. This enhances command discoverability and functionality. ```php $discord->registerCommand('hi', ['hey', 'hello', 'wussup'], ['aliases' => ['hey', 'hello', 'wassup']]); ``` -------------------------------- ### Create Channel Invite Source: https://github.com/discord-php/discordphp/blob/master/docs/src/pages/api/05_parts/02_channel.md Creates an invite for a channel with specified options like max age and max uses. Requires the channel object to be available. ```php $channel->createInvite([ 'max_age' => 60, // 1 minute 'max_uses' => 5, // 5 uses ])->then(function (Invite $invite) { // ... }); ``` -------------------------------- ### Configure Sharding Options Source: https://github.com/discord-php/discordphp/wiki/Basics Configure 'shardId' and 'shardCount' for bots that require sharding. These options are intended for large bots. ```php 'shardId' => 0, ``` ```php 'shardCount' => 5, ```