Search... Ctrl + K

Send direct message (slack)
One script reply has been approved by the moderators Verified

Created by mrl5 24 days ago Used 14 times 1 Point

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

No comments yet

Points: 0
deno
One script reply has been approved by the moderators
Ap­pro­ved
import { Resource } from "https://deno.land/x/windmill@v1.42.1/mod.ts";
import { WebClient } from "https://deno.land/x/slack_web_api@1.0.3/mod.ts";
import { isEmail } from "https://deno.land/x/isemail@v1.0.1/mod.ts";

export async function main(
  user_email: string,
  text: string,
  slack: Resource<"slack">,
) {
  throwOnInvalidEmail(user_email);

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

  return result;
}

interface UserData {
  id: string;
  email: string;
  real_name: string;
}

async function getUserData(client: WebClient, email: string): Promise<UserData> {
  try {
    const response = await client.users.lookupByEmail({ email: email });

    const { id, real_name } = response.user;
    return { id, email, real_name };
  } catch (err) {
    return handleApiResponse(email, err);
  }
}

async function sendDirectMessage(text: string, client: WebClient, userData: UserData) {
  const { ok, ts, channel } = await client.chat.postMessage({
    channel: userData.id,
    text,
  });
  return { ok, ts, channel, email: userData.email };
}

function throwOnInvalidEmail(email: string) {
  if (!isEmail(email)) {
    throw new Error('Expected user email');
  }
}

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

Submitted by mrl5 24 days ago

Edited 24 days ago

No comments yet