bolt.js 9.1 KB

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