Sending Messages with Discord API

Create an application

首先,先隨意建立一個 app


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

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

最後產生的 URL 會像這樣:{CLIENT_ID}&permissions=2048&scope=bot

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

Create message?

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

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


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://

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

Gateway 必須以 secure WebSocket 連接


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

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

// Ref:

$client = new WebSocket\Client('wss://');

    'op' => 2,
    'd' => [
        'token' => '...',

$response = $client->receive();


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

    "t": null,
    "s": null,
    "op": 10,
    "d": {
        "heartbeat_interval": 41250,
        "_trace": [

Opcode 的定義見:

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