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)
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'
... ]