Compare commits

..

16 Commits

Author SHA1 Message Date
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
semantic-release-bot
887ee85e41 chore(release): 1.0.0-dev.7 [skip ci]
# @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)
2024-07-30 19:13:45 +00:00
PalmDevs
c9b788dc51 build(Needs bump): do not minify builds 2024-07-31 02:12:31 +07:00
PalmDevs
ab62e55e76 fix(bots/discord): broken regex when prefix set to special characters 2024-07-31 02:12:30 +07:00
semantic-release-bot
8f83687b7c chore(release): 1.0.0-dev.12 [skip ci]
# @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)

### Bug Fixes

* **bots/discord:** deployment runtime errors due to minification ([a60c60c](a60c60c0f9))
2024-07-30 18:42:20 +00:00
PalmDevs
a60c60c0f9 fix(bots/discord): deployment runtime errors due to minification 2024-07-31 01:40:45 +07:00
semantic-release-bot
95a122a225 chore(release): 1.0.0-dev.11 [skip ci]
# @revanced/discord-bot [1.0.0-dev.11](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.10...@revanced/discord-bot@1.0.0-dev.11) (2024-07-30)

### Bug Fixes

* **bots/discord:** reset counter when reconnected to api, redo message scan filter logic ([d234d79](d234d79310))
2024-07-30 17:23:25 +00:00
PalmDevs
d234d79310 fix(bots/discord): reset counter when reconnected to api, redo message scan filter logic 2024-07-31 00:22:02 +07:00
20 changed files with 138 additions and 39 deletions

View File

@@ -1,3 +1,12 @@
# @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.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",
"type": "module",
"private": true,
"version": "1.0.0-dev.6",
"version": "1.0.0-dev.8",
"description": "🧦 WebSocket API server for bots assisting ReVanced",
"main": "dist/index.js",
"scripts": {

View File

@@ -11,7 +11,6 @@ await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
target: 'bun',
minify: true,
sourcemap: 'external',
})
@@ -21,7 +20,6 @@ await Bun.build({
external: ['tesseract.js-core/*'],
target: 'bun',
outdir: './dist/worker',
minify: true,
sourcemap: 'external',
})

View File

