Skip to content
Exanlv edited this page Nov 21, 2023 · 11 revisions

Fenrir, a PHP library for interacting with both Discord's Gateway and REST API. This library gives you reasonable control over the interaction with Discord, allowing for complete customization of your bot or application.

Basic ping-pong bot example:

use Exan\Fenrir\Bitwise\Bitwise;
use Exan\Fenrir\Constants\Events;
use Exan\Fenrir\Discord;
use Exan\Fenrir\Enums\Gateway\Intents;
use Exan\Fenrir\Rest\Helpers\Channel\MessageBuilder;
use Exan\Fenrir\Websocket\Events\MessageCreate;

require './vendor/autoload.php';

$discord = new Discord('TOKEN');

$discord
    ->withGateway(Bitwise::from(
        Intents::GUILD_MESSAGES,
        Intents::DIRECT_MESSAGES,
        Intents::MESSAGE_CONTENT,
    ))
    ->withRest();

$discord->gateway->events->on(Events::MESSAGE_CREATE, function (MessageCreate $message) use ($discord) {
    if ($message->content === '!ping') {
        $discord->rest->channel->createMessage(
            $message->channel_id,
            (new MessageBuilder())
                ->setContent('pong!')
        );
    }
});

$discord->gateway->open(); // Nothing after this line is executed

Rest, Gateway

Discord's API consists of two main components, Gateway and Rest. Both can be used independently in Fenrir.

Generally, it is recommended to initialize both. However, if you're operating in a HTTP webserver environment (Apache 2, nginx, etc), you should not use the Gateway.

Rest

Most actions you perform, responding to a command, sending a message, etc, make use of Discord's REST API. This uses regular ol' HTTP(s) and does not require a long-lived process.

You can initialize rest using $discord->withRest(). This will make REST calls immediately available through $discord->rest.

Gateway

For receiving realtime data and events from Discord, Gateway is used. This uses websockets and requires a long-lived process.

You can initialize the gateway using $discord->withGateway(...). This gets everything ready to connect but does not immediately start the connection.

To actually open the websocket connection and start receiving events, call $discord->gateway->open(). This function blocks further execution of your app. Any lines of code after this one will not be executed. You should register all your listeners before

Clone this wiki locally