- Создаём Discord-бота на PHP
- Saved searches
- Use saved searches to filter your results more quickly
- License
- discord-php/DiscordPHP
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- RestCord
- FAQ
- Getting Started
- Installing
- Getting Started
- Basic Example
- Options
- API Documentation
- Contributing
Создаём Discord-бота на PHP
Давно хотел написать статью про дискорд-ботов, но всё никак не мог определиться с конкретной тематикой, ведь подобных туториалов и уроков в интернете полно, и в основном для этих целей используют Python и Node.JS. А вот какой-либо документации и примеров написания ботов для дискорда на PHP почти нет, и уж тем более на русском языке. Поэтому в этой статье будем разбирать основы написания ботов на библиотеке Discord-PHP.
Шаг 1: Подготовка бота
1. Переходим по ссылке и создаём новое приложение:
2. Во вкладке Bot добавляем бота, подтверждаем выбор в появившемся окне:
3. Во вкладке OAuth2 -> URL Generator ставим галочку напротив пункта bot, ниже выбираем необходимые права доступа и копируем появившуюся внизу ссылку на инвайт бота:
4. Переходим по скопированной ссылке и приглашаем бота в нужный нам сервер.
5. Генерируем токен бота и сохраняем его у себя:
6. Включаем SERVER MEMBERS INTENT, дабы отслеживать события пользователей (например, вход на сервер):
Подключаем библиотеку через composer:
composer require team-reflex/discord-php
В этот раз много всего делать не будем, разберём только базовые вещи. В будущих уроках, возможно, напишем ещё что-нибудь. А, возможно, и сделаем бота на питоне. Впрочем, пока загадывать не буду.
Начинаем с подключения библиотеки, импортируем необходимые для работы классы:
Создаём экземпляр класса Discord:
$ds = new Discord( [ 'token' => '*****************', // Токен, который мы сгенерировали ранее 'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, // Понадобится для отслеживания событий участников ] );
Далее вставляем конструкцию, внутри которой будем прописывать конкретные события для отслеживания. В конец сразу добавил $ds->run() для запуска бота:
$ds->on( 'ready', function( $ds ) < // Тут продолжим писать код >); $ds->run();
И первое событие, которое мы обработаем — так это входящие сообщения:
$ds->on( Event::MESSAGE_CREATE, function( Message $msg, Discord $ds ) < // Тут будем обрабатывать входящие >);
if ( $msg->content == '/бот' ) < $msg->reply( 'Привет, ' . $msg->author->username ); >
Да, бот пока не запущен и не готов к работе, но я забегу наперёд и покажу, как это будет работать:
С помощью метода ban() можно заблокировать участника. В первом параметре можно указать, за какой промежуток времени нужно удалить сообщения этого пользователя (я для примера удалю сообщения за последние сутки), а во втором — причину бана:
else if ( str_contains( $msg->content, 'админ лох' ) ) < $msg->member->ban( 1, 'reason' ); >
Такое условие на практике, конечно, использоваться никогда не будет, да и в принципе банить людей по ключевым словам — решение не шибко надёжное. Но сейчас я просто показываю, как можно банить юзеров средствами библиотеки.
В первом шаге мы включили Members Intent, поэтому теперь можем отслеживать вход новых участников на наш сервер:
$ds->on( Event::GUILD_MEMBER_ADD, function( Member $member, Discord $ds ) < // Тут продолжим писать код >);
Давайте выдадим новым участникам какую-нибудь роль, а для этого нам понадобится получить ID этой самой роли. Чтобы его получить — включаем режим разработчика (Настройки -> Настройки приложения -> Расширенное):
Ну, и теперь копируем ID нужной роли:
Теперь мы можем воспользоваться методом addRole(), передав в него скопированный айдишник (в виде строки):
$member->addRole( '1007995229674156102' );
Ну, и ещё поменяем никнейм присоединившегося участника на сервере методом setNickname():
$member->setNickname( 'Новый никнейм' );
'******************', 'intents' => Intents::getDefaultIntents() | Intents::GUILD_MEMBERS, ] ); $ds->on( 'ready', function( $ds ) < $ds->on( Event::MESSAGE_CREATE, function( Message $msg, Discord $ds ) < if ( $msg->content == '/бот' ) < $msg->reply( 'Привет, ' . $msg->author->username ); > else if ( str_contains( $msg->content, 'админ лох' ) ) < $msg->member->ban( 1, 'reason' ); > > ); $ds->on( Event::GUILD_MEMBER_ADD, function( Member $member, Discord $ds ) < $member->addRole( '1007995229674156102' ); $member->setNickname( 'Новый никнейм' ); > ); > ); $ds->run();
Запустить бота можно на OpenServer. Для этого нужно перейти в консоль:
И ввести следующую команду (путь, естественно, указывать нужно свой):
Если же у вас есть купленный хост, который предоставляет возможность юзать консоль, то запустить бота можно там. Покажу на примере ISPManager принцип:
1. Переходим во вкладку Shell-клиент:
2. Вводим следующую команду:
Путь и версию PHP меняем под себя.
Чтобы быстро вставить команду в консоли — нажмите ПКМ -> Paste from browser:
- 5id15
- 13.08.2022
- 3 778
- 0
- 8
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
An API to interact with the popular messaging app Discord
License
discord-php/DiscordPHP
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A wrapper for the official Discord REST, gateway and voice APIs. Documentation is available here, 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.
Cache Interface (experimental)
Warning This branch contains an experimental feature, do not use it in production! See the wiki page for more information on how to set it up.
- 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 with your bot and run it through CLI.
- PHP is running out of memory?
- Try unlimit your PHP memory using ini_set(‘memory_limit’, ‘-1’); .
Before you start using this Library, you need to know how PHP works, 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.
- One of ext-uv (recommended), ext-ev or ext-event for a faster, and more performant event loop.
- ext-mbstring if handling non-latin characters.
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.
As such users of this library need to download a Certificate Authority extract from the cURL website.
The path to the caextract must be set in the php.ini for openssl.cafile .
DiscordPHP is installed using Composer.
- Run composer require team-reflex/discord-php . This will install the latest stable release.
- If you would like, you can also install the development branch by running composer require team-reflex/discord-php dev-master .
- Include the Composer autoload file at the top of your main file:
- include __DIR__.’/vendor/autoload.php’;
- Make a bot!
include __DIR__.'/vendor/autoload.php'; use Discord\Discord; use Discord\Parts\Channel\Message; use Discord\WebSockets\Intents; use Discord\WebSockets\Event; $discord = new Discord([ 'token' => 'bot-token', 'intents' => Intents::getDefaultIntents() // | Intents::MESSAGE_CONTENT, // Note: MESSAGE_CONTENT is privileged, see https://dis.gd/mcfaq ]); $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; // Note: MESSAGE_CONTENT intent must be enabled to get the content if the bot is not mentioned/DMed. >); >); $discord->run();
Documentation for the latest version can be found here. Community contributed tutorials can be found on the wiki.
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 .
MIT License, © David Cole and other contributers 2016-present.
About
An API to interact with the popular messaging app Discord
RestCord
This is a PHP library for the Discord API. This library is limited to the basic REST api that Discord provides. If you are doing anything heavy, or fancy, you should probably look at the other php library.
FAQ
- Can I run RestCord on a webserver (e.g. Apache, nginx)?
- Yes. There are caveats though. Some of the requests aren’t super fast, and can slow down your users responses. You should cache as much as you can.
- Can I use this to create a bot?
- Yes, but not the typical kind. This does not spawn a long running process, or connect to the websocket gateway like the other lib does.
- It wont let me send messages. Whats up?
- You have to have your bot connect to the websocket gateway at LEAST once before you can create messages. You can do that by opening up ./extra/gateway.html in your browser.
Getting Started
Installing
RestCord is installed using Composer. Make sure you have installed Composer and are used to how it operates. We require a minimum PHP version of PHP 7.0, but suggest keeping up with the current active versions of PHP: https://www.php.net/supported-versions.php This library REQUIRES 64bit PHP.
This library has not been tested with HHVM.
- Run composer require restcord/restcord . This will install the lastest release.
- If you would like, you can also install the development branch by running composer require restcord/restcord dev-master .
- Include the Composer autoload file at the top of your main file:
- include __DIR__.’/vendor/autoload.php’;
- Use it!
Getting Started
There’s an example below, and more listed in the menu to the left. The RestCord\DiscordClient is broken out into categories just like the api itself: channel, gateway, guild, invite, oauth2, user, voice, and webhook.
You can view the methods of each of these categories by selecting the menu items on the left.
Basic Example
include __DIR__.'/vendor/autoload.php'; use RestCord\DiscordClient; $discord = new DiscordClient(['token' => 'bot-token']); // Token is required var_dump($discord->guild->getGuild(['guild.id' => 81384788765712384]));
Options
Below is a table of the options available to the discord client
Name | Type | Required | Default | Description |
---|---|---|---|---|
token | string | Yes | ~ | Your bot token |
version | string | No | 1.0.0 | The version of the API to use. Should probably be left alone |
logger | Monolog\Logger | false | new Logger(‘Logger’) | An instance of a Monolog\Logger |
throwOnRatelimit | bool | false | false | Whether or not an exception is thrown when a ratelimit is supposed to hit |
apiUrl | string | false | https://discordapp.com/api/v6 | Should leave this alone. |
tokenType | string | false | Bot | Either Bot or OAuth |
API Documentation
API Documentation can be found in the menu to the left
Contributing
We are open to contributions. However, please make sure you follow our coding standards (PSR-4 autoloading and custom styling). We use StyleCI to format our code. Contributing is a little strange with this library. We use a service definition generator to create a service description for guzzle. All of the logic in this repo is built off of the service description in the src/Resources directory.
To build a new service definition, just run:
$ ./bin/downloadServiceDefinition