Sending Messages with Discord API

Create an application

https://discord.com/developers/applications

首先,先隨意建立一個 app

Authorization

https://discord.com/developers/applications/{APP_ID}/oauth2

在 app 的 OAuth2 項目裡就有 “OAuth2 URL Generator” 可以建立認證用的 URL 了

  • Scopes 勾選 bot
  • Bot permissions 先只勾選 Send Messages 一項

最後產生的 URL 會像這樣:

https://discord.com/api/oauth2/authorize?client_id={CLIENT_ID}&permissions=2048&scope=bot

建立好 OAuth2 URL 之後,直接以瀏覽器開啟 URL,再依頁面指示完成認證即可

Create message?

https://discord.com/developers/docs/resources/channel#create-message

Before using this endpoint, you must connect to and identify with a gateway at least once.

在實際使用 API 之前,還得先透過 gateway 認證才行

Gateways

https://discord.com/developers/docs/topics/gateway#gateways

With the resulting payload, you can now open a websocket connection to the “url” (or endpoint) specified. Generally, it is a good idea to explicitly pass the gateway version and encoding. For example, we may connect to wss://gateway.discord.gg/?v=6&encoding=json.

Once connected, the client should immediately receive an Opcode 10 Hello payload, with information on the connection’s heartbeat interval:

Gateway 必須以 secure WebSocket 連接

WebSocket

PHP 雖然可以透過 socket_create 等 API 實作 WebSocket client,但是實作起來太麻煩(首先預設就不支援 wss:// protocol 了),這裡就直接用別人做好的輪子吧

laravel-notification-channels/discord 的程式碼裡看來的做法(使用 textalk/websocket 套件):

// Ref: https://github.com/laravel-notification-channels/discord/blob/master/src/Commands/SetupCommand.php#L76-L97

$client = new WebSocket\Client('wss://gateway.discord.gg/?v=6&encoding=json');

$client->send(json_encode([
    'op' => 2,
    'd' => [
        'token' => '...',
    ],
]));

$response = $client->receive();

$client->close();

json_decode($response) 的內容會像這樣:

{
    "t": null,
    "s": null,
    "op": 10,
    "d": {
        "heartbeat_interval": 41250,
        "_trace": [
            "["gateway-prd-main-cc51",{"micros":0.0}]",
        ],
    }
}

Opcode 的定義見:https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-opcodes

認證成功後,就能使用 create message 等 API 了