@@ -1,3 +1,38 @@
# @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)
### Bug Fixes
* **bots/discord:** deployment runtime errors due to minification ([a60c60c](https://github.com/revanced/revanced-helper/commit/a60c60c0f994a4c256b7d0582e99a1731209cf49))
# @revanced/discord-bot [1.0.0-dev.11](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.10...@revanced/discord-bot@1.0.0-dev.11) (2024-07-30)
### Bug Fixes
* **bots/discord:** reset counter when reconnected to api, redo message scan filter logic ([d234d79](https://github.com/revanced/revanced-helper/commit/d234d79310caed9c43e14a905f9ef46a110e071d))
# @revanced/discord-bot [1.0.0-dev.10](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.9...@revanced/discord-bot@1.0.0-dev.10) (2024-07-30)

View File

@@ -9,6 +9,8 @@ export type Config = {
moderation?: {
roles: string[]
cure?: {
minimumNameLength?: number
removeCharactersRegex?: RegExp
defaultName: string
}
log?: {

View File

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

View File

@@ -12,7 +12,6 @@ await Bun.build({
outdir: './dist/src',
target: 'bun',
external: ['./config.js'],
minify: true,
sourcemap: 'external',
})

View File

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

View File

@@ -1,3 +1,7 @@
import { on, withContext } from '$utils/api/events'
withContext(on, 'ready', ({ logger }) => void logger.info('Connected to the bot API'))
withContext(on, 'ready', ({ api, logger }) => {
// Reset disconnect count, so it doesn't meet the threshold for an accidental disconnect
api.disconnectCount = 0
logger.info('Connected to the bot API')
})

View File

@@ -9,7 +9,8 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
const command = discord.commands[interaction.commandName]
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 {
logger.debug(`Command ${interaction.commandName} being executed`)

View File

@@ -8,7 +8,9 @@ withContext(on, 'messageCreate', async (context, msg) => {
if (msg.author.bot) return
const regex = new RegExp(`^(?:${config.prefix}|${msg.client.user.toString()}\\s*)([a-zA-Z-_]+)(?:\\s+)?(.+)?`)
const regex = new RegExp(
`^(?:${config.prefix ? `${escapeRegexSpecials(config.prefix)}|` : ''}${msg.client.user.toString()}\\s*)([a-zA-Z-_]+)(?:\\s+)?(.+)?`,
)
const matches = msg.content.match(regex)
if (!matches) return
@@ -17,7 +19,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
const command = discord.commands[commandName]
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 args: CommandArguments = []
@@ -51,3 +53,12 @@ withContext(on, 'messageCreate', async (context, msg) => {
await msg.reply({ embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)] })
}
})
const escapeRegexSpecials = (str: string): string => {
let escapedStr = ''
for (const char of str) {
if (['.', '+', '*', '?', '$', '(', ')', '[', ']', '{', '}', '|', '\\'].includes(char)) escapedStr += `\\${char}`
else escapedStr += char
}
return escapedStr
}

View File

@@ -33,7 +33,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
if (response) {
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({
...response,
embeds: response.embeds?.map(it => createMessageScanResponseEmbed(it, label ? 'nlp' : 'match')),

View File

@@ -10,5 +10,10 @@ if (missingEnvs.length) {
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()
discord.client.login()

View File

@@ -10,9 +10,12 @@ export const getResponseFromText = async (
// Just to be safe that we will never use data from the context parameter
{ api, logger }: Omit<typeof import('src/context'), 'config'>,
ocrMode = false,
): Promise<ConfigMessageScanResponse & { label?: string }> => {
let responseConfig: Awaited<ReturnType<typeof getResponseFromText>> = {
triggers: {},
): Promise<
Omit<ConfigMessageScanResponse, 'triggers'> & { label?: string; triggers?: ConfigMessageScanResponse['triggers'] }
> => {
type ResponseConfig = Awaited<ReturnType<typeof getResponseFromText>>
let responseConfig: Omit<ResponseConfig, 'triggers'> & { triggers?: ResponseConfig['triggers'] } = {
triggers: undefined,
response: null,
}
@@ -27,7 +30,6 @@ export const getResponseFromText = async (
const {
triggers: { text: textTriggers, image: imageTriggers },
} = trigger
if (responseConfig) break
if (ocrMode) {
if (imageTriggers)
@@ -55,7 +57,7 @@ export const getResponseFromText = async (
}
// 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')
const scan = await api.client.parseText(content)
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 (!responseConfig) {
if (!responseConfig.triggers) {
logger.debug('No match from NLP, doing after regexes')
for (let i = 0; i < responses.length; i++) {
const {
@@ -113,16 +115,23 @@ export const messageMatchesFilter = (message: Message, filter: NonNullable<Confi
if (!filter) return true
const memberRoles = new Set(message.member?.roles.cache.keys())
const blFilter = filter.blacklist
const { blacklist, whitelist } = filter
// If matches blacklist, will return false
// Any other case, will return true
return !(
blFilter &&
(blFilter.channels?.includes(message.channelId) ||
blFilter.roles?.some(role => memberRoles.has(role)) ||
blFilter.users?.includes(message.author.id))
)
// If matches only blacklist, will return false
// If matches whitelist but also matches blacklist, will return false
// If matches only whitelist, will return true
// If matches neither, will return true
return whitelist
? (whitelist.channels?.includes(message.channelId) ?? true) ||
(whitelist.roles?.some(role => memberRoles.has(role)) ?? true) ||
(whitelist.users?.includes(message.author.id) ?? true)
: true &&
!(
blacklist &&
(blacklist.channels?.includes(message.channelId) ||
blacklist.roles?.some(role => memberRoles.has(role)) ||
blacklist.users?.includes(message.author.id))
)
}
export const handleUserResponseCorrection = async (

View File

@@ -54,9 +54,9 @@ export const cureNickname = async (member: GuildMember) => {
const name = member.displayName
let cured = decancer(name)
.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 =
member.user.username.length >= 3
? member.user.username

BIN
bun.lockb

Binary file not shown.

View File

@@ -55,6 +55,7 @@
],
"patchedDependencies": {
"@semantic-release/npm@12.0.1": "patches/@semantic-release%2Fnpm@12.0.1.patch",
"drizzle-kit@0.22.8": "patches/drizzle-kit@0.22.8.patch"
"drizzle-kit@0.22.8": "patches/drizzle-kit@0.22.8.patch",
"decancer@3.2.3": "patches/decancer@3.2.3.patch"
}
}

View File

@@ -52,17 +52,20 @@ export default class Client {
// 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
// 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.ParseTextFailed, this.ws.timeout + 5000),
this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.currentSequence, this.ws.timeout + 5000),
])
.then(pkt => {
if (pkt.op === ServerOperation.ParsedText) return pkt.d
throw new Error('Failed to parse text, the API encountered an error')
return null
})
.catch(() => {
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
return Promise.race([
const packet = await Promise.race([
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 => {
if (pkt.op === ServerOperation.ParsedImage) return pkt.d
throw new Error('Failed to parse image, the API encountered an error')
return null
})
.catch(() => {
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) {
@@ -107,17 +113,20 @@ export default class Client {
})
// See line 50
return Promise.race([
const packet = await Promise.race([
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 => {
if (pkt.op === ServerOperation.TrainedMessage) return pkt.d
throw new Error('Failed to train message, the API encountered an error')
return null
})
.catch(() => {
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.#socket.send(serializePacket(packet), err => {
throw err
if (err) throw err
})
}

View File

@@ -0,0 +1,13 @@
diff --git a/src/lib.js b/src/lib.js
index de45d7dbe82975b09eff3742d0718accae2107fc..0575daa03dfabdd5c96928458ff4270cb8f7188a 100644
--- a/src/lib.js
+++ b/src/lib.js
@@ -42,7 +42,7 @@ function isMusl() {
}
function getBinding(name) {
- const path = join(__dirname, '..', `decancer.${name}.node`)
+ const path = join(import.meta.dir, '..', `decancer.${name}.node`)
return require(existsSync(path) ? path : `@vierofernando/decancer-${name}`)
}