Skip to content

Commit

Permalink
librarian message rewrite thingy
Browse files Browse the repository at this point in the history
  • Loading branch information
dispherical committed Oct 14, 2024
1 parent c099768 commit 48d5b94
Show file tree
Hide file tree
Showing 11 changed files with 82 additions and 266 deletions.
21 changes: 5 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ const receiver = new ExpressReceiver({
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode: process.env.PORT ? false : true,
socketMode: !Boolean(process.env.PORT),
appToken: process.env.SLACK_APP_TOKEN,
port: process.env.PORT,
receiver,
receiver: process.env.PORT ? reciever : undefined,
});

Array.prototype.random = function () {
Expand All @@ -34,15 +34,6 @@ Array.prototype.random = function () {
res.redirect(302, "https://github.com/hackclub/channel-directory");
else res.redirect(302, await client.get(`url.${id}`));
});
receiver.router.get("/:id", async (req, res) => {
const { id } = req.params;
if (!(await client.exists(`url.${id}`)))
res.send(
"Sorry, this URL does not exist. If you're following an emoji link, it is no longer valid.",
);
else res.redirect(302, await client.get(`url.${id}`));
});
// Load commands

await require("./commands/optout")({ app, client, prisma });
await require("./commands/setlocation")({ app, client, prisma });
Expand All @@ -51,18 +42,16 @@ Array.prototype.random = function () {
await require("./commands/setfeatured")({ app, client, prisma });


// This deletes and sends a new message to bypass the 10 day editing limit

// This deletes and sends a new message to bypass the 10 day editing limit and to show up on the user's unread channel list
// This runs the same thing on startup
await require("./utils/redo")({ app, client, prisma });
// app.message functions go here
await require("./interactions/message")({ app, client, prisma });

await require("./utils/pull")({ app, client, prisma });

setInterval(async function(){
setInterval(async function () {
await require("./utils/pull")({ app, client, prisma });
}, 5000)
}, 1000*10)
cron.schedule("0 0,12 * * *", async () => {
await client.del(`${process.env.INSTANCE_ID || "production"}.messageCache`);
await require("./utils/redo")({ app, client, prisma });
Expand Down
108 changes: 0 additions & 108 deletions interactions/message.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const utils = require("../utils");
const pms = require("pretty-ms");
const fs = require("node:fs");
const updateMessage = require("../utils/updateMessage");

/**
* @param {{app: import('@slack/bolt').App, client: import('redis').RedisClientType}} param1
Expand All @@ -21,112 +20,5 @@ module.exports = ({ app, client }) => {
`${process.env.INSTANCE_ID || "production"}.messageCache`,
JSON.stringify(message),
);
if (
(await client.exists(
`${process.env.INSTANCE_ID || "production"}.newChannelMessage`,
)) &&
Date.now() <
(await client.get(
`${process.env.INSTANCE_ID || "production"}.newChannelMessage`,
))
)
return;
return;
if (
(await client.exists(
`${process.env.INSTANCE_ID || "production"}.messageText`,
)) &&
(await client.exists(
`${process.env.INSTANCE_ID || "production"}.messageId`,
))
) {
const tmpText = await client.get(
`${process.env.INSTANCE_ID || "production"}.messageText`,
);
var newText = tmpText.replace(
/Latest message: .*? ago/,
`Latest message: (in <#${message.channel}>) ${pms(Date.now() - Math.floor(parseInt(message.ts) * 1000))} ago`,
);

newText = newText.replaceAll(
`<#${body.event.channel}>`,
`<#${body.event.channel}> :boom:`,
);

var subBlocks = [];
let bPromises = fs
.readdirSync("./buttons")
.filter((str) => str.endsWith(".js"))
.sort()
.map(async (fn) => {
const id = Math.random().toString(32).slice(2);
const button = await require(`../buttons/${fn}`);
subBlocks.push({
type: "button",
text: {
type: "plain_text",
text: button.title,
emoji: true,
},
value: `../buttons/${fn}`,
action_id: id,
});
app.action(id, async ({ ack, respond, say, body }) => {
await ack();

await app.client.chat.postEphemeral({
channel: body.channel.id,
user: body.user.id,
text: await require(body.actions[0].value).render({ app, body }),
});
});
});

await Promise.all(bPromises);
try {
await updateMessage({
app,
client,
text: `New directory update ${new Date()}`,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: newText,
},
},
{
type: "actions",
elements: subBlocks,
},
],
priority: "high",
});

setTimeout(async function () {
await updateMessage({
app,
client,
text: `New directory update ${new Date()}`,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: newText.replaceAll(" :boom:", ""),
},
},
{
type: "actions",
elements: subBlocks,
},
],
priority: "low",
});
}, 1000);
} catch (e) {}

}
});
};
1 change: 1 addition & 0 deletions sections/20-featured.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
title: "⭐ Featured Channels",
id: "featured",
description: "Channels featured by Hack Club",
/**
* @param {{app: import('@slack/bolt').App, prisma: import('@prisma/client').PrismaClient}} param1
Expand Down
1 change: 1 addition & 0 deletions sections/30-recent.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const generateMessageString = require("../utils/allTimeline");
//const timeline = require("../utils/timeline.disabled.js")
module.exports = {
title: "🆕 Most Recent Activity",
id: "recent",
description: "This gets the most recently updates channels",
/**
* @param {{app: import('@slack/bolt').App}} param1
Expand Down
7 changes: 4 additions & 3 deletions sections/40-threads.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const { createClient } = require("redis");

module.exports = {
title: "🧵 Top 10 most recently active threads",
id: "threads",
description: "Most active threads in Hack Club",
/**
* @param {{app: import('@slack/bolt').App}} param1
Expand Down Expand Up @@ -36,11 +37,11 @@ module.exports = {
!acc.find((item) => item.thread_ts === thread_ts) &&
!acc.find((item) => item.channel === message.channel)
) {
const id = crypto.randomUUID().slice(0, 3);
client.set(`url.${id}`, `https://hackclub.slack.com/archives/${message.channel}/p${message.ts.toString().replace(".", "")}`)
//const id = crypto.randomUUID().slice(0, 3);
//client.set(`url.${id}`,)
acc.push({
thread_ts: thread_ts,
permalink: `https://l.hack.club/${id}`,
permalink: `https://hackclub.slack.com/archives/${message.channel}/p${message.ts.toString().replace(".", "")}`,
text: message.text,
channel: message.channel,
});
Expand Down
3 changes: 1 addition & 2 deletions utils/allTimeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,11 @@ async function generateMessageString(messages, currentTime, prisma) {
const { emoji, permalink } = timeToEmojiMap[i];
const id = crypto.randomUUID().slice(0, 3);
await client.set(`url.${id}`, permalink);
messageString += `<https://l.hack.club/${id}|${emoji}>,`;
messageString += `<${permalink}|${emoji}>,`;
} else {
messageString += "-,";
}
}
await client.disconnect();
return messageString.split(",").slice(0, 30).join(",").replace(/,/g, "");
}

Expand Down
1 change: 1 addition & 0 deletions utils/joinall.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Array.prototype.random = function () {
};

module.exports = async function ({ app, client, prisma }) {
if (process.env.INSTANCE_ID !== "production") return
async function rake(cursor) {
const convos = await app.client.conversations.list({
limit: 999,
Expand Down
63 changes: 6 additions & 57 deletions utils/pull.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// This pulls all files in sections/*
// This allows directory to stay modular.
const fs = require("node:fs");
const updateMessage = require("../utils/updateMessage");

/**
* @param {{app: import('@slack/bolt').App}} param1
Expand All @@ -14,64 +13,14 @@ module.exports = async function ({ app, client, prisma }) {
for (const fn of sFilesSorted) {
const section = await require(`../sections/${fn}`);
const rend = (await section.render({ app, client, prisma })).trim();
text += `${section.title}\n\n${rend}\n\n════════════════════════════════════\n`;
}
var subBlocks = [];
let bPromises = fs
.readdirSync("./buttons")
.filter((str) => str.endsWith(".js"))
.sort()
.map(async (fn) => {
const id = Math.random().toString(32).slice(2);
const button = await require(`../buttons/${fn}`);
subBlocks.push({
type: "button",
text: {
type: "plain_text",
text: button.title,
emoji: true,
},
value: `../buttons/${fn}`,
action_id: id,
});
app.action(id, async ({ ack, respond, say, body }) => {
await ack();

await app.client.chat.postEphemeral({
channel: body.channel.id,
user: body.user.id,
text: await require(body.actions[0].value).render({
app,
body,
client,
}),
});
});
await app.client.chat.update({
channel: process.env.SLACK_CHANNEL,
ts: await client.get(`${process.env.INSTANCE_ID || "production"}.${section.id}.messageId`),
text: `*${section.title}*\n\n${rend}\n\n════════════════════════════════════\n`,
});
}


await Promise.all(bPromises);

try {
await updateMessage({
app,
client,
text: `New directory update ${new Date()}`,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: text
.replaceAll("@", "​@")
.replaceAll(/[\u{1F3FB}-\u{1F3FF}]/gmu, "").slice(0,2999),
},
},
{
type: "actions",
elements: subBlocks,
},
],
priority: "high",
});
} catch (e) {}
};
69 changes: 63 additions & 6 deletions utils/redo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* @param {{app: import('@slack/bolt').App}} param1
*/
const figlet = require("figlet");
const fs = require("node:fs")
module.exports = async function ({ app, client }) {
const data = await app.client.conversations.history({
channel: process.env.SLACK_CHANNEL,
Expand Down Expand Up @@ -36,15 +37,71 @@ module.exports = async function ({ app, client }) {
file: file,
filename: "welcome to the hack club channel library!.png",
});
var subBlocks = [];
let bPromises = fs
.readdirSync("./buttons")
.filter((str) => str.endsWith(".js"))
.sort()
.map(async (fn) => {
const id = Math.random().toString(32).slice(2);
const button = await require(`../buttons/${fn}`);
subBlocks.push({
type: "button",
text: {
type: "plain_text",
text: button.title,
emoji: true,
},
value: `../buttons/${fn}`,
action_id: id,
});
app.action(id, async ({ ack, respond, say, body }) => {
await ack();

await app.client.chat.postEphemeral({
channel: body.channel.id,
user: body.user.id,
text: await require(body.actions[0].value).render({
app,
body,
client,
}),
});
});
});

await Promise.all(bPromises);
setTimeout(async function () {
const tmesg = await app.client.chat.postMessage({
var sFiles = fs.readdirSync("./sections");
let sFilesSorted = sFiles.filter((str) => str.endsWith(".js")).sort().map(file => require(`../sections/${file}`))
for (const fn of sFilesSorted) {
var msg = await app.client.chat.postMessage({
channel: process.env.SLACK_CHANNEL,
text: `:spin-loading: Loading library section: ${fn.id}`,
});
await client.set(
`${process.env.INSTANCE_ID || "production"}.${fn.id}.messageId`,
msg.ts,
)
}

await app.client.chat.postMessage({
channel: process.env.SLACK_CHANNEL,
text: ":spin-loading: Loading library",
text: "Find more sections tailored to you by clicking a button below!",
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: "Find more sections tailored to you by clicking a button below!",
},
},
{
type: "actions",
elements: subBlocks,
},
],
});
await client.set(
`${process.env.INSTANCE_ID || "production"}.messageId`,
tmesg.ts,
);

}, 5000);
};
Loading

0 comments on commit 48d5b94

Please sign in to comment.