Commit inicial con archivos existentes

This commit is contained in:
2026-01-17 16:14:00 -06:00
parent 48671dc88e
commit 4c48c279de
2539 changed files with 2412708 additions and 0 deletions

15
vendor/team-reflex/discord-php/.editorconfig vendored Executable file
View File

@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.yml]
indent_size = 2
[*.js]
indent_size = 2

View File

@@ -0,0 +1,39 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
---
<!-- Please keep issues strictly about bugs and feature requests. -->
<!-- If you need help, please join our Discord server. The link is in the README. -->
<!-- Please provide your PHP and DiscordPHP version. This will help us debug. -->
<!-- PHP version can be retrieved by running `php -v` -->
<!-- DiscordPHP version can be retrieved by running `composer show team-reflex/discord-php` -->
**Environment**
- PHP Version:
- x.x.x
- DiscordPHP Version:
- x.x.x
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
```php
$discord->on(..., function () {
// ...
});
```
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,22 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: features
---
<!-- Please keep issues strictly about bugs and feature requests. -->
<!-- If you need help, please join our Discord server. The link is in the README. -->
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "composer" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"

View File

@@ -0,0 +1,36 @@
name: Build Docs
on:
push:
release:
types: [published]
jobs:
docs:
runs-on: ubuntu-latest
if: github.event_name == 'release' || contains(github.event.head_commit.message, 'build docs')
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '7.4'
extensions: iconv
tools: phive
- name: Install phpDocumentor
run: phive install phpDocumentor --trust-gpg-keys 67F861C3D889C656,6DA3ACC4991FFAE5
- name: Build class reference
run: ./tools/phpDocumentor
- name: Build documentation
run: |
cd ./docs
yarn install
yarn build
sudo mv public/* ../build
- name: Publish docs
uses: JamesIves/github-pages-deploy-action@3.7.1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages
FOLDER: build
CLEAN: true

View File

@@ -0,0 +1,34 @@
name: Unit Tests
on: [ push ]
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
TEST_CHANNEL: ${{ secrets.TEST_CHANNEL }}
TEST_CHANNEL_NAME: ${{ secrets.TEST_CHANNEL_NAME }}
jobs:
unit-lint:
name: PHPUnit and Lint
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, 'no test')"
concurrency: phpunit
strategy:
matrix:
php:
- '8.0'
- '7.4'
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: uv, zlib, mbstring
tools: phpunit, phplint
- name: Install dependencies
run: composer install
- name: Run PHPUnit
run: phpunit
- name: Run PHPLint
run: phplint

31
vendor/team-reflex/discord-php/.gitignore vendored Executable file
View File

@@ -0,0 +1,31 @@
# general
.env
.DS_Store
test*.php
.idea
.phplint-cache
dump.html
.vscode
# phive
/tools
.phive
# composer
/vendor
composer.lock
# docs
/build
.phpdoc
# php-cs-fixer
.php_cs.cache
.php_cs
.php-cs-fixer.php
.php-cs-fixer.cache
# phpunit
phpunit.log
/.phpunit*
/coverage

View File

@@ -0,0 +1,102 @@
<?php
$header = <<<'EOF'
This file is a part of the DiscordPHP project.
Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
This file is subject to the MIT license that is bundled
with this source code in the LICENSE.md file.
EOF;
$fixers = [
'blank_line_after_namespace',
'braces',
'class_definition',
'elseif',
'encoding',
'full_opening_tag',
'function_declaration',
'lowercase_keywords',
'method_argument_space',
'no_closing_tag',
'no_spaces_after_function_name',
'no_spaces_inside_parenthesis',
'no_trailing_whitespace',
'no_trailing_whitespace_in_comment',
'single_blank_line_at_eof',
'single_class_element_per_statement',
'single_import_per_statement',
'single_line_after_imports',
'switch_case_semicolon_to_colon',
'switch_case_space',
'visibility_required',
'blank_line_after_opening_tag',
'no_multiline_whitespace_around_double_arrow',
'no_empty_statement',
'include',
'no_trailing_comma_in_list_call',
'not_operator_with_successor_space',
'no_leading_namespace_whitespace',
'no_blank_lines_after_class_opening',
'no_blank_lines_after_phpdoc',
'object_operator_without_whitespace',
'binary_operator_spaces',
'phpdoc_indent',
'general_phpdoc_tag_rename',
'phpdoc_inline_tag_normalizer',
'phpdoc_tag_type',
'phpdoc_no_access',
'phpdoc_no_package',
'phpdoc_scalar',
'phpdoc_summary',
'phpdoc_trim',
'phpdoc_var_without_name',
'no_leading_import_slash',
'no_trailing_comma_in_singleline_array',
'single_blank_line_before_namespace',
'single_quote',
'no_singleline_whitespace_before_semicolons',
'cast_spaces',
'standardize_not_equals',
'ternary_operator_spaces',
'trim_array_spaces',
'unary_operator_spaces',
'no_unused_imports',
'no_useless_else',
'no_useless_return',
'phpdoc_no_empty_return',
'no_extra_blank_lines',
'multiline_whitespace_before_semicolons',
];
$rules = [
'concat_space' => ['spacing' => 'none'],
'phpdoc_no_alias_tag' => ['replacements' => ['type' => 'var']],
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => ['align_double_arrow' => true, 'align_equals' => true],
'header_comment' => ['header' => $header],
'indentation_type' => true,
'phpdoc_align' => [
'align' => 'vertical',
'tags' => ['param', 'property', 'property-read', 'property-write', 'return', 'throws', 'type', 'var', 'method'],
],
'blank_line_before_statement' => ['statements' => ['return']],
'constant_case' => ['case' => 'lower'],
'echo_tag_syntax' => ['format' => 'long'],
'trailing_comma_in_multiline' => ['elements' => ['arrays']],
];
foreach ($fixers as $fix) {
$rules[$fix] = true;
}
$config = new PhpCsFixer\Config();
return $config
->setRules($rules)
->setFinder(
PhpCsFixer\Finder::create()
->exclude('examples')
->in(__DIR__)
);

7
vendor/team-reflex/discord-php/.phplint.yml vendored Executable file
View File

@@ -0,0 +1,7 @@
path: ./
jobs: 10
extensions:
- php
exclude:
- vendor
warning: false

384
vendor/team-reflex/discord-php/CHANGELOG.md vendored Executable file
View File

@@ -0,0 +1,384 @@
# Changelog
## Version 7.0.0
This release contains breaking changes regarding messages.
- Read the [conversion guide](V7_CONVERSION.md) for a guide on how to upgrade from v6.x to v7.
- If you are coming from v5.x, also read the [v6.x conversion guide](V6_CONVERSION.md).
- Upgraded to Discord API v9.
- Added `MessagBuilder`.
- See the conversion guide for more information - most functions that send messages now take message builders instead of seperate parameters.
- Added support for [Discord Threads](https://discord.com/developers/docs/topics/threads).
- `$message->channel` will now return a `Channel` or `Thread` object.
- Added [guild feature flags](https://github.com/discord-php/DiscordPHP/blob/28d741c47e81f9957a3b0d92c2f187d81d26c9c8/src/Discord/Parts/Guild/Guild.php#L75-L95).
- Removed `premium_since` attribute from the `PresenceUpdate` object.
- This would have been null since v6 anyway.
- `$message->author` is now only return an `User` object and no longer return a `Member` object. `$message->user` is removed in favour of `$message->author`
- `Message::stickers` is now `Message::sticker_items`
- Deprecated old permission names: (#661)
- `use_slash_commands` is now `use_application_commands`
- `use_public_threads` is now `create_public_threads`
- `use_private_threads` is now `create_private_threads`
- `manage_emojis` is now `manage_emojis_and_stickers`
- `Guild::region` is deprecated and may be removed in future release
- Sticker `use Discord\Parts\Channel\Sticker` is now `use Discord\Parts\Guild\Sticker`
- Invite `use Discord\Parts\Guild\Invite` is now `use Discord\Parts\Channel\Invite`
- Some event handler arguments have been updated, check out the documentation.
## Version 6.0.2
- Added `link` attribute to `Message` - [#526]
- Added `filter` function to `Collection`.
- Fixed voice client error when using PHP 7.4
- Added 'Discord Certified Moderator' flag to `Member`.
- Fixed `member` attribute on `MessageReaction` returning the wrong type.
- Add `sendMessage` to `Member` object - [#538]
- Fixed command client mention prefix when mentioning nickname.
- Use `Embed` inside command client - [#546]
- Add `pending` flag to `Member` object - [#550]
- Add `updateRolePositions` to `Guild` to change position of roles.
- Added buttons to `Activity` - [#561]
- Allow bulk updating of permission overwrites through `Channel`.
- Fix emoji deletion on macOS.
- Add `__toString()` function to `Channel` for channel mention - [#575]
- Add function to escape Discord markdown - [#586]
Thank you to the following for contributions to this release:
- @valzargaming
- @Max2408
- @MohsinEngineer
- @rachids
- @key2peace
- @SQKo
- @davidcole1340
[#526]: https://github.com/discord-php/DiscordPHP/pull/526
[#538]: https://github.com/discord-php/DiscordPHP/pull/538
[#546]: https://github.com/discord-php/DiscordPHP/pull/546
[#550]: https://github.com/discord-php/DiscordPHP/pull/550
[#561]: https://github.com/discord-php/DiscordPHP/pull/561
[#575]: https://github.com/discord-php/DiscordPHP/pull/575
[#586]: https://github.com/discord-php/DiscordPHP/pull/586
## Version 6.0.1
- Fixed `Message::member` attribute returning a `User` - #523 @davidcole1340
- Added `loggerLevel` changes to changelog and conversion guide - c11af7c646c18b0e124b2b1fa349daeced76ad78
- Updated documentation to reflect missed changes in 6.0.0 - #520 #521 @hemberger
## Version 6.0.0
This version has also been known as `v5.2.0`, however, breaking changes caused the version to be increased.
- Discord Gateway and REST API versions changed to Version 8.
- Removed unnecessary deferred promises from various parts and repositories.
- `Message::reply()` now creates a "Discord reply" rather than the old way which was simply a mention with the content afterwards.
- Tidied up and removed any unessacary deferred promises and promise binds.
- Added `Message::delayedDelete(int $ms)` to delete a message after a delay.
- Fixed member chunking not working when the guild is not considered 'large'.
## Breaking Changes
- PHP 7.4 is now the lowest supported version of PHP.
- Versions as low as PHP 7.2 may still work, however, no support will be provided.
- PHP 8.0 is now recommended, and CI is run on PHP 7.4 and 8.0.
- With the update to gateway version 8, the `GUILD_MEMBER` and `PRESENCE_UPDATE` intents are not enabled by default.
- You must first enable these in your Discord developer portal before enabling them in DiscordPHP. See the documentation for an example.
- The `loadAllMembers` option requires the `GUILD_MEMBER` intent to be enabled.
- The `logging`, `httpLogger` and `loggerLevel` options have been removed.
- All HTTP logging information is now redirected to the `logger` that you have passed, or the default logger.
- For people that disabled logging by setting `logging` to false, you can create a logger with a [`NullHandler`](https://github.com/Seldaek/monolog/blob/main/src/Monolog/Handler/NullHandler.php).
- For voice client users, see the section below for breaking changes.
### HTTP Client
- HTTP client has been moved to a seperate package: [DiscordPHP-Http](https://github.com/discord-api/DiscordPHP-Http)
- Improved rate limits by grouping requests by major parameters.
### Voice Client
- The voice client now requires at least PHP 7.4 to operate. It will not attempt to start on any version lower.
- The voice client can now run on Windows, thanks to the introduction of socker pair descriptors in PHP 8.0 (see reactphp/child-process#85). As such, PHP 8.0 is required to run the voice client on Windows.
- DCA has been rebuilt and refactored for better use with DiscordPHP. Note that the binaries have only been rebuilt for the `amd64` architecture. The following platforms are now supported:
- Windows AMD64
- macOS AMD64
- Linux AMD64
- I'm happy to support DCA for other platforms if requested. Please ensure that your platform is supported by the Go compiler, see the supported list [here](https://golang.org/doc/install/source#introduction).
- The following functions no longer return promises, rather they throw exceptions and will return void. This is because none of these functions actually did any async work, therefore promises were redundant in this situation.
- `setSpeaking()`
- `switchChannel()`
- `setFrameSize()`
- `setBitrate()`
- `setVolume()`
- `setAudioApplication()`
- `setMuteDeaf()`
- `pause()`
- `unpause()`
- `stop()`
- `close()`
- `getRecieveStream()`
- Expect a voice client refactor in a future release.
## Version 5.1.3
- Added the `recipient_id` property to `Channel` - 8b3eb0e667b39d906b3962a55d1469f5184b63ff
- Fixed private channel caching bug - 8b3eb0e667b39d906b3962a55d1469f5184b63ff
- Fixed guild member chunking not working on some bot accounts - 96f1ce30236ec7b18b70216e7e4f73317f242073
## Version 5.1.2
- Fixed bug where websocket connection would fail and wouldn't reconnect.
- Expanded on documentation.
- Updated documentation `marked` version to `^2.0.0` due to security concern.
- Disabled happy eyeballs connector as Discord does not use IPv6, and this causes an error when using a debugger.
- Added options resolver for creating an invite.
- Added the option to delete all reactions of a certain emoji from a message.
- Fixed getting emoji ID for unicode emojis.
- Fixed audit log query not accepting an `Entry` object.
## Version 5.1.1
- Added permission checking before executing requests for channels.
- Fixed issue where global rate limits would delay too long.
- Added option to pass through `react/socket` connector options through `socket_options`.
- Fixed issue with case-insensitive commands in the command client.
- Fixed issue where users would not update in the user repository on an `GUILD_MEMBER_*` event.
- Repository is now hosted under the `discord-php` organisation on GitHub. This will not change anything unless you have the repository cloned.
- Fixed an issue where guild repositories would empty on `GUILD_UPDATE`.
- Fixed issue where buckets would deadlock when there is a global rate limit and a non-global rate limit at the same time.
- Token is now stripped from any text output.
- `TYPE_STREAMING` and `TYPE_COMPETING` is now allowed for bots.
- Fixed an issue where a bucket queue would be blocked when a request throws an exception.
## Version 5.1.0
- Refactored and rebuilt the HTTP client.
- Implemented the concept of "buckets" - to be worked on as at the moment requests are grouped by the exact endpoint only.
- Fixed guild member chunking with the gateway changes.
- Fixed `Channel::deleteMessages()` not working for 0 or 1 messages.
- Added the `allowed_mentions` option to `Channel::sendMessage()`.
- Converted message reactions to a repository.
- Changed `Message::mention_channels` to use a regular expression to find actual mentioned channels rather than relying on Discord to send them (which they don't).
- Fixed varius errors where the attribute does not exist.
- Added the `Reaction::getUsers()` method to retrieve users that have reacted with that reaction.
- Implemented audit logs - see the class reference and Discord developer docs for more information.
- Added new attributes to Guilds.
- Fixed permissions not calculating correctly.
- Fixed various errors with the voice client.
- Added an option to skip FFmpeg/DCA checks when starting the voice client (for Windows compatibility).
- Implemented `MESSAGE_REACTION_*` events.
- Added `\Discord\imageToBase64()` to convert an image to base 64 to be uploaded to Discord.
- Started documentation and tests.
### Command Client
- Added the `caseInsensitiveCommands` option to change whether commands should be case sensitive.
- Added sub-commands to the various help menus.
## Version 5.0.12
- Converted `PromiseInterface` to `ExtendedPromiseInterface` to allow `->done()` typehinting.
- Converted most `->then()` to `->done()` for better error handling.
- Fixed issue with member chunking not working correctly due to changes in Discord's gateway.
- Implemented gateway payload rate-limiting.
- Removed `illuminate/support` dependency.
- Fixed errors in HTTP going into the response handler function and causing errors.
- Added `Channel::limitDelete(n)` to delete the last n messages.
- Added setter functions to embeds. Now much easier to set, and more reliable.
- Added `$guild->leave()` as a shortcut to `$discord->guilds->leave($guild)`.
- Parts are now constructable without factory:
Old:
```php
$message = $discord->factory(Message::class);
```
New:
```php
$message = new Message($message);
```
Both methods are still valid.
- `AbstractRepository` now extends `Collection` rather than having magic functions to handle calls.
- Added `WebhookRepository::get()`.
- Added support functions:
- `getColor(int $color);`
- `contains(string $key, array $matches);`
- `studly(string $string)`
- `poly_strlen(string $string)`
## Version 5.0.11
- Added dependabot to update composer dependencies.
- Upgraded `react/partial` to `^3.0`.
- `Discord` will now emit `reconnected` when the client reconnects via identify OR resume.
- Fixed issue with resumes not working due to closing with opcode `1000`.
- Client will now attempt to resume after an invalid session if it is still resumable.
- Exceptions inside the `ready` handler will now be caught, emitted via `exception` and logged.
- Temporary fix until `react/promise ^3.0` is released, as any uncaught exceptions inside promises are dismissed.
- Added `Discord::getChannel(id)` which searches through all guilds and private channels to find a channel.
- `Channel::deleteMessages()` now works for private channels by looping through all messages and deleting.
- Added `Channel::editMessage()`.
- Added new activity types `Activity::TYPE_WATCHING` and `Activity::TYPE_COMPETING`.
- Fixed issue with `MESSAGE_DELETE` events not working correctly.
- Fixed issie with `VOICE_STATE_UPDATE` where members were not removed from their old channels.
## Version 5.0.10
- The PHP composer dependency has been updated to PHP 7.2. The library was not working on anything less in previous versions so I'm not deeming this a breaking change, just a formality.
- Added PHP 7.2 typehinting to functions.
- Added `Collection::first()` to get the first element of the collection.
- Added the ability to call `AbstractRepository::delete()` with a string ID instead of solely a part.
- Any custom logger now may be passed to the Discord client as long as it implementes `LoggerInterface` from PSR.
- Fixed phpdocs for collections, typehinting will now work when accessing it as an array.
- Fixed bug with `Collection::get()` when not searching by discriminator.
- Added `Webhook::execute()`.
- Added support for `illuminate/support` 8.0.
- `Channel::deleteMessages()` will no longer fail if 0 or 1 messages is given. The promise will instantly resolve when given 0, and will delete the one message then resolve for 1 message.
- Fixed error when handling message deletes.
- Websocket will no longer close when an error is seen, as Pawl's errors do not always cause closure of the websocket.
- Fixed bug with rate limiting after changing to `react/http`.
- Fixed bug with sending files after changing to `react/http`.
## Version 5.0.3
- Development of the library will now continue on the `master` branch. The `develop` branch will be removed and you should checkout the latest tag for the most stable version.
- Removed dependency of decepreated package `wyrihaximus/react-guzzle-psr7`, replaced with `react/http`.
- Rewrote HTTP client to remove dependency of Guzzle.
- Client will prevent updating presence with an invalid activity type.
- Collections:
- Added `Collection::set($offset, $value)`.
- Added `Collection::isset($offset)`.
- Added `Message::sendEmbed(Embed $embed)` as a shortcut to sending embeds.
- Fixed an issue on Windows where emoticons were not URL encoded.
- Added `Embed::addField(Field $field)` to add fields to an embed.
- Added user activity statuses constants to `Activity`.
- `Member::addRole(Role $role)` and `Member::removeRole(Role $role)` now modifies the member on Discord's end.
- You no longer need to run `$guild->members->save($member)`.
- The function now returns a promise.
- Added `Member::getPermissions(Channel? $channel)` to get the total permissions of the member for a guild or channel.
- The avatar attribute of a user will return their default avatar when it is null.
## Version 5.0.2
- Fixed updating and creating parts.
- Fixed repository saving.
- Removed debugging statement.
- Removed `bind_right` statement that was left over.
- Fixed setting overwrites.
## Version 5.0.1
- Removed option for `bot = false`. This option wouldn't have worked anyway so I am not classing it as a breaking change.
- Converted all getter and setter functions in parts to protected. Again, shouldn't be a breaking change as these function aren't meant to be used outside of the library.
- Webhooks:
- Added phpdoc to webhook part.
- Added webhook type constants
- Guilds:
- Added [new guild attributes.](https://github.com/discord-php/DiscordPHP/compare/develop#diff-4a22d1c34b22f50e90b71244aac252cdR43-R64)
- Removed unused attributes cache from part.
- Removed `password` attribute from `Client`.
- Added [new user attributes](https://github.com/discord-php/DiscordPHP/compare/develop#diff-3d3aea0229e2bfd3b386726702468115R29-R36) and flags.
- Voice client now handles websocket closes better.
- Client will now load online users regardless of `loadAllMembers` option. This option will now cause the client to initiate guild member chunking offline members.
## Version 5.0.0
First release for many years. Contains many bug fixes and stability patches so this is the most important update since.
### Breaking Changes
- PHP 7.0 is now required. PHP 5.x is no longer supported.
- Package versions:
- illuminate/support: now supports Laravel 6.x and 7.x
- nesbot/carbon: was ^1.18, now ^2.38
- symfony/options-resolver: was ^3.0, now ^5.1.3
- monolog/monolog: was ^1.19, now ^2.1
- Cache adapters such as apc, memcache and redis are no longer supported. There is no longer a `cachePool` option.
- ext-libevent is no longer supported as it only applies for PHP 5.x.
- The `Collection` class no longer extends Laravel collections.
- As such, some functions are no longer present.
- Feel free to add an issue if you would like to see a function added.
- Channels:
- `Channel::setPermissions()` function now takes a role or member as well as two arrays: one array of allow permissions and one array of deny permissions.
- `Channel::createInvite()` now takes an array of options. See the [Discord developer docs](https://discord.com/developers/docs/resources/channel#create-channel-invite) for a list of valid options.
- Messages can no longer be created using the message repository as part of the channel. Use `Channel::sendMessage()` instead.
- Overwrites:
- The `allow` and `deny` parameters of an overwrite are an instance of `ChannelPermission` instead of `int`.
- Guilds:
- Removed [old region constants](https://github.com/discord-php/DiscordPHP/blob/ca05832fa0d5700d96f5ecee2fe32a3aa6125f41/src/Discord/Parts/Guild/Guild.php). Added the `Guild::getVoiceRegions()` function to get an array of valid regions.
- `Guild::validateRegion()` now has to perform an async HTTP request to validate the region. Only use this if nessasary.
- Removed the `Game` class. Renamed to `Activity` and new attributes added.
- `Discord::updatePresence()` now takes an `Activity` object as well as options `idle`, `status` and `afk`.
### Features
- Added `getLoop()` and `getLogger()` functions to the `Discord` client.
- Collectors:
- Channels now have message collectors. See the phpdoc of `Channel::createMessageColletor()` for more information.
- Messages now have reaction collectors. See the phpdoc of `Message::createReactionCollector()` for more information.
- Added the [`Reaction`](https://github.com/discord-php/DiscordPHP/blob/ca05832fa0d5700d96f5ecee2fe32a3aa6125f41/src/Discord/Parts/Channel/Reaction.php) class.
- Added the [`Webhook`](https://github.com/discord-php/DiscordPHP/blob/ca05832fa0d5700d96f5ecee2fe32a3aa6125f41/src/Discord/Parts/Channel/Webhook.php) class.
- Implemented gateway intents:
- See the [`Intents` class](https://github.com/discord-php/DiscordPHP/blob/ca05832fa0d5700d96f5ecee2fe32a3aa6125f41/src/Discord/WebSockets/Intents.php) for constants.
- User can specify an `intents` field in the options array, containing either an array of intents or an integer corresponding to the intents.
### Changes
- WebSocket:
- Added new events: `GUILD_INTEGRATIONS_UPDATE`, `INVITE_CREATE`, `INVITE_DELETE`, `MESSAGE_REACTION_REMOVE_EMOJI`.
- Client will not retrieve guild bans by default anymore. Set `retrieveBans` to `true` in options to retrieve on guild availability.
- Command client:
- Help command now prints a rich embed (#305 thanks @oliverschloebe)
- Commands have a short and long description.
- Commands have a cooldown option.
- Factory now has a `part()` and `repository()` function to bypass `strpos` functions.
- Channels:
- [Added new attributes](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-d1f173f4572644420fb9cd5d0b540c59R51-R58).
- [Added new channel types](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-d1f173f4572644420fb9cd5d0b540c59R66-R72).
- Added webhook classes and repositories.
- `Channel::setOverwrite()` has been added to perform the action of `setPermissions()` from the previous version.
- Messages:
- [Added new attributes](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-dcdab880a1ed5dbd0b65000834e4955cR44-R55).
- [Added new message types](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-dcdab880a1ed5dbd0b65000834e4955cR59-R78).
- Added `Message::delayedReply()` to perform a reply after a specified duration.
- `Message::react()` and `Message::deleteReaction()` now takes an `Emoji` object or a string emoji.
- Added `Message::delete()` to delete a message without using the repository.
- Added `Message::addEmbed()` to add an embed to the message.
- Added the [`MessageReaction` class](https://github.com/discord-php/DiscordPHP/blob/ca05832fa0d5700d96f5ecee2fe32a3aa6125f41/src/Discord/Parts/WebSockets/MessageReaction.php) to represent a reaction to a message.
- Embeds:
- Added the `type` parameter.
- Emojis:
- Added the `animated` parameter.
- Added the `Emoji::toReactionString()` function to convert to a format to put in a `Reaction` object.
- Added the `Emoji::__toString()` object for sending emojis in messages.
- Guilds:
- Guild region is no longer checked before saving. Make sure to handle any exceptions from Discord servers and do not spam.
- Roles can now update their `mentionable` attribute.
- Permissions:
- [Added new permissions.](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-60e83a1d96a4957061230b770a056001R5-R35)
- Members:
- [Added new attributes.](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-8f236f99fe6eec45c56cff1be0ba0f90R40-R42)
- The `game` attribute now returns an `Activity` part.
- Presence updates:
- [Added new attributes.](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-d6e13d509fb506d128c564d3ea4217adR25-R32)
- Typing updates:
- [Added new attributes.](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-bc4d0e1ce4e436c29b922dd26266df68R26-R32)
- Voice state updates:
- [Added new attributes.](https://github.com/discord-php/DiscordPHP/pull/309/files#diff-4aa18d683d39063927ff9ff28149698fR21-R35)
### Bug Fixes
- Improved memory usage by removing `resolve` and `reject` functions from `Part`s.
- Memory leak has been improved but is still preset.
- `AbstractRepository::freshen()` now actually freshens the part, rather than being cached.
- Voice client has been updated to use the correct UDP server given by the web socket.
- Events *should* update their corresponding repositories more consistently.
- Improved the processing speed of `GUILD_CREATE` and `GUILD_MEMBERS_CHUNK` events.
- Added new gateway operation and close codes.
- Client will not attempt to reconnect to Discord servers if it receives a "critical" opcode (one that cannot be resolved by the bot).

View File

@@ -0,0 +1,3 @@
We are open to contributions. However, please make sure you follow our coding standards (PSR-4 autoloading and custom styling). Please run php-cs-fixer before opening a pull request by running ``composer run-script cs.``
Please only use the issue tracker for submitting issues with the code. If you have questions about how to use DiscordPHP, hop over to our discord at [![PHP Discorders](https://discord.com/api/guilds/115233111977099271/widget.png?style=banner1)](https://discord.gg/dphp)

21
vendor/team-reflex/discord-php/LICENSE.md vendored Executable file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 David Cole <david.cole1340@gmail.com> and all contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

105
vendor/team-reflex/discord-php/README.md vendored Executable file
View File

@@ -0,0 +1,105 @@
DiscordPHP
====
[![Latest Stable Version](https://poser.pugx.org/team-reflex/discord-php/v)](https://packagist.org/packages/team-reflex/discord-php) [![Total Downloads](https://poser.pugx.org/team-reflex/discord-php/downloads)](https://packagist.org/packages/team-reflex/discord-php) [![PHP Version Require](https://poser.pugx.org/team-reflex/discord-php/require/php)](https://packagist.org/packages/team-reflex/discord-php)
[![PHP Discorders](https://discord.com/api/guilds/115233111977099271/widget.png?style=banner1)](https://discord.gg/dphp)
A wrapper for the official [Discord](https://discordapp.com) REST, gateway and voice APIs. Documentation is [available here](http://discord-php.github.io/DiscordPHP), albeit limited at the moment, as well as a class reference. Feel free to ask questions in the Discord server above.
For testing and stability it would be greatly appreciated if you were able to add our test bot to your server. We don't store any data - the bot simply idles and does not interact with anyone and is used to test stability with large numbers of guilds. You can invite the bot [here.](https://discord.com/oauth2/authorize?client_id=157746770539970560&scope=bot)
## Before you start
Before you start using this Library, you **need** to know how PHP works, you need to know the language and you need to know how Event Loops and Promises work. This is a fundamental requirement before you start. Without this knowledge, you will only suffer.
## FAQ
1. Can I run DiscordPHP on a webserver (e.g. Apache, nginx)?
- No, DiscordPHP will only run in CLI. If you want to have an interface for your bot you can integrate [react/http](https://github.com/ReactPHP/http) with your bot and run it through CLI.
2. PHP is running out of memory?
- Try increase your memory limit using `ini_set('memory_limit', '-1');`.
## Getting Started
### Requirements
- PHP 7.4
- We recommend PHP 8.0 as it will be the most stable and most performant.
- x86 (32-bit) PHP requires [`ext-gmp` extension](https://www.php.net/manual/en/book.gmp.php) enabled for handling Permissions.
- Composer
- `ext-json`
- `ext-zlib`
### Windows and SSL
Unfortunately PHP on Windows does not have access to the Windows Certificate Store. This is an issue because TLS gets used and as such certificate verification gets applied (turning this off is **not** an option).
You will notice this issue by your script exiting immediately after one loop turn without any errors. Unfortunately there is for some reason no error or exception.
As such users of this library need to download a [Certificate Authority extract](https://curl.haxx.se/docs/caextract.html) from the cURL website.<br>
The path to the caextract must be set in the [`php.ini`](https://secure.php.net/manual/en/openssl.configuration.php) for `openssl.cafile`.
#### Recommended Extensions
- The latest PHP version.
- One of `ext-uv` (recommended), `ext-libev` or `ext-event` for a faster, and more performant event loop.
- `ext-mbstring` if handling non-english characters.
- `ext-gmp` if using 32-bit PHP.
#### Voice Requirements
- 64-bit Linux or Darwin based OS.
- If you are running on Windows, you must be using PHP 8.0.
- `ext-sodium`
- FFmpeg
### Installing DiscordPHP
DiscordPHP is installed using [Composer](https://getcomposer.org).
1. Run `composer require team-reflex/discord-php`. This will install the latest release.
- If you would like, you can also install the development branch by running `composer require team-reflex/discord-php dev-master`.
2. Include the Composer autoload file at the top of your main file:
- `include __DIR__.'/vendor/autoload.php';`
3. Make a bot!
### Basic Example
```php
<?php
include __DIR__.'/vendor/autoload.php';
use Discord\Discord;
use Discord\Parts\Channel\Message;
use Discord\WebSockets\Event;
$discord = new Discord([
'token' => 'bot-token',
]);
$discord->on('ready', function (Discord $discord) {
echo "Bot is ready!", PHP_EOL;
// Listen for messages.
$discord->on(Event::MESSAGE_CREATE, function (Message $message, Discord $discord) {
echo "{$message->author->username}: {$message->content}", PHP_EOL;
});
});
$discord->run();
```
See [examples folder](examples) for more.
## Documentation
Documentation can be found [here](//discord-php.github.io/DiscordPHP/guide). Raw documentation can be found in-line in the code. Community contributed tutorials can be found on the [wiki](//github.com/discord-php/DiscordPHP/wiki).
## Contributing
We are open to contributions. However, please make sure you follow our coding standards (PSR-4 autoloading and custom styling). Please run php-cs-fixer before opening a pull request by running `composer run-script cs`.
## License
MIT License, &copy; David Cole and other contributers 2016-present.

View File

@@ -0,0 +1,110 @@
# Version 5.x to 6.0 Conversion Guide
## PHP Version
PHP 7.4 is now required. Please update to _at least_ PHP 7.4, but we recommend PHP 8.x for the best performance.
## Options removal
The `logging`, `httpLogger` and `loggerLevel` options have been removed. Any logs that went to the HTTP logger are now sent to the default `logger`.
If you were using the `logging` option to disable logging, you can do the same by creating a null logger:
```php
<?php
use Discord\Discord;
use Monolog\Logger;
use Monolog\Handler\NullLogger;
$logger = new Logger('Logger');
$logger->pushHandler(new NullHandler());
$discord = new Discord([
// ...
'logger' => $logger,
]);
```
If you were using the `loggerLevel` option to change the logger level, you can do the same by creating a logger and changing the level of the handler:
```php
<?php
use Discord\Discord;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('Logger');
$logger->pushHandler(new StreamHandler('php://stdout'), Logger::DEBUG); // Change the second parameter of this function call.
$discord = new Discord([
// ...
'logger' => $logger,
]);
```
## Loading all members
Alongside the `loadAllMembers` option, you now must enable the `GUILD_MEMBERS` intent. You can do this by specifying the `intents` option in the options array:
```php
<?php
use Discord\Discord;
use Discord\WebSockets\Intents;
$discord = new Discord([
// ...
'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS,
]);
```
Note that your bot will not be able to connect to the gateway if you have not enabled this intent in the Discord developer portal.
## Presence Updates
If you use the `PRESENCE_UPDATE` event, you must enable the intent in your Discord options array:
```php
<?php
use Discord\Discord;
use Discord\WebSockets\Intents;
$discord = new Discord([
// ...
'intents' => Intents::getDefaultIntents() | Intents::GUILD_PRESENCES,
]);
```
Note that your bot will not be able to connect to the gateway if you have not enabled this intent in the Discord developer portal.
## Message Replies
If you were using the `$message->reply()` function, this now returns a Discord reply rather than a 'quote'. If you want to keep the old functionality, use `$message->channel->sendMessage()`.
## Voice Client
Copied from the changelog:
- The voice client now requires at least PHP 7.4 to operate. It will not attempt to start on any version lower.
- The voice client can now run on Windows, thanks to the introduction of socker pair descriptors in PHP 8.0 (see reactphp/child-process#85). As such, PHP 8.0 is required to run the voice client on Windows.
- DCA has been rebuilt and refactored for better use with DiscordPHP. Note that the binaries have only been rebuilt for the `amd64` architecture. The following platforms are now supported:
- Windows AMD64
- macOS AMD64
- Linux AMD64
- I'm happy to support DCA for other platforms if requested. Please ensure that your platform is supported by the Go compiler, see the supported list [here](https://golang.org/doc/install/source#introduction).
- The following functions no longer return promises, rather they throw exceptions and will return void. This is because none of these functions actually did any async work, therefore promises were redundant in this situation.
- `setSpeaking()`
- `switchChannel()`
- `setFrameSize()`
- `setBitrate()`
- `setVolume()`
- `setAudioApplication()`
- `setMuteDeaf()`
- `pause()`
- `unpause()`
- `stop()`
- `close()`
- `getRecieveStream()`
- Expect a voice client refactor in a future release.

View File

@@ -0,0 +1,100 @@
# Version 6.x to 7.x Conversion Guide
Another breaking change unfourtunately, due to various factors including the addition of thread support as well
as future proofing for message components (buttons).
## Sending messages
Sending messages is now done through the [`MessageBuilder`](src/Discord/Builders/MessageBuilder.php) class.
See the [documentation](http://discord-php.github.io/DiscordPHP/) section on the message builder for usage.
This has been added to support a few features:
- Sending multiple embeds in a message.
- Sending multiple files in a message.
- Sending file attachments alongside embeds (e.g. images).
- Unifying `sendMessage` and `sendFile` functions.
- Adding message components.
The following functions have been changed, alongside their new signature:
- `Channel::sendMessage(MessageBuilder $message)`
- `Member::sendMessage(MessageBuilder $message)`
- `User::sendMessage(MessageBuilder $message)`
```php
// Old
$message->channel->sendMessage('hello, world!');
// New
$message->channel->sendMessage(MessageBuilder::new()
->setContent('hello, world!'));
```
The following functions have been added:
- `Message::edit(MessageBuilder $builder)`
The following functions have been deprecated:
- `Channel::editMessage(Message $message, MessageBuilder $builder)` - deprecated in favour of `Message::edit(MessageBuilder $builder)`.
- `Channel::sendFile()` - deprecated in favour of `Channel::sendMessage(MessageBuilder $builder)`.
- `Channel::getMessage(string $id)` - deprecated in favour of `Channel::messages::fetch(string $id)`.
## `Message::channel` now return `Channel|Thread`
With the addition of threads, messages can now be sent in text channels OR threads. These are not the same part.
If you depend on a function or property which is only present on `Channel`, you should check the type of `$message->channel`:
```php
$discord->on('message', function (Message $message) {
if ($message->channel instanceof Channel) {
// is channel...
} else {
// is thread...
}
});
```
## Message components
Message components (buttons, select menus) are now availabe! See the [documentation](https://discord-php.github.io/DiscordPHP/) on how to use implement these into your bot.
## Slash Commands
If you previously linked [DiscordPHP-Slash](https://github.com/discord-php/DiscordPHP-Slash), you can remove the package and change your code:
### Register Client
| |DiscordPHP-Slash|DiscordPHP|
|-----|-----|-----|
|Register Client|`$client = new RegisterClient('your-bot-token-here');`|*Removed*, the `$discord` can deal with commands from REST API, requires `application.commands` scope|
|Get list of all Global Commands|`$commands = $client->getCommands();`|`$discord->application->commands->freshen()->done(function ($commands) { /* ... */ });`|
|Get list of all Guild Commands|`$guildCommands = $client->getCommands('guild_id_here');`|`$discord->guilds['guild_id_here']->commands->freshen()->done(function ($commands) { /* ... */ });`|
|Get a specific Global Command|`$command = $client->getCommand('command_id');`|`$discord->application->commands->fetch('command_id')->done(function ($command) { /* ... */ });`|
|Get a specific Guild Commands|`$command = $client->getCommand('command_id', 'guild_id');`|`$discord->guilds['guild_id']->commands->fetch('command_id')->done(function ($command) { /* ... */ });`|
|Create a Global Command|`$command = $client->createGlobalCommand('command_name', 'command_description', [ /* optional array of options */ ]);`|`$command = new Command($discord, ['name' => 'command_name', 'description' => 'command_description', /* optional array of options */]);`<br/>`$discord->application->commands->save($command)`|
|Create a Guild Command|`$command = $client->createGuildSpecificCommand('guild_id', 'command_name', 'command_description', [ /* optional array of options */ ]);`|`$command = new Command($discord, ['name' => 'command_name', 'description' => 'command_description', /* optional array of options */]);`<br/>`$discord->guilds['guild_id']->commands->save($command)`|
|Updating a Global command|`$command->name = 'newcommandname';`<br/>`$client->updateCommand($command);`|`$command->name = 'newcommandname';`<br/>`$discord->application->commands->save($command);`|
|Updating a Guild command|`$command->name = 'newcommandname';`<br/>`$client->updateCommand($command);`|`$command->name = 'newcommandname';`<br/>`$discord->guilds['guild_id']->commands->save($command);`|
|Deleting a Global command|`$client->deleteCommand($command);`|`$discord->application->commands->delete($command);`|
|Deleting a Guild command|`$client->deleteCommand($command);`|`$discord->guilds['guild_id']->commands->delete($command);`|
### Slash Client
| |DiscordPHP-Slash|DiscordPHP|
|-----|-----|-----|
|Client|`$client = new Client([ /* options */ ]);`|*Removed*, all options are present when constructing `$discord`|
|Link|`$client->linkDiscord($discord, false);`|*Removed*, this is already the `$discord`|
|Register a Command|`$client->registerCommand('hello', function (Interaction $interaction, Choices $choices) {`|`$discord->listenCommand('hello', function (Interaction $interaction) {`<br/>Choices are inside `$interaction->data->options`|
|Acknowledge|`$interaction->acknowledge();`|*Same as below*|
|Acknowledge with source|`$interaction->acknowledge(true);`|`$interaction->acknowledgeWithResponse();`|
|Reply|`$interaction->reply('Hello world!');`|*Same as below*|
|Reply with source|`$interaction->replyWithSource('Hello world!');`|`$interaction->respondWithMessage(MessageBuilder::new()->setContent('Hello world!'));`|
|Update initial response|`$interaction->updateInitialResponse('text');`|`$interaction->updateOriginalResponse(MessageBuilder::new()->setContent('text'));`|
|Delete initial response|`$interaction->deleteInitialResponse();`|`$interaction->deleteOriginalResponse();`|
|Send a follow up message|`$interaction->sendFollowUpMessage('text');`|`$interaction->sendFollowUpMessage(MessageBuilder::new()->setContent('text'));`|
|Update follow up message|`$interaction->updateFollowUpMessage('message_id', 'text');`|`$interaction->updateFollowUpMessage('message_id', MessageBuilder::new()->setContent('text'));`|
|Delete follow up message|`$interaction->deleteFollowUpMessage('message_id');`|`$interaction->deleteFollowUpMessage('message_id');`|
|ApplicationCommandOptionType|`ApplicationCommandOptionType::x`<br/>`ApplicationCommandOptionType::SUB_COMMAND`|`Option::x`<br/>`Option::SUB_COMMAND`|

Binary file not shown.

Binary file not shown.

Binary file not shown.

61
vendor/team-reflex/discord-php/composer.json vendored Executable file
View File

@@ -0,0 +1,61 @@
{
"name": "team-reflex/discord-php",
"description": "An unofficial API to interact with the voice and text service Discord.",
"license": "MIT",
"authors": [
{
"name": "David Cole",
"email": "david.cole1340@gmail.com"
}
],
"support": {
"issues": "https://github.com/discord-php/DiscordPHP/issues",
"wiki": "https://github.com/discord-php/DiscordPHP/wiki",
"docs": "https://discord-php.github.io/DiscordPHP/",
"chat": "https://discord.gg/dphp"
},
"require": {
"php": "^7.4|^8.0",
"nesbot/carbon": "^2.38",
"ratchet/pawl": "^0.4.1",
"react/datagram": "1.5.*",
"symfony/options-resolver": "^5.1.3 || ^6.0",
"trafficcophp/bytebuffer": "^0.3",
"monolog/monolog": "^2.1 || ^3.0",
"react/partial": "^3.0",
"mollie/polyfill-libsodium": "^1.1",
"react/http": "^1.1",
"ext-json": "*",
"ext-zlib": "*",
"discord-php/http": "^9.0.12",
"react/child-process": "^0.6.2",
"discord/interactions": "^2.2"
},
"require-dev": {
"symfony/var-dumper": "*",
"friendsofphp/php-cs-fixer": "^3",
"phpunit/phpunit": "^9.4",
"davidcole1340/reactsh": "dev-master"
},
"autoload": {
"files": [
"src/Discord/functions.php"
],
"psr-4": {
"Discord\\": "src/Discord"
}
},
"suggest": {
"ext-uv": "For a faster, and more performant loop. Preferred.",
"ext-libev": "For a faster, and more performant loop.",
"ext-event": "For a faster, and more performant loop.",
"ext-mbstring": "For accurate calculations of string length when handling non-english characters.",
"ext-gmp": "For Permissions and 64 bit calculations on x86 (32 bit) PHP.",
"clue/zlib-react": "For gateway message transport compression with zlib-stream."
},
"scripts": {
"cs": ["./vendor/bin/php-cs-fixer fix"],
"unit": ["./vendor/bin/phpunit --testdox"],
"coverage": ["XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html coverage --testdox"]
}
}

View File

@@ -0,0 +1,6 @@
# gatsby files
.cache/
node_modules
public
package-lock.json
yarn.lock

17
vendor/team-reflex/discord-php/docs/README.md vendored Executable file
View File

@@ -0,0 +1,17 @@
# DiscordPHP Documentation
Static documentation website, built with [Gatsby](https://www.gatsbyjs.org/).
Special thanks to the amazing guys over at [@octokit/rest.js](https://octokit.github.io/rest.js/) for the amazing template!
## License
Original template is licensed under the MIT license from [@octokit/rest.js](https://github.com/octokit/rest.js/blob/master/LICENSE).
Any changes are licensed under the MIT license from [DiscordPHP](https://github.com/discord-php/DiscordPHP/blob/master/LICENSE.md).
## Local Development
```
cd ./docs
yarn install
yarn develop
```

View File

@@ -0,0 +1 @@
require("prismjs/themes/prism-okaidia.css");

View File

@@ -0,0 +1,89 @@
module.exports = {
// https://www.gatsbyjs.org/docs/how-gatsby-works-with-github-pages/
pathPrefix: "/DiscordPHP",
siteMetadata: {
title: `DiscordPHP`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `api`,
path: `${__dirname}/src/pages/api`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-prismjs`,
options: {
// Class prefix for <pre> tags containing syntax highlighting;
// defaults to 'language-' (eg <pre class="language-js">).
// If your site loads Prism into the browser at runtime,
// (eg for use with libraries like react-live),
// you may use this to prevent Prism from re-processing syntax.
// This is an uncommon use-case though;
// If you're unsure, it's best to use the default value.
classPrefix: "language-",
// This is used to allow setting a language for inline code
// (i.e. single backticks) by creating a separator.
// This separator is a string and will do no white-space
// stripping.
// A suggested value for English speakers is the non-ascii
// character ''.
inlineCodeMarker: null,
// This lets you set up language aliases. For example,
// setting this to '{ sh: "bash" }' will let you use
// the language "sh" which will highlight using the
// bash highlighter.
aliases: {},
// This toggles the display of line numbers globally alongside the code.
// To use it, add the following line in src/layouts/index.js
// right after importing the prism color scheme:
// `require("prismjs/plugins/line-numbers/prism-line-numbers.css");`
// Defaults to false.
// If you wish to only show line numbers on certain code blocks,
// leave false and use the {numberLines: true} syntax below
showLineNumbers: false,
// If setting this to true, the parser won't handle and highlight inline
// code used in markdown i.e. single backtick code like `this`.
noInlineHighlight: false,
},
},
],
},
},
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`,
},
},
{
resolve: `@gatsby-contrib/gatsby-plugin-elasticlunr-search`,
options: {
// Fields to index
fields: [`title`, `name`, `scope`, `route`, `method`],
// How to resolve each field`s value for a supported node type
resolvers: {
// For any node of type MarkdownRemark, list how to resolve the fields` values
MarkdownRemark: {
title: (node) => node.frontmatter.title,
name: (node) => node.frontmatter.name,
slug: (node) =>
`#${node.frontmatter.scope ? node.frontmatter.scope + "-" : ""}${
node.fields.idName
}`,
route: (node) => `${node.frontmatter.route}`,
method: (node) => `${node.frontmatter.example}`,
type: (node) => node.frontmatter.type || "API",
version: (node) => node.fields.version,
},
},
},
},
],
};

