LoginSignup
0
0

More than 1 year has passed since last update.

Slack WebAPI の conversations.list を JavaScript の fetch() で実行する

Posted at

環境

Slack WebAPI
JavaScript
Chrome

結論

index.js
let token = `${Bot User OAuth Token}`; //@comment <- ★1 Installed App Settings にある Bot User OAuth Tokenに書き換える
let url = new URL('https://slack.com/api/conversations.list');

//@comment POST method 用に FormData を作る
let fd = new FormData();
// Slack App Bot トークンをセット
fd.set('token', token);

//@comment 何も考えずに fetch に FormData を渡すと、'Content-Type': 'multipart/form-data' になってしまうので、Request Body を事前に String 化する必要がある。
//@comment Slack WebAPI は、Content-Type : 'application/x-www-form-urlencoded' のみにしか対応していない。
let body = ((ary, fd) => {
    for (let entry of fd.entries()) {
        ary.push(entry[0] + '=' + encodeURIComponent(entry[1]));
    }
    return ary.join('&');
})([], fd);

//@see https://api.slack.com/methods/conversations.list
//@comment GET って書いてあるけど、POST らしい。
//@comment 事実、単純に GET しても invalied_auth、コードで Request Header を変更すると、ブラウザ側の CROSS Policy により block される。
fetch(url.toString(), {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: body
}).then((res) => {
    // Response を JSON に変換
    return res.json();
}).then((json) => {
    // JSON を String に変換
    let text = JSON.stringify(json);
    // 以降、text を処理する
});

参考

上記コードを参照の事。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0