bolt.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. const logger = require('@alias/logger')('growi:service:BoltService');
  2. class BoltReciever {
  3. init(app) {
  4. this.bolt = app;
  5. }
  6. async requestHandler(body) {
  7. if (this.bolt === undefined) {
  8. throw new Error('Slack Bot service is not setup');
  9. }
  10. let ackCalled = false;
  11. const payload = body.payload;
  12. let reqBody;
  13. if (payload != null) {
  14. reqBody = JSON.parse(payload);
  15. }
  16. else {
  17. reqBody = body;
  18. }
  19. const event = {
  20. body: reqBody,
  21. ack: (response) => {
  22. if (ackCalled) {
  23. return;
  24. }
  25. ackCalled = true;
  26. if (response instanceof Error) {
  27. const message = response.message || 'Error occurred';
  28. throw new Error(message);
  29. }
  30. return;
  31. },
  32. };
  33. await this.bolt.processEvent(event);
  34. }
  35. }
  36. const { App } = require('@slack/bolt');
  37. const { WebClient, LogLevel } = require('@slack/web-api');
  38. class BoltService {
  39. constructor(crowi) {
  40. this.crowi = crowi;
  41. this.receiver = new BoltReciever();
  42. const signingSecret = crowi.configManager.getConfig('crowi', 'slackbot:signingSecret');
  43. const token = crowi.configManager.getConfig('crowi', 'slackbot:token');
  44. const client = new WebClient(token, { logLevel: LogLevel.DEBUG });
  45. this.client = client;
  46. if (token != null || signingSecret != null) {
  47. logger.debug('SlackBot: setup is done');
  48. this.bolt = new App({
  49. token,
  50. signingSecret,
  51. receiver: this.receiver,
  52. });
  53. this.init();
  54. }
  55. }
  56. init() {
  57. // Example of listening for event
  58. // See. https://github.com/slackapi/bolt-js#listening-for-events
  59. // or https://slack.dev/bolt-js/concepts#basic
  60. this.bolt.command('/growi-bot', async({ command, ack, say }) => { // demo
  61. await say('Hello');
  62. });
  63. // The echo command simply echoes on command
  64. this.bolt.command('/echo', async({ command, ack, say }) => {
  65. // Acknowledge command request
  66. await ack();
  67. await say(`${command.text}`);
  68. });
  69. this.bolt.command('/growi', async({
  70. command, client, body, ack,
  71. }) => {
  72. await ack();
  73. const args = command.text.split(' ');
  74. const firstArg = args[0];
  75. switch (firstArg) {
  76. case 'search':
  77. await this.showEphemeralSearchResults(command, args);
  78. break;
  79. case 'create':
  80. await this.createModal(command, client, body);
  81. break;
  82. default:
  83. this.notCommand(command);
  84. break;
  85. }
  86. });
  87. this.bolt.view('createPage', async({
  88. ack, view, body, client,
  89. }) => {
  90. await ack();
  91. await this.createPageInGrowi(view, body);
  92. });
  93. this.bolt.action('showNextResults', async({
  94. ack, action,
  95. }) => {
  96. await ack();
  97. const parsedValue = JSON.parse(action.value);
  98. const command = parsedValue.command;
  99. const args = parsedValue.args;
  100. const offset = parsedValue.offset;
  101. const newOffset = offset + 10;
  102. this.showEphemeralSearchResults(command, args, newOffset);
  103. });
  104. this.bolt.action('shareSearchResults', async({
  105. body, ack, say, action,
  106. }) => {
  107. await ack();
  108. await say(action.value);
  109. });
  110. }
  111. notCommand(command) {
  112. logger.error('Invalid first argument');
  113. this.client.chat.postEphemeral({
  114. channel: command.channel_id,
  115. user: command.user_id,
  116. blocks: [
  117. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  118. ],
  119. });
  120. return;
  121. }
  122. async getSearchResultPaths(command, args, offset = 0) {
  123. const firstKeyword = args[1];
  124. if (firstKeyword == null) {
  125. this.client.chat.postEphemeral({
  126. channel: command.channel_id,
  127. user: command.user_id,
  128. blocks: [
  129. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  130. ],
  131. });
  132. return;
  133. }
  134. const keywordsArr = [];
  135. for (let i = 1; i < args.length; i++) {
  136. keywordsArr.push(args[i]);
  137. }
  138. const keywords = keywordsArr.join(' ');
  139. const { searchService } = this.crowi;
  140. const options = { limit: 10, offset };
  141. const results = await searchService.searchKeyword(keywords, null, {}, options);
  142. // no search results
  143. if (results.data.length === 0) {
  144. logger.info(`No page found with "${keywords}"`);
  145. this.client.chat.postEphemeral({
  146. channel: command.channel_id,
  147. user: command.user_id,
  148. blocks: [
  149. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  150. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  151. this.divider(),
  152. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  153. this.divider(),
  154. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  155. this.divider(),
  156. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  157. this.divider(),
  158. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  159. this.divider(),
  160. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  161. this.divider(),
  162. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  163. this.divider(),
  164. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  165. ],
  166. });
  167. return;
  168. }
  169. const resultPaths = results.data.map((data) => {
  170. return data._source.path;
  171. });
  172. return {
  173. resultPaths, offset, keywords,
  174. };
  175. }
  176. async showEphemeralSearchResults(command, args, offsetNum) {
  177. const {
  178. resultPaths, offset, keywords,
  179. } = await this.getSearchResultPaths(command, args, offsetNum);
  180. if (resultPaths == null) {
  181. return;
  182. }
  183. const base = this.crowi.appService.getSiteUrl();
  184. const urls = resultPaths.map((path) => {
  185. const url = new URL(path, base);
  186. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  187. });
  188. const searchResultsNum = resultPaths.length;
  189. let searchResultsDesc;
  190. switch (searchResultsNum) {
  191. case 10:
  192. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  193. break;
  194. case 1:
  195. searchResultsDesc = `${searchResultsNum} page is found`;
  196. break;
  197. default:
  198. searchResultsDesc = `${searchResultsNum} pages are found`;
  199. break;
  200. }
  201. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  202. try {
  203. if (searchResultsNum < 10) {
  204. return await this.client.chat.postEphemeral({
  205. channel: command.channel_id,
  206. user: command.user_id,
  207. blocks: [
  208. this.generateMarkdownSectionBlock(keywordsAndDesc),
  209. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  210. {
  211. type: 'actions',
  212. elements: [
  213. {
  214. type: 'button',
  215. text: {
  216. type: 'plain_text',
  217. text: 'Share',
  218. },
  219. style: 'primary',
  220. action_id: 'shareSearchResults',
  221. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  222. },
  223. ],
  224. },
  225. ],
  226. });
  227. }
  228. await this.client.chat.postEphemeral({
  229. channel: command.channel_id,
  230. user: command.user_id,
  231. blocks: [
  232. this.generateMarkdownSectionBlock(keywordsAndDesc),
  233. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  234. {
  235. type: 'actions',
  236. elements: [
  237. {
  238. type: 'button',
  239. text: {
  240. type: 'plain_text',
  241. text: 'Next',
  242. },
  243. action_id: 'showNextResults',
  244. value: JSON.stringify({ offset, command, args }),
  245. },
  246. {
  247. type: 'button',
  248. text: {
  249. type: 'plain_text',
  250. text: 'Share',
  251. },
  252. style: 'primary',
  253. action_id: 'shareSearchResults',
  254. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  255. },
  256. ],
  257. },
  258. ],
  259. });
  260. }
  261. catch {
  262. logger.error('Failed to get search results.');
  263. await this.client.chat.postEphemeral({
  264. channel: command.channel_id,
  265. user: command.user_id,
  266. blocks: [
  267. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  268. ],
  269. });
  270. throw new Error('/growi command:search: Failed to search');
  271. }
  272. }
  273. async createModal(command, client, body) {
  274. const User = this.crowi.model('User');
  275. const slackUser = await User.findUserByUsername('slackUser');
  276. // if "slackUser" is null, don't show create Modal
  277. if (slackUser == null) {
  278. logger.error('Failed to create a page because slackUser is not found.');
  279. this.client.chat.postEphemeral({
  280. channel: command.channel_id,
  281. user: command.user_id,
  282. blocks: [this.generateMarkdownSectionBlock('*slackUser does not exist.*')],
  283. });
  284. throw new Error('/growi command:create: slackUser is not found');
  285. }
  286. try {
  287. await client.views.open({
  288. trigger_id: body.trigger_id,
  289. view: {
  290. type: 'modal',
  291. callback_id: 'createPage',
  292. title: {
  293. type: 'plain_text',
  294. text: 'Create Page',
  295. },
  296. submit: {
  297. type: 'plain_text',
  298. text: 'Submit',
  299. },
  300. close: {
  301. type: 'plain_text',
  302. text: 'Cancel',
  303. },
  304. blocks: [
  305. this.generateMarkdownSectionBlock('Create new page.'),
  306. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  307. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  308. ],
  309. },
  310. });
  311. }
  312. catch (err) {
  313. logger.error('Failed to create a page.');
  314. await this.client.chat.postEphemeral({
  315. channel: command.channel_id,
  316. user: command.user_id,
  317. blocks: [
  318. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  319. ],
  320. });
  321. throw err;
  322. }
  323. }
  324. // Submit action in create Modal
  325. async createPageInGrowi(view, body) {
  326. const User = this.crowi.model('User');
  327. const Page = this.crowi.model('Page');
  328. const pathUtils = require('growi-commons').pathUtils;
  329. const contentsBody = view.state.values.contents.contents_input.value;
  330. try {
  331. // search "slackUser" to create page in slack
  332. const slackUser = await User.findUserByUsername('slackUser');
  333. let path = view.state.values.path.path_input.value;
  334. // sanitize path
  335. path = this.crowi.xss.process(path);
  336. path = pathUtils.normalizePath(path);
  337. const user = slackUser._id;
  338. await Page.create(path, contentsBody, user, {});
  339. }
  340. catch (err) {
  341. this.client.chat.postMessage({
  342. channel: body.user.id,
  343. blocks: [
  344. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  345. });
  346. logger.error('Failed to create page in GROWI.');
  347. throw err;
  348. }
  349. }
  350. generateMarkdownSectionBlock(blocks) {
  351. return {
  352. type: 'section',
  353. text: {
  354. type: 'mrkdwn',
  355. text: blocks,
  356. },
  357. };
  358. }
  359. divider() {
  360. return {
  361. type: 'divider',
  362. };
  363. }
  364. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  365. return {
  366. type: 'input',
  367. block_id: blockId,
  368. label: {
  369. type: 'plain_text',
  370. text: labelText,
  371. },
  372. element: {
  373. type: 'plain_text_input',
  374. action_id: actionId,
  375. multiline: isMultiline,
  376. placeholder: {
  377. type: 'plain_text',
  378. text: placeholder,
  379. },
  380. },
  381. };
  382. }
  383. }
  384. module.exports = BoltService;