View File

@@ -0,0 +1,55 @@
const path = require(`path`);
const _ = require("lodash");
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.onCreateNode = ({ node, getNode, actions }, pluginOptions) => {
const { createNodeField } = actions;
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `pages` });
const parent = getNode(node.parent);
const idName = _.kebabCase(node.frontmatter.title || parent.name);
createNodeField({
node,
name: `slug`,
value: slug
});
createNodeField({
node,
name: `idName`,
value: idName
});
// save the file's directory so it can be used by the Template
// component to group data in a GraphQL query
createNodeField({
node,
name: `parentRelativeDirectory`,
value: parent.relativeDirectory
});
// set a version field on pages so they can be queried
// appropriately in the Template component
let version = pluginOptions.currentVersion;
if (parent.gitRemote___NODE) {
const { sourceInstanceName } = getNode(parent.gitRemote___NODE);
version = sourceInstanceName;
}
createNodeField({
node,
name: `version`,
value: version
});
}
};
exports.createPages = async ({ actions, graphql }, pluginOptions) => {
actions.createPage({
path: `/`,
component: path.resolve(`./src/components/template.js`)
});
};

View File

@@ -0,0 +1,33 @@
{
"name": "discordphp-docs",
"description": "Documentation site for DiscordPHP",
"license": "MIT",
"scripts": {
"develop": "gatsby develop",
"start": "npm run develop",
"build": "gatsby build",
"serve": "gatsby serve"
},
"devDependencies": {
"@gatsby-contrib/gatsby-plugin-elasticlunr-search": "^2.2.1",
"gatsby": "^2.19.12",
"gatsby-plugin-react-helmet": "^3.0.12",
"gatsby-plugin-typography": "^2.2.6",
"gatsby-remark-prismjs": "^3.2.6",
"gatsby-source-filesystem": "^2.0.28",
"gatsby-source-git": "^1.0.2",
"gatsby-transformer-remark": "^2.3.8",
"html-react-parser": "^0.10.1",
"lodash": "^4.17.15",
"marked": "^4.0.10",
"prismjs": "^1.16.0",
"react": "^16.8.6",
"react-debounce-render": "^6.0.0",
"react-dom": "^16.8.6",
"react-helmet": "^5.2.0",
"react-typography": "^0.16.18",
"title-case": "^3.0.2",
"typography": "^0.16.18",
"typography-theme-github": "^0.16.19"
}
}

