2
Send direct message
One script reply has been approved by the moderators Verified

Sends direct message to user (you must know user email)

Created by mrl5 736 days ago Viewed 10386 times
0
Submitted by mrl5 Deno
Verified 736 days ago
1
import { WebClient } from "https://deno.land/x/slack_web_api@1.0.3/mod.ts";
2
import { isEmail } from "https://deno.land/x/isemail@v1.0.1/mod.ts";
3

4
type Slack = {
5
  token: string;
6
};
7
export async function main(user_email: string, text: string, slack: Slack) {
8
  throwOnInvalidEmail(user_email);
9

10
  const client = new WebClient(slack.token);
11
  const userData = await getUserData(client, user_email);
12
  console.log(userData);
13
  const result = await sendDirectMessage(text, client, userData);
14

15
  return result;
16
}
17

18
interface UserData {
19
  id: string;
20
  email: string;
21
  real_name: string;
22
}
23

24
async function getUserData(
25
  client: WebClient,
26
  email: string,
27
): Promise<UserData> {
28
  try {
29
    const response = await client.users.lookupByEmail({ email: email });
30

31
    const { id, real_name } = response.user;
32
    return { id, email, real_name };
33
  } catch (err) {
34
    return handleApiResponse(email, err);
35
  }
36
}
37

38
async function sendDirectMessage(
39
  text: string,
40
  client: WebClient,
41
  userData: UserData,
42
) {
43
  const { ok, ts, channel } = await client.chat.postMessage({
44
    channel: userData.id,
45
    text,
46
  });
47
  return { ok, ts, channel, email: userData.email };
48
}
49

50
function throwOnInvalidEmail(email: string) {
51
  if (!isEmail(email)) {
52
    throw new Error("Expected user email");
53
  }
54
}
55

56
function handleApiResponse(email: string, error: Error) {
57
  return Promise.reject({ email, err_msg: error.message });
58
}
59