1 | import { WebClient } from "@slack/web-api"; |
2 |
|
3 | const isEmail = (email: string): boolean => |
4 | /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); |
5 |
|
6 | type Slack = { |
7 | token: string; |
8 | }; |
9 | export async function main(user_email: string, text: string, slack: Slack) { |
10 | throwOnInvalidEmail(user_email); |
11 |
|
12 | const client = new WebClient(slack.token); |
13 | const userData = await getUserData(client, user_email); |
14 | console.log(userData); |
15 | const result = await sendDirectMessage(text, client, userData); |
16 |
|
17 | return result; |
18 | } |
19 |
|
20 | interface UserData { |
21 | id: string; |
22 | email: string; |
23 | real_name: string; |
24 | } |
25 |
|
26 | async function getUserData( |
27 | client: WebClient, |
28 | email: string, |
29 | ): Promise<UserData> { |
30 | try { |
31 | const response = await client.users.lookupByEmail({ email: email }); |
32 |
|
33 | const { id, real_name } = response.user; |
34 | return { id, email, real_name }; |
35 | } catch (err) { |
36 | return handleApiResponse(email, err); |
37 | } |
38 | } |
39 |
|
40 | async function sendDirectMessage( |
41 | text: string, |
42 | client: WebClient, |
43 | userData: UserData, |
44 | ) { |
45 | const { ok, ts, channel } = await client.chat.postMessage({ |
46 | channel: userData.id, |
47 | text, |
48 | }); |
49 | return { ok, ts, channel, email: userData.email }; |
50 | } |
51 |
|
52 | function throwOnInvalidEmail(email: string) { |
53 | if (!isEmail(email)) { |
54 | throw new Error("Expected user email"); |
55 | } |
56 | } |
57 |
|
58 | function handleApiResponse(email: string, error: Error) { |
59 | return Promise.reject({ email, err_msg: error.message }); |
60 | } |
61 |
|