View File

@@ -0,0 +1,45 @@
import React from 'react';
import apiStyles from "./api.module.css";
export default class NodeList extends React.Component {
constructor(props) {
super(props);
this.titleNode = this.props.nodes.shift();
}
isActive() {
return this.props.getCurrentTitle() === this.titleNode.fields.idName;
}
onTitleClick() {
this.props.onTitleClick(this.titleNode);
}
createMenuItemName(node) {
return `${this.titleNode.fields.idName}/${node.fields.idName}`;
}
render() {
return (
<li>
<a
href={`#${this.titleNode.fields.idName}`}
onClick={this.onTitleClick.bind(this)}
class={this.isActive() ? apiStyles.activelink : undefined}
>
{this.titleNode.frontmatter.title}
</a>
<ol className={this.isActive() ? undefined : apiStyles.subhidden}>
{this.props.nodes.map(node => (
<li key={node.id}>
<a href={`#${node.fields.idName}`}>
{node.frontmatter.title}
</a>
</li>
))}
</ol>
</li>
);
}
}

View File

@@ -0,0 +1,114 @@
import React, { Component } from "react";
import apiStyles from "./api.module.css";
import _ from 'lodash';
import NodeList from "./NodeList";
export default class Api extends Component {
constructor(props) {
super(props);
this.state = {
activeSubMenu: null,
activeMenuItem: null,
};
this.setActiveSubMenu = this.setActiveSubMenu.bind(this);
this.isActiveSubMenu = this.isActiveSubMenu.bind(this);
this.getActiveMenuItem = this.getActiveMenuItem.bind(this);
this.onVisibleEndPoint = this.onVisibleEndPoint.bind(this);
this.onVisibleEndPointGroup = this.onVisibleEndPointGroup.bind(this);
this.subMenus = [];
}
setActiveSubMenu(id) {
this.setState({
activeSubMenu: id,
});
}
setActiveMenuItem(id) {
this.setState({
activeMenuItem: id,
});
}
getActiveMenuItem() {
return this.state.activeMenuItem;
}
isActiveSubMenu(id) {
return this.state.activeSubMenu === id;
}
hasActiveApiMenu() {
return this.state.activeMenuItem || this.state.activeSubMenu;
}
onVisibleEndPointGroup(id) {
this.setActiveSubMenu(id);
this.setActiveMenuItem(id);
}
onVisibleEndPoint(id) {
this.setActiveMenuItem(id);
}
getNavigation() {
return _.groupBy(this.props.data.staticMethods.edges, ({ node }) => {
const slugs = node.fields.slug.slice(1, -1).split('/');
return slugs[0];
});
}
renderNavigation([ head, nodes ]) {
if (nodes.length > 1) {
return (
<NodeList
nodes={nodes.map(({ node }) => node)}
onTitleClick={(title) => this.setState({
activeSubMenu: title.fields.idName
})}
getCurrentTitle={() => this.state.activeSubMenu}
/>
);
} else {
return (({ node }) => (
<li key={node.id}>
<a
href={`#${node.fields.idName}`}
onClick={() => this.setState({ activeSubMenu: undefined })}
>
{node.frontmatter.title}
</a>
</li>
))(nodes[0]);
}
}
render() {
return (
<React.Fragment>
<nav className={apiStyles.nav}>
<ol className={this.props.isMenuActive() ? "" : apiStyles.hidden}>
{Object.entries(this.getNavigation()).map(this.renderNavigation.bind(this))}
</ol>
</nav>
<main className={apiStyles.container}>
<h1>DiscordPHP</h1>
{this.props.data.staticMethods.edges.map(({ node }) => {
return (
<React.Fragment key={node.id}>
<h2 id={node.fields.idName}>{node.frontmatter.title}</h2>
<div
className={apiStyles.section}
dangerouslySetInnerHTML={{ __html: node.html }}
/>
</React.Fragment>
);
})}
</main>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,164 @@
.container {
--description-background-color: white;
--code-background-color: #191a18;
--code-foreground-color: white;
padding: 1.25rem 1rem;
}
.table {
max-width: 100%;
overflow-x: auto;
}
main *[id]:before {
display: block;
content: " ";
margin-top: -5rem;
height: 5rem;
visibility: hidden;
}
main h2:first-child {
margin-top: 0;
}
.container pre {
background-color: var(--code-background-color);
color: var(--code-foreground-color);
padding: calc(1.45em / 2) 1.45em;
width: 100%;
overflow-x: auto;
}
@media (min-width: 55em) {
.container {
padding: 0;
}
main {
--description-background-color: white;
--code-background-color: #0a0b09;
--code-foreground-color: white;
background-image: linear-gradient(
90deg,
var(--description-background-color) 0%,
var(--description-background-color) 50%,
var(--code-background-color) 50%,
var(--code-background-color) 100%
);
}
.section {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 2.9em;
}
.section > :not([data-language]) {
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
grid-column: 1/2;
padding-bottom: 0.11rem;
}
.section > [data-language] {
overflow-x: auto;
grid-column: 2/3;
background-color: var(--code-background-color);
color: var(--code-foreground-color);
}
.section > [data-language] pre {
margin: 0;
padding: 0;
}
}
.nav {
position: sticky;
top: 0rem;
background-color: #eee;
padding: 0;
/* Give the navigation a maximum height, so the “stickyness” will have an effect. */
max-height: calc(100vh);
overflow-y: auto;
/* TBD: Would it better to limit the navigation height so that all of the items
are visible when scrolled to the top of the page?
max-height: calc(100vh - var(--header-height-in-ems)); */
/* TBD: Is it useful to use em units here? (so that it will scale with the font size)
Are there other places where were using pixel values that make this moot?
--header-height-in-ems: calc(var(--header-height) / var(--font-size) * 1em); */
/* TBD: Should these value come from a custom property instead?
--header-height: 102.5;
--font-size: 20; */
}
.nav h1 {
display: inline;
}
.nav button {
display: block;
margin-bottom: 0.75em;
}
.nav a:not(:hover):not(:active):not(:focus) {
color: inherit;
}
.nav a {
text-shadow: none;
background-image: none;
text-decoration: none;
display: block;
}
.nav > ol {
padding: 1rem !important;
}
.nav ol,
.nav li {
list-style: none;
margin-left: 0;
padding-left: 0;
}
.nav li li {
/* padding-left: 1.45rem; */
font-size: 0.875em;
}
.subhidden {
display: none !important;
}
.activelink {
position: sticky;
top: 0;
display: block;
background-color: white;
border-bottom: 1px solid hsla(0, 0%, 0%, 0.12); /* Copied from the table style in the main content area */
}
.activemenuitem {
font-weight: bold;
}
.deprecated {
background-color: #ffe7e8;
padding: 1.25rem;
border-radius: 0.25rem;
margin-bottom: 1rem;
}
/* Hide the navigation on small screens, until the toggle button is pressed */
@media (max-width: 55em) {
/* --wide-enough-for-two-columns */
.hidden {
display: none !important;
}
}

View File

@@ -0,0 +1,40 @@
import React, { Component } from "react";
import layoutStyles from "../components/layout.module.css";
import "../components/layout.css";
import Api from "../components/api";
export default class IndexPage extends Component {
constructor(props) {
super(props);
this.state = {
menuActive: false,
};
this.onToggleMenu = this.onToggleMenu.bind(this);
this.isMenuActive = this.isMenuActive.bind(this);
}
onToggleMenu() {
this.setState({
menuActive: !this.state.menuActive,
});
}
isMenuActive() {
return this.state.menuActive;
}
render() {
return (
<div>
<div className={layoutStyles.container}>
<Api
data={this.props.data}
isMenuActive={this.isMenuActive}
></Api>
</div>
</div>
);
}
}

View File

@@ -0,0 +1,167 @@
header {
--header-background-color: #fff;
--input-background-color: #eee;
display: flex;
background-color: var(--header-background-color);
color: white;
position: sticky;
z-index: 1;
top: 0;
border-bottom: 3px solid #fff;
}
header h1 {
grid-column: 2/3;
grid-row: 1/2;
color: inherit;
margin: 0;
font-size: 1.125rem;
align-self: center;
text-align: right;
}
@media (min-width: 55em) {
/* The breakpoint when the navigation is in the left column */
header {
grid-template-columns: calc(1.45em * 9) auto max-content; /* The width of the left column */
grid-column-gap: 2.9em;
}
header h1 {
text-align: left;
}
}
header > .search {
display: grid;
grid-template-rows: auto 1fr;
max-height: 100vh;
grid-column: 1/3;
grid-row: 1/2;
--whitespace: 1.25rem;
width: 100%;
position: relative;
z-index: 1;
}
header > .search .input {
background-color: var(--header-background-color);
color: #fff;
display: grid;
}
header > .search .input input {
display: block;
box-sizing: border-box;
width: 100%;
border: 0;
outline: none;
background: var(--input-background-color);
padding: 0.1rem var(--whitespace);
grid-row: 1/-1;
grid-column: 1/-1;
}
header .icon-search {
fill: currentColor;
grid-row: 1/-1;
grid-column: 1/-1;
align-self: center;
margin-left: 0.3rem;
width: 1em;
height: 1em;
font-size: 0.6em;
color: #000;
position: relative;
z-index: 1;
}
header > .search .input input::placeholder {
color: #000;
}
header > .search .results {
overflow-y: auto;
margin: 0;
background: white;
color: black;
list-style: none;
padding: 0 var(--whitespace);
width: 100%;
}
header > .search .results li:first-child {
padding-top: var(--whitespace);
}
header > .search .results li:last-child {
padding-bottom: var(--whitespace);
margin-bottom: 0;
}
header > .search .results li:last-child {
border-bottom: 3px solid #eee;
}
header > .search a {
color: inherit;
background: none;
display: block;
}
header > .search a:hover,
header > .search a:focus {
text-decoration: underline;
}
header > button {
grid-row: 1/2;
grid-column: -2/-1;
background: transparent;
color: #ddd;
border: 0;
padding: 0 1rem;
cursor: pointer;
height: 2rem;
}
header > button:hover,
header > button:active,
header > button:focus {
color: #1ca086;
}
/* Set table-layout: fixed for small screens where table contents can break out of their container */
table {
table-layout: fixed;
}
/* Hide the navigation toggle button on big screens, since its not needed */
@media (min-width: 55em) {
/* --wide-enough-for-two-columns */
header > .search {
grid-column: 1/-1;
}
header button {
display: none !important;
}
}
header > button > svg {
fill: currentColor;
vertical-align: middle;
}
/* override prism default css */
main :not(pre) > code[class*="language-"] {
color: #000;
padding: 0.2em 0.4em;
border-radius: 3px;
white-space: normal;
background: #1b1f230d;
text-shadow: none;
font-size: 85%;
overflow-wrap: break-word;
word-break: break-word;
}

View File

@@ -0,0 +1,29 @@
.container > header {
margin-bottom: 1.5rem;
}
.hidden {
opacity: 0;
}
@media (min-width: 55em) {
/* --wide-enough-for-two-columns */
.container {
display: grid;
grid-column-gap: 2.9em;
grid-template-columns: calc(1.45em * 9) 2fr;
}
.container > nav {
grid-column: 1/2;
}
.container > main {
grid-column: 2/3;
}
}
.versionDropdown {
display: flex;
align-items: flex-start;
}

View File

@@ -0,0 +1,41 @@
import React, { Fragment } from "react";
import { Helmet } from "react-helmet";
import { graphql } from "gatsby";
import IndexPage from "./index-page";
export default ({ data }) => {
return (
<Fragment>
<Helmet>
<meta charset="utf-8" />
<title>DiscordPHP</title>
</Helmet>
<IndexPage data={data} />
</Fragment>
);
};
export const query = graphql`
query {
# staticMethods are pages sourced from this repo
staticMethods: allMarkdownRemark(
sort: { fields: fields___slug }
) {
edges {
node {
id
frontmatter {
title
}
html
fields {
idName
slug
}
}
}
}
}
`;

View File

@@ -0,0 +1,75 @@
---
title: "Intro"
---
DiscordPHP is a wrapper for the Discord REST, WebSocket and Voice APIs. Built on top of [ReactPHP](https://reactphp.org/) components. This documentation is based off the latest release.
The class reference has moved. You can now access it [here](http://discord-php.github.io/DiscordPHP/guide/).
### Requirements
- PHP 7.4 CLI
- Will not run on a webserver (FPM, CGI), you must run through CLI. A bot is a long-running process.
- 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](https://microsoft.github.io/language-server-protocol/).
A list of supported editors can be found [here](https://microsoft.github.io/language-server-protocol/implementors/servers/).
Here are some commonly used editors:
- Visual Studio Code (built-in LSP support)
- Vim/Neovim (with the [coc.nvim](https://github.com/neoclide/coc.nvim) plugin for LSP support)
- PHPStorm (built-in PHP support)
We recommend installing [PHP Intelephense](https://intelephense.com/) 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](https://getcomposer.org).
To install the latest release:
```shell
> composer require team-reflex/discord-php
```
If you would like to run on the latest `master` branch:
```shell
> 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](https://reactphp.org/promise/).
### Help
If you need any help, feel free to join the [PHP Discorders](https://discord.gg/dphp) 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

View File

@@ -0,0 +1,39 @@
---
title: "FAQ"
---
### `Class 'X' not found`
You most likely haven't imported the class that you are trying to use. Please check the [class reference](http://discord-php.github.io/DiscordPHP/guide/) and search for the class that you are trying to use. Add an import statement at the top of the file like shown on the right.
```php
<?php
use Discord\X;
```
If you don't want to have to import a class every time, you should look into the PHP Intelephense language server (written above) which will do automatic imports for you.
### There are less members and/or users than expected
Server members are guarded by a priviliged server intent which must be enabled in the [Discord Developer Portal](https://discord.com/developers/applications). 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.
```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).
```php
$discord = new Discord([
'token' => '...',
'loadAllMembers' => true,
'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS // Enable the `GUILD_MEMBERS` intent
])
```

View File

@@ -0,0 +1,162 @@
---
title: "Basics"
---
First step is to include the Composer autoload file and [import](https://www.php.net/manual/en/language.namespaces.importing.php) any required classes.
```php
<?php
use Discord\Discord;
use Discord\WebSockets\Intents;
use Discord\WebSockets\Event;
include __DIR__.'/vendor/autoload.php';
```
<br>
The Discord instance can be set up with an array of options. All are optional except for token:
```php
$discord = new Discord([
```
`token` is your Discord token. **Required**.
```php
'token' => 'Your-Token-Here',
```
`intents` can be an array of valid intents _or_ an integer representing the intents. Default is all intents minus any privileged intents.
At the moment this means all intents minus `GUILD_MEMBERS` and `GUILD_PRESENCES`. To enable these intents you must first enable them in your
Discord developer portal.
```php
'intents' => [
Intents::GUILDS, Intents::GUILD_BANS, // ...
],
// or
'intents' => 12345,
// or
'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, // default intents as well as guild members
```
`loadAllMembers` is a boolean whether all members should be fetched and stored on bot start.
Loading members takes a while to retrieve from Discord and store, so default is false.
This requires the `GUILD_MEMBERS` intent to be enabled in DiscordPHP. See above for more details.
```php
'loadAllMembers' => false,
```
`storeMessages` is a boolean whether messages received and sent should be stored. Default is false.
```php
'storeMessages' => false,
```
`retrieveBans` is a boolean whether bans should be retrieved on bot load. Default is false.
```php
'retrieveBans' => false,
```
`pmChannels` is a boolean whether PM channels should be stored on bot load. Default is false.
```php
'pmChannels' => false,
```
`disabledEvents` is an array of events that will be disabled. By default all events are enabled.
```php
'disabledEvents' => [
Event::MESSAGE_CREATE, Event::MESSAGE_DELETE, // ...
],
```
`loop` is an instance of a ReactPHP event loop that can be provided to the client rather than creating a new loop.
Useful if you want to use other React components. By default, a new loop is created.
```php
'loop' => \React\EventLoop\Factory::create(),
```
`logger` is an instance of a logger that implements `LoggerInterface`. By default, a new Monolog logger with log level DEBUG is created to print to stdout.
```php
'logger' => new \Monolog\Logger('New logger'),
```
`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.
```php
'dnsConfig' => '1.1.1.1',
```
<hr>
The following options should only be used by large bots that require sharding. If you plan to use sharding, [read up](https://discord.com/developers/docs/topics/gateway#sharding) on how Discord implements it.
`shardId` is the ID of the bot shard.
```php
'shardId' => 0,
```
`shardCount` is the number of shards that you are using.
```php
'shardCount' => 5,
```
```
]);
```
<hr>
Gateway events should be registered inside the `ready` event, which is emitted once when the bot first starts and has connected to the gateway.
```php
$discord->on('ready', function (Discord $discord) {
```
To register an event we use the `$discord->on(...)` function, which registers a handler.
A list of events is available [here](https://github.com/discord-php/DiscordPHP/blob/master/src/Discord/WebSockets/Event.php#L30-L75). 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.
```php
$discord->on(Event::MESSAGE_CREATE, function (Message $message, Discord $discord) {
// ... handle message sent
});
```
```
});
```
<br>
Finally, the event loop needs to be started. Treat this as an infinite loop.
```php
$discord->run();
```
<div>
If you want to stop the bot you can run:
```php
$discord->close();
```
If you want to stop the bot without stopping the event loop, the close function takes a boolean:
```php
$discord->close(false);
```
</div>

View File

@@ -0,0 +1,17 @@
---
title: "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](https://discord.com/developers/applications)) 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.

View File

@@ -0,0 +1,17 @@
---
title: "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!
```php
// use Discord\Parts\Interactions\Command\Overwrite;
$discord->on(Event::APPLICATION_COMMAND_PERMISSIONS_UPDATE, function (Overwrite $overwrite, Discord $discord, ?Overwrite $oldOverwrite) {
// ...
});
```

View File

@@ -0,0 +1,53 @@
---
title: "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.
```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.
```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.
```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).
```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.

View File

@@ -0,0 +1,117 @@
---
title: "Channels"
---
Requires the `Intents::GUILDS` intent.
### Channel Create
Called with a `Channel` object when a new channel is created, relevant to the Bot.
```php
$discord->on(Event::CHANNEL_CREATE, function (Channel $channel, Discord $discord) {
// ...
});
```
### Channel Update
Called with two `Channel` objects when a channel is updated.
```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.
```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.
```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.
```php
$discord->on(Event::THREAD_CREATE, function (Thread $thread, Discord $discord) {
// ...
});
```
### Thread Update
Called with a `Thread` object when a thread is updated.
```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.
```php
$discord->on(Event::THREAD_DELETE, function (?Thread $thread, Discord $discord) {
// ...
});
```
### Thread List Sync
Called when list of threads are synced.
```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.
```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.
```php
$discord->on(Event::THREAD_MEMBERS_UPDATE, function (Thread $thread, Discord $discord) {
// ...
});
```

View File

@@ -0,0 +1,276 @@
---
title: "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.
```php
$discord->on(Event::GUILD_CREATE, function (Guild $guild, Discord $discord) {
// ...
});
```
### Guild Update
Called with two `Guild` objects when a guild is updated.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```php
$discord->on(Event::INTEGRATION_DELETE, function (?Integration $integration, Discord $discord) {
// ...
});
```

View File

@@ -0,0 +1,35 @@
---
title: "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.
```php
$discord->on(Event::INVITE_CREATE, function (Invite $invite, Discord $discord) {
// ...
});
```
### Invite Delete
Called with an object when an invite is created.
```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
// }
}
});
```

View File

@@ -0,0 +1,18 @@
---
title: "Interactions"
---
### Interaction Create
Called with an `Interaction` object when an interaction is created.
```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.

View File

@@ -0,0 +1,121 @@
---
title: "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.
```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.
```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.
```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.
```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.
```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.
```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.
```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.
```php
$discord->on(Event::MESSAGE_REACTION_REMOVE_EMOJI, function (MessageReaction $reaction, Discord $discord) {
// ...
});
```

View File

@@ -0,0 +1,39 @@
---
title: "Presences"
---
### Presence Update
Called with a `PresenceUpdate` object when a member's presence is updated.
```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.
```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.
```php
$discord->on(Event::USER_UPDATE, function (User $user, Discord $discord, ?User $oldUser) {
// ...
});
```

View File

@@ -0,0 +1,35 @@
---
title: "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").
```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.
```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).
```php
$discord->on(Event::STAGE_INSTANCE_DELETE, function (StageInstance $stageInstance, Discord $discord) {
// ...
});
```

View File

@@ -0,0 +1,29 @@
---
title: "Voices"
---
### Voice State Update
Called with a `VoiceStateUpdate` object when a member joins, leaves or moves between voice channels.
```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.
```php
// use Discord\Parts\WebSockets\VoiceServerUpdate;
$discord->on(Event::VOICE_SERVER_UPDATE, function (VoiceServerUpdate $guild, Discord $discord) {
// ...
});
```

View File

@@ -0,0 +1,15 @@
---
title: "Webhooks"
---
### Webhooks Update
Called with a `Guild` and `Channel` object when a guild channel's webhooks are is created, updated, or deleted.
```php
$discord->on(Event::WEBHOOKS_UPDATE, function (?Guild $guild, Discord $discord, ?Channel $channel) {
// ...
});
```
Requires the `Intents::GUILD_WEBHOOKS` intent.

View File

@@ -0,0 +1,90 @@
---
title: "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.
```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 |
```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 |
```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 |
```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 |
```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) {
// ...
});
```

View File

@@ -0,0 +1,54 @@
---
title: "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:
```php
$message = new Message($discord);
// or
$message = $discord->factory->create(Message::class);
```
<br>
Part attributes can be accessed similar to an object or like an array:
```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.
```php
$message->fill([
'content' => 'hello!',
]);
```
### Getting the raw attributes of a part
The `->getRawAttributes()` function returns the array representation of the part.
```php
$attributes = $message->getRawAttributes();
/**
* [
* "id" => "",
* "content" => "",
* // ...
* ]
*/
```

View File

@@ -0,0 +1,131 @@
---
title: "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 |
```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
| name | type | description |
| ------ | ------------------- | --------------------------- |
| member | Member or member ID | The member to get ownership |
| reason | string | Reason for Audit Log |
```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
| name | type | description |
| ------- | ----------------- | ----------------- |
| user_id | `User` or user ID | The user to unban |
```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
| 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 |
```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
| 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 | [] |
```php
$guild->createEmoji([
'name' => 'elephpant',
// ...
],
'/path/to/file.jpg',
'audit-log reason'
)->done(function (Emoji $emoji) {
// ...
});
```

View File

@@ -0,0 +1,363 @@
---
title: "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 | [] |
```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
| 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 |
```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
| name | type | description | default |
| ------ | --------------------------- | ------------------ | -------- |
| member | [Member](#member) or string | The member to move | required |
```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
| name | type | description | default |
| ------ | --------------------------- | ------------------------- | -------- |
| member | [Member](#member) or string | The member to mute/unmute | required |
```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
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 | |
```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
| 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 | |
```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
| 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 |
```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
| name | type | description | default |
| ------ | ------ | ------------------------------------------------ | -------- |
| value | int | number of messages to delete, in the range 1-100 | required |
| reason | string | Reason for Audit Log | |
```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
| name | type | description | default |
| ------- | ------------------- | ------------------------ | -------- |
| message | [Message](#message) | The message to pin/unpin | required |
| reason | string | Reason for Audit Log | |
```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.
```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
| name | type | description | default |
| ------- | ------------------------------ | -------------------------- | -------- |
| message | MessageBuilder | Message content | required |
```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
| name | type | description | default |
| ----- | --------------- | ----------------- | -------- |
| embed | [Embed](#embed) | The embed to send | required |
```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.
```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
| name | type | description | default |
| ------- | -------- | ------------------------------------- | -------- |
| filter | callable | The callback to call on every message | required |
| options | array | Array of options | [] |
```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.
```php
$channel->getPinnedMessages()->done(function (Collection $messages) {
foreach ($messages as $message) {
// $message->...
}
});
```

View File

@@ -0,0 +1,203 @@
---
title: "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:
```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 |
```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
| name | type | description |
| ---- | ------ | --------------------------------------------------- |
| nick | string | nickname of the member, null to clear, default null |
```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
| name | type | description |
| ------- | ----------------------------- | --------------------------------- |
| channel | [Channel](#channel) or string | the channel to move the member to |
```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
| name | type | description |
| ---- | ----------------------- | ----------------------------- |
| role | [Role](#role) or string | the role to add the member to |
```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
| name | type | description |
| ---- | ----------------------- | ----------------------------- |
| role | [Role](#role) or string | the role to remove the member from |
```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
| name | type | description |
| ---------------------------- | ------------------ | -------------------------------- |
| communication_disabled_until | `Carbon` or `null` | the time for timeout to lasts on |
```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
| name | type | description |
| ------- | --------------------------- | ------------------------------------------------ |
| channel | [Channel](#channel) or null | the channel to get the effective permissions for |
```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
| 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 |
```php
$url = $member->getAvatarAttribute('png', 2048);
echo $url; // https://cdn.discordapp.com/guilds/:guild_id/users/:id/avatars/:avatar_hash.png?size=2048
```

View File

@@ -0,0 +1,235 @@
---
title: "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 |
```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.
```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
| name | type | description |
| ----- | ------ | -------------------------------------------------------- |
| text | string | text to send in the message |
| delay | int | time in milliseconds to delay before sending the message |
```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
| name | type | description |
| -------- | ------------------------- | ----------------------- |
| emoticon | [Emoji](#emoji) or string | the emoji to react with |
```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
| 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
```php
$message->deleteReaction(Message::REACT_DELETE_ALL)->done(function () {
// ...
});
```
#### Delete reaction by current user
```php
$message->deleteReaction(Message::REACT_DELETE_ME, $emoji)->done(function () {
// ...
});
```
#### Delete reaction by another user
```php
$message->deleteReaction(Message::REACT_DELETE_ID, $emoji, 'member_id')->done(function () {
// ...
});
```
#### Delete all reactions of one emoji
```php
$message->deleteReaction(Message::REACT_DELETE_EMOJI, $emoji)->done(function () {
// ...
});
```
### Delete the message
Deletes the message. Returns nothing in a promise.
```php
$message->delete()->done(function () {
// ...
});
```
### Edit the message
Updates the message. Takes a message builder. Returns the updated message in a promise.
```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 |
```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
| name | type | description |
| ----- | --------------- | ---------------- |
| embed | [Embed](#embed) | the embed to add |
```php
$message->addEmbed($embed)->done(function (Message $message) {
// ...
});
```

View File

@@ -0,0 +1,89 @@
---
title: "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.
```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 |
```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
| 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 |
```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
| 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 |
```php
$url = $user->getBannerAttribute('png', 1024);
echo $url; // https://cdn.discordapp.com/banners/:user_id/:banner_hash.png?size=1024
```

View File

@@ -0,0 +1,233 @@
---
title: "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.
<div>
Collections implement interfaces allowing them to be accessed like arrays, such as:
```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)
```
</div>
#### 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 |
```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 |
```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 |
```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 |
```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.
```php
$collec = new Collection([], null, null);
$collec->fill([
1, 2, 3, 4,
]);
```
#### Number of items
Returns the number of items in the collection.
```php
$collec = new Collection([
1, 2, 3
], null, null);
echo $collec->count(); // 3
```
#### Getting the first item
Gets the first item of the collection.
```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 |
```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.
```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 |
```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.
```php
$arr = $collec->toArray();
```

View File

@@ -0,0 +1,109 @@
---
title: "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.
```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`

View File

@@ -0,0 +1,118 @@
---
title: "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:
```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.
```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.
```php
$builder->setContent('Hello, world!');
```
#### Setting TTS value
Sets the TTS value of the message.
```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:
```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.
```php
$embeds = [...];
$builder->setEmbeds($embeds);
```
#### Replying to a message
Sets the message as replying to another message. Takes a `Message` object.
```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.
```php
$builder->addFile('/path/to/file', 'file.png');
```
You can also add files to messages with the content as a string:
```php
$builder->addFileFromContent('file.txt', 'contents of my file!');
```
You can also remove all files from a builder:
```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.
```php
$builder->addSticker($sticker);
```
To remove a sticker:
```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.
```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.
```php
$component = SelectMenu::new();
$builder->addComponent($component);
```

View File

@@ -0,0 +1,167 @@
---
title: "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.
```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`.
```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 |
![Discord button styles](https://discord.com/assets/7bb017ce52cfd6575e21c058feb3883b.png)
### 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.
```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:
```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.
```php
$select = SelectMenu::new()
->addOption(Option::new('me?'))
->addOption(Option::new('or me?'));
```
### 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.
```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.
```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
| 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. |

View File

@@ -0,0 +1,54 @@
---
title: "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](https://discord.com/developers/docs/reference#locales).
### 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<void>` |
| `getOriginalResponse()` | gets the original interaction response | `Promise<Message>` |
| `updateOriginalResponse(MessageBuilder $message)` | updates the original interaction response | `Promise<Message>` |
| `deleteOriginalResponse()` | deletes the original interaction response | `Promise<void>` |
| `sendFollowUpMessage(MessageBuilder $builder, ?bool $ephemeral)` | sends a follow up message to the interaction. ephemeral is defalt false | `Promise<Message>` |
| `getFollowUpMessage(string $message_id)` | gets a non ephemeral follow up message from the interaction | `Promise<Message>` |
| `updateFollowUpMessage(string $message_id, MessageBuilder $builder)` | updates the follow up message of the interaction | `Promise<Message>` |
| `deleteFollowUpMessage(string $message_id)` | deletes a follow up message from the interaction | `Promise<void>` |

View File

@@ -0,0 +1,5 @@
import kebabCase from "lodash/kebabCase";
export function createGroupIdName({ fieldValue }) {
return kebabCase(fieldValue.slice("docs/".length));
}

View File

@@ -0,0 +1,6 @@
import Typography from "typography";
import githubTheme from "typography-theme-github";
const typography = new Typography(githubTheme);
export default typography;

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,3 @@
<html>
<meta http-equiv="refresh" content="0; url=../guide">
</html>

View File

@@ -0,0 +1,75 @@
<?php
/**
* Example Bot with Discord-PHP and ReactPHP HTTP Browser
*
* When an User says "discordstatus", the Bot will reply Discord service status
*
* @see https://reactphp.org/http/#browser
*
* Run this example bot from main directory using command:
* php examples/browser.php
*/
include __DIR__.'/../vendor/autoload.php';
// Import classes, install a LSP such as Intelephense to auto complete imports
use Discord\Discord;
use Discord\Parts\Channel\Message;
use Psr\Http\Message\ResponseInterface;
use React\Http\Browser;
// Create a $discord BOT
$discord = new Discord([
'token' => '', // Put your Bot token here from https://discord.com/developers/applications/
]);
// Create a $browser with same loop as $discord
$browser = new Browser(null, $discord->getLoop());
// When the Bot is ready
$discord->on('ready', function (Discord $discord) {
// Listen for messages
$discord->on('message', function (Message $message, Discord $discord) {
// Ignore messages from any Bots
if ($message->author->bot) return;
// If message is "discordstatus"
if ($message->content == 'discordstatus') {
// Get the $browser from global scope
global $browser;
// Make GET request to API of discordstatus.com
$browser->get('https://discordstatus.com/api/v2/status.json')->then(
function (ResponseInterface $response) use ($message) { // Request success
// Get response body
$result = (string) $response->getBody();
// Uncomment to debug result
//var_dump($result);
// Parse JSON
$discordstatus = json_decode($result);
// Send reply about the discord status
$message->reply('Discord status: ' . $discordstatus->status->description);
},
function (Exception $e) use ($message) { // Request failed
// Uncomment to debug exceptions
//var_dump($e);
// Send reply about the discord status
$message->reply('Unable to acesss the Discord status API :(');
}
);
}
});
});
// Start the Bot (must be at the bottom)
$discord->run();

View File

@@ -0,0 +1,46 @@
<?php
/**
* Example Bot with Discord-PHP
*
* When an User says "ping", the Bot will reply "pong"
*
* Run this example bot from main directory using command:
* php examples/ping.php
*/
include __DIR__.'/../vendor/autoload.php';
// Import classes, install a LSP such as Intelephense to auto complete imports
use Discord\Discord;
use Discord\Parts\Channel\Message;
// Create a $discord BOT
$discord = new Discord([
'token' => '', // Put your Bot token here from https://discord.com/developers/applications/
]);
// When the Bot is ready
$discord->on('ready', function (Discord $discord) {
// Listen for messages
$discord->on('message', function (Message $message, Discord $discord) {
// If message is from a bot
if ($message->author->bot) {
// Do nothing
return;
}
// If message is "ping"
if ($message->content == 'ping') {
// Reply with "pong"
$message->reply('pong');
}
});
});
// Start the Bot (must be at the bottom)
$discord->run();

View File

@@ -0,0 +1,105 @@
======
Basics
======
First step is to include the Composer autoload file and `import <https://www.php.net/manual/en/language.namespaces.importing.php>`_ any required classes.
.. code:: php
<?php
use Discord\Discord;
use Discord\WebSockets\Intents;
use Discord\WebSockets\Event;
include __DIR__.'/vendor/autoload.php';
The Discord instance can be set up with an array of options. All are optional except for token:
.. code:: php
$discord = new Discord([
'token' => 'Your-Token-Here',
'intents' => [
Intents::GUILDS, Intents::GUILD_BANS, // ...
],
// or
'intents' => 12345,
// or
'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, // default intents as well as guild members
'loadAllMembers' => false,
'storeMessages' => false,
'retrieveBans' => false,
'pmChannels' => false,
'disabledEvents' => [
Event::MESSAGE_CREATE, Event::MESSAGE_DELETE, // ...
],
'loop' => \React\EventLoop\Factory::create(),
'logger' => new \Monolog\Logger('New logger'),
'dnsConfig' => '1.1.1.1',
'shardId' => 0,
'shardCount' => 5,
]);
``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 <https://discord.com/developers/docs/topics/gateway#sharding>`_ 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 <https://github.com/discord-php/DiscordPHP/blob/master/src/Discord/WebSockets/Event.php#L30-L75>`_. 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);

View File

@@ -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();

View File

@@ -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. |
+----------------------------------+-------------------------------------------------------------------------------------------------------------+

View File

@@ -0,0 +1,19 @@
====================
Application Commands
====================
Application Command Permissions Update
======================================
Called with an ``Overwrite`` object when an application commands 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) {
// ...
});

View File

@@ -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.

View File

@@ -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) {
// ...
});

View File

@@ -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 guilds 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 guilds 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) {
// ...
});

View File

@@ -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 <https://discord.com/developers/applications>`_) 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.

View File

@@ -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.

View File

@@ -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
// }
}
});

