respond-if-slackbot-error.js 1.9 KB

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