Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
♻️ Add Slack method to message channel
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary authored Nov 25, 2020
1 parent 918fbc6 commit 5afc6d2
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/providers/slack/slack.service.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<number>('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);
}
Expand Down

0 comments on commit 5afc6d2

Please sign in to comment.