1
0
Fork 0
out-of-your-element-fork-th.../d2m/actions/speedbump.js

53 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-01-19 12:01:34 +00:00
// @ts-check
const DiscordTypes = require("discord-api-types/v10")
const passthrough = require("../../passthrough")
const {discord, db} = passthrough
const SPEEDBUMP_SPEED = 4000 // 4 seconds delay
const SPEEDBUMP_UPDATE_FREQUENCY = 2 * 60 * 60 // 2 hours
/** @type {Set<any>} */
const KNOWN_BOTS = new Set([
"466378653216014359" // PluralKit
])
/**
* Fetch new speedbump data for the channel and put it in the database as cache
* @param {string} channelID
* @param {number?} lastChecked
2024-01-19 12:01:34 +00:00
*/
async function updateCache(channelID, lastChecked) {
2024-01-19 12:01:34 +00:00
const now = Math.floor(Date.now() / 1000)
if (lastChecked && now - lastChecked < SPEEDBUMP_UPDATE_FREQUENCY) return
2024-01-19 12:01:34 +00:00
const webhooks = await discord.snow.webhook.getChannelWebhooks(channelID)
2024-01-20 11:54:18 +00:00
const found = webhooks.find(b => KNOWN_BOTS.has(b.application_id))
const foundApplication = found?.application_id
const foundWebhook = found?.id
db.prepare("UPDATE channel_room SET speedbump_id = ?, speedbump_webhook_id = ?, speedbump_checked = ? WHERE channel_id = ?").run(foundApplication, foundWebhook, now, channelID)
2024-01-19 12:01:34 +00:00
}
/** @type {Set<string>} set of messageID */
const bumping = new Set()
/**
* Slow down a message. After it passes the speedbump, return whether it's okay or if it's been deleted.
* @param {string} messageID
*/
async function doSpeedbump(messageID) {
bumping.add(messageID)
await new Promise(resolve => setTimeout(resolve, SPEEDBUMP_SPEED))
return !bumping.delete(messageID)
}
/**
* @param {string} messageID
*/
function onMessageDelete(messageID) {
bumping.delete(messageID)
}
module.exports.updateCache = updateCache
module.exports.doSpeedbump = doSpeedbump
module.exports.onMessageDelete = onMessageDelete