1
0

slack.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. const
  2. WebSocket = require('ws'),
  3. https = require('https'),
  4. sleep = require("sleep").sleep
  5. ,SlackData = require("./slackData.js").SlackData
  6. ,SlackHistory = require("./slackHistory.js").SlackHistory
  7. ,config = require("../config.js")
  8. ,httpsRequest = require('./httpsRequest.js').httpsRequest
  9. ;
  10. const SLACK_ENDPOINT = "https://slack.com/api/"
  11. ,SLACK_HOSTNAME = "slack.com"
  12. ,SLACK_ENDPOINT_PATH = "/api/"
  13. ,GETAPI = {
  14. rtmStart: "rtm.start"
  15. ,oauth: "oauth.access"
  16. ,identityEmail: "users.identity"
  17. ,channelHistory: "channels.history"
  18. ,directHistory: "im.history"
  19. ,groupHistory: "groups.history"
  20. ,starChannel: "stars.add"
  21. ,unstarChannel: "stars.remove"
  22. ,postMsg: "chat.postMessage"
  23. ,postMeMsg: "chat.meMessage"
  24. ,editMsg: "chat.update"
  25. ,removeMsg: "chat.delete"
  26. ,postFile: "files.upload"
  27. ,setActive: "users.setActive"
  28. ,emojiList: "emoji.list"
  29. ,slashList: "commands.list"
  30. ,slashExec: "chat.command"
  31. ,addReaction: "reactions.add"
  32. ,removeReaction: "reactions.remove"
  33. ,sendAction: "chat.attachmentAction"
  34. ,read: {
  35. group: "groups.mark"
  36. ,im: "im.mark"
  37. ,group: "mpim.mark"
  38. ,channel: "channels.mark"
  39. }
  40. }
  41. ,HISTORY_LENGTH = 35
  42. ,HISTORY_MAX_AGE = 10000// * 60 * 1000
  43. ,UPDATE_LIVE = [
  44. "message"
  45. ,"pin_added"
  46. ,"pin_removed"
  47. ,"reaction_added"
  48. ,"reaction_removed"
  49. ,"star_added"
  50. ,"star_removed"
  51. ] // Message type that affect live history
  52. ;
  53. /**
  54. * @implements {ChatSystem}
  55. **/
  56. function Slack(slackToken, manager) {
  57. this.token = slackToken;
  58. this.manager = manager;
  59. this.rtm = null;
  60. this.rtmId = 1;
  61. this.data = new SlackData(this);
  62. this.history = {};
  63. this.pendingRtm = {};
  64. this.pendingMessages = [];
  65. this.pendingPing = false;
  66. this.connected = false;
  67. this.closing = false;
  68. }
  69. Slack.prototype.getId = function() {
  70. return this.data.team ? this.data.team.id : null;
  71. };
  72. Slack.prototype.onRequest = function() {
  73. if (this.connected === false) {
  74. this.connect();
  75. }
  76. };
  77. Slack.prototype.connect = function(cb) {
  78. var _this = this;
  79. this.connected = undefined;
  80. httpsRequest(SLACK_ENDPOINT +GETAPI.rtmStart +"?token=" +this.token, (status, body) => {
  81. if (!body || !body.ok) {
  82. _this.error = "Slack API error";
  83. _this.connected = false;
  84. console.error("Slack api responded " +status +" with body " +JSON.stringify(body));
  85. cb && cb(_this);
  86. } else if (status !== 200) {
  87. _this.error = body.error;
  88. _this.connected = false;
  89. console.error("Slack api responded " +status);
  90. cb && cb(_this);
  91. } else {
  92. _this.data.updateStatic({
  93. team: body["team"],
  94. users: body["users"],
  95. bots: body["bots"],
  96. self: body["self"]
  97. }, Date.now());
  98. _this.connectRtm(body.url);
  99. }
  100. });
  101. };
  102. Slack.prototype.sendCommand = function(room, cmd, arg) {
  103. httpsRequest(
  104. SLACK_ENDPOINT
  105. +GETAPI.slashExec
  106. +"?token=" +this.token
  107. +"&command=" +encodeURIComponent(cmd.name)
  108. +"&disp=" +encodeURIComponent(cmd.name)
  109. +"&channel=" +room.remoteId
  110. +"&text=" +arg);
  111. }
  112. Slack.prototype.sendTyping = function(room) {
  113. this.rtm.send('{"id":' +this.rtmId++ +',"type":"typing","channel":"' +room.remoteId +'"}');
  114. }
  115. Slack.prototype.getSlashCommands = function(cb) {
  116. httpsRequest(SLACK_ENDPOINT +GETAPI.slashList +"?token=" +this.token, (status, body) => {
  117. if (!status || !body || !body.ok)
  118. cb(null);
  119. else
  120. cb(body.commands || {});
  121. });
  122. };
  123. Slack.prototype.getEmojis = function(cb) {
  124. httpsRequest(SLACK_ENDPOINT +GETAPI.emojiList +"?token=" +this.token, (status, body) => {
  125. if (!status || !body || !body.ok)
  126. cb(null);
  127. else
  128. cb(body.emoji || {});
  129. });
  130. };
  131. Slack.prototype.poll = function(knownVersion, now) {
  132. if (this.connected) {
  133. var updatedCtx = this.data.getUpdates(knownVersion)
  134. ,updatedTyping = this.data.getWhoIsTyping(now)
  135. ,updatedLive = this.getLiveUpdates(knownVersion);
  136. if (updatedCtx || updatedLive || updatedTyping) {
  137. return {
  138. "static": updatedCtx,
  139. "live": updatedLive,
  140. "typing": updatedTyping,
  141. "v": Math.max(this.data.liveV, this.data.staticV)
  142. };
  143. }
  144. }
  145. };
  146. /** @return {Object|undefined} */
  147. Slack.prototype.getLiveUpdates = function(knownVersion) {
  148. var result = {};
  149. for (var roomId in this.history) {
  150. var history = this.history[roomId];
  151. if (history.isNew) {
  152. result[roomId] = history.toStatic(0);
  153. history.isNew = false;
  154. }
  155. else {
  156. var roomData = history.toStatic(knownVersion);
  157. if (roomData.length)
  158. result[roomId] = roomData;
  159. }
  160. }
  161. for (var roomId in result) {
  162. return result;
  163. }
  164. return undefined;
  165. };
  166. Slack.prototype.unstackPendingMessages = function() {
  167. for (var i = this.pendingMessages.length -1; i >= 0; i--) {
  168. this.onMessage(this.pendingMessages[0], Date.now());
  169. this.pendingMessages.shift();
  170. }
  171. };
  172. Slack.prototype.resetVersions = function(v) {
  173. this.data.team.version = v;
  174. for (var i in this.data.channels)
  175. this.data.channels[i].version = v;
  176. for (var i in this.data.users)
  177. this.data.users[i].version = v;
  178. if (this.data.self && this.data.self.prefs)
  179. this.data.self.prefs.version = v;
  180. this.data.staticV = v;
  181. };
  182. Slack.prototype.onMessage = function(msg, t) {
  183. if (msg["reply_to"] && this.pendingRtm[msg["reply_to"]]) {
  184. var ts = msg["ts"]
  185. ,rtmId = msg["reply_to"];
  186. msg = this.pendingRtm[rtmId];
  187. msg["ts"] = ts;
  188. delete this.pendingRtm[rtmId];
  189. }
  190. if (msg["type"] === "hello" && msg["start"] && msg["start"]["rtm_start"]) {
  191. var _this = this;
  192. _this.getEmojis((emojis) => {
  193. _this.getSlashCommands((commands) => {
  194. var msgContent = msg.start.rtm_start;
  195. var now = Date.now();
  196. msgContent.self = msg.self;
  197. msgContent.emojis = emojis;
  198. msgContent.commands = commands;
  199. _this.resetVersions(now);
  200. _this.data.updateStatic(msgContent, now);
  201. _this.connected = true;
  202. _this.unstackPendingMessages();
  203. });
  204. });
  205. } else if (this.connected) {
  206. this.data.onMessage(msg, t);
  207. if ((msg["channel"] || msg["channel_id"] || (msg["item"] && msg["item"]["channel"])) && msg["type"] && UPDATE_LIVE.indexOf(msg["type"]) !== -1) {
  208. var channelId = this.data.team.id +'|' +(msg["channel"] || msg["channel_id"] || msg["item"]["channel"])
  209. ,channel = this.data.channels[channelId]
  210. ,histo = this.history[channelId];
  211. // FIXME remove typing for user
  212. if (!histo) {
  213. histo = this.history[channelId] = new SlackHistory(this, channel.remoteId, channelId, this.data.team.id +'|', HISTORY_LENGTH);
  214. histo.isNew = true;
  215. }
  216. var lastMsg = histo.push(msg, t);
  217. if (lastMsg)
  218. this.data.liveV = t;
  219. histo.resort();
  220. if (channel)
  221. channel.setLastMsg(lastMsg, t);
  222. }
  223. } else {
  224. this.pendingMessages.push(msg);
  225. }
  226. };
  227. /**
  228. * @param {SlackChan|SlackGroup|SlackIms} chan
  229. * @param {string} id
  230. * @param {number} ts
  231. **/
  232. Slack.prototype.markRead = function(chan, id, ts) {
  233. var apiURI;
  234. if (chan.remoteId[0] === 'C')
  235. apiURI = SLACK_ENDPOINT+GETAPI.read.channel;
  236. else if (chan.remoteId[0] === 'G')
  237. apiURI = SLACK_ENDPOINT+GETAPI.read.group;
  238. else if (chan.remoteId[0] === 'D')
  239. apiURI = SLACK_ENDPOINT+GETAPI.read.im;
  240. httpsRequest(apiURI
  241. +"?token=" +this.token
  242. +"&channel="+chan.remoteId
  243. +"&ts="+id);
  244. };
  245. Slack.prototype.connectRtm = function(url, cb) {
  246. var _this = this;
  247. this.rtmId = 1;
  248. var protocol = url.substr(0, url.indexOf('://') +3);
  249. url = url.substr(protocol.length);
  250. url = protocol +url.substr(0, url.indexOf('/'))+
  251. "/?flannel=1&token=" +this.token+
  252. "&start_args="+
  253. encodeURIComponent("?simple_latest=true&presence_sub=true&mpim_aware=false&canonical_avatars=true")
  254. this.rtm = new WebSocket(url);
  255. this.rtm.on("message", function(msg) {
  256. if (!_this.connected && cb) {
  257. cb();
  258. }
  259. try {
  260. msg = JSON.parse(msg);
  261. } catch (ex) {
  262. console.error("WTF invalid JSON ", msg);
  263. }
  264. _this.onMessage(msg, Date.now());
  265. });
  266. this.rtm.once("error", function(e) {
  267. _this.connected = false;
  268. console.error(e);
  269. _this.close();
  270. });
  271. this.rtm.once("end", function() {
  272. console.error("RTM hang up");
  273. _this.onClose();
  274. });
  275. };
  276. Slack.prototype.onClose = function() {
  277. this.manager.suicide(this);
  278. };
  279. Slack.prototype.ping = function() {
  280. httpsRequest(SLACK_ENDPOINT+GETAPI.setActive
  281. +"?token=" +this.token);
  282. };
  283. Slack.prototype.rtmPing = function() {
  284. if (this.connected) {
  285. if (this.pendingPing && this.pendingRtm[this.pendingPing]) {
  286. //FIXME timeout
  287. console.error("Ping timeout");
  288. } else {
  289. var rtmId = this.rtmId++;
  290. this.pendingRtm[rtmId] = { type: 'ping' };
  291. this.pendingPing = rtmId;
  292. this.rtm.send('{"id":' +rtmId +',"type":"ping"}');
  293. }
  294. }
  295. };
  296. Slack.prototype.close = function() {
  297. if (!this.closing) {
  298. this.closing = true;
  299. if (this.rtm)
  300. this.rtm.close();
  301. this.onClose();
  302. }
  303. };
  304. Slack.getUserId = function(code, redirectUri, cb) {
  305. Slack.getOauthToken(code, redirectUri, (token) => {
  306. if (token) {
  307. httpsRequest(SLACK_ENDPOINT+GETAPI.identityEmail +"?token="+token,
  308. (status, resp) => {
  309. if (status === 200 && resp.ok && resp.user && resp.user.email) {
  310. cb(resp.user.id +'_' +resp.team.id);
  311. } else {
  312. cb(null);
  313. }
  314. });
  315. } else {
  316. cb(null);
  317. }
  318. });
  319. };
  320. Slack.getOauthToken = function(code, cb) {
  321. httpsRequest(SLACK_ENDPOINT+GETAPI.oauth
  322. +"?client_id=" +config.services.Slack.clientId
  323. +"&client_secret=" +config.services.Slack.clientSecret
  324. +"&redirect_uri=" +encodeURIComponent(config.rootUrl +"account/addservice/slack")
  325. +"&code=" +code,
  326. (status, resp) => {
  327. if (status === 200 && resp.ok) {
  328. cb(resp["team_name"], resp["team_id"] +resp["user_id"], resp["access_token"]);
  329. } else {
  330. cb(null);
  331. }
  332. });
  333. };
  334. /**
  335. * @param {SlackChan|SlackGroup|SlackIms} channel
  336. * @param {string} contentType
  337. * @param {function(string|null)} callback
  338. **/
  339. Slack.prototype.openUploadFileStream = function(channel, contentType, callback) {
  340. var req = https.request({
  341. hostname: SLACK_HOSTNAME
  342. ,method: 'POST'
  343. ,path: SLACK_ENDPOINT_PATH +GETAPI.postFile
  344. +"?token=" +this.token
  345. +"&channels=" +channel.remoteId
  346. ,headers: {
  347. "Content-Type": contentType
  348. }
  349. }, (res) => {
  350. var errorJson;
  351. res.on("data", (chunk) => {
  352. errorJson = errorJson ? Buffer.concat([errorJson, chunk], errorJson.length +chunk.length) : Buffer.from(chunk);
  353. });
  354. res.once("end", () => {
  355. if (res.statusCode === 200) {
  356. callback(null);
  357. } else {
  358. try {
  359. errorJson = JSON.parse(errorJson.toString());
  360. } catch(e) {
  361. callback("error");
  362. return;
  363. }
  364. callback(errorJson["error"] || "error");
  365. }
  366. });
  367. });
  368. return req;
  369. };
  370. function findBoundary() {
  371. const prefix = '-'.repeat(15)
  372. ,alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  373. ,doYouKnowWhoManyTheyAre = alphabet.length // 26 letters in da alphabet
  374. ,nbArg = arguments.length;
  375. for (let i =0; i < doYouKnowWhoManyTheyAre; i++)
  376. bLoop: for (let j =0; j < doYouKnowWhoManyTheyAre; j++) {
  377. const boundary = prefix +alphabet[i] +alphabet[j];
  378. for (let argIndex =0; argIndex < nbArg; argIndex++) {
  379. if (arguments[argIndex].indexOf(boundary) >= 0)
  380. continue bLoop;
  381. }
  382. return boundary;
  383. }
  384. }
  385. function encodeWithBoundary(boundary, data) {
  386. var resp = "";
  387. for (var k in data) {
  388. resp += '--' +boundary +'\r\n';
  389. resp += 'Content-Disposition: form-data; name="' +k +'"\r\n\r\n'
  390. +data[k]
  391. +'\r\n';
  392. };
  393. return resp +'--' +boundary +'--\r\n';
  394. }
  395. /**
  396. * @param {string} serviceId
  397. * @param {Object} payload
  398. * @param {function(string|null)=} callback
  399. **/
  400. Slack.prototype.sendAction = function(serviceId, payload, callback) {
  401. var channel = this.data.channels[payload["channel_id"]]
  402. ,service = this.data.users[serviceId];
  403. if (channel && service) {
  404. payload["channel_id"] = channel.remoteId;
  405. var payloadString = JSON.stringify(payload)
  406. ,boundary = findBoundary(service.remoteId, payloadString)
  407. ,body = encodeWithBoundary(boundary, {
  408. "service_id": service.remoteId
  409. ,"payload": payloadString
  410. });
  411. var req = https.request({
  412. hostname: SLACK_HOSTNAME
  413. ,method: 'POST'
  414. ,path: SLACK_ENDPOINT_PATH +GETAPI.sendAction +"?token=" +this.token
  415. ,headers: {
  416. "Content-Type": "multipart/form-data; boundary=" +boundary,
  417. "Content-Length": body.length
  418. }
  419. }, (res) => {
  420. if (callback) {
  421. var resp = [];
  422. res.on("data", (chunk) => { resp.push(chunk); });
  423. res.once("end", () => {
  424. resp = Buffer.concat(resp).toString();
  425. try {
  426. resp = JSON.parse(resp);
  427. } catch (e) {
  428. resp = null;
  429. }
  430. callback(resp && resp.ok ? resp : false);
  431. });
  432. }
  433. });
  434. req.end(body);
  435. return true;
  436. }
  437. return false;
  438. };
  439. /**
  440. * @param {SlackChan|SlackGroup|SlackIms} channel
  441. * @param {string} contentType
  442. * @param {function(string|null)} callback
  443. **/
  444. Slack.prototype.openUploadFileStream = function(channel, contentType, callback) {
  445. var req = https.request({
  446. hostname: SLACK_HOSTNAME
  447. ,method: 'POST'
  448. ,path: SLACK_ENDPOINT_PATH +GETAPI.postFile
  449. +"?token=" +this.token
  450. +"&channels=" +channel.remoteId
  451. ,headers: {
  452. "Content-Type": contentType
  453. }
  454. }, (res) => {
  455. var errorJson;
  456. res.on("data", (chunk) => {
  457. errorJson = errorJson ? Buffer.concat([errorJson, chunk], errorJson.length +chunk.length) : Buffer.from(chunk);
  458. });
  459. res.once("end", () => {
  460. if (res.statusCode === 200) {
  461. callback(null);
  462. } else {
  463. try {
  464. errorJson = JSON.parse(errorJson.toString());
  465. } catch(e) {
  466. callback("error");
  467. return;
  468. }
  469. callback(errorJson["error"] || "error");
  470. }
  471. });
  472. });
  473. return req;
  474. };
  475. /**
  476. * @param {SlackChan|SlackGroup|SlackIms} channel
  477. * @param {string} msgId
  478. * @param {string} reaction
  479. **/
  480. Slack.prototype.addReaction = function(channel, msgId, reaction) {
  481. httpsRequest(SLACK_ENDPOINT +GETAPI.addReaction
  482. +"?token=" +this.token
  483. +"&name=" +reaction
  484. +"&channel="+channel.remoteId
  485. +"&timestamp="+msgId);
  486. }
  487. /**
  488. * @param {SlackChan|SlackGroup|SlackIms} channel
  489. * @param {string} msgId
  490. * @param {string} reaction
  491. **/
  492. Slack.prototype.removeReaction = function(channel, msgId, reaction) {
  493. httpsRequest(SLACK_ENDPOINT +GETAPI.removeReaction
  494. +"?token=" +this.token
  495. +"&name=" +reaction
  496. +"&channel="+channel.remoteId
  497. +"&timestamp="+msgId);
  498. }
  499. /**
  500. * @param {SlackChan|SlackGroup|SlackIms} channel
  501. * @param {Array.<string>} text
  502. **/
  503. Slack.prototype.sendMeMsg = function(channel, text) {
  504. httpsRequest(SLACK_ENDPOINT +GETAPI.postMeMsg
  505. +"?token=" +this.token
  506. +"&channel=" +channel.remoteId
  507. +"&text=" +text.join("\n")
  508. +"&as_user=true");
  509. };
  510. /**
  511. * @param {SlackChan|SlackGroup|SlackIms} channel
  512. **/
  513. Slack.prototype.starChannel = function(channel) {
  514. httpsRequest(SLACK_ENDPOINT +GETAPI.starChannel
  515. +"?token=" +this.token
  516. +"&channel=" +channel.remoteId);
  517. };
  518. /**
  519. * @param {SlackChan|SlackGroup|SlackIms} channel
  520. **/
  521. Slack.prototype.unstarChannel = function(channel) {
  522. httpsRequest(SLACK_ENDPOINT +GETAPI.unstarChannel
  523. +"?token=" +this.token
  524. +"&channel=" +channel.remoteId);
  525. };
  526. /**
  527. * @param {SlackChan|SlackGroup|SlackIms} channel
  528. * @param {Array.<string>} text
  529. * @param {Array.<Object>=} attachments
  530. **/
  531. Slack.prototype.sendMsg = function(channel, text, attachments) {
  532. if (attachments) {
  533. attachments.forEach((attachmentObj) => {
  534. if (attachmentObj["ts"])
  535. attachmentObj["ts"] /= 1000;
  536. });
  537. httpsRequest(SLACK_ENDPOINT +GETAPI.postMsg
  538. +"?token=" +this.token
  539. +"&channel=" +channel.remoteId
  540. +"&text=" +text.join("\n")
  541. + (attachments ? ("&attachments=" +encodeURIComponent(JSON.stringify(attachments))) : "")
  542. +"&as_user=true");
  543. } else {
  544. var decodedText = [];
  545. text.forEach(function(i) {
  546. decodedText.push(decodeURIComponent(i));
  547. });
  548. var fullDecodedText = decodedText.join("\n");
  549. this.pendingRtm[this.rtmId] = {
  550. type: 'message',
  551. channel: channel.remoteId,
  552. user: this.data.self.remoteId,
  553. text: fullDecodedText
  554. };
  555. this.rtm.send('{"id":' +this.rtmId++ +',"type":"message","channel":"' +channel.remoteId +'", "text":' +JSON.stringify(fullDecodedText) +'}');
  556. }
  557. };
  558. /**
  559. * @param {SlackChan|SlackGroup|SlackIms} channel
  560. * @param {string} msgId
  561. **/
  562. Slack.prototype.removeMsg = function(channel, msgId) {
  563. httpsRequest(SLACK_ENDPOINT +GETAPI.removeMsg
  564. +"?token=" +this.token
  565. +"&channel=" +channel.remoteId
  566. +"&ts=" +msgId
  567. +"&as_user=true");
  568. };
  569. /**
  570. * @param {SlackChan|SlackGroup|SlackIms} channel
  571. * @param {string} msgId
  572. * @param {string} text
  573. **/
  574. Slack.prototype.editMsg = function(channel, msgId, text) {
  575. httpsRequest(SLACK_ENDPOINT +GETAPI.editMsg
  576. +"?token=" +this.token
  577. +"&channel=" +channel.remoteId
  578. +"&ts=" +msgId
  579. +"&text=" +text.join("\n")
  580. +"&as_user=true");
  581. };
  582. /**
  583. * @param {SlackChan|SlackGroup|SlackIms} target
  584. **/
  585. Slack.prototype.fetchHistory = function(target, cb, count, firstMsgId) {
  586. var _this = this
  587. ,baseUrl = ""
  588. ,targetId = target.remoteId;
  589. if (targetId[0] === 'D') {
  590. baseUrl = SLACK_ENDPOINT +GETAPI.directHistory;
  591. } else if (targetId[0] === 'C') {
  592. baseUrl = SLACK_ENDPOINT +GETAPI.channelHistory;
  593. } else if (targetId[0] === 'G') {
  594. baseUrl = SLACK_ENDPOINT +GETAPI.groupHistory;
  595. }
  596. httpsRequest(baseUrl
  597. +"?token="+this.token
  598. +"&channel=" +targetId
  599. +(firstMsgId ? ("&inclusive=true&latest=" +firstMsgId) : "")
  600. +"&count=" +(count || 100),
  601. (status, resp) => {
  602. var history = [];
  603. if (status === 200 && resp && resp.ok) {
  604. var histo = this.history[target.id];
  605. if (!histo)
  606. histo = this.history[target.id] = new SlackHistory(_this, target.remoteId, target.id, this.data.team.id +'|', HISTORY_LENGTH, HISTORY_MAX_AGE);
  607. resp.messages.forEach((respMsg) => {
  608. respMsg["id"] = respMsg["ts"];
  609. history.push(histo.messageFactory(histo.prepareMessage(respMsg)));
  610. });
  611. }
  612. cb(history);
  613. });
  614. };
  615. Slack.prototype.getChatContext = function() {
  616. return this.data;
  617. };
  618. module.exports.Slack = Slack;