【GAS×SlackAPI】ワークスペースのユーザー名とIDをスプレッドシートに取得する【1000ユーザー以上対応版】

2022-01-17

当サイトではアフィリエイト広告を利用して商品を紹介しています。

みなさん、こんにちは!
そーちゃん(@black777cat)です。


【GAS×SlackAPI】ワークスペースのユーザー名とIDをスプレッドシートに取得する
を参考にSlackからユーザー名とユーザーIDをスプレッドシートに書き出しを行ったところ、1000ユーザー以降書き出せていない・・・!

ということで、困ったのでその解決方法としてこちらの記事を残しておきます。

コード


/**
 * 1度だけ実行して環境変数を指定してください。
 *
 */
function setProperties() {
  PropertiesService.getScriptProperties().setProperty('SLACK_ACCESS_TOKEN',"xoxp-**********");
  PropertiesService.getScriptProperties().setProperty('SS_ID',"**********");
  PropertiesService.getScriptProperties().setProperty('SS_NAME',"*****");
}

/**
 * SlackのAPIから削除済、botユーザー、Slackbotを除くuser情報のIDと名前をすべて取得します。
 *
 */
function getSlackUser() {

  const slack_app_token = PropertiesService.getScriptProperties().getProperty('SLACK_ACCESS_TOKEN');

  //スプレッドシートを1度削除
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('slack');
  sheet.getRange(1, 1, sheet.getMaxRows() - 1, 2).clearContent();

  let arr = [["id","name"]];
  let nextCorsor = ""
  let is_loop = true
  let is_first = true
  while(is_loop) {

    const options = {
      "method": "get",
      "contentType": "application/x-www-form-urlencoded",
      "payload": {
        "token": slack_app_token,
        "limit": 1000, //何件取得をするか最大1000
        "cursor": nextCorsor //次にどこから取得をするか
      }
    };

    const url = "https://slack.com/api/users.list";
    const response = UrlFetchApp.fetch(url, options);
    const contentText = JSON.parse(response.getContentText());
    const members = contentText.members;
    nextCorsor = contentText.response_metadata.next_cursor

    for (const member of members) {
      //削除済、botユーザー、Slackbotを除く
      if (!member.deleted && !member.is_bot && member.id !== "USLACKBOT") {
        let id = member.id;
        let real_name = member.real_name; //氏名(※表示名ではない)
        arr.push([real_name, id]);
      }
    }
    if( is_first === false &&  nextCorsor === ""){
      is_loop = false
    }
    is_first = false
  }

  //スプレッドシートに書き込み
  sheet.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}

コード解説

元記事から変わった点をかいつまんで解説します。

変更点としては、下記の2点です。

payloadの中身のcursorを指定した点
ループ処理で1000件以上ある場合に複数回アカウントを取得するようにした点

ページングはcursorを指定する。

payloadのcursorを指定するとどこから取得するのかを指定できます。

1回目・・・cursorに何も入れない

2回目・・・前回のリクエストから返ってきたnext_cursorを取得してcursorに指定する。

n回目・・・前回のリクエストから返ってきたnext_cursorが空文字("")だったらこれで最後なのでループから抜ける。

という用になっています。

参考:SlackAPI users.list

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