Get messages on Slack by command line / terminal.
https://api.slack.com/custom-integrations/legacy-tokens で token 作成
https://api.slack.com/methods/search.all を使用。
パラメータ query の内容は下記を参考に。
https://get.slack.help/hc/ja/articles/202528808-Slack-%E5%86%85%E3%82%92%E6%A4%9C%E7%B4%A2%E3%81%99%E3%82%8B
const TOKEN = "PUT TOKEN HERE"; // Usage // node slackget.js [desc] var http = require('https'); var DESC; process.argv.find(function(e){ if (e == "desc"){ DESC = true; } }); let page = 1; var start = new Date(Date.now() - 4 * 24 * 3600 * 1000); var startDate = dateTimeStr(start).slice(0, 10); console.log("get from " + startDate); getMessages(); function getMessages(){ http.get( 'https://slack.com/api/search.all?token=' + TOKEN + '&page=' + page + // '&query=after%3Ayesterday&sort=timestamp', (res) => '&query=after%3A' + startDate + '&sort=timestamp', (res) => { const { statusCode } = res; const contentType = res.headers['content-type']; let error; if (statusCode !== 200) { error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); // consume response data to free up memory res.resume(); return; } res.setEncoding('utf8'); let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { try { processResult(JSON.parse(rawData)); } catch (e) { console.error(e.message); } }); }).on('error', (e) => { console.error(`Got error: ${e.message}`); }); } var list; function processResult(json){ //console.log(json); console.log("page=" + page); if (!list){ list = json.messages.matches; }else{ list = list.concat(json.messages.matches); } if (json.messages.paging.pages != page){ ++page; getMessages(); }else{ // got all pages list.sort(function(a,b){ if (a.ts > b.ts) {return DESC ? -1 : 1;} if (a.ts < b.ts) {return DESC ? 1 : -1;} return 0; }); list.forEach(function(e){ //console.log(e); console.log( dateTimeStr(new Date(e.ts * 1000)) + " " + e.channel.name + " " + e.username); if (e.text != null){ var text = e.text.replace(">", ">"); console.log(text); } console.log(''); }); } } function dateTimeStr(date){ let padm = ''; let padd = ''; let padh = ''; let padmin = ''; let pads = ''; let month = date.getMonth() + 1; if (month < 10){ padm = 0; } if (date.getDate() < 10){ padd = 0; } if (date.getHours() < 10){ padh = 0; } if (date.getMinutes() < 10){ padmin = 0; } if (date.getSeconds() < 10){ pads = 0; } return date.getFullYear() + '/' + padm + month + '/' + padd + date.getDate() + ' ' + padh + date.getHours() + ':' + padmin + date.getMinutes() + ':' + pads + date.getSeconds(); }