Compare commits

...

12 Commits

Author SHA1 Message Date
semantic-release-bot
9fe6b4ca70 chore(release): 1.0.0-dev.15 [skip ci]
# @revanced/discord-bot [1.0.0-dev.15](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.14...@revanced/discord-bot@1.0.0-dev.15) (2024-07-31)

### Bug Fixes

* **bots/discord:** import `config` from context ([763ef25](763ef253f9))

### Features

* **bots/discord:** add sticky messages ([bf66155](bf661556e1))
2024-07-31 19:31:21 +00:00
PalmDevs
bf661556e1 feat(bots/discord): add sticky messages 2024-08-01 02:29:49 +07:00
PalmDevs
763ef253f9 fix(bots/discord): import config from context 2024-07-31 21:25:12 +07:00
semantic-release-bot
561426028c chore(release): 1.0.0-dev.14 [skip ci]
# @revanced/discord-bot [1.0.0-dev.14](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.13...@revanced/discord-bot@1.0.0-dev.14) (2024-07-31)

### Bug Fixes

* **bots/discord:** always true check causing no messages to be scanned ([98ec37b](98ec37b5d1))
* other small issues ([bc437a5](bc437a5ec7))

### Features

* **bots/discord:** add more options for curing, fix default regex ([1a4ec1e](1a4ec1ece8))
* **bots/discord:** allow admins to bypass permission checks ([620f933](620f9339f0))
2024-07-31 12:36:12 +00:00
semantic-release-bot
b726c40fd4 chore(release): 1.0.0-dev.8 [skip ci]
# @revanced/bot-websocket-api [1.0.0-dev.8](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.7...@revanced/bot-websocket-api@1.0.0-dev.8) (2024-07-31)

### Bug Fixes

* other small issues ([bc437a5](bc437a5ec7))
2024-07-31 12:35:31 +00:00
PalmDevs
bc437a5ec7 fix: other small issues 2024-07-31 19:34:12 +07:00
PalmDevs
620f9339f0 feat(bots/discord): allow admins to bypass permission checks 2024-07-31 19:34:11 +07:00
PalmDevs
1a4ec1ece8 feat(bots/discord): add more options for curing, fix default regex 2024-07-31 19:34:10 +07:00
PalmDevs
98ec37b5d1 fix(bots/discord): always true check causing no messages to be scanned 2024-07-31 19:34:10 +07:00
PalmDevs
711f57f4a1 fix(packages/api): null errors being thrown 2024-07-31 19:34:09 +07:00
PalmDevs
e29e9c3dd1 fix(packages/api): properly await failed packets 2024-07-31 19:34:08 +07:00
semantic-release-bot
b832311f7e chore(release): 1.0.0-dev.13 [skip ci]
# @revanced/discord-bot [1.0.0-dev.13](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.12...@revanced/discord-bot@1.0.0-dev.13) (2024-07-30)

### Bug Fixes

* **bots/discord:** broken regex when prefix set to special characters ([ab62e55](ab62e55e76))
2024-07-30 19:14:27 +00:00
21 changed files with 220 additions and 61 deletions

View File

