diff --git a/guide/basics.rst b/guide/basics.rst new file mode 100644 index 000000000..7d747e718 --- /dev/null +++ b/guide/basics.rst @@ -0,0 +1,105 @@ +====== +Basics +====== + +First step is to include the Composer autoload file and `import `_ any required classes. + +.. code:: php + + '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, + ]); + +``token`` is your Discord token. **Required**. + +``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. + +``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. + +``storeMessages`` is a boolean whether messages received and sent should be stored. Default is false. + +``retrieveBans`` is a boolean whether bans should be retrieved on bot load. Default is false. + +``pmChannels`` is a boolean whether PM channels should be stored on bot load. Default is false. + +``disabledEvents`` is an array of events that will be disabled. By default all events are enabled. + +``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. + +``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. + +``dnsConfig`` is an instace of ``Config`` or a string of name server address. By default system setting is used and fall back to 8.8.8.8 when system configuration is not found. Currently only used for VoiceClient. + +---- + +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. + +``shardCount`` is the number of shards that you are using. + +---- + +Gateway events should be registered inside the ``ready`` event, which is emitted once when the bot first starts and has connected to the gateway. + +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. + +.. code:: php + + $discord->on('ready', function (Discord $discord) { + + $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. + +.. code:: php + + $discord->run(); + +If you want to stop the bot you can run: + +.. code:: php + + $discord->close(); + +If you want to stop the bot without stopping the event loop, the close function takes a boolean: + +.. code:: php + + $discord->close(false); diff --git a/guide/collection.rst b/guide/collection.rst new file mode 100644 index 000000000..2439535f7 --- /dev/null +++ b/guide/collection.rst @@ -0,0 +1,258 @@ +========== +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. + +.. container:: + + Collections implement interfaces allowing them to be accessed like arrays, such as: + + .. code:: php + + // 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 | ++---------+----------------+--------------------------------------------------------------------+ + +.. code:: php + + // 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 +===== ==== =================================== + +.. code:: php + + // 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 +===== ==== ================== + +.. code:: php + + // 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 +======= ==== ========================================= + +.. code:: php + + $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. + +.. code:: php + + $collec = new Collection([], null, null); + $collec->fill([ + 1, 2, 3, 4, + ]); + +Number of items +=============== + +Returns the number of items in the collection. + +.. code:: php + + $collec = new Collection([ + 1, 2, 3 + ], null, null); + + echo $collec->count(); // 3 + +Getting the first item +====================== + +Gets the first item of the collection. + +.. code:: php + + $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 +======== ======== ================================= + +.. code:: php + + $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. + +.. code:: php + + $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 +======== ======== ================================= + +.. code:: php + + $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. + +.. code:: php + + $arr = $collec->toArray(); \ No newline at end of file diff --git a/guide/components.rst b/guide/components.rst new file mode 100644 index 000000000..fa86156a2 --- /dev/null +++ b/guide/components.rst @@ -0,0 +1,218 @@ +================== +Message Components +================== + + +Message components are new components you can add to messages, such as buttons and select menus. There are currently four different types of message components: + +``ActionRow`` +============= + +Represents a row of buttons on a message. You can add up to 5 buttons to the row, which can then be added to the message. You can only add buttons to action rows. + +.. code:: php + + $row = ActionRow::new() + ->addComponent(Button::new(Button::STYLE_SUCCESS)); + +Functions +--------- + ++----------------------------------+-------------------------------------------------------------+ +| name | description | ++==================================+=============================================================+ +| ``addComponent($component)`` | adds a component to action row. must be a button component. | ++----------------------------------+-------------------------------------------------------------+ +| ``removeComponent($component)`` | removes the given component from the action row. | ++----------------------------------+-------------------------------------------------------------+ +| ``getComponents(): Component[]`` | returns all the action row components in an array. | ++----------------------------------+-------------------------------------------------------------+ + +``Button`` +========== + +Represents a button attached to a message. You cannot directly attach a button to a message, it must be contained inside an ``ActionRow``. + +.. code:: php + + $button = Button::new(Button::STYLE_SUCCESS) + ->setLabel('push me!'); + +There are 5 different button styles: + +========= =========================== ======= +name constant colour +========= =========================== ======= +primary ``Button::STYLE_PRIMARY`` blurple +secondary ``Button::STYLE_SECONDARY`` grey +success ``Button::STYLE_SUCCESS`` green +danger ``Button::STYLE_DANGER`` red +link ``Button::STYLE_LINK`` grey +========= =========================== ======= + +.. image:: https://discord.com/assets/7bb017ce52cfd6575e21c058feb3883b.png + :alt: Discord button styles + + Discord button styles + +.. _functions-1: + +Functions +--------- + ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| name | description | ++======================================+==========================================================================================================================================+ +| ``setStyle($style)`` | sets the style of the button. must be one of the above constants. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``setLabel($label)`` | sets the label of the button. maximum 80 characters. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``setEmoji($emoji)`` | sets the emoji for the button. must be an ``Emoji`` object. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``setCustomId($custom_id)`` | sets the custom ID of the button. maximum 100 characters. will be automatically generated if left null. not applicable for link buttons. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``setUrl($url)`` | sets the url of the button. only for buttons with the ``Button::STYLE_LINK`` style. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``setDisabled($disabled)`` | sets whether the button is disabled or not. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``setListener($listener, $discord)`` | sets the listener for the button. see below for more information. not applicable for link buttons. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ +| ``removeListener()`` | removes the listener from the button. | ++--------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------+ + +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. + +.. code:: php + + $button->setListener(function (Interaction $interaction) { + $interaction->respondWithMessage(MessageBuilder::new() + ->setContent('why\'d u push me?')); + }, $discord); + +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: + +.. code:: php + + $button->setListener(function (Interaction $interaction) use ($discord) { + return someFunctionWhichWillReturnAPromise()->then(function ($returnValueFromFunction) use ($interaction) { + $interaction->respondWithMessage(MessageBuilder::new() + ->setContent($returnValueFromFunction)); + }); + }, $discord); + +``SelectMenu`` +============== + +Select menus are a dropdown which can be attached to a message. They operate similar to buttons. They do not need to be attached to an ``ActionRow``. You may have up to 25 ``Option``\ s attached to a select menu. + +.. code:: php + + $select = SelectMenu::new() + ->addOption(Option::new('me?')) + ->addOption(Option::new('or me?')); + +.. _functions-2: + +Functions +--------- + ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| name | description | ++======================================+========================================================================================================+ +| ``addOption($option)`` | adds an option to the select menu. maximum 25 options per menu. options must have unique values. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``removeOption($option)`` | removes an option from the select menu. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``setPlaceholder($placeholder)`` | sets a placeholder string to be displayed when nothing is selected. null to clear. max 150 characters. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``setMinValues($min_values)`` | the number of values which must be selected to submit the menu. between 0 and 25, default 1. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``setMaxValues($max_values)`` | the maximum number of values which can be selected. maximum 25, default 1. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``setDisabled($disabled)`` | sets whether the menu is disabled or not. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``setListener($listener, $discord)`` | sets the listener for the select menu. see below for more information. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ +| ``removeListener()`` | removes the listener from the select menu. | ++--------------------------------------+--------------------------------------------------------------------------------------------------------+ + +``Option`` functions +-------------------- + ++----------------------------------+---------------------------------------------------------------------------------------------------------------------------+ +| name | description | ++==================================+===========================================================================================================================+ +| ``new($label, ?$value)`` | creates a new option. requires a label to display, and optionally an internal value (leave as null to auto-generate one). | ++----------------------------------+---------------------------------------------------------------------------------------------------------------------------+ +| ``setDescription($description)`` | sets the description of the option. null to clear. maximum 100 characters. | ++----------------------------------+---------------------------------------------------------------------------------------------------------------------------+ +| ``setEmoji($emoji)`` | sets the emoji of the option. null to clear. must be an emoji object. | ++----------------------------------+---------------------------------------------------------------------------------------------------------------------------+ +| ``setDefault($default)`` | sets whether the option is the default option. | ++----------------------------------+---------------------------------------------------------------------------------------------------------------------------+ +| ``getValue()`` | gets the internal developer value of the option. | ++----------------------------------+---------------------------------------------------------------------------------------------------------------------------+ + +Adding a select menu listener +----------------------------- + +Select menu listeners operate similar to the button listeners, so please read the above section first. The callback function will be called with the ``Interaction`` object as well as a collection of selected ``Option``\ s. + +.. code:: php + + $select->setListener(function (Interaction $interaction, Collection $options) { + foreach ($options as $option) { + echo $option->getValue().PHP_EOL; + } + + $interaction->respondWithMessage(MessageBuilder::new()->setContent('thanks!')); + }, $discord); + +``TextInput`` +============= + +Text inputs are an interactive component that render on modals. + +.. code:: php + + $textInput = TextInput::new('Label', TextInput::TYPE_SHORT, 'custom id') + ->setRequired(true); + +They can be used to collect short-form or long-form text: + +====================== ============================== +style constant +====================== ============================== +Short (single line) ``TextInput::STYLE_SHORT`` +Paragraph (multi line) ``TextInput::STYLE_PARAGRAPH`` +====================== ============================== + +.. _functions-3: + +Functions +--------- + ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| name | description | ++==================================+=============================================================================================================+ +| ``setCustomId($custom_id)`` | sets the custom ID of the text input. maximum 100 characters. will be automatically generated if left null. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setStyle($style)`` | sets the style of the text input. must be one of the above constants. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setLabel($label)`` | sets the label of the button. maximum 80 characters. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setMinLength($min_length)`` | the minimum length of value. between 0 and 4000, default 0. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setMaxLength($max_length)`` | the maximum length of value. between 1 and 4000, default 4000. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setValue($value)`` | sets a pre-filled value for the text input. maximum 4000 characters. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setPlaceholder($placeholder)`` | sets a placeholder string to be displayed when text input is empty. max 100 characters. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ +| ``setRequired($required)`` | sets whether the text input is required or not. | ++----------------------------------+-------------------------------------------------------------------------------------------------------------+ \ No newline at end of file diff --git a/guide/events/application_commands.rst b/guide/events/application_commands.rst new file mode 100644 index 000000000..f56c5f531 --- /dev/null +++ b/guide/events/application_commands.rst @@ -0,0 +1,19 @@ +==================== +Application Commands +==================== + + +Application Command Permissions Update +====================================== + +Called with an ``Overwrite`` object when an application command’s permissions are updated. + + Warning: The class Overwrite will be changed in future version! + +.. code:: php + + // use Discord\Parts\Interactions\Command\Overwrite; + + $discord->on(Event::APPLICATION_COMMAND_PERMISSIONS_UPDATE, function (Overwrite $overwrite, Discord $discord, ?Overwrite $oldOverwrite) { + // ... + }); diff --git a/guide/events/auto_moderations.rst b/guide/events/auto_moderations.rst new file mode 100644 index 000000000..1c843bdb7 --- /dev/null +++ b/guide/events/auto_moderations.rst @@ -0,0 +1,59 @@ +================ +Auto Moderations +================ + + +All auto moderation related events are currently only sent to bot users which have the ``MANAGE_GUILD`` permission. + +Auto Moderation Rule Create +=========================== + +Called with a ``Rule`` object when an auto moderation rule is created. + +.. code:: php + + $discord->on(Event::AUTO_MODERATION_RULE_CREATE, function (Rule $rule, Discord $discord) { + // ... + }); + +Requires the ``Intents::AUTO_MODERATION_CONFIGURATION`` intent. + +Auto Moderation Rule Update +=========================== + +Called with a ``Rule`` object when an auto moderation rule is updated. + +.. code:: php + + $discord->on(Event::AUTO_MODERATION_RULE_UPDATE, function (Rule $rule, Discord $discord, ?Rule $oldRule) { + // ... + }); + +Auto Moderation Rule Delete +=========================== + +Called with a ``Rule`` object when an auto moderation rule is deleted. + +.. code:: php + + $discord->on(Event::AUTO_MODERATION_RULE_DELETE, function (Rule $rule, Discord $discord) { + // ... + }); + +Requires the ``Intents::AUTO_MODERATION_CONFIGURATION`` intent. + +Auto Moderation Action Execution +================================ + +Called with an ``AutoModerationActionExecution`` object when an auto moderation rule is triggered and an action is executed (e.g. when a message is blocked). + +.. code:: php + + // use `Discord\Parts\WebSockets\AutoModerationActionExecution`; + + $discord->on(Event::AUTO_MODERATION_ACTION_EXECUTION, function (AutoModerationActionExecution $actionExecution, Discord $discord) { + // ... + }); + +Requires the ``Intents::AUTO_MODERATION_EXECUTION`` intent. + diff --git a/guide/events/channels.rst b/guide/events/channels.rst new file mode 100644 index 000000000..23d103d8b --- /dev/null +++ b/guide/events/channels.rst @@ -0,0 +1,132 @@ +======== +Channels +======== + + +Requires the ``Intents::GUILDS`` intent. + +Channel Create +============== + +Called with a ``Channel`` object when a new channel is created, relevant to the Bot. + +.. code:: php + + $discord->on(Event::CHANNEL_CREATE, function (Channel $channel, Discord $discord) { + // ... + }); + +Channel Update +============== + +Called with two ``Channel`` objects when a channel is updated. + +.. code:: php + + $discord->on(Event::CHANNEL_UPDATE, function (Channel $channel, Discord $discord, ?Channel $oldChannel) { + // ... + }); + +Channel Delete +============== + +Called with a ``Channel`` object when a channel relevant to the Bot is deleted. + +.. code:: php + + $discord->on(Event::CHANNEL_DELETE, function (Channel $channel, Discord $discord) { + // ... + }); + +Channel Pins Update +=================== + +Called with an object when a message is pinned or unpinned in a text channel. This is not sent when a pinned message is deleted. + +.. code:: php + + $discord->on(Event::CHANNEL_PINS_UPDATE, function ($pins, Discord $discord) { + // { + // "guild_id": "", + // "channel_id": "", + // "last_pin_timestamp": "" + // } + }); + +.. + + For direct messages, it only requires the ``Intents::DIRECT_MESSAGES`` intent. + +Threads +======= + +Requires the ``Intents::GUILDS`` intent. + +Thread Create +------------- + +Called with a ``Thread`` object when a thread is created, relevant to the Bot. + +.. code:: php + + $discord->on(Event::THREAD_CREATE, function (Thread $thread, Discord $discord) { + // ... + }); + +Thread Update +------------- + +Called with a ``Thread`` object when a thread is updated. + +.. code:: php + + $discord->on(Event::THREAD_UPDATE, function (Thread $thread, Discord $discord, ?Thread $oldThread) { + // ... + }); + +Thread Delete +------------- + +Called with an old ``Thread`` object when a thread relevant to the Bot is deleted. + +.. code:: php + + $discord->on(Event::THREAD_DELETE, function (?Thread $thread, Discord $discord) { + // ... + }); + +Thread List Sync +---------------- + +Called when list of threads are synced. + +.. code:: php + + $discord->on(Event::THREAD_LIST_SYNC, function (Collection $threads, Discord $discord) { + // ... + }); + +Thread Member Update +-------------------- + +Called with a Thread ``Member`` object when the thread member for the current Bot is updated. + +.. code:: php + + // use Discord\Parts\Thread\Member; + + $discord->on(Event::THREAD_MEMBER_UPDATE, function (Member $threadMember, Discord $discord) { + // ... + }); + +Thread Members Update +--------------------- + +Called with a ``Thread`` object when anyone is added to or removed from a thread. If the Bot does not have the ``Intents::GUILD_MEMBERS``, then this event will only be called if the Bot was added to or removed from the thread. + +.. code:: php + + $discord->on(Event::THREAD_MEMBERS_UPDATE, function (Thread $thread, Discord $discord) { + // ... + }); + diff --git a/guide/events/guilds.rst b/guide/events/guilds.rst new file mode 100644 index 000000000..9b3aaa7d8 --- /dev/null +++ b/guide/events/guilds.rst @@ -0,0 +1,303 @@ +====== +Guilds +====== + + +Requires the ``Intents::GUILDS`` intent. + +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. + +.. code:: php + + $discord->on(Event::GUILD_CREATE, function (Guild $guild, Discord $discord) { + // ... + }); + +Guild Update +============ + +Called with two ``Guild`` objects when a guild is updated. + +.. code:: php + + $discord->on(Event::GUILD_UPDATE, function (Guild $guild, Discord $discord, ?Guild $oldGuild) { + // ... + }); + +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. + +.. code:: php + + $discord->on(Event::GUILD_DELETE, function (object $guild, Discord $discord, bool $unavailable) { + // ... + if ($unavailable) { + // the guild is unavailabe due to an outage + // { + // "id": "" // guild ID + // "unavailable": true + // } + } else { + // the Bot has been kicked from the guild + } + }); + +Guild Bans +========== + +Requires the ``Intents::GUILD_BANS`` intent and ``ban_members`` permission. + +Guild Ban Add +------------- + +Called with a ``Ban`` object when a member is banned from a guild. + +.. code:: php + + $discord->on(Event::GUILD_BAN_ADD, function (Ban $ban, Discord $discord) { + // ... + }); + +Guild Ban Remove +---------------- + +Called with a ``Ban`` object when a user is unbanned from a guild. + +.. code:: php + + $discord->on(Event::GUILD_BAN_REMOVE, function (Ban $ban, Discord $discord) { + // ... + }); + +Guild Emojis and Stickers +========================= + +Requires the ``Intents::GUILD_EMOJIS_AND_STICKERS`` intent. + +Guild Emojis Update +------------------- + +Called with two Collections of ``Emoji`` objects when a guild’s emojis have been added/updated/deleted. ``$oldEmojis`` *may* be empty if it was not cached or there were previously no emojis. + +.. code:: php + + $discord->on(Event::GUILD_EMOJIS_UPDATE, function (Collection $emojis, Discord $discord, Collection $oldEmojis) { + // ... + }); + +Guild Stickers Update +--------------------- + +Called with two Collections of ``Sticker`` objects when a guild’s stickers have been added/updated/deleted. ``$oldStickers`` *may* be empty if it was not cached or there were previously no stickers. + +.. code:: php + + $discord->on(Event::GUILD_STICKERS_UPDATE, function (Collection $stickers, Discord $discord, Collecetion $oldStickers) { + // ... + }); + +Guild Members +============= + +Requires the ``Intents::GUILD_MEMBERS`` intent. This intent is a priviliged intent, it must be enabled in your Discord Bot developer settings. + +Guild Member Add +---------------- + +Called with a ``Member`` object when a new user joins a guild. + +.. code:: php + + $discord->on(Event::GUILD_MEMBER_ADD, function (Member $member, Discord $discord) { + // ... + }); + +Guild Member Remove +------------------- + +Called with a ``Member`` object when a member is removed from a guild (leave/kick/ban). Note that the member *may* only have ``User`` data if ``loadAllMembers`` is disabled. + +.. code:: php + + $discord->on(Event::GUILD_MEMBER_REMOVE, 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 member *may* be ``null`` if ``loadAllMembers`` is disabled. + +.. code:: php + + $discord->on(Event::GUILD_MEMBER_UPDATE, function (Member $member, Discord $discord, ?Member $oldMember) { + // ... + }); + +Guild Roles +=========== + +Requires the ``Intents::GUILDS`` intent. + +Guild Role Create +----------------- + +Called with a ``Role`` object when a role is created in a guild. + +.. code:: php + + $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. + +.. code:: php + + $discord->on(Event::GUILD_ROLE_UPDATE, function (Role $role, Discord $discord, ?Role $oldRole) { + // ... + }); + +Guild Role Delete +----------------- + +Called with a ``Role`` object when a role is deleted in a guild. ``$role`` may return ``Role`` object if it was cached. + +.. code:: php + + $discord->on(Event::GUILD_ROLE_DELETE, function (object $role, Discord $discord) { + if ($role instanceof Role) { + // Role is present in cache + } + // If the role is not present in the cache: + else { + // { + // "guild_id": "" // role guild ID + // "role_id": "", // role ID, + // } + } + }); + +Guild Scheduled Events +====================== + +Requires the ``Intents::GUILD_SCHEDULED_EVENTS`` intent. + +Guild Scheduled Event Create +---------------------------- + +Called with a ``ScheduledEvent`` object when a scheduled event is created in a guild. + +.. code:: php + + $discord->on(Event::GUILD_SCHEDULED_EVENT_CREATE, function (ScheduledEvent $scheduledEvent, Discord $discord) { + // ... + }); + +Guild Scheduled Event Update +---------------------------- + +Called with a ``ScheduledEvent`` object when a scheduled event is updated in a guild. + +.. code:: php + + $discord->on(Event::GUILD_SCHEDULED_EVENT_UPDATE, function (ScheduledEvent $scheduledEvent, Discord $discord, ?ScheduledEvent $oldScheduledEvent) { + // ... + }); + +Guild Scheduled Event Delete +---------------------------- + +Called with a ``ScheduledEvent`` object when a scheduled event is deleted in a guild. + +.. code:: php + + $discord->on(Event::GUILD_SCHEDULED_EVENT_DELETE, function (ScheduledEvent $scheduledEvent, Discord $discord) { + // ... + }); + +Guild Scheduled Event User Add +------------------------------ + +Called when a user has subscribed to a scheduled event in a guild. + +.. code:: php + + $discord->on(Event::GUILD_SCHEDULED_EVENT_USER_ADD, function ($data, Discord $discord) { + // ... + }); + +Guild Scheduled Event User Remove +--------------------------------- + +Called when a user has unsubscribed from a scheduled event in a guild. + +.. code:: php + + $discord->on(Event::GUILD_SCHEDULED_EVENT_USER_REMOVE, function ($data, Discord $discord) { + // ... + }); + +Integrations +============ + +Requires the ``Intents::GUILD_INTEGRATIONS`` intent. + +Guild Integrations Update +------------------------- + +Called with a cached ``Guild`` object when a guild integration is updated. + +.. code:: php + + $discord->on(Event::GUILD_INTEGRATIONS_UPDATE, function (?Guild $guild, Discord $discord) { + // ... + }); + +Integration Create +------------------ + +Called with an ``Integration`` object when an integration is created in a guild. + +.. code:: php + + $discord->on(Event::INTEGRATION_CREATE, function (Integration $integration, Discord $discord) { + // ... + }); + +Integration Update +------------------ + +Called with an ``Integration`` object when a integration is updated in a guild. + +.. code:: php + + $discord->on(Event::INTEGRATION_UPDATE, function (Integration $integration, Discord $discord, ?Integration $oldIntegration) { + // ... + }); + +Integration Delete +------------------ + +Called with an old ``Integration`` object when a integration is deleted from a guild. ``$integration`` *may* be ``null`` if Integration is not cached. + +.. code:: php + + $discord->on(Event::INTEGRATION_DELETE, function (?Integration $integration, Discord $discord) { + // ... + }); diff --git a/guide/events/index.rst b/guide/events/index.rst new file mode 100644 index 000000000..a02dfbcf6 --- /dev/null +++ b/guide/events/index.rst @@ -0,0 +1,32 @@ +.. toctree:: + :hidden: + + application_commands + auto_moderations + channels + guilds + invites + interactions + messages + presences + stage_instances + voices + webhooks + +====== +Events +====== + + +Events are payloads sent over the socket to a client that correspond to events in Discord. + +All gateway events are enabled by default and can be individually disabled using ``disabledEvents`` options. Most events also requires the respective Intents enabled (as well privileged ones enabled from `Developers Portal `_) regardless the enabled event setting. + +To listen on gateway events, use the event emitter callback and ``Event`` name constants. Some events are internally handled by the library and may not be registered a listener: + +- ``Event::READY`` (not to be confused with ``'ready'``) +- ``Event::RESUMED`` +- ``Event::GUILD_MEMBERS_CHUNK`` + +If you are an advanced user, you may listen to those events before internally handled with the library by parsing the ‘raw’ dispatch event data. + diff --git a/guide/events/interactions.rst b/guide/events/interactions.rst new file mode 100644 index 000000000..d7b50396a --- /dev/null +++ b/guide/events/interactions.rst @@ -0,0 +1,20 @@ +============ +Interactions +============ + + +Interaction Create +================== + +Called with an ``Interaction`` object when an interaction is created. + +.. code:: php + + // use Discord\Parts\Interactions\Interaction; + + $discord->on(Event::INTERACTION_CREATE, function (Interaction $interaction, Discord $discord) { + // ... + }); + +Application Command & Message component listeners are processed before this event is called. Useful if you want to create a customized callback or have interaction response persists after Bot restart. + diff --git a/guide/events/invites.rst b/guide/events/invites.rst new file mode 100644 index 000000000..14e3f4b39 --- /dev/null +++ b/guide/events/invites.rst @@ -0,0 +1,39 @@ +======= +Invites +======= + + +Requires the ``Intents::GUILD_INVITES`` intent and ``manage_channels`` permission. + +Invite Create +============= + +Called with an ``Invite`` object when a new invite to a channel is created. + +.. code:: php + + $discord->on(Event::INVITE_CREATE, function (Invite $invite, Discord $discord) { + // ... + }); + +Invite Delete +============= + +Called with an object when an invite is created. + +.. code:: php + + $discord->on(Event::INVITE_DELETE, function (object $invite, Discord $discord) { + if ($invite instanceof Invite) { + // Invite is present in cache + } + // If the invite is not present in the cache: + else { + // { + // "channel_id": "", + // "guild_id": "", + // "code": "" // the unique invite code + // } + } + }); + diff --git a/guide/events/messages.rst b/guide/events/messages.rst new file mode 100644 index 000000000..dbc398173 --- /dev/null +++ b/guide/events/messages.rst @@ -0,0 +1,124 @@ +======== +Messages +======== + + + Unlike persistent messages, ephemeral messages are sent directly to the user and the Bot who sent the message rather than through the guild channel. Because of this, ephemeral messages are tied to the ``Intents::DIRECT_MESSAGES``, and the message object won’t include ``guild_id`` or ``member``. + +Requires the ``Intents::GUILD_MESSAGES`` intent for guild or ``Intents::DIRECT_MESSAGES`` for direct messages. + +Message Create +============== + +Called with a ``Message`` object when a message is sent in a guild or private channel. + +.. code:: php + + $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. + +.. code:: php + + $discord->on(Event::MESSAGE_UPDATE, function (Message $message, Discord $discord, ?Message $oldMessage) { + // ... + }); + +Message Delete +============== + +Called with an old ``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. + +.. code:: php + + $discord->on(Event::MESSAGE_DELETE, function (object $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 old ``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. + +.. code:: php + + $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 Reactions +================= + +Requires the ``Intents::GUILD_MESSAGE_REACTIONS`` intent for guild or ``Intents::DIRECT_MESSAGE_REACTIONS`` for direct messages. + +Message Reaction Add +-------------------- + +Called with a ``MessageReaction`` object when a user added a reaction to a message. + +.. code:: php + + $discord->on(Event::MESSAGE_REACTION_ADD, function (MessageReaction $reaction, Discord $discord) { + // ... + }); + +Message Reaction Remove +----------------------- + +Called with a ``MessageReaction`` object when a user removes a reaction from a message. + +.. code:: php + + $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. + +.. code:: php + + $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. Unlike Message Reaction Remove, this event contains no users or members. + +.. code:: php + + $discord->on(Event::MESSAGE_REACTION_REMOVE_EMOJI, function (MessageReaction $reaction, Discord $discord) { + // ... + }); + diff --git a/guide/events/presences.rst b/guide/events/presences.rst new file mode 100644 index 000000000..96029fd61 --- /dev/null +++ b/guide/events/presences.rst @@ -0,0 +1,44 @@ +========= +Presences +========= + + +Presence Update +=============== + +Called with a ``PresenceUpdate`` object when a member’s presence is updated. + +.. code:: php + + $discord->on(Event::PRESENCE_UPDATE, function (PresenceUpdate $presence, Discord $discord) { + // ... + }); + +Requires the ``Intents::GUILD_PRESENCES`` intent. This intent is a priviliged intent, it must be enabled in your Discord Bot developer settings. + +Typing Start +============ + +Called with a ``TypingStart`` object when a user starts typing in a channel. + +.. code:: php + + // use Discord\Parts\WebSockets\TypingStart; + + $discord->on(Event::TYPING_START, function (TypingStart $typing, Discord $discord) { + // ... + }); + +Requires the ``Intents::GUILD_MESSAGE_TYPING`` intent. + +User Update +=========== + +Called with a ``User`` object when the Bot’s user properties change. + +.. code:: php + + $discord->on(Event::USER_UPDATE, function (User $user, Discord $discord, ?User $oldUser) { + // ... + }); + diff --git a/guide/events/stage_instances.rst b/guide/events/stage_instances.rst new file mode 100644 index 000000000..0383f3fab --- /dev/null +++ b/guide/events/stage_instances.rst @@ -0,0 +1,40 @@ +=============== +Stage Instances +=============== + + +Requires the ``Intents::GUILDS`` intent. + +Stage Instance Create +===================== + +Called with a ``StageInstance`` object when a stage instance is created (i.e. the Stage is now “live”). + +.. code:: php + + $discord->on(Event::STAGE_INSTANCE_CREATE, function (StageInstance $stageInstance, Discord $discord) { + // ... + }); + +Stage Instance Update +===================== + +Called with a ``StageInstance`` objects when a stage instance has been updated. + +.. code:: php + + $discord->on(Event::STAGE_INSTANCE_UPDATE, function (StageInstance $stageInstance, Discord $discord, ?StageInstance $oldStageInstance) { + // ... + }); + +Stage Instance Delete +===================== + +Called with a ``StageInstance`` object when a stage instance has been deleted (i.e. the Stage has been closed). + +.. code:: php + + $discord->on(Event::STAGE_INSTANCE_DELETE, function (StageInstance $stageInstance, Discord $discord) { + // ... + }); + diff --git a/guide/events/voices.rst b/guide/events/voices.rst new file mode 100644 index 000000000..457818362 --- /dev/null +++ b/guide/events/voices.rst @@ -0,0 +1,33 @@ +====== +Voices +====== + + +Voice State Update +================== + +Called with a ``VoiceStateUpdate`` object when a member joins, leaves or moves between voice channels. + +.. code:: php + + // use Discord\Parts\WebSockets\VoiceStateUpdate; + + $discord->on(Event::VOICE_STATE_UPDATE, function (VoiceStateUpdate $state, Discord $discord, $oldstate) { + // ... + }); + +Requires the ``Intents::GUILD_VOICE_STATES`` intent. + +Voice Server Update +=================== + +Called with a ``VoiceServerUpdate`` object when a voice server is updated in a guild. + +.. code:: php + + // use Discord\Parts\WebSockets\VoiceServerUpdate; + + $discord->on(Event::VOICE_SERVER_UPDATE, function (VoiceServerUpdate $guild, Discord $discord) { + // ... + }); + diff --git a/guide/events/webhooks.rst b/guide/events/webhooks.rst new file mode 100644 index 000000000..e3bd9fa41 --- /dev/null +++ b/guide/events/webhooks.rst @@ -0,0 +1,18 @@ +======== +Webhooks +======== + + +Webhooks Update +=============== + +Called with a ``Guild`` and ``Channel`` object when a guild channel’s webhooks are is created, updated, or deleted. + +.. code:: php + + $discord->on(Event::WEBHOOKS_UPDATE, function (?Guild $guild, Discord $discord, ?Channel $channel) { + // ... + }); + +Requires the ``Intents::GUILD_WEBHOOKS`` intent. + diff --git a/guide/faq.rst b/guide/faq.rst new file mode 100644 index 000000000..43ea866cf --- /dev/null +++ b/guide/faq.rst @@ -0,0 +1,43 @@ +=== +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. + +.. code-block:: php + + `_. 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. + +.. code-block:: php + + $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). + +.. code-block:: php + + $discord = new Discord([ + 'token' => '...', + 'loadAllMembers' => true, + 'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS // Enable the `GUILD_MEMBERS` intent + ]) + diff --git a/guide/index.rst b/guide/index.rst new file mode 100644 index 000000000..03aff8cdd --- /dev/null +++ b/guide/index.rst @@ -0,0 +1,96 @@ +.. toctree:: + :hidden: + + index + faq + basics + events/index + repositories + parts/index + collection + permissions + message_builder + components + interactions + +===== +Guide +===== + +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. + +Requirements +============ + +- `PHP 7.4 CLI`_ or higher + + + Will not run on a webserver (FPM, CGI), you must run through CLI. A bot is a long-running process. + + x86 (32-bit) PHP requires ext-gmp extension enabled for handling new Permission values. + +- ``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. +- ``ext-gmp`` if running 32-bit PHP. + +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 `PHP Intelephense `_ alongside your LSP-equipped editor for code completion alongside other helpful features. There is no need to pay for the premium features, 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 diff --git a/guide/interactions.rst b/guide/interactions.rst new file mode 100644 index 000000000..e08a1c46c --- /dev/null +++ b/guide/interactions.rst @@ -0,0 +1,85 @@ +============ +Interactions +============ + + +Interactions are utilized in message components and slash commands. + +Attributes +========== + ++----------------+----------------------+------------------------------------------------------+ +| name | type | description | ++================+======================+======================================================+ +| id | string | id of the interaction. | ++----------------+----------------------+------------------------------------------------------+ +| application_id | string | id of the application associated to the interaction. | ++----------------+----------------------+------------------------------------------------------+ +| int | type | type of interaction. | ++----------------+----------------------+------------------------------------------------------+ +| data | ``?InteractionData`` | data associated with the interaction. | ++----------------+----------------------+------------------------------------------------------+ +| guild | ``?Guild`` | guild interaction was triggered from, null if DM. | ++----------------+----------------------+------------------------------------------------------+ +| channel | ``?Channel`` | channel interaction was triggered from. | ++----------------+----------------------+------------------------------------------------------+ +| member | ``?Member`` | member that triggered interaction. | ++----------------+----------------------+------------------------------------------------------+ +| user | ``User`` | user that triggered interaction. | ++----------------+----------------------+------------------------------------------------------+ +| token | string | internal token for responding to interaction. | ++----------------+----------------------+------------------------------------------------------+ +| version | int | version of interaction. | ++----------------+----------------------+------------------------------------------------------+ +| message | ``?Message`` | message that triggered interaction. | ++----------------+----------------------+------------------------------------------------------+ +| locale | ?string | The selected language of the invoking user. | ++----------------+----------------------+------------------------------------------------------+ +| guild_locale | ?string | The guild’s preferred locale, if invoked in a guild. | ++----------------+----------------------+------------------------------------------------------+ + +The locale list can be seen on `Discord API reference `_. + +Functions on interaction create +=============================== + +The following functions are used to respond an interaction after being created ``Event::INTERACTION_CREATE``, responding interaction with wrong type throws a ``LogicException`` + ++----------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------+------------------------------------------------------------------+ +| name | description | valid for interaction type | ++==============================================================================================+=============================================================================+==================================================================+ +| ``acknowledgeWithResponse(?bool $ephemeral)`` | acknowledges the interaction, creating a placeholder response to be updated | ``APPLICATION_COMMAND``, ``MESSAGE_COMPONENT``, ``MODAL_SUBMIT`` | ++----------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------+------------------------------------------------------------------+ +| ``acknowledge()`` | defer the interaction | ``MESSAGE_COMPONENT``, ``MODAL_SUBMIT`` | ++----------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------+------------------------------------------------------------------+ +| ``respondWithMessage(MessageBuilder $builder, ?bool $ephemeral)`` | responds to the interaction with a message. ephemeral is default false | ``APPLICATION_COMMAND``, ``MESSAGE_COMPONENT``, ``MODAL_SUBMIT`` | ++----------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------+------------------------------------------------------------------+ +| ``autoCompleteResult(array $choices)`` | responds a suggestion to options with auto complete | ``APPLICATION_COMMAND_AUTOCOMPLETE`` | ++----------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------+------------------------------------------------------------------+ +| ``showModal(string $title, string $custom_id, array $components, ?callable $submit = null)`` | responds to the interaction with a popup modal | ``MODAL_SUBMIT`` | ++----------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------+------------------------------------------------------------------+ + +Functions after interaction response +==================================== + +The following functions can be only used after interaction respond above, otherwise throws a ``RuntimeException`` “Interaction has not been responded to.” + ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| name | description | return | ++========================================================================+================================================================================================+======================+ +| ``updateMessage(MessageBuilder $message)`` | updates the message the interaction was triggered from. only for message component interaction | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``getOriginalResponse()`` | gets the original interaction response | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``updateOriginalResponse(MessageBuilder $message)`` | updates the original interaction response | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``deleteOriginalResponse()`` | deletes the original interaction response | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``sendFollowUpMessage(MessageBuilder $builder, ?bool $ephemeral)`` | sends a follow up message to the interaction. ephemeral is defalt false | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``getFollowUpMessage(string $message_id)`` | gets a non ephemeral follow up message from the interaction | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``updateFollowUpMessage(string $message_id, MessageBuilder $builder)`` | updates the follow up message of the interaction | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ +| ``deleteFollowUpMessage(string $message_id)`` | deletes a non ephemeral follow up message from the interaction | ``Promise`` | ++------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+ diff --git a/guide/message_builder.rst b/guide/message_builder.rst new file mode 100644 index 000000000..cf5152099 --- /dev/null +++ b/guide/message_builder.rst @@ -0,0 +1,123 @@ +=============== +Message Builder +=============== + + +The ``MessageBuilder`` class is used to describe the contents of a new (or to be updated) message. + +A new message builder can be created with the ``new`` function: + +.. code:: php + + $builder = MessageBuilder::new(); + +Most builder functions return itself, so you can easily chain function calls together for a clean API, an example is shown on the right. + +.. code:: php + + $channel->sendMessage(MessageBuilder::new() + ->setContent('Hello, world!') + ->addEmbed($embed) + ->addFile('/path/to/file')); + +Setting content +=============== + +Sets the text content of the message. Throws an ``LengthException`` if the content is greater than 2000 characters. + +.. code:: php + + $builder->setContent('Hello, world!'); + +Setting TTS value +================= + +Sets the TTS value of the message. + +.. code:: php + + $builder->setTts(true); + +Adding embeds +============= + +You can add up to 10 embeds to a message. The embed functions takes ``Embed`` objects or associative arrays: + +.. code:: php + + $builder->addEmbed($embed); + +You can also set the embeds from another array of embeds. Note this will remove the current embeds from the message. + +.. code:: php + + $embeds = [...]; + $builder->setEmbeds($embeds); + +Replying to a message +===================== + +Sets the message as replying to another message. Takes a ``Message`` object. + +.. code:: php + + $discord->on(Event::MESSAGE_CREATE, function (Message $message) use ($builder) { + $builder->setReplyTo($message); + }); + +Adding files to the message +=========================== + +You can add multiple files to a message. The ``addFile`` function takes a path to a file, as well as an optional filename. + +If the filename parameter is ommited, it will take the filename from the path. Throws an exception if the path does not exist. + +.. code:: php + + $builder->addFile('/path/to/file', 'file.png'); + +You can also add files to messages with the content as a string: + +.. code:: php + + $builder->addFileFromContent('file.txt', 'contents of my file!'); + +You can also remove all files from a builder: + +.. code:: php + + $builder->clearFiles(); + +There is no limit on the number of files you can upload, but the whole request must be less than 8MB (including headers and JSON payload). + +Adding sticker +============== + +You can add up to 3 stickers to a message. The function takes ``Sticker`` object. + +.. code:: php + + $builder->addSticker($sticker); + +To remove a sticker: + +.. code:: php + + $builder->removeSticker($sticker); + +You can also set the stickers from another array of stickers. Note this will remove the current stickers from the message. + +.. code:: php + + $stickers = [...]; + $builder->setStickers($stickers); + +Adding message components +========================= + +Adds a message component to the message. You can only add ``ActionRow`` and ``SelectMenu`` objects. To add buttons, wrap the button in an ``ActionRow`` object. Throws an ``InvalidArgumentException`` if the given component is not an ``ActionRow`` or ``SelectMenu`` Throws an ``OverflowException`` if you already have 5 components in the message. + +.. code:: php + + $component = SelectMenu::new(); + $builder->addComponent($component); \ No newline at end of file diff --git a/guide/parts/channel.rst b/guide/parts/channel.rst new file mode 100644 index 000000000..e53208954 --- /dev/null +++ b/guide/parts/channel.rst @@ -0,0 +1,487 @@ +======= +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 | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| last_message_id | string | id of the last message sent in the channel | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| bitrate | int | bitrate of the voice channel | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| recipient | `User <#user>`_ | recipient of the direct message, only for direct message channel | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| recipients | Collection of `Users <#user>`_ | 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 | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| rate_limit_per_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 | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| last_pin_timestamp | ``Carbon`` timestamp | when the last message was pinned in the channel | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| rtc_region | string | Voice region id for the voice channel, automatic when set to null. | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| video_quality_mode | int | The camera video quality mode of the voice channel, 1 when not present. | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| default_auto_archive_duration | int | Default duration for newly created threads, in minutes, to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080. | ++-------------------------------+---------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ + +Repositories +============ + ++------------+----------------------------+-------------------------------------------------+ +| name | type | notes | ++============+============================+=================================================+ +| overwrites | `Overwrite <#overwrite>`_ | Contains permission overwrites | ++------------+----------------------------+-------------------------------------------------+ +| members | VoiceStateUpdate | Only for voice channels. Contains voice members | ++------------+----------------------------+-------------------------------------------------+ +| messages | `Message <#message>`_ | | ++------------+----------------------------+-------------------------------------------------+ +| webhooks | `Webhook <#webhook>`_ | Only available in text channels | ++------------+----------------------------+-------------------------------------------------+ +| threads | `Thread <#thread>`_ | Only available in text channels | ++------------+----------------------------+-------------------------------------------------+ +| invites | `Invite <#invite>`_ | | ++------------+----------------------------+-------------------------------------------------+ + +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 <#permissions>`_ for a valid list of permissions. Returns nothing in a promise. + +Parameters +---------- + ++-------+------------------------------------------+----------------------------------------+----------+ +| name | type | description | default | ++=======+==========================================+========================================+==========+ +| part | `Member <#member>`_ or `Role <#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 | [] | ++-------+------------------------------------------+----------------------------------------+----------+ + +.. code:: php + + // 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-1: + +Parameters +---------- + ++-----------+------------------------------------------+--------------------------------------+----------+ +| name | type | description | default | ++===========+==========================================+======================================+==========+ +| part | `Member <#member>`_ or `Role <#role>`_ | The part to apply the permissions to | required | ++-----------+------------------------------------------+--------------------------------------+----------+ +| overwrite | ``Overwrite`` part | The overwrite to apply | required | ++-----------+------------------------------------------+--------------------------------------+----------+ + +.. code:: php + + $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 <#member>`_ object or member ID and returns nothing in a promise. + +.. _parameters-2: + +Parameters +---------- + +====== ============================== ================== ======== +name type description default +====== ============================== ================== ======== +member `Member <#member>`_ or string The member to move required +====== ============================== ================== ======== + +.. code:: php + + $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 <#member>`_ object or member ID and returns nothing in a promise. + +.. _parameters-3: + +Parameters +---------- + +====== ============================== ========================= ======== +name type description default +====== ============================== ========================= ======== +member `Member <#member>`_ or string The member to mute/unmute required +====== ============================== ========================= ======== + +.. code:: php + + // 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-4: + +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 | ++-----------------------+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ +| target_type | int | The type of target for this voice channel invite | | ++-----------------------+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ +| target_user_id | string | The id of the user whose stream to display for this invite, required if target_type is ``Invite::TARGET_TYPE_STREAM``, the user must be streaming in the channel | | ++-----------------------+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ +| target_application_id | string | The id of the embedded application to open for this invite, required if target_type is ``Invite::TARGET_TYPE_EMBEDDED_APPLICATION``, the application must have the EMBEDDED flag | | ++-----------------------+--------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ + +.. code:: php + + $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-5: + +Parameters +---------- + ++----------+----------------------------------------------------+------------------------+---------+ +| name | type | description | default | ++==========+====================================================+========================+=========+ +| messages | array or collection of messages and/or message IDs | The messages to delete | default | ++----------+----------------------------------------------------+------------------------+---------+ +| reason | string | Reason for Audit Log | | ++----------+----------------------------------------------------+------------------------+---------+ + +.. code:: php + + $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-6: + +Parameters +---------- + ++--------+--------------------------------------+----------------------------------------------+---------+ +| name | type | description | default | ++========+======================================+==============================================+=========+ +| before | `Message <#message>`_ or message ID | Get messages before this message | | ++--------+--------------------------------------+----------------------------------------------+---------+ +| after | `Message <#message>`_ or message ID | Get messages after this message | | ++--------+--------------------------------------+----------------------------------------------+---------+ +| around | `Message <#message>`_ or message ID | Get messages around this message | | ++--------+--------------------------------------+----------------------------------------------+---------+ +| limit | int | Number of messages to get, between 1 and 100 | 100 | ++--------+--------------------------------------+----------------------------------------------+---------+ + +.. code:: php + + $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-7: + +Parameters +---------- + ++--------+--------+--------------------------------------------------+----------+ +| name | type | description | default | ++========+========+==================================================+==========+ +| value | int | number of messages to delete, in the range 1-100 | required | ++--------+--------+--------------------------------------------------+----------+ +| reason | string | Reason for Audit Log | | ++--------+--------+--------------------------------------------------+----------+ + +.. code:: php + + // 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-8: + +Parameters +---------- + +======= ====================== ======================== ======== +name type description default +======= ====================== ======================== ======== +message `Message <#message>`_ The message to pin/unpin required +reason string Reason for Audit Log +======= ====================== ======================== ======== + +.. code:: php + + // 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. + +.. code:: php + + $channel->getInvites()->done(function (Collection $invites) { + foreach ($invites as $invite) { + // ... + } + }); + +Send a message +============== + +Sends a message to the channel. Takes a message builder. Returns the message in a promise. + +.. _parameters-9: + +Parameters +---------- + ++---------+-----------------------------+-------------------------+----------+ +| name | type | description | default | ++=========+=============================+=========================+==========+ +| message | MessageBuilder | Message content | required | ++---------+-----------------------------+-------------------------+----------+ + +.. code:: php + + $message = MessageBuilder::new() + ->setContent('Hello, world!') + ->addEmbed($embed) + ->setTts(true); + + $channel->sendMessage($message)->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-10: + +Parameters +---------- + +===== ================== ================= ======== +name type description default +===== ================== ================= ======== +embed `Embed <#embed>`_ The embed to send required +===== ================== ================= ======== + +.. code:: php + + $channel->sendEmbed($embed)->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. + +.. code:: php + + $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-11: + +Parameters +---------- + +======= ======== ===================================== ======== +name type description default +======= ======== ===================================== ======== +filter callable The callback to call on every message required +options array Array of options [] +======= ======== ===================================== ======== + +.. code:: php + + // 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. + +.. code:: php + + $channel->getPinnedMessages()->done(function (Collection $messages) { + foreach ($messages as $message) { + // $message->... + } + }); diff --git a/guide/parts/guild.rst b/guide/parts/guild.rst new file mode 100644 index 000000000..e8b51b186 --- /dev/null +++ b/guide/parts/guild.rst @@ -0,0 +1,184 @@ +===== +Guild +===== + + +Guilds represent Discord ‘servers’. + +Repositories +============ + ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| name | type | notes | ++========================+=======================================+==================================================================================+ +| roles | `Role <#role>`_ | | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| emojis | `Emoji <#emoji>`_ | | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| members | `Member <#member>`_ | May not contain offline members, see the ```loadAllMembers`` option <#basics>`_ | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| channels | `Channel <#channel>`_ | | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| stage_instances | `StageInstance <#stage_instance>`_ | | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| guild_scheduled_events | `ScheduledEvent <#scheduled_event>`_ | | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| stickers | `Sticker <#sticker>`_ | | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| invites | `Invite <#invite>`_ | Not initially loaded | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| bans | `Ban <#ban>`_ | Not initially loaded without ```retrieveBans`` option <#basics>`_ | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| commands | `Command <#command>`_ | Not initially loaded | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| templates | `GuildTemplate <#guild_template>`_ | Not initially loaded | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ +| integrations | `Integration <#integration>`_ | Not initially loaded | ++------------------------+---------------------------------------+----------------------------------------------------------------------------------+ + +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 | ++---------------+---------+------------------------------+-----------------------+ +| permissions | string | Bitwise value of permissions | @everyone permissions | ++---------------+---------+------------------------------+-----------------------+ +| color | integer | RGB color value | 0 | ++---------------+---------+------------------------------+-----------------------+ +| hoist | bool | Hoisted role? | false | ++---------------+---------+------------------------------+-----------------------+ +| icon | string | image data for Role icon | null | ++---------------+---------+------------------------------+-----------------------+ +| unicode_emoji | string | unicode emoji for Role icon | null | ++---------------+---------+------------------------------+-----------------------+ +| mentionable | bool | Mentionable role? | false | ++---------------+---------+------------------------------+-----------------------+ + +.. code:: php + + $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-1: + +Parameters +---------- + +====== =================== =========================== +name type description +====== =================== =========================== +member Member or member ID The member to get ownership +reason string Reason for Audit Log +====== =================== =========================== + +.. code:: php + + $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-2: + +Parameters +---------- + +======= =================== ================= +name type description +======= =================== ================= +user_id ``User`` or user ID The user to unban +======= =================== ================= + +.. code:: php + + $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-3: + +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 | ++-------------+-----------------------------------+--------------------------------------------------------+ + +.. code:: php + + $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->... + } + }); + +Creating an Emoji +================= + +Takes an array of parameters for an emoji and returns an emoji part in a promise. Use the second parameter to specify local file path instead. + +.. _parameters-4: + +Parameters +---------- + ++-------+--------+------------------------------------------------------------------+------------+ +| name | type | description | default | ++=======+========+==================================================================+============+ +| name | string | Emoji name | *required* | ++-------+--------+------------------------------------------------------------------+------------+ +| image | string | image data with base64 format, ignored if file path is specified | | ++-------+--------+------------------------------------------------------------------+------------+ +| roles | array | Role IDs that are allowed to use the emoji | [] | ++-------+--------+------------------------------------------------------------------+------------+ + +.. code:: php + + $guild->createEmoji([ + 'name' => 'elephpant', + // ... + ], + '/path/to/file.jpg', + 'audit-log reason' + )->done(function (Emoji $emoji) { + // ... + }); \ No newline at end of file diff --git a/guide/parts/index.rst b/guide/parts/index.rst new file mode 100644 index 000000000..16fb188ca --- /dev/null +++ b/guide/parts/index.rst @@ -0,0 +1,64 @@ +.. toctree:: + :hidden: + + guild + channel + member + message + user + +===== +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: + +.. code:: php + + $message = new Message($discord); + // or + $message = $discord->factory->create(Message::class); + +Part attributes can be accessed similar to an object or like an array: + +.. code:: php + + $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. + +.. code:: php + + $message->fill([ + 'content' => 'hello!', + ]); + +Getting the raw attributes of a part +==================================== + +The ``->getRawAttributes()`` function returns the array representation of the part. + +.. code:: php + + $attributes = $message->getRawAttributes(); + /** + * [ + * "id" => "", + * "content" => "", + * // ... + * ] + */ diff --git a/guide/parts/member.rst b/guide/parts/member.rst new file mode 100644 index 000000000..337650cbf --- /dev/null +++ b/guide/parts/member.rst @@ -0,0 +1,271 @@ +====== +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: + +.. code:: php + + $discord->on(Event::MESSAGE_CREATE, function (Message $message) { + // Hello <@member_id>! + // Note: `$message->member` will be `null` if the message originated from + // a private message, or if the member object was not cached. + $message->channel->sendMessage('Hello '.$message->member.'!'); + }); + +Properties +========== + ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| name | type | description | ++==============================+==========================================+==========================================================================================================================================================+ +| user | `User <#user>`_ | the user part of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| nick | string | the nickname of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| avatar | ?string | The guild avatar URL of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| avatar_hash | ?string | The guild avatar hash of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| roles | Collection of `Roles <#role>`_ | roles the member is a part of | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| joined_at | ``Carbon`` timestamp | when the member joined the guild | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| deaf | bool | whether the member is deafened | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| mute | bool | whether the member is muted | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| pending | ?string | whether the user has not yet passed the guild’s Membership Screening requirements | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| communication_disabled_until | ``?Carbon`` | when the user’s timeout will expire and the user will be able to communicate in the guild again, null or a time in the past if the user is not timed out | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| id | string | the user ID of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| username | string | the username of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| discriminator | string | the four digit discriminator of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| displayname | string | nick/username#discriminator | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| 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 <#activity>`_ | the current activity of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| premium_since | ``Carbon`` timestamp | when the member started boosting the guild | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| activities | Collection of `Activities <#activity>`_ | the current activities of the member | ++------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+ + +Ban the member +============== + +Bans the member from the guild. Returns a `Ban <#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 +============ ====== ==================================================== + +.. code:: php + + $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 or ``CHANGE_NICKNAME`` if changing self nickname. Returns nothing in a promise. + +.. _parameters-1: + +Parameters +---------- + +==== ====== =================================================== +name type description +==== ====== =================================================== +nick string nickname of the member, null to clear, default null +==== ====== =================================================== + +.. code:: php + + $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-2: + +Parameters +---------- + ++---------+----------------------------------+-----------------------------------+ +| name | type | description | ++=========+==================================+===================================+ +| channel | `Channel <#channel>`_ or string | the channel to move the member to | ++---------+----------------------------------+-----------------------------------+ + +.. code:: php + + $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-3: + +Parameters +---------- + +==== ========================== ============================= +name type description +==== ========================== ============================= +role `Role <#role>`_ or string the role to add the member to +==== ========================== ============================= + +.. code:: php + + $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-4: + +Parameters +---------- + +==== ========================== ================================== +name type description +==== ========================== ================================== +role `Role <#role>`_ or string the role to remove the member from +==== ========================== ================================== + +.. code:: php + + $member->removeRole($role)->done(function () { + // ... + }); + + // or + + $member->removeRole('1231231231')->done(function () { + // ... + }); + +Timeout member +============== + +Times out the member in the server. Takes a carbon or null to remove. Returns nothing in a promise. + +.. _parameters-5: + +Parameters +---------- + ++------------------------------+------------------------+----------------------------------+ +| name | type | description | ++==============================+========================+==================================+ +| communication_disabled_until | ``Carbon`` or ``null`` | the time for timeout to lasts on | ++------------------------------+------------------------+----------------------------------+ + +.. code:: php + + $member->timeoutMember(new Carbon('6 hours'))->done(function () { + // ... + }); + + // to remove + $member->timeoutMember()->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 <#permissions>`_ in a promise. + +.. _parameters-6: + +Parameters +---------- + ++---------+--------------------------------+--------------------------------------------------+ +| name | type | description | ++=========+================================+==================================================+ +| channel | `Channel <#channel>`_ or null | the channel to get the effective permissions for | ++---------+--------------------------------+--------------------------------------------------+ + +.. code:: php + + $member->getPermissions($channel)->done(function (RolePermission $permission) { + // ... + }); + + // or + + $member->getPermissions()->done(function (RolePermission $permission) { + // ... + }); + +Get guild specific avatar URL +============================= + +Gets the server-specific avatar URL for the member. Only call this function if you need to change the format or size of the image, otherwise use ``$member->avatar``. Returns a string. + +.. _parameters-7: + +Parameters +---------- + ++--------+--------+--------------------------------------------------------------------------------+ +| name | type | description | ++========+========+================================================================================+ +| format | string | format of the image, one of png, jpg or webp, default webp and gif if animated | ++--------+--------+--------------------------------------------------------------------------------+ +| size | int | size of the image, default 1024 | ++--------+--------+--------------------------------------------------------------------------------+ + +.. code:: php + + $url = $member->getAvatarAttribute('png', 2048); + echo $url; // https://cdn.discordapp.com/guilds/:guild_id/users/:id/avatars/:avatar_hash.png?size=2048 diff --git a/guide/parts/message.rst b/guide/parts/message.rst new file mode 100644 index 000000000..3f5ef37a6 --- /dev/null +++ b/guide/parts/message.rst @@ -0,0 +1,322 @@ +======= +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>`_ | channel the message was sent in | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| guild_id | string or null | the unique identifier of the guild that the channel the message was sent in belongs to | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| guild | `Guild <#guild>`_ or null | the guild that the message was sent in | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| content | string | content of the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| type | int, `Message <#message>`_ constants | type of the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| mentions | Collection of `Users <#user>`_ | users mentioned in the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| author | `User <#user>`_ | the author of the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| user_id | string | id of the user that sent the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| member | `Member <#member>`_ | the member that sent this message, or null if it was in a private 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 | Collection of `Attachments <#attachment>`_ | array of attachments | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| embeds | Collection of `Embeds <#embed>`_ | embeds contained in the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| nonce | string | randomly generated string for client | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| mention_roles | Collection of `Roles <#role>`_ | any roles that were mentioned in the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| mention_channels | Collection of `Channels <#channel>`_ | 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 | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| application_id | string | if the message is a response to an Interaction, this is the id of the interaction’s application | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| message_reference | object | message that is referenced by the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| referenced_message | `Message <#message>`_ | the message that is referenced in a reply | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| interaction | object | the interaction which triggered the message (application commands) | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| thread | `Thread <#thread>`_ | the thread that the message was sent in | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| components | `Component <#component>`_ | sent if the message contains components like buttons, action rows, or other interactive components | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| sticker_items | `Sticker <#sticker>`_ | stickers attached to the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| flags | int | message flags, see below 5 properties | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| crossposted | bool | whether the message has been crossposted | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| is_crosspost | bool | whether the message is a crosspost | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| suppress_embeds | bool | whether embeds have been supressed | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| source_message_deleted | bool | whether the source message has been deleted e.g. crosspost | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| urgent | bool | whether message is urgent | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| has_thread | bool | whether this message has an associated thread, with the same id as the message | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| ephemeral | bool | whether this message is only visible to the user who invoked the Interaction | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| loading | bool | whether this message is an Interaction Response and the bot is “thinking” | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| failed_to_mention_some_roles_in_thread | bool | this message failed to mention some roles and add their members to the thread | ++----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ + +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 +==== ====== =========================== + +.. code:: php + + $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. + +.. code:: php + + $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-1: + +Parameters +---------- + +===== ====== ======================================================== +name type description +===== ====== ======================================================== +text string text to send in the message +delay int time in milliseconds to delay before sending the message +===== ====== ======================================================== + +.. code:: php + + // <@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 <#emoji>`_ object, a custom emoji string or a unicode emoji. Returns nothing in a promise. + +.. _parameters-2: + +Parameters +---------- + +======== ============================ ======================= +name type description +======== ============================ ======================= +emoticon `Emoji <#emoji>`_ or string the emoji to react with +======== ============================ ======================= + +.. code:: php + + $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-3: + +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 <#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 +-------------------- + +.. code:: php + + $message->deleteReaction(Message::REACT_DELETE_ALL)->done(function () { + // ... + }); + +Delete reaction by current user +------------------------------- + +.. code:: php + + $message->deleteReaction(Message::REACT_DELETE_ME, $emoji)->done(function () { + // ... + }); + +Delete reaction by another user +------------------------------- + +.. code:: php + + $message->deleteReaction(Message::REACT_DELETE_ID, $emoji, 'member_id')->done(function () { + // ... + }); + +Delete all reactions of one emoji +--------------------------------- + +.. code:: php + + $message->deleteReaction(Message::REACT_DELETE_EMOJI, $emoji)->done(function () { + // ... + }); + +Delete the message +================== + +Deletes the message. Returns nothing in a promise. + +.. code:: php + + $message->delete()->done(function () { + // ... + }); + +Edit the message +================ + +Updates the message. Takes a message builder. Returns the updated message in a promise. + +.. code:: php + + $message->edit(MessageBuilder::new() + ->setContent('new content'))->done(function (Message $message) { + // ... + }); + +Note fields not set in the builder will not be updated, and will retain their previous value. + +Create reaction collector +========================= + +Creates a reaction collector. Works similar to `Channel <#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 | ++-------+--------------+------------------------------------------------------------------+ + +.. code:: 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, + ])->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-4: + +Parameters +---------- + +===== ================== ================ +name type description +===== ================== ================ +embed `Embed <#embed>`_ the embed to add +===== ================== ================ + +.. code:: php + + $message->addEmbed($embed)->done(function (Message $message) { + // ... + }); diff --git a/guide/parts/user.rst b/guide/parts/user.rst new file mode 100644 index 000000000..064077b6a --- /dev/null +++ b/guide/parts/user.rst @@ -0,0 +1,128 @@ +==== +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 | ++---------------+---------+--------------------------------------------------------------------------+ +| discriminator | string | four-digit discriminator of the user | ++---------------+---------+--------------------------------------------------------------------------+ +| displayname | string | username#discriminator | ++---------------+---------+--------------------------------------------------------------------------+ +| avatar | string | avatar URL of the user | ++---------------+---------+--------------------------------------------------------------------------+ +| avatar_hash | string | avatar hash 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 | ++---------------+---------+--------------------------------------------------------------------------+ +| banner | ?string | the banner URL of the user. | ++---------------+---------+--------------------------------------------------------------------------+ +| banner_hash | ?string | the banner URL of the user. | ++---------------+---------+--------------------------------------------------------------------------+ +| accent_color | ?int | the user’s banner color encoded as an integer representation | ++---------------+---------+--------------------------------------------------------------------------+ +| 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 <#channel>`_ in a promise. + +.. code:: php + + $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 +======= ====== ============================================= + +.. code:: php + + $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-1: + +Parameters +---------- + ++--------+--------+-------------------------------------------------------------------------------+ +| name | type | description | ++========+========+===============================================================================+ +| format | string | format of the image, one of png, jpg or webp, default webp or gif if animated | ++--------+--------+-------------------------------------------------------------------------------+ +| size | int | size of the image, default 1024 | ++--------+--------+-------------------------------------------------------------------------------+ + +.. code:: php + + $url = $user->getAvatarAttribute('png', 2048); + echo $url; // https://cdn.discordapp.com/avatars/:user_id/:avatar_hash.png?size=2048 + +Get banner URL +============== + +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. + +.. _parameters-2: + +Parameters +---------- + ++--------+--------+------------------------------------------------------------------------------+ +| name | type | description | ++========+========+==============================================================================+ +| format | string | format of the image, one of png, jpg or webp, default png or gif if animated | ++--------+--------+------------------------------------------------------------------------------+ +| size | int | size of the image, default 600 | ++--------+--------+------------------------------------------------------------------------------+ + +.. code:: php + + $url = $user->getBannerAttribute('png', 1024); + echo $url; // https://cdn.discordapp.com/banners/:user_id/:banner_hash.png?size=1024 diff --git a/guide/permissions.rst b/guide/permissions.rst new file mode 100644 index 000000000..65996cebb --- /dev/null +++ b/guide/permissions.rst @@ -0,0 +1,121 @@ +=========== +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 +===================== ==== ====================== + +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. + +.. code:: php + + var_dump(ChannelPermission::getPermissions()); + // [ + // 'priority_speaker' => 8, + // // ... + // ] + +Channel Permission +================== + +Represents permissions for text, voice, and stage instance channels. + +Text Channel Permissions +------------------------ + +- ``create_instant_invite`` +- ``manage_channels`` +- ``view_channel`` +- ``manage_roles`` +- ``add_reactions`` +- ``send_messages`` +- ``send_tts_messages`` +- ``manage_messages`` +- ``embed_links`` +- ``attach_files`` +- ``read_message_history`` +- ``mention_everyone`` +- ``use_external_emojis`` +- ``manage_webhooks`` +- ``use_application_commands`` +- ``manage_threads`` +- ``create_public_threads`` +- ``create_private_threads`` +- ``use_external_stickers`` +- ``send_messages_in_threads`` + +Voice Channel Permissions +------------------------- + +- ``create_instant_invite`` +- ``manage_channels`` +- ``view_channel`` +- ``manage_roles`` +- ``priority_speaker`` +- ``stream`` +- ``connect`` +- ``speak`` +- ``mute_members`` +- ``deafen_members`` +- ``move_members`` +- ``use_vad`` +- ``manage_events`` +- ``use_embedded_activities`` was ``start_embedded_activities`` + +Stage Instance Channel Permissions +---------------------------------- + +- ``create_instant_invite`` +- ``manage_channels`` +- ``view_channel`` +- ``manage_roles`` +- ``connect`` +- ``mute_members`` +- ``deafen_members`` +- ``move_members`` +- ``request_to_speak`` +- ``manage_events`` + +Role Permissions +================ + +Represents permissions for roles. + +Permissions +----------- + +- ``create_instant_invite`` +- ``manage_channels`` +- ``view_channel`` +- ``manage_roles`` +- ``kick_members`` +- ``ban_members`` +- ``administrator`` +- ``manage_guild`` +- ``view_audit_log`` +- ``view_guild_insights`` +- ``change_nickname`` +- ``manage_nicknames`` +- ``manage_emojis_and_stickers`` +- ``moderate_members`` \ No newline at end of file diff --git a/guide/repositories.rst b/guide/repositories.rst new file mode 100644 index 000000000..8fae8db30 --- /dev/null +++ b/guide/repositories.rst @@ -0,0 +1,106 @@ +============ +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 <#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. + +.. code:: php + + $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 +========== ===== ================================================= + +.. code:: php + + $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 +==== ==== ============================ + +.. code:: php + + $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 +==== ==== ================== + +.. code:: php + + $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 | ++-------+--------+----------------------------------------------------------------+ + +.. code:: php + + $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) { + // ... + }); \ No newline at end of file diff --git a/phpdoc.dist.xml b/phpdoc.dist.xml index c9520a528..fe35c3034 100644 --- a/phpdoc.dist.xml +++ b/phpdoc.dist.xml @@ -5,14 +5,23 @@ xmlns="https://www.phpdoc.org" xsi:noNamespaceSchemaLocation="https://docs.phpdoc.org/latest/phpdoc.xsd" > + DiscordPHP Documentation - build/reference + build src + reference + + + guide + + guide + +