From 5afc6d2323e354f5c9889f5b039e8f341877085d Mon Sep 17 00:00:00 2001 From: Anand Chowdhary Date: Wed, 25 Nov 2020 20:52:35 +0530 Subject: [PATCH] :recycle: Add Slack method to message channel --- src/providers/slack/slack.service.ts | 33 +++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/providers/slack/slack.service.ts b/src/providers/slack/slack.service.ts index 219a9eb8e..624fdc564 100644 --- a/src/providers/slack/slack.service.ts +++ b/src/providers/slack/slack.service.ts @@ -1,6 +1,10 @@ import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { ChatPostMessageArguments, WebClient } from '@slack/web-api'; +import { + ChatPostMessageArguments, + WebAPICallResult, + WebClient, +} from '@slack/web-api'; import PQueue from 'p-queue'; import pRetry from 'p-retry'; import { Configuration } from '../../config/configuration.interface'; @@ -37,6 +41,33 @@ export class SlackService { .catch(() => {}); } + sendToChannel(channelName: string, text: string) { + this.queue + .add(() => + pRetry(() => this.sendMessageToChannel(channelName, text), { + retries: this.configService.get('slack.retries') ?? 3, + onFailedAttempt: (error) => { + this.logger.error( + `Message to ${channelName} failed, retrying (${error.retriesLeft} attempts left)`, + error.name, + ); + }, + }), + ) + .then(() => {}) + .catch(() => {}); + } + + private async sendMessageToChannel(channelName: string, text: string) { + const conversations = (await this.client?.conversations.list()) as WebAPICallResult & { + channels: { name: string; id: string }[]; + }; + const channel = conversations.channels.find( + (channel) => channel.name === channelName, + ); + const options: ChatPostMessageArguments = { text, channel: channel.id }; + return this.client?.chat.postMessage(options); + } private async sendMessage(options: ChatPostMessageArguments) { return this.client?.chat.postMessage(options); }