bolt.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. this.showNextResults(command, args, offset);
  102. });
  103. this.bolt.action('shareSearchResults', async({
  104. body, ack, say, action,
  105. }) => {
  106. await ack();
  107. await say(action.value);
  108. });
  109. }
  110. notCommand(command) {
  111. logger.error('Invalid first argument');
  112. this.client.chat.postEphemeral({
  113. channel: command.channel_id,
  114. user: command.user_id,
  115. blocks: [
  116. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  117. ],
  118. });
  119. return;
  120. }
  121. showNextResults = (command, args, offset) => {
  122. const newOffset = offset + 10;
  123. this.showEphemeralSearchResults(command, args, newOffset);
  124. }
  125. async getSearchResultPaths(command, args, offset = 0) {
  126. const firstKeyword = args[1];
  127. if (firstKeyword == null) {
  128. this.client.chat.postEphemeral({
  129. channel: command.channel_id,
  130. user: command.user_id,
  131. blocks: [
  132. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  133. ],
  134. });
  135. return;
  136. }
  137. // removing 'search' from the head in the array.
  138. const shiftedValue = args.shift();
  139. const keywords = args.join(' ');
  140. // adding 'search' to the head in the array again.
  141. args.unshift(shiftedValue);
  142. const { searchService } = this.crowi;
  143. const options = { limit: 10, offset };
  144. const results = await searchService.searchKeyword(keywords, null, {}, options);
  145. // no search results
  146. if (results.data.length === 0) {
  147. logger.info(`No page found with "${keywords}"`);
  148. this.client.chat.postEphemeral({
  149. channel: command.channel_id,
  150. user: command.user_id,
  151. blocks: [
  152. this.generateMarkdownSectionBlock(`*No page that matches your keyword(s) "${keywords}".*`),
  153. this.generateMarkdownSectionBlock(':mag: *Help: Searching*'),
  154. this.divider(),
  155. this.generateMarkdownSectionBlock('`word1` `word2` (divide with space) \n Search pages that include both word1, word2 in the title or body'),
  156. this.divider(),
  157. this.generateMarkdownSectionBlock('`"This is GROWI"` (surround with double quotes) \n Search pages that include the phrase "This is GROWI"'),
  158. this.divider(),
  159. this.generateMarkdownSectionBlock('`-keyword` \n Exclude pages that include keyword in the title or body'),
  160. this.divider(),
  161. this.generateMarkdownSectionBlock('`prefix:/user/` \n Search only the pages that the title start with /user/'),
  162. this.divider(),
  163. this.generateMarkdownSectionBlock('`-prefix:/user/` \n Exclude the pages that the title start with /user/'),
  164. this.divider(),
  165. this.generateMarkdownSectionBlock('`tag:wiki` \n Search for pages with wiki tag'),
  166. this.divider(),
  167. this.generateMarkdownSectionBlock('`-tag:wiki` \n Exclude pages with wiki tag'),
  168. ],
  169. });
  170. return;
  171. }
  172. const resultPaths = results.data.map((data) => {
  173. return data._source.path;
  174. });
  175. return {
  176. resultPaths, offset, keywords,
  177. };
  178. }
  179. async showEphemeralSearchResults(command, args, offset) {
  180. const {
  181. resultPaths, offset, keywords,
  182. } = await this.getSearchResultPaths(command, args, offset);
  183. if (resultPaths == null) {
  184. return;
  185. }
  186. const base = this.crowi.appService.getSiteUrl();
  187. const urls = resultPaths.map((path) => {
  188. const url = new URL(path, base);
  189. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  190. });
  191. const searchResultsNum = resultPaths.length;
  192. let searchResultsDesc;
  193. switch (searchResultsNum) {
  194. case 10:
  195. searchResultsDesc = 'Maximum number of results that can be displayed is 10';
  196. break;
  197. case 1:
  198. searchResultsDesc = `${searchResultsNum} page is found`;
  199. break;
  200. default:
  201. searchResultsDesc = `${searchResultsNum} pages are found`;
  202. break;
  203. }
  204. const keywordsAndDesc = `keyword(s) : "${keywords}" \n ${searchResultsDesc}.`;
  205. try {
  206. await this.client.chat.postEphemeral({
  207. channel: command.channel_id,
  208. user: command.user_id,
  209. blocks: [
  210. this.generateMarkdownSectionBlock(keywordsAndDesc),
  211. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  212. {
  213. type: 'actions',
  214. elements: [
  215. {
  216. type: 'button',
  217. text: {
  218. type: 'plain_text',
  219. text: 'Next',
  220. },
  221. action_id: 'showNextResults',
  222. value: JSON.stringify({ offset, command, args }),
  223. },
  224. {
  225. type: 'button',
  226. text: {
  227. type: 'plain_text',
  228. text: 'Share',
  229. },
  230. style: 'primary',
  231. action_id: 'shareSearchResults',
  232. value: `${keywordsAndDesc} \n\n ${urls.join('\n')}`,
  233. },
  234. ],
  235. },
  236. ],
  237. });
  238. }
  239. catch {
  240. logger.error('Failed to get search results.');
  241. await this.client.chat.postEphemeral({
  242. channel: command.channel_id,
  243. user: command.user_id,
  244. blocks: [
  245. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  246. ],
  247. });
  248. throw new Error('/growi command:search: Failed to search');
  249. }
  250. }
  251. async createModal(command, client, body) {
  252. const User = this.crowi.model('User');
  253. const slackUser = await User.findUserByUsername('slackUser');
  254. // if "slackUser" is null, don't show create Modal
  255. if (slackUser == null) {
  256. logger.error('Failed to create a page because slackUser is not found.');
  257. this.client.chat.postEphemeral({
  258. channel: command.channel_id,
  259. user: command.user_id,
  260. blocks: [this.generateMarkdownSectionBlock('*slackUser does not exist.*')],
  261. });
  262. throw new Error('/growi command:create: slackUser is not found');
  263. }
  264. try {
  265. await client.views.open({
  266. trigger_id: body.trigger_id,
  267. view: {
  268. type: 'modal',
  269. callback_id: 'createPage',
  270. title: {
  271. type: 'plain_text',
  272. text: 'Create Page',
  273. },
  274. submit: {
  275. type: 'plain_text',
  276. text: 'Submit',
  277. },
  278. close: {
  279. type: 'plain_text',
  280. text: 'Cancel',
  281. },
  282. blocks: [
  283. this.generateMarkdownSectionBlock('Create new page.'),
  284. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  285. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  286. ],
  287. },
  288. });
  289. }
  290. catch (err) {
  291. logger.error('Failed to create a page.');
  292. await this.client.chat.postEphemeral({
  293. channel: command.channel_id,
  294. user: command.user_id,
  295. blocks: [
  296. this.generateMarkdownSectionBlock(`*Failed to create new page.*\n ${err}`),
  297. ],
  298. });
  299. throw err;
  300. }
  301. }
  302. // Submit action in create Modal
  303. async createPageInGrowi(view, body) {
  304. const User = this.crowi.model('User');
  305. const Page = this.crowi.model('Page');
  306. const pathUtils = require('growi-commons').pathUtils;
  307. const contentsBody = view.state.values.contents.contents_input.value;
  308. try {
  309. // search "slackUser" to create page in slack
  310. const slackUser = await User.findUserByUsername('slackUser');
  311. let path = view.state.values.path.path_input.value;
  312. // sanitize path
  313. path = this.crowi.xss.process(path);
  314. path = pathUtils.normalizePath(path);
  315. const user = slackUser._id;
  316. await Page.create(path, contentsBody, user, {});
  317. }
  318. catch (err) {
  319. this.client.chat.postMessage({
  320. channel: body.user.id,
  321. blocks: [
  322. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  323. });
  324. logger.error('Failed to create page in GROWI.');
  325. throw err;
  326. }
  327. }
  328. generateMarkdownSectionBlock(blocks) {
  329. return {
  330. type: 'section',
  331. text: {
  332. type: 'mrkdwn',
  333. text: blocks,
  334. },
  335. };
  336. }
  337. divider() {
  338. return {
  339. type: 'divider',
  340. };
  341. }
  342. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  343. return {
  344. type: 'input',
  345. block_id: blockId,
  346. label: {
  347. type: 'plain_text',
  348. text: labelText,
  349. },
  350. element: {
  351. type: 'plain_text_input',
  352. action_id: actionId,
  353. multiline: isMultiline,
  354. placeholder: {
  355. type: 'plain_text',
  356. text: placeholder,
  357. },
  358. },
  359. };
  360. }
  361. }
  362. module.exports = BoltService;