bolt.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. // for verification request URL on Event Subscriptions
  12. if (body.type === 'url_verification') {
  13. return body;
  14. }
  15. const payload = body.payload;
  16. let reqBody;
  17. if (payload != null) {
  18. reqBody = JSON.parse(payload);
  19. }
  20. else {
  21. reqBody = body;
  22. }
  23. const event = {
  24. body: reqBody,
  25. ack: (response) => {
  26. if (ackCalled) {
  27. return null;
  28. }
  29. ackCalled = true;
  30. if (response instanceof Error) {
  31. const message = response.message || 'Error occurred';
  32. throw new Error(message);
  33. }
  34. else if (!response) {
  35. return null;
  36. }
  37. else {
  38. return response;
  39. }
  40. },
  41. };
  42. await this.bolt.processEvent(event);
  43. }
  44. }
  45. const { App } = require('@slack/bolt');
  46. const { WebClient, LogLevel } = require('@slack/web-api');
  47. class BoltService {
  48. constructor(crowi) {
  49. this.crowi = crowi;
  50. this.receiver = new BoltReciever();
  51. const signingSecret = crowi.configManager.getConfig('crowi', 'slackbot:signingSecret');
  52. const token = crowi.configManager.getConfig('crowi', 'slackbot:token');
  53. const client = new WebClient(token, { logLevel: LogLevel.DEBUG });
  54. this.client = client;
  55. if (token != null || signingSecret != null) {
  56. logger.debug('SlackBot: setup is done');
  57. this.bolt = new App({
  58. token,
  59. signingSecret,
  60. receiver: this.receiver,
  61. });
  62. this.init();
  63. }
  64. }
  65. init() {
  66. // Example of listening for event
  67. // See. https://github.com/slackapi/bolt-js#listening-for-events
  68. // or https://slack.dev/bolt-js/concepts#basic
  69. this.bolt.command('/growi-bot', async({ command, ack, say }) => { // demo
  70. await say('Hello');
  71. });
  72. // The echo command simply echoes on command
  73. this.bolt.command('/echo', async({ command, ack, say }) => {
  74. // Acknowledge command request
  75. await ack();
  76. await say(`${command.text}`);
  77. });
  78. this.bolt.command('/growi', async({
  79. command, client, body, ack,
  80. }) => {
  81. await ack();
  82. const args = command.text.split(' ');
  83. const firstArg = args[0];
  84. switch (firstArg) {
  85. case 'search':
  86. await this.showEphemeralSearchResults(command, args);
  87. break;
  88. case 'create':
  89. await this.createModal(command, client, body);
  90. break;
  91. default:
  92. this.notCommand(command);
  93. break;
  94. }
  95. });
  96. this.bolt.view('createPage', async({
  97. ack, view, body, client,
  98. }) => {
  99. await ack();
  100. await this.createPageInGrowi(view, body);
  101. });
  102. this.bolt.action('shareSearchResults', async({
  103. body, ack, say, action,
  104. }) => {
  105. await ack();
  106. await say(action.value);
  107. });
  108. }
  109. notCommand(command) {
  110. logger.error('Invalid first argument');
  111. this.client.chat.postEphemeral({
  112. channel: command.channel_id,
  113. user: command.user_id,
  114. blocks: [
  115. this.generateMarkdownSectionBlock('*No command.*\n Hint\n `/growi [command] [keyword]`'),
  116. ],
  117. });
  118. throw new Error('/growi command: Invalid first argument');
  119. }
  120. async getSearchResultPaths(command, args) {
  121. const firstKeyword = args[1];
  122. if (firstKeyword == null) {
  123. this.client.chat.postEphemeral({
  124. channel: command.channel_id,
  125. user: command.user_id,
  126. blocks: [
  127. this.generateMarkdownSectionBlock('*Input keywords.*\n Hint\n `/growi search [keyword]`'),
  128. ],
  129. });
  130. throw new Error('/growi command:search: Invalid keyword');
  131. }
  132. // remove leading 'search'.
  133. args.shift();
  134. const keywords = args.join(' ');
  135. const { searchService } = this.crowi;
  136. const option = { limit: 10 };
  137. const results = await searchService.searchKeyword(keywords, null, {}, option);
  138. // no search results
  139. if (results.data.length === 0) {
  140. logger.info(`No page found with "${keywords}"`);
  141. this.client.chat.postEphemeral({
  142. channel: command.channel_id,
  143. user: command.user_id,
  144. blocks: [this.generateMarkdownSectionBlock('*No page that match your keywords.*')],
  145. });
  146. return;
  147. }
  148. const resultPaths = results.data.map((data) => {
  149. return data._source.path;
  150. });
  151. return resultPaths;
  152. }
  153. async showEphemeralSearchResults(command, args) {
  154. const resultPaths = await this.getSearchResultPaths(command, args);
  155. try {
  156. await this.client.chat.postEphemeral({
  157. channel: command.channel_id,
  158. user: command.user_id,
  159. blocks: [
  160. this.generateMarkdownSectionBlock('10 results.'),
  161. this.generateMarkdownSectionBlock(`${resultPaths.join('\n')}`),
  162. {
  163. type: 'actions',
  164. elements: [
  165. {
  166. type: 'button',
  167. text: {
  168. type: 'plain_text',
  169. text: 'Share',
  170. },
  171. style: 'primary',
  172. action_id: 'shareSearchResults',
  173. value: `${resultPaths.join('\n')}`,
  174. },
  175. ],
  176. },
  177. ],
  178. });
  179. }
  180. catch {
  181. logger.error('Failed to get search results.');
  182. await this.client.chat.postEphemeral({
  183. channel: command.channel_id,
  184. user: command.user_id,
  185. blocks: [
  186. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  187. ],
  188. });
  189. throw new Error('/growi command:search: Failed to search');
  190. }
  191. }
  192. async createModal(command, client, body) {
  193. const User = this.crowi.model('User');
  194. const slackUser = await User.findUserByUsername('slackUser');
  195. // if "slackUser" is null, don't show create Modal
  196. if (slackUser == null) {
  197. logger.error('Failed to create a page because slackUser is not found.');
  198. this.client.chat.postEphemeral({
  199. channel: command.channel_id,
  200. user: command.user_id,
  201. blocks: [this.generateMarkdownSectionBlock('*slackUser does not exist.*')],
  202. });
  203. throw new Error('/growi command:create: slackUser is not found');
  204. }
  205. try {
  206. await client.views.open({
  207. trigger_id: body.trigger_id,
  208. view: {
  209. type: 'modal',
  210. callback_id: 'createPage',
  211. title: {
  212. type: 'plain_text',
  213. text: 'Create Page',
  214. },
  215. submit: {
  216. type: 'plain_text',
  217. text: 'Submit',
  218. },
  219. close: {
  220. type: 'plain_text',
  221. text: 'Cancel',
  222. },
  223. blocks: [
  224. this.generateMarkdownSectionBlock('Create new page.'),
  225. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  226. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  227. ],
  228. },
  229. });
  230. }
  231. catch (err) {
  232. logger.error('Failed to create a page.');
  233. await this.client.chat.postEphemeral({
  234. channel: command.channel_id,
  235. user: command.user_id,
  236. blocks: [
  237. this.generateMarkdownSectionBlock('*Failed to create new page.*\n Hint\n `/growi create`'),
  238. ],
  239. });
  240. throw err;
  241. }
  242. }
  243. // Submit action in create Modal
  244. async createPageInGrowi(view, body) {
  245. const User = this.crowi.model('User');
  246. const Page = this.crowi.model('Page');
  247. const pathUtils = require('growi-commons').pathUtils;
  248. const contentsBody = view.state.values.contents.contents_input.value;
  249. try {
  250. // search "slackUser" to create page in slack
  251. const slackUser = await User.findUserByUsername('slackUser');
  252. let path = view.state.values.path.path_input.value;
  253. // sanitize path
  254. path = this.crowi.xss.process(path);
  255. path = pathUtils.normalizePath(path);
  256. const user = slackUser._id;
  257. await Page.create(path, contentsBody, user, {});
  258. }
  259. catch (err) {
  260. this.client.chat.postMessage({
  261. channel: body.user.id,
  262. blocks: [
  263. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  264. });
  265. logger.error('Failed to create page in GROWI.');
  266. throw err;
  267. }
  268. }
  269. generateMarkdownSectionBlock(blocks) {
  270. return {
  271. type: 'section',
  272. text: {
  273. type: 'mrkdwn',
  274. text: blocks,
  275. },
  276. };
  277. }
  278. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  279. return {
  280. type: 'input',
  281. block_id: blockId,
  282. label: {
  283. type: 'plain_text',
  284. text: labelText,
  285. },
  286. element: {
  287. type: 'plain_text_input',
  288. action_id: actionId,
  289. multiline: isMultiline,
  290. placeholder: {
  291. type: 'plain_text',
  292. text: placeholder,
  293. },
  294. },
  295. };
  296. }
  297. }
  298. module.exports = BoltService;