LoginSignup
11
18

More than 3 years have passed since last update.

Slack APIを使ってチャンネルのメンバー名一覧を取得する

Last updated at Posted at 2017-07-14

Slackの特定のチャンネルに入っているメンバーの名前をSlack APIを使って取得しました。
チームの人数が多い場合のちょっとした管理表(夏休みの予定表とか)を作る時に使えます。
今回はNode環境で、es2017のasync functionsを使ってみました。

環境

Node v7.10+

(async functionsがサポートされているのがv7.10以上のため
http://node.green/#ES2017-features-async-functions)

事前準備

Slack API Tokenを取得する

Slack API Tokenを以下にアクセスして取得します。
https://api.slack.com/custom-integrations/legacy-tokens

チャンネルIDを取得する

ブラウザでSlackを開きURLから取得します。

https://{team}.slack.com/messages/{channel_id}/

packageのインストール

今回はnode-fetchを使用したのでインストールします。

$ npm install node-fetch --save

コード

Slack API Methodsからchannels.infoとusers.infoを使用します。
(詳細はこちら https://api.slack.com/methods)

main.js
const fetch = require('node-fetch');

const TOKEN = '{Slack_API_token}';
const CHANNEL_ID = '{Channel_ID}';
const SLACK_API_BASE = 'https://slack.com/api';

function fetchChannel() {
  return fetch(`${SLACK_API_BASE}/channels.info?token=${TOKEN}&channel=${CHANNEL_ID}&pretty=1`)
    .then(res => res.json())
    .then((res) => {
      if (!res.ok) throw new Error(res.error);
      return res.channel;
    });
}

function fetchMembers(ids) {
  return Promise.all(ids.map((id) => {
    return fetch(`${SLACK_API_BASE}/users.info?token=${TOKEN}&user=${id}&pretty=1`)
      .then(res => res.json())
      .then((res) => {
        if (!res.ok) throw new Error(res.error);
        return res.user;
      });
  }))
  .then(users => users.filter(x => !x.deleted));
}

(async () => {
  const channel = await fetchChannel();
  const members = await fetchMembers(channel.members);
  const names = members.map(x => x.real_name).sort();
  console.log(names);
})()
  .catch(err => console.error(err));

先頭の{Slack_API_token}{Channel_ID}を事前に取得しておいた値に変更してください。

実行すると、以下のように配列でメンバーの名前(First name + Last Name)を取得できました。

$ node .
[ 'James Hetfield',
  'Lars Ulrich',
  'Kirk Hammett',
  'Robert Trujillo'
  ... ]
11
18
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
11
18