Avatar

glommer

3 public vals
Joined January 3, 2024
1
2
3
4
5
6
7
8
9
10
import { getThreadsActivity } from "https://esm.town/v/glommer/getThreadsActivity";
export default async function(interval: Interval) {
const guild = Deno.env.get("DISCORD_GUILD_ID");
const token = Deno.env.get("DISCORD_IKU_BOT_TOKEN");
const slackToken = Deno.env.get("SLACK_TOKEN");
const channel = Deno.env.get("SLACK_NOTIFY_CHANNEL_ID");
await getThreadsActivity(token, guild, slackToken, channel);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export async function slackPost(token, channel, text) {
const resp = await fetch(
`https://slack.com/api/chat.postMessage`,
{
method: "POST",
headers: {
'Authorization': `Bearer ${token}`,
'Content-type': 'application/json; charset=utf-8',
},
body: JSON.stringify({
channel,
text
})
})
if (!resp.ok) {
let { message } = await resp.json();
throw new Error("Error: " + message);
}
return await resp.json();
}
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
import { slackPost } from "https://esm.town/v/glommer/sendMsgToSlack";
import { sqlite } from "https://esm.town/v/std/sqlite";
import { sql } from "npm:drizzle-orm";
import { drizzle } from "npm:drizzle-orm/libsql";
import { integer, sqliteTable, text } from "npm:drizzle-orm/sqlite-core";
const db = drizzle(sqlite as any);
const threadsTbl = sqliteTable("threads", {
id: text("id").primaryKey(),
last_message_id: text("last_message_id"),
});
async function getKnownThreads() {
const result = await db.select().from(threadsTbl);
return result.reduce((r, { id, last_message_id }) => {
r[id] = parseInt(last_message_id ?? "0");
return r;
}, {});
}
async function getNewThreads() {
const resp = await fetch(`https://discord.com/api/guilds/${guild}/threads/active`, {
headers: {
"Authorization": `Bot ${token}`,
},
});
if (!resp.ok) {
const err = await resp.json();
console.log(`response failed: ${err}`);
return;
}
const j = await resp.json();
return j.threads;
}
export async function getThreadsActivity(
token: string,
guild: string,
slackToken: string,
slackChannel: string,
) {
const knownThreads = await getKnownThreads();
const threads = await getNewThreads();
const ops = [db.delete(threadsTbl)];
for (let i = 0; i < threads.length; i++) {
const t = threads[i];
const id = t.id;
const name = t.name;
// don't do parseInt here, need to be text, so we can save text back to sqlite
const last_message_id = t.last_message_id;
const parent_id = t.parent_id;
const lastKnown = knownThreads[id] ?? 0;
if (parseInt(last_message_id) > lastKnown) {
await slackPost(
slackToken,
slackChannel,
`New activity for "${name}: https://discord.com/channels/${guild}/${id}/${id}"`,
);
}
ops.push(db.insert(threadsTbl).values({ id, last_message_id }));
}
await db.batch(ops);
}
Next