DEV Community

kaede
kaede

Posted on • Edited on

GAS の UrlFetchApp で Slack API の conversations.list で全てのチャンネルリストを取得する

GAS プロジェクト作成

Image description

getSlackChByName と言うプロジェクト名で作成

Slack API 公式 Doc からコピペ

api.slack.com の Slack API 公式ドキュメントを読む

https://api.slack.com/messaging/retrieving#finding_conversation

このメッセージを見つけるコードは

const { WebClient, LogLevel } = require("@slack/web-api"); 
Enter fullscreen mode Exit fullscreen mode

GAS が npm モジュールを使えないことにより断念

チャンネルリストを conversations.list で確認する

https://api.slack.com/methods/conversations.list

公式のここによれば

GET で

https://slack.com/api/conversations.list

を叩けば手に入るらしい

API リクエストのラッパーを導入する

https://qiita.com/seratch/items/2158cb0abed5b8e12809

この記事を参考に作る。 payload は省略した。

function callWebApi(token, apiMethod) { const response = UrlFetchApp.fetch( `https://www.slack.com/api/${apiMethod}`, { method: "post", contentType: "application/x-www-form-urlencoded", headers: { "Authorization": `Bearer ${token}` }, } ); console.log(`Web API (${apiMethod}) response: ${response}`) return response; } 
Enter fullscreen mode Exit fullscreen mode

UrlFetchApp と言う GAS の組み込み関数で fetch する。

apiMethod は GET/POST ではなく、Slack の API Method のこと。
Slack Workspace のトークンと Slack API Method を引数で受け取るようにする。

const token = "xoxp-1234" const apiResponse = callWebApi(token, "conversations.list"); 
Enter fullscreen mode Exit fullscreen mode

これに Slack のトークンを入れて conversations.list の Slack API Method で呼ぶ。

これを GAS で実行すると

Web API (conversations.list) response: { "ok":true,"channels":[ {"id":"C0385KDLRD5","name":"making-bot",... }, {"id":"C038L782V3M","name":"random",... }, {"id":"C038NHHFN3E","name":"general",...}, "response_metadata":{"next_cursor":""}, } 
Enter fullscreen mode Exit fullscreen mode

レスポンスでチャンネルのリストが json で取れた。

Image description

デフォルトの random と general, 自分で作った making-bot,
これらのチャンネル名と、チャンネル情報がとれた。

making-bot の詳細を見ていく

"name":"making-bot", "is_channel":true, "is_group":false, "is_im":false, "is_mpim":false, "is_private":false, "created":1648155092, "is_archived":false, "is_general":false, "unlinked":0, "name_normalized":"making-bot", "is_shared":false, "is_org_shared":false, "is_pending_ext_shared":false, "pending_shared":[], "parent_conversation":null, "creator":"U038DHKP87Q", "is_ext_shared":false, "shared_team_ids":["T038NHHEJJY"], "pending_connected_team_ids":[], "is_member":true, 
Enter fullscreen mode Exit fullscreen mode

チャンネル名、チャンネルかグループか、プライベートか、アーカイブされいているか、共有されているか、誰に作られたか、このリクエストのトークンの人間がこのチャンネルに入っているか、これらが確認できた。

他のチャンネルも同じデータ構造。

今後

これでは各チャンネルの肝心のチャットの中身が見れないので
次は単一チャンネルの中身を取り出す Slack API メソッドを試す
メンバーリストや DM リストも試してみる。

Slack とは別に DogAPI や Twitter API など他も試してみる

Top comments (0)