LoginSignup
5
6

More than 3 years have passed since last update.

【Node.js】Slackのuser idから情報を取得する

Last updated at Posted at 2019-04-03

Slack APPでユーザーを取得しようとするとユーザーIDが取得される為
APIを用いてユーザーIDからユーザーの詳細情報を取得する

requestモジュール

https://www.npmjs.com/package/request
requestモジュールは HTTP/HTTPS 通信を行うためのクライアント。
image.png

users.infoメソッド

Slack APIには様々なメソッドが用意されている
今回はアカウントの詳細情報を取得したいので users.infoを使って取得する

Slack APIからの情報取得

簡単に言うと下記のURLにトークンとユーザーIDをつけてアクセスすると詳細情報が返ってくる仕組み

https://slack.com/api/users.info?token=トークン&user=ユーザーID&pretty=1

サンプルコード

Node.jsでAPIを叩くときは以下のように書く
TOKENとUSERIDを書き換える

index.js
// パッケージの読み込み
let request = require('request');

// ヘッダーを定義
var headers = {'Content-type': 'application/json'};

// オプションを定義
var options = {
  url: 'https://slack.com/api/users.info?token=TOKEN&user=USERID&pretty=1',
  method: 'GET',
  headers: headers,
  json: true,
};

// リクエスト送信
request(options, function (error, response, body) {
  console.log(body); // body内に取得したJSONが入っている
})

ユーザーIDを動的にしてAPIを叩く

Slack APPなどから取得したユーザーIDを使って検索する際はES2015(ES6)から追加されたテンプレート構文を用いると便利

JavaScript (ES2015) 文字列中に変数展開できるテンプレート構文のメモ

index.js
// パッケージの読み込み
let request = require('request');

// message.channels eventで取得した場合
if (payload.event && payload.event.type === 'message'){

  // 取得したユーザーIDを代入
  user_id = payload.event.user;

  // ヘッダーを定義
  var headers = {'Content-type': 'application/json'};

  // オプションを定義
  var options = {
    // バックスラッシュ内のテキストに ${変数名} で変数を入れられる
    url: `https://slack.com/api/users.info?token=TOKEN&user=${user_id}&pretty=1`, 
    method: 'GET',
    headers: headers,
    json: true,
  };

  // リクエスト送信
  request(options, function (error, response, body) {
    console.log(body); // body内に取得したJSONが入っている
  })
};

前まではuserを取得したらメールアドレスが返ってきていたような気がするけど
こっちのほうがユーザーIDから一気に様々な情報が取れるから便利

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