slack-legacy.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import type { ChatPostMessageArguments } from '@slack/web-api';
  2. import { WebClient } from '@slack/web-api';
  3. import { IncomingWebhook, type IncomingWebhookSendArguments } from '@slack/webhook';
  4. import loggerFactory from '~/utils/logger';
  5. const logger = loggerFactory('growi:util:slack-legacy');
  6. interface SlackLegacyUtil {
  7. postMessage(messageObj: IncomingWebhookSendArguments | ChatPostMessageArguments): Promise<void>,
  8. }
  9. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  10. export const slackLegacyUtilFactory = (configManager: any): SlackLegacyUtil => {
  11. const postWithIwh = async(messageObj: IncomingWebhookSendArguments) => {
  12. const webhook = new IncomingWebhook(configManager.getConfig('notification', 'slack:incomingWebhookUrl'));
  13. try {
  14. await webhook.send(messageObj);
  15. }
  16. catch (error) {
  17. logger.debug('Post error', error);
  18. logger.debug('Sent data to slack is:', messageObj);
  19. throw error;
  20. }
  21. };
  22. const postWithWebApi = async(messageObj?: ChatPostMessageArguments) => {
  23. const client = new WebClient(configManager.getConfig('notification', 'slack:token'));
  24. try {
  25. await client.chat.postMessage(messageObj);
  26. }
  27. catch (error) {
  28. logger.debug('Post error', error);
  29. logger.debug('Sent data to slack is:', messageObj);
  30. throw error;
  31. }
  32. };
  33. return {
  34. postMessage: async(messageObj) => {
  35. // when incoming Webhooks is prioritized
  36. if (configManager.getConfig('notification', 'slack:isIncomingWebhookPrioritized')) {
  37. if (configManager.getConfig('notification', 'slack:incomingWebhookUrl')) {
  38. logger.debug('posting message with IncomingWebhook');
  39. return postWithIwh(messageObj as IncomingWebhookSendArguments);
  40. }
  41. if (configManager.getConfig('notification', 'slack:token')) {
  42. logger.debug('posting message with Web API');
  43. return postWithWebApi(messageObj as ChatPostMessageArguments);
  44. }
  45. }
  46. // else
  47. else {
  48. if (configManager.getConfig('notification', 'slack:token')) {
  49. logger.debug('posting message with Web API');
  50. return postWithWebApi(messageObj as ChatPostMessageArguments);
  51. }
  52. if (configManager.getConfig('notification', 'slack:incomingWebhookUrl')) {
  53. logger.debug('posting message with IncomingWebhook');
  54. return postWithIwh(messageObj as IncomingWebhookSendArguments);
  55. }
  56. }
  57. },
  58. };
  59. };