Public
HTTP
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

A simple Slack chat bot prototype able to reply to mentions, channel messages containing keywords, add reactions and act on the slash commands.

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
const { env } = Deno;
const SLACK_BOT_TOKEN = env.get("SLACK_BOT_TOKEN");
const SLACK_SIGNING_SECRET = env.get("SLACK_SIGNING_SECRET");
const SLACK_VERIFICATION_TOKEN = env.get("SLACK_VERIFICATION_TOKEN");
async function message(channel: string, text: string, thread_ts?: string) {
return await fetchJSON(
"https://slack.com/api/chat.postMessage",
{
headers: { "Authorization": `Bearer ${SLACK_BOT_TOKEN}` },
method: "POST",
body: JSON.stringify({ channel, text, thread_ts }),
},
);
}
async function reaction(channel: string, timestamp: string, name: string = "thumbsup") {
return await fetchJSON(
"https://slack.com/api/reactions.add",
{
headers: { "Authorization": `Bearer ${SLACK_BOT_TOKEN}` },
method: "POST",
body: JSON.stringify({ channel, name, timestamp }),
},
);
}
export const slacker = async (req: Request) => {
const url = new URL(req.url);
const path = url.pathname;
const method = req.method;
console.log(method, path);
if (method == "GET" && path == "/") return new Response("ha?");
if (path == "/q") {
console.log("question", url);
const data = await req.text();
const params = new URLSearchParams(data);
console.log({ params });
const channel_id = params.get("channel_id");
const command = params.get("command");
const text = params.get("text");
const response = `command [${command}] [${text}]`;
await message(channel_id, response);
return new Response(response);
}
const body = await req.json();
console.log("INVOKED", body);
if (body.token !== SLACK_VERIFICATION_TOKEN) {
console.error("token mismatch", { received: body.token, expected: SLACK_VERIFICATION_TOKEN });
return new Response(undefined, { status: 401 });
}
if (body.challenge) {
return Response.json({ challenge: body.challenge });
}
const { event } = body;
const { channel } = event;
if (event.type === "app_mention") {
const text = `asking [${event.text}] [${event.ts}/${event.text.includes("?")}]?`;
const thread = event.text.includes("?") ? event.ts : undefined;
await message(channel, text, thread);
}
if (event.type === "message" && event.text.includes("what's up?")) {
await message(channel, "<@" + event.user + ">: all good!");
console.log("reaction", await reaction(channel, event.ts));
}
return Response.json({ ok: true });
};
begoon-slackbot.web.val.run
September 14, 2024