bolt.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. const base = this.crowi.appService.getSiteUrl();
  156. const urls = resultPaths.map((path) => {
  157. const url = new URL(path, base);
  158. return `<${decodeURI(url.href)} | ${decodeURI(url.pathname)}>`;
  159. });
  160. try {
  161. await this.client.chat.postEphemeral({
  162. channel: command.channel_id,
  163. user: command.user_id,
  164. blocks: [
  165. this.generateMarkdownSectionBlock('10 results.'),
  166. this.generateMarkdownSectionBlock(`${urls.join('\n')}`),
  167. {
  168. type: 'actions',
  169. elements: [
  170. {
  171. type: 'button',
  172. text: {
  173. type: 'plain_text',
  174. text: 'Share',
  175. },
  176. style: 'primary',
  177. action_id: 'shareSearchResults',
  178. value: `${urls.join('\n')}`,
  179. },
  180. ],
  181. },
  182. ],
  183. });
  184. }
  185. catch {
  186. logger.error('Failed to get search results.');
  187. await this.client.chat.postEphemeral({
  188. channel: command.channel_id,
  189. user: command.user_id,
  190. blocks: [
  191. this.generateMarkdownSectionBlock('*Failed to search.*\n Hint\n `/growi search [keyword]`'),
  192. ],
  193. });
  194. throw new Error('/growi command:search: Failed to search');
  195. }
  196. }
  197. async createModal(command, client, body) {
  198. const User = this.crowi.model('User');
  199. const slackUser = await User.findUserByUsername('slackUser');
  200. // if "slackUser" is null, don't show create Modal
  201. if (slackUser == null) {
  202. logger.error('Failed to create a page because slackUser is not found.');
  203. this.client.chat.postEphemeral({
  204. channel: command.channel_id,
  205. user: command.user_id,
  206. blocks: [this.generateMarkdownSectionBlock('*slackUser does not exist.*')],
  207. });
  208. throw new Error('/growi command:create: slackUser is not found');
  209. }
  210. try {
  211. await client.views.open({
  212. trigger_id: body.trigger_id,
  213. view: {
  214. type: 'modal',
  215. callback_id: 'createPage',
  216. title: {
  217. type: 'plain_text',
  218. text: 'Create Page',
  219. },
  220. submit: {
  221. type: 'plain_text',
  222. text: 'Submit',
  223. },
  224. close: {
  225. type: 'plain_text',
  226. text: 'Cancel',
  227. },
  228. blocks: [
  229. this.generateMarkdownSectionBlock('Create new page.'),
  230. this.generateInputSectionBlock('path', 'Path', 'path_input', false, '/path'),
  231. this.generateInputSectionBlock('contents', 'Contents', 'contents_input', true, 'Input with Markdown...'),
  232. ],
  233. },
  234. });
  235. }
  236. catch (err) {
  237. logger.error('Failed to create a page.');
  238. await this.client.chat.postEphemeral({
  239. channel: command.channel_id,
  240. user: command.user_id,
  241. blocks: [
  242. this.generateMarkdownSectionBlock('*Failed to create new page.*\n Hint\n `/growi create`'),
  243. ],
  244. });
  245. throw err;
  246. }
  247. }
  248. // Submit action in create Modal
  249. async createPageInGrowi(view, body) {
  250. const User = this.crowi.model('User');
  251. const Page = this.crowi.model('Page');
  252. const pathUtils = require('growi-commons').pathUtils;
  253. const contentsBody = view.state.values.contents.contents_input.value;
  254. try {
  255. // search "slackUser" to create page in slack
  256. const slackUser = await User.findUserByUsername('slackUser');
  257. let path = view.state.values.path.path_input.value;
  258. // sanitize path
  259. path = this.crowi.xss.process(path);
  260. path = pathUtils.normalizePath(path);
  261. const user = slackUser._id;
  262. await Page.create(path, contentsBody, user, {});
  263. }
  264. catch (err) {
  265. this.client.chat.postMessage({
  266. channel: body.user.id,
  267. blocks: [
  268. this.generateMarkdownSectionBlock(`Cannot create new page to existed path\n *Contents* :memo:\n ${contentsBody}`)],
  269. });
  270. logger.error('Failed to create page in GROWI.');
  271. throw err;
  272. }
  273. }
  274. generateMarkdownSectionBlock(blocks) {
  275. return {
  276. type: 'section',
  277. text: {
  278. type: 'mrkdwn',
  279. text: blocks,
  280. },
  281. };
  282. }
  283. generateInputSectionBlock(blockId, labelText, actionId, isMultiline, placeholder) {
  284. return {
  285. type: 'input',
  286. block_id: blockId,
  287. label: {
  288. type: 'plain_text',
  289. text: labelText,
  290. },
  291. element: {
  292. type: 'plain_text_input',
  293. action_id: actionId,
  294. multiline: isMultiline,
  295. placeholder: {
  296. type: 'plain_text',
  297. text: placeholder,
  298. },
  299. },
  300. };
  301. }
  302. }
  303. module.exports = BoltService;