View File

@@ -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 wont 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) {
// ...
});

View File

@@ -0,0 +1,44 @@
=========
Presences
=========
Presence Update
===============
Called with a ``PresenceUpdate`` object when a members 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 Bots user properties change.
.. code:: php
$discord->on(Event::USER_UPDATE, function (User $user, Discord $discord, ?User $oldUser) {
// ...
});

View File

@@ -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) {
// ...
});

View File

@@ -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) {
// ...
});

View File

@@ -0,0 +1,18 @@
========
Webhooks
========
Webhooks Update
===============
Called with a ``Guild`` and ``Channel`` object when a guild channels 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.

43
vendor/team-reflex/discord-php/guide/faq.rst vendored Executable file
View File

@@ -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 <http://discord-php.github.io/DiscordPHP/namespaces/discord>`_ 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
<?php
use Discord\X;
If you don't want to have to import a class every time, you should look into the PHP Intelephense language server (written above) which will do automatic imports for you.
There are less members and/or users than expected
=================================================
Server members are guarded by a priviliged server intent which must be enabled in the `Discord Developer Portal <https://discord.com/developers/applications>`_. 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
])

View File

@@ -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 <https://reactphp.org/>`_ components. This documentation is based off the latest release.
Requirements
============
- `PHP 7.4 CLI<https://php.net>`_ 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<https://microsoft.github.io/language-server-protocol/>`_.
A list of supported editors can be found `here <https://microsoft.github.io/language-server-protocol/implementors/servers/>`_.
Here are some commonly used editors:
- Visual Studio Code (built-in LSP support)
- Vim/Neovim (with the `coc.nvim <https://github.com/neoclide/coc.nvim>`_ plugin for LSP support)
- PHPStorm (built-in PHP support)
We recommend installing `PHP Intelephense <https://intelephense.com/>`_ 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 <https://getcomposer.org>`_.
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 <https://reactphp.org/promise/>`_.
Help
====
If you need any help, feel free to join the `PHP Discorders <https://discord.gg/dphp>`_ 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

