feat(bots/discord): add sticky messages

This commit is contained in:
PalmDevs
2024-08-01 02:28:54 +07:00
parent 763ef253f9
commit bf661556e1
9 changed files with 123 additions and 24 deletions

View File

@@ -6,6 +6,7 @@ export type Config = {
users?: string[] users?: string[]
roles?: Record<string, string[]> roles?: Record<string, string[]>
} }
stickyMessages?: Record<string, Record<string, StickyMessageConfig>>
moderation?: { moderation?: {
roles: string[] roles: string[]
cure?: { cure?: {
@@ -50,6 +51,12 @@ export type Config = {
} }
} }
export type StickyMessageConfig = {
timeout: number
forceSendTimeout?: number
message: BaseMessageOptions
}
export type RolePresetConfig = { export type RolePresetConfig = {
give: string[] give: string[]
take: string[] take: string[]

View File

@@ -43,4 +43,4 @@
"discord-api-types": "^0.37.92", "discord-api-types": "^0.37.92",
"drizzle-kit": "^0.22.8" "drizzle-kit": "^0.22.8"
} }
} }

View File

@@ -3,7 +3,7 @@ import { existsSync, readFileSync, readdirSync } from 'fs'
import { join } from 'path' import { join } from 'path'
import { Client as APIClient } from '@revanced/bot-api' import { Client as APIClient } from '@revanced/bot-api'
import { createLogger } from '@revanced/bot-shared' import { createLogger } from '@revanced/bot-shared'
import { Client as DiscordClient, Partials } from 'discord.js' import { Client as DiscordClient, type Message, Partials } from 'discord.js'
import { drizzle } from 'drizzle-orm/bun-sqlite' import { drizzle } from 'drizzle-orm/bun-sqlite'
// Export some things first, as commands require them // Export some things first, as commands require them
@@ -85,4 +85,19 @@ export const discord = {
string, string,
Command<boolean, CommandOptionsOptions | undefined, boolean> Command<boolean, CommandOptionsOptions | undefined, boolean>
>, >,
stickyMessages: {} as Record<
string,
Record<
string,
{
forceSendTimerActive?: boolean
timeoutMs: number
forceSendMs?: number
send: (forced?: boolean) => Promise<void>
currentMessage?: Message<true>
interval?: NodeJS.Timeout
forceSendInterval?: NodeJS.Timeout
}
>
>,
} as const } as const

View File

@@ -0,0 +1,30 @@
import { on, withContext } from '$utils/discord/events'
withContext(on, 'messageCreate', async ({ discord, logger }, msg) => {
if (!msg.inGuild()) return
if (msg.author.id === msg.client.user.id) return
const store = discord.stickyMessages[msg.guildId]?.[msg.channelId]
if (!store) return
if (!store.interval) store.interval = setTimeout(store.send, store.timeoutMs) as NodeJS.Timeout
else {
store.interval.refresh()
if (!store.forceSendTimerActive && store.forceSendMs) {
logger.debug(`Channel ${msg.channelId} in guild ${msg.guildId} is active, starting force send timer`)
store.forceSendTimerActive = true
if (!store.forceSendInterval)
store.forceSendInterval = setTimeout(
() =>
store.send(true).then(() => {
store.forceSendTimerActive = false
}),
store.forceSendMs,
) as NodeJS.Timeout
else store.forceSendInterval.refresh()
}
}
})

View File

