slackbot-response.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const logger = require('@alias/logger')('growi:service:SlackCommandHandler:slack-bot-response');
  2. const { markdownSectionBlock } = require('@growi/slack');
  3. const SlackbotError = require('../../models/vo/slackbot-error');
  4. module.exports = async function(client, body, callback) {
  5. // check if the request is to /commands OR /interactions
  6. const isInteraction = !body.channel_id;
  7. try {
  8. await callback();
  9. }
  10. catch (err) {
  11. // throw non-SlackbotError
  12. if (!SlackbotError.isSlackbotError(err)) {
  13. logger.error(`A non-SlackbotError error occured.\n${err.toString()}`);
  14. throw err;
  15. }
  16. // for both postMessage and postEphemeral
  17. let toChannel;
  18. // for only postEphemeral
  19. let toUser;
  20. // decide which channel to send to
  21. switch (err.to) {
  22. case 'dm':
  23. toChannel = isInteraction ? JSON.parse(body.payload).user.id : body.user_id;
  24. toUser = toChannel;
  25. break;
  26. case 'channel':
  27. toChannel = isInteraction ? JSON.parse(body.payload).channel.id : body.channel_id;
  28. toUser = isInteraction ? JSON.parse(body.payload).user.id : body.user_id;
  29. break;
  30. default:
  31. logger.error('The "to" property of SlackbotError must be "dm" or "channel".');
  32. break;
  33. }
  34. // argumentObj object to pass to postMessage OR postEphemeral
  35. let argumentsObj = {};
  36. switch (err.method) {
  37. case 'postMessage':
  38. argumentsObj = {
  39. channel: toChannel,
  40. text: err.popupMessage,
  41. blocks: [
  42. markdownSectionBlock(err.mainMessage),
  43. ],
  44. };
  45. break;
  46. case 'postEphemeral':
  47. argumentsObj = {
  48. channel: toChannel,
  49. user: toUser,
  50. text: err.popupMessage,
  51. blocks: [
  52. markdownSectionBlock(err.mainMessage),
  53. ],
  54. };
  55. break;
  56. default:
  57. logger.error('The "method" property of SlackbotError must be "postMessage" or "postEphemeral".');
  58. break;
  59. }
  60. await client.chat[err.method](argumentsObj);
  61. }
  62. };