View File

@@ -0,0 +1,37 @@
Documentation
=============
Welcome to the documentation for phpDocumentor.
phpDocumentor is the de-facto documentation application for PHP projects. Your project can benefit too from more
than 20 years of experience and setting the standard for documenting PHP Applications.
With these tutorials, guides and references we aim to provide you with all the information that you need to optimally
document your code and leverage phpDocumentor to generate an extensive set of documentation for your application.
What does it do?
----------------
phpDocumentor analyzes the code of your application and generates a set of documentation that describes what each
element in your code does, what it expects and what it returns. With it, you can easily navigate through your codebase
and see how it works without having to read the actual code.
For an example on how that would look like, check the sidebar in
`our own documentation <https://docs.phpdoc.org/latest/>`_.
.. hint::
There is a new feature underway to render handwritten documentation, like the one you are reading now. Check this
space for updates in the coming months.
Where to start?
---------------
We have divided the documentation into 4 sections:
1. :doc:`getting-started/index`, which is a series of concise tutorials that will help you get running within minutes.
2. :doc:`guides/index`, these chapters provide in-depth information in the usage and all features of phpDocumentor.
3. :doc:`references/index`, here you can find the nitty-gritty lists of commonly used components, options and
configuration.
4. :doc:`internals/index`, care to contribute to phpDocumentor or interested in its architecture? Then this section
is for you.