@@ -1,3 +1,10 @@
# @revanced/bot-websocket-api [1.0.0-dev.8](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.7...@revanced/bot-websocket-api@1.0.0-dev.8) (2024-07-31)
### Bug Fixes
* other small issues ([bc437a5](https://github.com/revanced/revanced-helper/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
# @revanced/bot-websocket-api [1.0.0-dev.7](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.6...@revanced/bot-websocket-api@1.0.0-dev.7) (2024-07-30) # @revanced/bot-websocket-api [1.0.0-dev.7](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.6...@revanced/bot-websocket-api@1.0.0-dev.7) (2024-07-30)
# @revanced/bot-websocket-api [1.0.0-dev.6](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.5...@revanced/bot-websocket-api@1.0.0-dev.6) (2024-07-30) # @revanced/bot-websocket-api [1.0.0-dev.6](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.5...@revanced/bot-websocket-api@1.0.0-dev.6) (2024-07-30)

View File

@@ -2,7 +2,7 @@
"name": "@revanced/bot-websocket-api", "name": "@revanced/bot-websocket-api",
"type": "module", "type": "module",
"private": true, "private": true,
"version": "1.0.0-dev.7", "version": "1.0.0-dev.8",
"description": "🧦 WebSocket API server for bots assisting ReVanced", "description": "🧦 WebSocket API server for bots assisting ReVanced",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {

View File

@@ -1,3 +1,36 @@
# @revanced/discord-bot [1.0.0-dev.15](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.14...@revanced/discord-bot@1.0.0-dev.15) (2024-07-31)
### Bug Fixes
* **bots/discord:** import `config` from context ([763ef25](https://github.com/revanced/revanced-helper/commit/763ef253f9d4ff70a8b79969a7f4f41cba7f3c59))
### Features
* **bots/discord:** add sticky messages ([bf66155](https://github.com/revanced/revanced-helper/commit/bf661556e131bf0ef24e47f658fbcd701960e312))
# @revanced/discord-bot [1.0.0-dev.14](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.13...@revanced/discord-bot@1.0.0-dev.14) (2024-07-31)
### Bug Fixes
* **bots/discord:** always true check causing no messages to be scanned ([98ec37b](https://github.com/revanced/revanced-helper/commit/98ec37b5d18cade85270ab83b0ed0abe41244dd9))
* other small issues ([bc437a5](https://github.com/revanced/revanced-helper/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
### Features
* **bots/discord:** add more options for curing, fix default regex ([1a4ec1e](https://github.com/revanced/revanced-helper/commit/1a4ec1ece80becd9156582cc490f6681cb2a1f39))
* **bots/discord:** allow admins to bypass permission checks ([620f933](https://github.com/revanced/revanced-helper/commit/620f9339f0737b79d72c66d90ffa42ea3f987710))
# @revanced/discord-bot [1.0.0-dev.13](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.12...@revanced/discord-bot@1.0.0-dev.13) (2024-07-30)
### Bug Fixes
* **bots/discord:** broken regex when prefix set to special characters ([ab62e55](https://github.com/revanced/revanced-helper/commit/ab62e55e76005f5999d7413d1158e54053f28d1f))
# @revanced/discord-bot [1.0.0-dev.12](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.11...@revanced/discord-bot@1.0.0-dev.12) (2024-07-30) # @revanced/discord-bot [1.0.0-dev.12](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.11...@revanced/discord-bot@1.0.0-dev.12) (2024-07-30)

View File

@@ -6,9 +6,12 @@ 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?: {
minimumNameLength?: number
removeCharactersRegex?: RegExp
defaultName: string defaultName: string
} }
log?: { log?: {
@@ -48,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

@@ -2,7 +2,7 @@
"name": "@revanced/discord-bot", "name": "@revanced/discord-bot",
"type": "module", "type": "module",
"private": true, "private": true,
"version": "1.0.0-dev.12", "version": "1.0.0-dev.15",
"description": "🤖 Discord bot assisting ReVanced", "description": "🤖 Discord bot assisting ReVanced",
"main": "src/index.ts", "main": "src/index.ts",
"scripts": { "scripts": {

View File

@@ -291,6 +291,9 @@ export default class Command<
async canExecute(executor: User | GuildMember, channelId: string): Promise<boolean> { async canExecute(executor: User | GuildMember, channelId: string): Promise<boolean> {
if (!this.requirements) return false if (!this.requirements) return false
const isExecutorAdmin = isAdmin(executor)
if (isExecutorAdmin) return true
const { const {
adminOnly, adminOnly,
channels, channels,
@@ -307,7 +310,7 @@ export default class Command<
const bMemReqForUsers = memberRequirementsForUsers !== 'fail' const bMemReqForUsers = memberRequirementsForUsers !== 'fail'
const conditions = [ const conditions = [
adminOnly ? isAdmin(executor) : bDefCond, adminOnly ? isExecutorAdmin : bDefCond,
channels ? channels.includes(channelId) : bDefCond, channels ? channels.includes(channelId) : bDefCond,
member ? (roles ? roles.some(role => member.roles.cache.has(role)) : bDefCond) : bMemReqForUsers, member ? (roles ? roles.some(role => member.roles.cache.has(role)) : bDefCond) : bMemReqForUsers,
member ? (permissions ? member.permissions.has(permissions) : bDefCond) : bMemReqForUsers, member ? (permissions ? member.permissions.has(permissions) : bDefCond) : bMemReqForUsers,

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

@@ -9,7 +9,8 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
const command = discord.commands[interaction.commandName] const command = discord.commands[interaction.commandName]
logger.debug(`Command ${interaction.commandName} being invoked by ${interaction.user.tag}`) logger.debug(`Command ${interaction.commandName} being invoked by ${interaction.user.tag}`)
if (!command) return void logger.error(`Command ${interaction.commandName} not implemented but registered!!!`) if (!command)
return void logger.error(`Interaction command ${interaction.commandName} not implemented but registered!!!`)
try { try {
logger.debug(`Command ${interaction.commandName} being executed`) logger.debug(`Command ${interaction.commandName} being executed`)

View File

@@ -19,7 +19,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
const command = discord.commands[commandName] const command = discord.commands[commandName]
logger.debug(`Command ${commandName} being invoked by ${msg.author.id}`) logger.debug(`Command ${commandName} being invoked by ${msg.author.id}`)
if (!command) return void logger.error(`Command ${commandName} not implemented`) if (!command) return void logger.debug(`Message command ${commandName} not implemented`)
const argsRegex: RegExp = /[^\s"]+|"([^"]*)"/g const argsRegex: RegExp = /[^\s"]+|"([^"]*)"/g
const args: CommandArguments = [] const args: CommandArguments = []

View File

@@ -33,7 +33,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
if (response) { if (response) {
logger.debug('Response found') logger.debug('Response found')
const toReply = replyToReplied ? await msg.fetchReference() : msg const toReply = replyToReplied ? (msg.reference?.messageId ? await msg.fetchReference() : msg) : msg
const reply = await toReply.reply({ const reply = await toReply.reply({
...response, ...response,
embeds: response.embeds?.map(it => createMessageScanResponseEmbed(it, label ? 'nlp' : 'match')), embeds: response.embeds?.map(it => createMessageScanResponseEmbed(it, label ? 'nlp' : 'match')),

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

@@ -10,5 +10,10 @@ if (missingEnvs.length) {
process.exit(1) process.exit(1)
} }
// Handle uncaught exceptions
process.on('uncaughtException', error => console.error('Uncaught exception:', error))
process.on('unhandledRejection', reason => console.error('Unhandled rejection:', reason))
api.client.connect() api.client.connect()
discord.client.login() discord.client.login()

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
} }

View File

@@ -10,9 +10,12 @@ export const getResponseFromText = async (
// Just to be safe that we will never use data from the context parameter // Just to be safe that we will never use data from the context parameter
{ api, logger }: Omit<typeof import('src/context'), 'config'>, { api, logger }: Omit<typeof import('src/context'), 'config'>,
ocrMode = false, ocrMode = false,
): Promise<ConfigMessageScanResponse & { label?: string }> => { ): Promise<
let responseConfig: Awaited<ReturnType<typeof getResponseFromText>> = { Omit<ConfigMessageScanResponse, 'triggers'> & { label?: string; triggers?: ConfigMessageScanResponse['triggers'] }
triggers: {}, > => {
type ResponseConfig = Awaited<ReturnType<typeof getResponseFromText>>
let responseConfig: Omit<ResponseConfig, 'triggers'> & { triggers?: ResponseConfig['triggers'] } = {
triggers: undefined,
response: null, response: null,
} }
@@ -27,7 +30,6 @@ export const getResponseFromText = async (
const { const {
triggers: { text: textTriggers, image: imageTriggers }, triggers: { text: textTriggers, image: imageTriggers },
} = trigger } = trigger
if (responseConfig) break
if (ocrMode) { if (ocrMode) {
if (imageTriggers) if (imageTriggers)
@@ -55,7 +57,7 @@ export const getResponseFromText = async (
} }
// If none of the regexes match, we can search for labels immediately // If none of the regexes match, we can search for labels immediately
if (!responseConfig && !ocrMode) { if (!responseConfig.triggers && !ocrMode) {
logger.debug('No match from before regexes, doing NLP') logger.debug('No match from before regexes, doing NLP')
const scan = await api.client.parseText(content) const scan = await api.client.parseText(content)
if (scan.labels.length) { if (scan.labels.length) {
@@ -84,7 +86,7 @@ export const getResponseFromText = async (
} }
// If we still don't have a response config, we can match all regexes after the initial label trigger // If we still don't have a response config, we can match all regexes after the initial label trigger
if (!responseConfig) { if (!responseConfig.triggers) {
logger.debug('No match from NLP, doing after regexes') logger.debug('No match from NLP, doing after regexes')
for (let i = 0; i < responses.length; i++) { for (let i = 0; i < responses.length; i++) {
const { const {
@@ -119,19 +121,17 @@ export const messageMatchesFilter = (message: Message, filter: NonNullable<Confi
// If matches whitelist but also matches blacklist, will return false // If matches whitelist but also matches blacklist, will return false
// If matches only whitelist, will return true // If matches only whitelist, will return true
// If matches neither, will return true // If matches neither, will return true
return ( return whitelist
(whitelist ? (whitelist.channels?.includes(message.channelId) ?? true) ||
? whitelist.channels?.includes(message.channelId) || (whitelist.roles?.some(role => memberRoles.has(role)) ?? true) ||
whitelist.roles?.some(role => memberRoles.has(role)) || (whitelist.users?.includes(message.author.id) ?? true)
whitelist.users?.includes(message.author.id) : true &&
: true) && !(
!( blacklist &&
blacklist && (blacklist.channels?.includes(message.channelId) ||
(blacklist.channels?.includes(message.channelId) || blacklist.roles?.some(role => memberRoles.has(role)) ||
blacklist.roles?.some(role => memberRoles.has(role)) || blacklist.users?.includes(message.author.id))
blacklist.users?.includes(message.author.id)) )
)
)
} }
export const handleUserResponseCorrection = async ( export const handleUserResponseCorrection = async (

View File

@@ -54,9 +54,9 @@ export const cureNickname = async (member: GuildMember) => {
const name = member.displayName const name = member.displayName
let cured = decancer(name) let cured = decancer(name)
.toString() .toString()
.replace(/[^a-zA-Z0-9]/g, '') .replace(new RegExp(config.moderation?.cure?.removeCharactersRegex ?? '[^a-zA-Z0-9 \\-_]', 'g'), '')
if (cured.length < 3 || !/^[a-zA-Z]/.test(cured)) if (cured.length < (config?.moderation?.cure?.minimumNameLength ?? 3))
cured = cured =
member.user.username.length >= 3 member.user.username.length >= 3
? member.user.username ? member.user.username

View File

@@ -1,5 +1,5 @@
import { GuildMember, type User } from 'discord.js' import { GuildMember, type User } from 'discord.js'
import config from '../../../config' import { config } from '../../context'
export const isAdmin = (userOrMember: User | GuildMember) => { export const isAdmin = (userOrMember: User | GuildMember) => {
return ( return (

BIN
bun.lockb

Binary file not shown.

View File

@@ -52,17 +52,20 @@ export default class Client {
// But if we add anything similar, this will cause another race condition // But if we add anything similar, this will cause another race condition
// To fix this, we can try adding a instanced function that would return the currentSequence // To fix this, we can try adding a instanced function that would return the currentSequence
// and it would be updated every time a "heartbeat ack" packet is received // and it would be updated every time a "heartbeat ack" packet is received
return Promise.race([ const packet = await Promise.race([
this.#awaiter.await(ServerOperation.ParsedText, this.ws.currentSequence), this.#awaiter.await(ServerOperation.ParsedText, this.ws.currentSequence),
this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.timeout + 5000), this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.currentSequence, this.ws.timeout + 5000),
]) ])
.then(pkt => { .then(pkt => {
if (pkt.op === ServerOperation.ParsedText) return pkt.d if (pkt.op === ServerOperation.ParsedText) return pkt.d
throw new Error('Failed to parse text, the API encountered an error') return null
}) })
.catch(() => { .catch(() => {
throw new Error('Failed to parse text, the API did not respond in time') throw new Error('Failed to parse text, the API did not respond in time')
}) })
if (!packet) throw new Error('Failed to parse text, the API encountered an error')
return packet
} }
/** /**
@@ -82,17 +85,20 @@ export default class Client {
// See line 50 // See line 50
return Promise.race([ const packet = await Promise.race([
this.#awaiter.await(ServerOperation.ParsedImage, this.ws.currentSequence), this.#awaiter.await(ServerOperation.ParsedImage, this.ws.currentSequence),
this.#awaiter.await(ServerOperation.ParseImageFailed, this.ws.timeout + 5000), this.#awaiter.await(ServerOperation.ParseImageFailed, this.ws.currentSequence, this.ws.timeout + 5000),
]) ])
.then(pkt => { .then(pkt => {
if (pkt.op === ServerOperation.ParsedImage) return pkt.d if (pkt.op === ServerOperation.ParsedImage) return pkt.d
throw new Error('Failed to parse image, the API encountered an error') return null
}) })
.catch(() => { .catch(() => {
throw new Error('Failed to parse image, the API did not respond in time') throw new Error('Failed to parse image, the API did not respond in time')
}) })
if (!packet) throw new Error('Failed to parse image, the API encountered an error')
return packet
} }
async trainMessage(text: string, label: string) { async trainMessage(text: string, label: string) {
@@ -107,17 +113,20 @@ export default class Client {
}) })
// See line 50 // See line 50
return Promise.race([ const packet = await Promise.race([
this.#awaiter.await(ServerOperation.TrainedMessage, this.ws.currentSequence), this.#awaiter.await(ServerOperation.TrainedMessage, this.ws.currentSequence),
this.#awaiter.await(ServerOperation.TrainMessageFailed, this.ws.timeout + 5000), this.#awaiter.await(ServerOperation.TrainMessageFailed, this.ws.currentSequence, this.ws.timeout + 5000),
]) ])
.then(pkt => { .then(pkt => {
if (pkt.op === ServerOperation.TrainedMessage) return pkt.d if (pkt.op === ServerOperation.TrainedMessage) return pkt.d
throw new Error('Failed to train message, the API encountered an error') return null
}) })
.catch(() => { .catch(() => {
throw new Error('Failed to train message, the API did not respond in time') throw new Error('Failed to train message, the API did not respond in time')
}) })
if (!packet) throw new Error('Failed to train message, the API encountered an error')
return packet
} }
/** /**

View File

@@ -123,7 +123,7 @@ export class ClientWebSocketManager {
this.currentSequence++ this.currentSequence++
this.#socket.send(serializePacket(packet), err => { this.#socket.send(serializePacket(packet), err => {
throw err if (err) throw err
}) })
} }