-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslack.service.ts
More file actions
49 lines (43 loc) · 1.38 KB
/
slack.service.ts
File metadata and controls
49 lines (43 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { BadRequestException, Injectable } from '@nestjs/common';
import { WebAPICallResult, WebClient } from '@slack/web-api';
import { ConfigService } from 'nestjs-config';
@Injectable()
export class SlackService {
private readonly webClient: WebClient;
private readonly channel: string;
constructor(
private readonly configService: ConfigService,
) {
this.webClient = new WebClient(configService.get('slack.apiToken'));
this.channel = configService.get('slack.channel');
}
public async sendToChannel(message: string, channel = null): Promise<WebAPICallResult> {
try {
return this.webClient.chat.postMessage({
channel: channel || this.channel,
text: message,
});
} catch (e) {
throw new BadRequestException(`Unable to post a message to channel ${channel}`);
}
}
public async sendToUser(message: string, email: string): Promise<WebAPICallResult> {
let user;
try {
const userResponse = await this.webClient.users.lookupByEmail({
email,
});
user = userResponse.user;
} catch (e) {
throw new BadRequestException(`Unable to lookup user by email '${email}'`);
}
try {
return await this.webClient.chat.postMessage({
channel: user.id,
text: message,
});
} catch (e) {
throw new BadRequestException(`Unable to post a message to ${email}`);
}
}
}