当社でもSlackを初めてもうすぐ2年になります。全履歴を取得して、何かできないかなと思ったので、調べてスクリプトを書いたので公開します。
Slackで使用するAPI
以下です。
https://api.slack.com/methods/search.messages
このAPIを使用するにはTokenが必要なので、それは自分のSlackを使って発行しておいてください。おそらく以下から発行できます。(他人に見られないように)
https://api.slack.com/custom-integrations/legacy-tokens
使用したスクリプト
もちろん、最近習得カーブが急上昇しているJavaScriptです。
外部APIにアクセスするので、superagentを使用します。
もしかするとたくさんのAPIをコールする可能性もあるのでpromise使っています。
PromiseはAPI名と検索条件をオブジェクトで渡すため、関数でラップしてます。
(検索条件はオブジェクトリテラルでそのまま突っ込んでいますがこの辺りは要改善)
const request = require('superagent');
const url = "https://slack.com/api/";
const slackLegacyToken = process.env.slackLegacyToken;
var queryObject = {
"token":slackLegacyToken,
"query":"after:2017/12/1", //2017/12/1以降
"count":"2", //1度に2件表示する
"sort":"timestamp",
"pretty":"1"};
function callSlackApi(apiName,queryObject) {
return new Promise(
(resolve, reject) => {
request.post(url + apiName)
.query(queryObject)
.set('Content-Type', 'application/x-www-form-urlencoded')
.end(
(error, response) => {
if (error) {
reject(error);
} else {
resolve(JSON.stringify(response.body, null, "\t"));
}
}
);
});
}
callSlackApi("search.messages", queryObject)
.then(
(obj) => {
console.log(obj);
}
).catch(
(err) => {console.error(err); }
);