@@ -1,14 +1,68 @@
import { database, logger } from '$/context' import { database, logger } from '$/context'
import { appliedPresets } from '$/database/schemas' import { appliedPresets } from '$/database/schemas'
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
import { on, withContext } from '$/utils/discord/events'
import { removeRolePreset } from '$/utils/discord/rolePresets' import { removeRolePreset } from '$/utils/discord/rolePresets'
import type { Client } from 'discord.js'
import { lt } from 'drizzle-orm' import { lt } from 'drizzle-orm'
import { on, withContext } from 'src/utils/discord/events'
export default withContext(on, 'ready', ({ config, logger }, client) => { import type { Client } from 'discord.js'
export default withContext(on, 'ready', async ({ config, discord, logger }, client) => {
logger.info(`Connected to Discord API, logged in as ${client.user.displayName} (@${client.user.tag})!`) logger.info(`Connected to Discord API, logged in as ${client.user.displayName} (@${client.user.tag})!`)
logger.info(`Bot is in ${client.guilds.cache.size} guilds`) logger.info(`Bot is in ${client.guilds.cache.size} guilds`)
if (config.stickyMessages)
for (const [guildId, channels] of Object.entries(config.stickyMessages)) {
const guild = await client.guilds.fetch(guildId)
discord.stickyMessages[guildId] = {}
for (const [channelId, { message, timeout, forceSendTimeout }] of Object.entries(channels)) {
const channel = await guild.channels.fetch(channelId)
if (!channel?.isTextBased()) return
const send = async (forced = false) => {
try {
const msg = await channel.send({
...message,
embeds: message.embeds?.map(it => applyCommonEmbedStyles(it, true, true, true)),
})
const store = discord.stickyMessages[guildId]![channelId]
if (!store) return
await store.currentMessage?.delete().catch()
store.currentMessage = msg
if (!forced) {
clearTimeout(store.forceSendInterval)
logger.debug(
`Timeout ended for sticky message in channel ${channelId} in guild ${guildId}, channel is inactive`,
)
} else {
clearTimeout(store.interval)
logger.debug(
`Forced send timeout for sticky message in channel ${channelId} in guild ${guildId} ended, channel is too active`,
)
}
logger.debug(`Sent sticky message to channel ${channelId} in guild ${guildId}`)
} catch (e) {
logger.error(
`Error while sending sticky message to channel ${channelId} in guild ${guildId}:`,
e,
)
}
}
discord.stickyMessages[guildId]![channelId] = {
forceSendMs: forceSendTimeout,
timeoutMs: timeout,
send,
forceSendTimerActive: false,
}
}
}
if (config.rolePresets) { if (config.rolePresets) {
removeExpiredPresets(client) removeExpiredPresets(client)
setTimeout(() => removeExpiredPresets(client), config.rolePresets.checkExpiredEvery) setTimeout(() => removeExpiredPresets(client), config.rolePresets.checkExpiredEvery)

View File

@@ -1,5 +1,5 @@
import { DefaultEmbedColor, MessageScanHumanizedMode, ReVancedLogoURL } from '$/constants' import { DefaultEmbedColor, MessageScanHumanizedMode, ReVancedLogoURL } from '$/constants'
import { EmbedBuilder, type EmbedField, type User } from 'discord.js' import { type APIEmbed, EmbedBuilder, type EmbedField, type JSONEncodable, type User } from 'discord.js'
import type { ConfigMessageScanResponseMessage } from '../../../config.schema' import type { ConfigMessageScanResponseMessage } from '../../../config.schema'
export const createErrorEmbed = (title: string | null, description?: string) => export const createErrorEmbed = (title: string | null, description?: string) =>
@@ -26,23 +26,12 @@ export const createSuccessEmbed = (title: string | null, description?: string) =
export const createMessageScanResponseEmbed = ( export const createMessageScanResponseEmbed = (
response: NonNullable<ConfigMessageScanResponseMessage['embeds']>[number], response: NonNullable<ConfigMessageScanResponseMessage['embeds']>[number],
mode: 'ocr' | 'nlp' | 'match', mode: 'ocr' | 'nlp' | 'match',
) => { ) =>
// biome-ignore lint/style/noParameterAssign: While this is confusing, it is fine for this purpose applyCommonEmbedStyles(response, true, true, true).setFooter({
if ('toJSON' in response) response = response.toJSON()
const embed = new EmbedBuilder().setTitle(response.title ?? null)
if (response.description) embed.setDescription(response.description)
if (response.fields) embed.addFields(response.fields)
embed.setFooter({
text: `ReVanced • Via ${MessageScanHumanizedMode[mode]}`, text: `ReVanced • Via ${MessageScanHumanizedMode[mode]}`,
iconURL: ReVancedLogoURL, iconURL: ReVancedLogoURL,
}) })
return applyCommonEmbedStyles(embed, true, true, true)
}
export const createModerationActionEmbed = ( export const createModerationActionEmbed = (
action: string, action: string,
user: User, user: User,
@@ -77,19 +66,23 @@ export const applyReferenceToModerationActionEmbed = (embed: EmbedBuilder, refer
} }
export const applyCommonEmbedStyles = ( export const applyCommonEmbedStyles = (
embed: EmbedBuilder, embed: EmbedBuilder | JSONEncodable<APIEmbed> | APIEmbed,
setThumbnail = false, setThumbnail = false,
setFooter = false, setFooter = false,
setColor = false, setColor = false,
) => { ) => {
// biome-ignore lint/style/noParameterAssign: While this is confusing, it is fine for this purpose
if ('toJSON' in embed) embed = embed.toJSON()
const builder = new EmbedBuilder(embed)
if (setFooter) if (setFooter)
embed.setFooter({ builder.setFooter({
text: 'ReVanced', text: 'ReVanced',
iconURL: ReVancedLogoURL, iconURL: ReVancedLogoURL,
}) })
if (setColor) embed.setColor(DefaultEmbedColor) if (setColor) builder.setColor(DefaultEmbedColor)
if (setThumbnail) embed.setThumbnail(ReVancedLogoURL) if (setThumbnail) builder.setThumbnail(ReVancedLogoURL)
return embed return builder
} }

BIN
bun.lockb

Binary file not shown.