View File

@@ -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 guilds preferred locale, if invoked in a guild. |
+----------------+----------------------+------------------------------------------------------+
The locale list can be seen on `Discord API reference <https://discord.com/developers/docs/reference#locales>`_.
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<void>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``getOriginalResponse()`` | gets the original interaction response | ``Promise<Message>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``updateOriginalResponse(MessageBuilder $message)`` | updates the original interaction response | ``Promise<Message>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``deleteOriginalResponse()`` | deletes the original interaction response | ``Promise<void>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``sendFollowUpMessage(MessageBuilder $builder, ?bool $ephemeral)`` | sends a follow up message to the interaction. ephemeral is defalt false | ``Promise<Message>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``getFollowUpMessage(string $message_id)`` | gets a non ephemeral follow up message from the interaction | ``Promise<Message>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``updateFollowUpMessage(string $message_id, MessageBuilder $builder)`` | updates the follow up message of the interaction | ``Promise<Message>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+
| ``deleteFollowUpMessage(string $message_id)`` | deletes a follow up message from the interaction | ``Promise<void>`` |
+------------------------------------------------------------------------+------------------------------------------------------------------------------------------------+----------------------+

View File

@@ -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);

View File

@@ -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->...
}
});

View File

@@ -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) {
// ...
});

View File

