5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[SlackAPI][node-slack-sdk] Workspace内の全てのChannel名を取得する (conversations.list を使う)

Posted at

これまでの一般的な方法

普通にググると大抵はこの channels.list を使っているサンプルに行き着く。
https://api.slack.com/methods/channels.list

ただし、最近気づいた下記の文言、

Don't use this method. Use conversations.list instead.

他にも移行が必須なケースがあって、例えば channels.listShared channelsを返してくれない。ここは場合によっては結構困るのでconversations.listへ移行した。

サンプル

conversations.list ではpaginationを意識する必要があるが、node-slack-sdkのサンプルを参照すると下記のようになる。
https://github.com/slackapi/node-slack-sdk/blob/master/docs/_pages/web_client.md#pagination

const { WebClient } = require('@slack/client');
const token = process.env.SLACK_BOT_TOKEN;
const web = new WebClient(token);
  
function getChannels() {
  const param = {
    exclude_archived: true,
    types: 'public_channel',
    limit: 200
  };
  let channels = [];
  function pageLoaded(res) {
    // 今回はチャンネル名だけ欲しかったので "name" だけ。
    res.channels.forEach(c => channels.push(c.name));
    if (res.response_metadata && res.response_metadata.next_cursor && res.response_metadata.next_cursor !== '') {
      param.cursor = res.response_metadata.next_cursor;
      return web.conversations.list(param).then(pageLoaded);
    }
    return channels;
  }
  return web.conversations.list(param).then(pageLoaded);
}

getChannels()
  .then((d) => console.log(JSON.stringify(d)))
  .catch(console.error);

conversations.list に渡すことのできるArgumentsはいくつかあるのでドキュメントを参照のこと。上記の例では、archive済みのチャンネルは省略、Publicチャンネルのみ、1ページ毎に200個まで、と指定している。limit: 200 の理由は、一応ドキュメントに下記のように記載があるため。

To begin pagination, specify a limit value under 1000. We recommend no more than 200 results at a time.

普通にwhileで回してもいいとは思う。
https://blog.frame.ai/migrating-to-the-slack-conversations-api-89692b016eea

5
3
0

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?