@@ -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" => "",
* // ...
* ]
*/

View File

@@ -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 guilds Membership Screening requirements |
+------------------------------+------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| communication_disabled_until | ``?Carbon`` | when the users 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

View File

@@ -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 hasnt 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 interactions 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) {
// ...
});

View File

@@ -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 users 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

View File

@@ -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``

View File

@@ -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) {
// ...
});

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" ?>
<phpdocumentor
configVersion="3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://www.phpdoc.org"
xsi:noNamespaceSchemaLocation="https://docs.phpdoc.org/latest/phpdoc.xsd"
>
<title>DiscordPHP Documentation</title>
<paths>
<output>build</output>
</paths>
<version number="latest">
<api>
<source dsn=".">
<path>src</path>
</source>
<output>reference</output>
</api>
<guide>
<source dsn=".">
<path>guide</path>
</source>
<output>guide</output>
</guide>
</version>
<setting name="guides.enabled" value="true"/>
</phpdocumentor>

26
vendor/team-reflex/discord-php/phpunit.xml vendored Executable file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="tests/bootstrap.php"
cacheResultFile=".phpunit.cache/test-results"
executionOrder="depends,defects"
forceCoversAnnotation="false"
beStrictAboutCoversAnnotation="false"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
failOnRisky="true"
failOnWarning="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<coverage cacheDirectory=".phpunit.cache/code-coverage"
processUncoveredFiles="true">
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>

View File

@@ -0,0 +1,268 @@
<?php
/*
* This file is a part of the DiscordPHP project.
*
* Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord\Builders;
use Discord\Parts\Interactions\Command\Command;
use Discord\Parts\Interactions\Command\Option;
use function Discord\poly_strlen;
/**
* Application Command attributes.
*
* @see Discord\Builders\CommandBuilder
* @see Discord\Parts\Interactions\Command\Command
*
* @property int $type The type of the command, defaults 1 if not set.
* @property string $name 1-32 character name of the command.
* @property ?string[]|null $name_localizations Localization dictionary for the name field. Values follow the same restrictions as name.
* @property string $description 1-100 character description for CHAT_INPUT commands, empty string for USER and MESSAGE commands.
* @property ?string[]|null $description_localizations Localization dictionary for the description field. Values follow the same restrictions as description.
* @property Collection|Option[]|null $options The parameters for the command, max 25. Only for Slash command (CHAT_INPUT).
* @property ?string $default_member_permissions Set of permissions represented as a bit set.
* @property bool|null $dm_permission Indicates whether the command is available in DMs with the app, only for globally-scoped commands. By default, commands are visible.
* @property ?bool $default_permission Whether the command is enabled by default when the app is added to a guild. SOON DEPRECATED.
*/
trait CommandAttributes
{
/**
* Sets the type of the command.
*
* @param int $type Type of the command.
*
* @throws \InvalidArgumentException `$type` is not 1-3.
*
* @return self
*/
public function setType(int $type): self
{
if ($type < 1 || $type > 3) {
throw new \InvalidArgumentException('Invalid type provided.');
}
$this->type = $type;
return $this;
}
/**
* Sets the name of the command.
*
* @param string $name Name of the command. Slash command names are lowercase.
*
* @throws \LengthException `$name` is not 1-32 characters long.
* @throws \DomainException `$name` contains invalid characters.
*
* @return self
*/
public function setName(string $name): self
{
$nameLen = poly_strlen($name);
if ($nameLen < 1) {
throw new \LengthException('Command name can not be empty.');
} elseif ($nameLen > 32) {
throw new \LengthException('Command name can be only up to 32 characters long.');
}
if (isset($this->type) && $this->type == Command::CHAT_INPUT && preg_match('/^[-_\p{L}\p{N}\p{Devanagari}\p{Thai}]{1,32}$/u', $name) === 0) {
throw new \DomainException('Slash command name contains invalid characters.');
}
$this->name = $name;
return $this;
}
/**
* Sets the name of the command in another language.
*
* @param string $locale Discord locale code.
* @param string|null $name Localized name of the command. Slash command names are lowercase.
*
* @throws \LengthException `$name` is not 1-32 characters long.
* @throws \DomainException `$name` contains invalid characters.
*
* @return self
*/
public function setNameLocalization(string $locale, ?string $name): self
{
if (isset($name)) {
$nameLen = poly_strlen($name);
if ($nameLen < 1) {
throw new \LengthException('Command name can not be empty.');
} elseif ($nameLen > 32) {
throw new \LengthException('Command name can be only up to 32 characters long.');
}
if (isset($this->type) && $this->type == Command::CHAT_INPUT && preg_match('/^[-_\p{L}\p{N}\p{Devanagari}\p{Thai}]{1,32}$/u', $name) === 0) {
throw new \DomainException('Slash command localized name contains invalid characters.');
}
}
$this->name_localizations ??= [];
$this->name_localizations[$locale] = $name;
return $this;
}
/**
* Sets the description of the command.
*
* @param string $description Description of the command
*
* @throws \LengthException `$description` is not 1-100 characters long.
*
* @return self
*/
public function setDescription(string $description): self
{
$descriptionLen = poly_strlen($description);
if ($descriptionLen < 1) {
throw new \LengthException('Command description can not be empty.');
} elseif ($descriptionLen > 100) {
throw new \LengthException('Command description can be only up to 100 characters long.');
}
$this->description = $description;
return $this;
}
/**
* Sets the description of the command in another language.
*
* @param string $locale Discord locale code.
* @param string|null $description Localized description of the command.
*
* @throws \LengthException `$description` is not 1-100 characters long.
*
* @return self
*/
public function setDescriptionLocalization(string $locale, ?string $description): self
{
if (isset($description, $this->type) && $this->type == Command::CHAT_INPUT && poly_strlen($description) > 100) {
throw new \LengthException('Command description must be less than or equal to 100 characters.');
}
$this->description_localizations ??= [];
$this->description_localizations[$locale] = $description;
return $this;
}
/**
* Sets the default permission of the command.
*
* @deprecated 7.1.0 See `CommandAttributes::setDefaultMemberPermissions()`.
*
* @param ?bool $permission Default permission of the command
*
* @return self
*/
public function setDefaultPermission(?bool $permission): self
{
$this->default_permission = $permission;
return $this;
}
/**
* Sets the default member permissions of the command.
*
* @param string|int $permissions Default member permission bits of the command.
*
* @return self
*/
public function setDefaultMemberPermissions($permissions): self
{
$this->default_member_permissions = (string) $permissions;
return $this;
}
/**
* Sets the DM permission of the command.
*
* @param bool $permission DM permission of the command.
*
* @return self
*/
public function setDmPermission(bool $permission): self
{
$this->dm_permission = $permission;
return $this;
}
/**
* Adds an option to the command.
*
* @param Option $option The option.
*
* @throws \DomainException Command type is not CHAT_INPUT (1).
* @throws \OverflowException Command exceeds maximum 25 options.
*
* @return self
*/
public function addOption(Option $option): self
{
if (isset($this->type) && $this->type != Command::CHAT_INPUT) {
throw new \DomainException('Only CHAT_INPUT Command type can have option.');
}
if (isset($this->options) && count($this->options) >= 25) {
throw new \OverflowException('Command can only have a maximum of 25 options.');
}
$this->options ??= [];
$this->options[] = $option;
return $this;
}
/**
* Removes an option from the command.
*
* @param Option $option Option to remove.
*
* @throws \DomainException Command type is not CHAT_INPUT (1).
*
* @return self
*/
public function removeOption(Option $option): self
{
if (isset($this->type) && $this->type != Command::CHAT_INPUT) {
throw new \DomainException('Only CHAT_INPUT Command type can have option.');
}
if (isset($this->options) && ($idx = array_search($option, $this->options)) !== false) {
array_splice($this->options, $idx, 1);
}
return $this;
}
/**
* Clear all options from the command.
*
* @return self
*/
public function clearOptions(): self
{
$this->options = [];
return $this;
}
}

View File

@@ -0,0 +1,104 @@
<?php
/*
* This file is a part of the DiscordPHP project.
*
* Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord\Builders;
use Discord\Parts\Interactions\Command\Command;
use Discord\Parts\Interactions\Command\Option;
use JsonSerializable;
/**
* Helper class used to build application commands.
*
* @author Mark `PeanutNL` Versluis
*/
class CommandBuilder implements JsonSerializable
{
use CommandAttributes;
/**
* Type of the command. The type defaults to 1.
*
* @var int
*/
protected $type = Command::CHAT_INPUT;
/**
* The default permission of the command. If true the command is enabled when the app is added to the guild.
*
* @var bool
*/
protected $default_permission = true;
/**
* Creates a new command builder.
*
* @return self
*/
public static function new(): self
{
return new static();
}
/**
* Returns all the options in the command.
*
* @return Option[]|null
*/
public function getOptions(): ?array
{
return $this->options ?? null;
}
/**
* Returns an array with all the options.
*
* @throws \LengthException
* @throws \DomainException
*
* @return array
*/
public function toArray(): array
{
$arrCommand = [
'name' => $this->name,
'description' => $this->description,
];
$optionals = [
'type',
'name_localizations',
'description_localizations',
'default_member_permissions',
'default_permission',
];
foreach ($optionals as $optional) {
if (property_exists($this, $optional)) {
$arrCommand[$optional] = $this->$optional;
}
}
foreach ($this->options ?? [] as $option) {
$arrCommand['options'][] = $option->getRawAttributes();
}
return $arrCommand;
}
/**
* @inheritdoc
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
}

View File

@@ -0,0 +1,116 @@
<?php
/*
* This file is a part of the DiscordPHP project.
*
* Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord\Builders\Components;
/**
* An Action Row is a non-interactive container component for other types of components.
* It has a type: 1 and a sub-array of components of other types.
*
* @see https://discord.com/developers/docs/interactions/message-components#action-rows
*/
class ActionRow extends Component
{
/**
* Components contained by the action row.
*
* @var Component[]
*/
private $components = [];
/**
* Creates a new action row.
*
* @return self
*/
public static function new(): self
{
return new self();
}
/**
* Adds a component to the action row.
*
* @param Component $component Component to add.
*
* @throws \InvalidArgumentException
* @throws \OverflowException
*
* @return self
*/
public function addComponent(Component $component): self
{
if ($component instanceof ActionRow) {
throw new \InvalidArgumentException('You cannot add another `ActionRow` to this action row.');
}
if ($component instanceof SelectMenu) {
throw new \InvalidArgumentException('Cannot add a select menu to an action row.');
}
if (count($this->components) >= 5) {
throw new \OverflowException('You can only have 5 components per action row.');
}
$this->components[] = $component;
return $this;
}
/**
* Removes a component from the action row.
*
* @param Component $component Component to remove.
*
* @return self
*/
public function removeComponent(Component $component): self
{
if (($idx = array_search($component, $this->components)) !== null) {
array_splice($this->components, $idx, 1);
}
return $this;
}
/**
* Removes all components from the action row.
*
* @return self
*/
public function clearComponents(): self
{
$this->components = [];
return $this;
}
/**
* Returns all the components in the action row.
*
* @return Component[]
*/
public function getComponents(): array
{
return $this->components;
}
/**
* @inheritdoc
*/
public function jsonSerialize(): array
{
return [
'type' => Component::TYPE_ACTION_ROW,
'components' => $this->components,
];
}
}

View File

@@ -0,0 +1,467 @@
<?php
/*
* This file is a part of the DiscordPHP project.
*
* Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord\Builders\Components;
use Discord\Discord;
use Discord\Parts\Guild\Emoji;
use Discord\Parts\Interactions\Interaction;
use Discord\WebSockets\Event;
use React\Promise\PromiseInterface;
use function Discord\poly_strlen;
/**
* Buttons are interactive components that render on messages.
* They can be clicked by users, and send an interaction to your app when clicked.
*
* @see https://discord.com/developers/docs/interactions/message-components#buttons
*/
class Button extends Component
{
public const STYLE_PRIMARY = 1;
public const STYLE_SECONDARY = 2;
public const STYLE_SUCCESS = 3;
public const STYLE_DANGER = 4;
public const STYLE_LINK = 5;
/**
* Style of button.
*
* @var int
*/
private $style = 1;
/**
* Label for the button.
*
* @var string|null
*/
private $label;
/**
* Emoji to display on the button.
*
* @var array|null
*/
private $emoji;
/**
* Custom ID to send with the button.
*
* @var string|null
*/
private $custom_id;
/**
* URL to send as the button. Only for link buttons.
*
* @var string|null
*/
private $url;
/**
* Whether the button is disabled.
*
* @var bool
*/
private $disabled = false;
/**
* Listener for when the button is pressed.
*
* @var callable|null
*/
private $listener;
/**
* Discord instance when the listener is set.
*
* @var Discord|null
*/
private $discord;
/**
* Creates a new button.
*
* @param int $style Style of the button.
* @param string|null $custom_id custom ID of the button. If not given, an UUID will be used
*
* @throws \InvalidArgumentException
*/
public function __construct(int $style, ?string $custom_id = null)
{
if (! in_array($style, [
self::STYLE_PRIMARY,
self::STYLE_SECONDARY,
self::STYLE_SUCCESS,
self::STYLE_DANGER,
self::STYLE_LINK,
])) {
throw new \InvalidArgumentException('Invalid button style.');
}
$this->style = $style;
if ($this->style != self::STYLE_LINK) {
$this->setCustomId($custom_id ?? $this->generateUuid());
}
}
/**
* Creates a new button.
*
* @param int $style Style of the button.
* @param string|null $custom_id custom ID of the button.
*
* @return self
*/
public static function new(int $style, ?string $custom_id = null): self
{
return new self($style, $custom_id);
}
/**
* Sets the style of the button.
*
* If the button is originally a link button, the link attribute will be cleared.
* If the button was changed to a link button, the listener will be cleared.
*
* @param int $style
*
* @throws \InvalidArgumentException
*
* @return self
*/
public function setStyle(int $style): self
{
if (! in_array($style, [
self::STYLE_PRIMARY,
self::STYLE_SECONDARY,
self::STYLE_SUCCESS,
self::STYLE_DANGER,
self::STYLE_LINK,
])) {
throw new \InvalidArgumentException('Invalid button style.');
}
if ($this->style == self::STYLE_LINK && $style != self::STYLE_LINK) {
$this->url = null;
} elseif ($this->style != self::STYLE_LINK && $style == self::STYLE_LINK && $this->listener && $this->discord) {
$this->setListener(null, $this->discord);
}
$this->style = $style;
return $this;
}
/**
* Sets the label of the button.
*
* @param string|null $label Label of the button. Maximum 80 characters.
*
* @throws \LengthException
*
* @return self
*/
public function setLabel(?string $label): self
{
if (isset($label) && poly_strlen($label) > 80) {
throw new \LengthException('Label must be maximum 80 characters.');
}
$this->label = $label;
return $this;
}
/**
* Sets the emoji of the button. Null to clear.
*
* @param Emoji|string|null $emoji Emoji to set.
*
* @return self
*/
public function setEmoji($emoji): self
{
$this->emoji = (function () use ($emoji) {
if ($emoji === null) {
return null;
}
if ($emoji instanceof Emoji) {
return [
'id' => $emoji->id,
'name' => $emoji->name,
'animated' => $emoji->animated,
];
}
$parts = explode(':', $emoji, 3);
if (count($parts) < 3) {
return [
'id' => null,
'name' => $emoji,
'animated' => false,
];
}
[$animated, $name, $id] = $parts;
return [
'id' => $id,
'name' => $name,
'animated' => $animated == 'a',
];
})();
return $this;
}
/**
* Sets the custom ID of the button.
*
* @param string|null $custom_id
*
* @throws \LogicException
* @throws \LengthException
*
* @return self
*/
public function setCustomId(?string $custom_id): self
{
if ($this->style == Button::STYLE_LINK) {
throw new \LogicException('You cannot set the custom ID of a link button.');
}
if (isset($custom_id) && poly_strlen($custom_id) > 100) {
throw new \LengthException('Custom ID must be maximum 100 characters.');
}
$this->custom_id = $custom_id;
return $this;
}
/**
* Sets the URL of the button. Only valid for link buttons.tatic.
*
* @param string|null $url
*
* @throws \LogicException
*
* @return self
*/
public function setUrl(?string $url): self
{
if ($this->style != Button::STYLE_LINK) {
throw new \LogicException('You cannot set the URL of a non-link button.');
}
$this->url = $url;
return $this;
}
/**
* Sets the button as disabled/not disabled.
*
* @param bool $disabled
*
* @return self
*/
public function setDisabled(bool $disabled): self
{
$this->disabled = $disabled;
return $this;
}
/**
* Sets the callable listener for the button. The `$callback` will be called when the button
* is pressed.
*
* If you do not respond to or acknowledge the `Interaction`, it will be acknowledged for you.
* Note that if you intend to respond to or acknowledge the interaction inside a promise, you should
* return a promise that resolves *after* you respond or acknowledge.
*
* The callback will only be called once with the `$oneOff` parameter set to true.
* This can be changed to false, and the callback will be called each time the button is pressed.
* To remove the listener, you can pass `$callback` as null.
*
* The button listener will not persist when the bot restarts.
*
* @param callable $callback Callback to call when the button is pressed. Will be called with the interaction object.
* @param Discord $discord Discord client.
* @param bool $oneOff Whether the listener should be removed after the button is pressed for the first time.
*
* @throws \LogicException
*
* @return self
*/
public function setListener(?callable $callback, Discord $discord, bool $oneOff = false): self
{
if ($this->style == Button::STYLE_LINK) {
throw new \LogicException('You cannot add a listener to a link button.');
}
if (! isset($this->custom_id)) {
$this->custom_id = $this->generateUuid();
}
// Remove any existing listener
if ($this->listener) {
$this->discord->removeListener(Event::INTERACTION_CREATE, $this->listener);
}
$this->discord = $discord;
if ($callback == null) {
return $this;
}
$this->listener = function (Interaction $interaction) use ($callback, $oneOff) {
if ($interaction->data->component_type == Component::TYPE_BUTTON && $interaction->data->custom_id == $this->custom_id) {
$response = $callback($interaction);
$ack = function () use ($interaction) {
// attempt to acknowledge interaction if it has not already been responded to.
try {
$interaction->acknowledge();
} catch (\Exception $e) {
}
};
if ($response instanceof PromiseInterface) {
$response->then($ack);
} else {
$ack();
}
if ($oneOff) {
$this->removeListener();
}
}
};
$discord->on(Event::INTERACTION_CREATE, $this->listener);
return $this;
}
/**
* Removes the listener from the button.
*
* @return self
*/
public function removeListener(): self
{
return $this->setListener(null, $this->discord);
}
/**
* Returns the style for the button.
*
* @return int
*/
public function getStyle(): int
{
return $this->style;
}
/**
* Returns the label for the button.
*
* @return string|null
*/
public function getLabel(): ?string
{
return $this->label;
}
/**
* Returns the emoji display on the button.
*
* @return array|null
*/
public function getEmoji(): ?array
{
return $this->emoji;
}
/**
* Returns the custom ID of the button.
*
* @return string|null
*/
public function getCustomId(): ?string
{
return $this->custom_id;
}
/**
* Returns the URL of the button. Only for link buttons.
*
* @return string|null
*/
public function getURL(): ?string
{
return $this->url;
}
/**
* Returns whether the button is disabled.
*
* @return bool
*/
public function isDisabled(): bool
{
return $this->disabled;
}
/**
* @inheritdoc
*/
public function jsonSerialize(): array
{
$content = [
'type' => Component::TYPE_BUTTON,
'style' => $this->style,
];
if (isset($this->label)) {
$content['label'] = $this->label;
}
if (isset($this->emoji)) {
$content['emoji'] = $this->emoji;
}
if (isset($this->custom_id)) {
$content['custom_id'] = $this->custom_id;
} elseif ($this->style != Button::STYLE_LINK) {
throw new \DomainException('Buttons must have a `custom_id` field set.');
}
if ($this->style == Button::STYLE_LINK) {
if (! isset($this->url)) {
throw new \DomainException('Link buttons must have a `url` field set.');
}
$content['url'] = $this->url;
}
if ($this->disabled) {
$content['disabled'] = true;
}
return $content;
}
}

View File

@@ -0,0 +1,37 @@
<?php
/*
* This file is a part of the DiscordPHP project.
*
* Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord\Builders\Components;
use JsonSerializable;
/**
* Components are a new field on the message object, so you can use them whether you're sending messages or responding to a slash command or other interaction.
*
* @see https://discord.com/developers/docs/interactions/message-components#what-is-a-component
*/
abstract class Component implements JsonSerializable
{
public const TYPE_ACTION_ROW = 1;
public const TYPE_BUTTON = 2;
public const TYPE_SELECT_MENU = 3;
public const TYPE_TEXT_INPUT = 4;
/**
* Generates a UUID which can be used for component custom IDs.
*
* @return string
*/
protected static function generateUuid(): string
{
return uniqid(time(), true);
}
}

Some files were not shown because too many files have changed in this diff Show More