Compare commits

...

9 Commits

Author SHA1 Message Date
semantic-release-bot
8aefcdb2e8 chore(release): 1.0.0-dev.31 [skip ci]
# @revanced/discord-bot [1.0.0-dev.31](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.30...@revanced/discord-bot@1.0.0-dev.31) (2024-09-25)

### Bug Fixes

* **bots/discord:** persist changes in context for eval command ([5b4965d](5b4965dcc7))
2024-09-25 05:46:18 +00:00
PalmDevs
5b4965dcc7 fix(bots/discord): persist changes in context for eval command 2024-09-25 12:43:42 +07:00
semantic-release-bot
37e64a2eb8 chore(release): 1.0.0-dev.30 [skip ci]
# @revanced/discord-bot [1.0.0-dev.30](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.29...@revanced/discord-bot@1.0.0-dev.30) (2024-09-24)

### Features

* **bots/discord:** improve admin commands ([0346741](0346741188))
2024-09-24 23:48:53 +00:00
PalmDevs
59dd803529 chore(bots/discord): temporarily fix timer statuses being both active 2024-09-25 06:47:15 +07:00
PalmDevs
2ef66fbc87 chore(bots/discord): add more debug logs on messageScan 2024-09-25 06:47:13 +07:00
PalmDevs
0346741188 feat(bots/discord): improve admin commands
- The reload command now properly reloads configuration changes by skipping the configuration cache
- The eval command now sends a file if the output is too long
- The eval command now restricts access to the bot token by removing it and sandboxing the input code execution
2024-09-25 06:45:52 +07:00
semantic-release-bot
e0e40237fa chore(release): 1.0.0-dev.29 [skip ci]
# @revanced/discord-bot [1.0.0-dev.29](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.28...@revanced/discord-bot@1.0.0-dev.29) (2024-09-21)

### Bug Fixes

* **bots/discord:** fix get response logic ([3261294](3261294822))
2024-09-21 21:03:36 +00:00
PalmDevs
d3c56222be chore: update dependencies 2024-09-22 04:02:20 +07:00
PalmDevs
3261294822 fix(bots/discord): fix get response logic 2024-09-22 04:01:36 +07:00
10 changed files with 198 additions and 86 deletions

View File

@@ -1,3 +1,24 @@
# @revanced/discord-bot [1.0.0-dev.31](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.30...@revanced/discord-bot@1.0.0-dev.31) (2024-09-25)
### Bug Fixes
* **bots/discord:** persist changes in context for eval command ([5b4965d](https://github.com/revanced/revanced-helper/commit/5b4965dcc7285676b2b3b6756c249bd56eaf8485))
# @revanced/discord-bot [1.0.0-dev.30](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.29...@revanced/discord-bot@1.0.0-dev.30) (2024-09-24)
### Features
* **bots/discord:** improve admin commands ([0346741](https://github.com/revanced/revanced-helper/commit/03467411882b8598e2c06f389a09ef2e201bb43f))
# @revanced/discord-bot [1.0.0-dev.29](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.28...@revanced/discord-bot@1.0.0-dev.29) (2024-09-21)
### Bug Fixes
* **bots/discord:** fix get response logic ([3261294](https://github.com/revanced/revanced-helper/commit/3261294822b0a9faec094536ed5be2d3e1d5e17b))
# @revanced/discord-bot [1.0.0-dev.28](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.27...@revanced/discord-bot@1.0.0-dev.28) (2024-09-20)

View File

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

View File

@@ -1,8 +1,12 @@
import { unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { inspect } from 'util'
import { runInContext } from 'vm'
import { ApplicationCommandOptionType } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { parseDuration } from '$/utils/duration'
export default new AdminCommand({
name: 'eval',
@@ -18,26 +22,73 @@ export default new AdminCommand({
type: ApplicationCommandOptionType.Boolean,
required: false,
},
['inspect-depth']: {
description: 'How many times to recurse while formatting the object (default: 1)',
type: ApplicationCommandOptionType.Integer,
required: false,
},
timeout: {
description: 'Timeout for the evaluation (default: 10s)',
type: ApplicationCommandOptionType.String,
required: false,
},
},
async execute(context, trigger, { code, 'show-hidden': showHidden }) {
// So it doesn't show up as unused, and we can use it in `code`
context
async execute(context, trigger, { code, 'show-hidden': showHidden, timeout, ['inspect-depth']: inspectDepth }) {
const currentToken = context.discord.client.token
const currentEnvToken = process.env['DISCORD_TOKEN']
context.discord.client.token = null
process.env['DISCORD_TOKEN'] = undefined
// This allows developers to access and modify the context object to apply changes
// to the bot while the bot is running, minus malicious actors getting the token to perform malicious actions
const output = await runInContext(
code,
{
...globalThis,
context,
},
{
timeout: parseDuration(timeout ?? '10s'),
filename: 'eval',
displayErrors: true,
},
)
context.discord.client.token = currentToken
process.env['DISCORD_TOKEN'] = currentEnvToken
const inspectedOutput = inspect(output, {
depth: inspectDepth ?? 1,
showHidden,
getters: showHidden,
numericSeparator: true,
showProxy: showHidden,
})
const embed = createSuccessEmbed('Evaluate', `\`\`\`js\n${code}\`\`\``)
const files: string[] = []
const filepath = join(Bun.main, '..', `output-eval-${Date.now()}.js`)
if (inspectedOutput.length > 1000) {
writeFileSync(filepath, inspectedOutput)
files.push(filepath)
embed.addFields({
name: 'Result',
value: '```js\n// (output too long, file uploaded)```',
})
} else
embed.addFields({
name: 'Result',
value: `\`\`\`js\n${inspectedOutput}\`\`\``,
})
await trigger.reply({
ephemeral: true,
embeds: [
createSuccessEmbed('Evaluate', `\`\`\`js\n${code}\`\`\``).addFields({
name: 'Result',
// biome-ignore lint/security/noGlobalEval: This is fine as it's an admin command
value: `\`\`\`js\n${inspect(await eval(code), {
depth: 1,
showHidden,
getters: true,
numericSeparator: true,
showProxy: true,
})}\`\`\``,
}),
],
embeds: [embed],
files,
})
if (files.length) unlinkSync(filepath)
},
})

View File

@@ -11,7 +11,10 @@ export default new AdminCommand({
description: 'The type of exception to throw',
type: ApplicationCommandOptionType.String,
required: true,
choices: Object.keys(CommandErrorType).map(k => ({ name: k, value: k })),
choices: [
{ name: 'Process', value: 'Process' },
...Object.keys(CommandErrorType).map(k => ({ name: k, value: k })),
],
},
},
async execute(_, __, { type }) {

View File

@@ -1,5 +1,5 @@
import { dirname, join } from 'path'
import { AdminCommand } from '$/classes/Command'
import { join, dirname } from 'path'
import type { Config } from 'config.schema'
@@ -8,7 +8,12 @@ export default new AdminCommand({
description: 'Reload configuration',
async execute(context, trigger) {
const { api, logger, discord } = context
context.config = ((await import(join(dirname(Bun.main), '..', 'config.js'))) as { default: Config }).default
logger.info(`Reload triggered by ${context.executor.tag} (${context.executor.id})`)
// Apparently the query strings only work with non-Windows "URLs", otherwise it'd just infinitely hang
const path = `${Bun.pathToFileURL(join(dirname(Bun.main), '..', 'config.js')).toString()}?cache=${Date.now()}`
logger.debug(`Reloading configuration from: ${path}`)
context.config = ((await import(path)) as { default: Config }).default
if ('deferReply' in trigger) await trigger.deferReply({ ephemeral: true })
@@ -32,6 +37,6 @@ export default new AdminCommand({
await discord.client.login(process.env['DISCORD_TOKEN'])
// @ts-expect-error: TypeScript dum
await trigger[('deferReply' in trigger ? 'editReply' : 'reply')]({ content: 'Reloaded configuration' })
await trigger['deferReply' in trigger ? 'editReply' : 'reply']({ content: 'Reloaded configuration' })
},
})

View File

@@ -1,4 +1,3 @@
import { MessageScanLabeledResponseReactions } from '$/constants'
import { responses } from '$/database/schemas'
import { getResponseFromText, messageMatchesFilter } from '$/utils/discord/messageScan'
import { createMessageScanResponseEmbed } from '$utils/discord/embeds'
@@ -22,7 +21,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
if (msg.content.length) {
try {
logger.debug(`Classifying message ${msg.id}`)
logger.debug(`Classifying message ${msg.id}, possible responses is ${filteredResponses.length}`)
const { response, label, respondToReply } = await getResponseFromText(
msg.content,
@@ -48,10 +47,6 @@ withContext(on, 'messageCreate', async (context, msg) => {
label,
content: msg.content,
})
for (const reaction of Object.values(MessageScanLabeledResponseReactions)) {
await reply.react(reaction)
}
}
}
} catch (e) {
@@ -60,7 +55,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
}
if (msg.attachments.size && config.attachments?.scanAttachments) {
logger.debug(`Classifying message attachments for ${msg.id}`)
logger.debug(`Classifying message attachments for ${msg.id}, possible responses is ${filteredResponses.length}`)
for (const attachment of msg.attachments.values()) {
const mimeType = attachment.contentType?.split(';')?.[0]

View File

@@ -7,6 +7,18 @@ withContext(on, 'messageCreate', async ({ discord, logger }, msg) => {
const store = discord.stickyMessages[msg.guildId]?.[msg.channelId]
if (!store) return
// TODO: Fix this by fixing the logic below
if (store.timerActive && store.forceTimerActive) {
logger.error(
`Both timers are active in sticky message store: ${msg.guildId}.${msg.channelId}, this should not happen!`,
)
logger.info('Clearing the timer and the restarting the force timer...')
clearTimeout(store.timer)
store.timerActive = false
// If the force timer is active, it implies the force timer exists
store.forceTimer!.refresh()
}
const timerPreviouslyActive = store.timerActive
// If there isn't a timer, start it up
store.timerActive = true

View File

@@ -1,6 +1,7 @@
import { type Response, responses } from '$/database/schemas'
import type { Config, ConfigMessageScanResponse, ConfigMessageScanResponseLabelConfig } from 'config.schema'
import type { Message, PartialUser, User } from 'discord.js'
import { ButtonStyle, ComponentType } from 'discord.js'
import type { APIActionRowComponent, APIButtonComponent, Message, PartialUser, User } from 'discord.js'
import { eq } from 'drizzle-orm'
import { createMessageScanResponseEmbed } from './embeds'
@@ -54,59 +55,56 @@ export const getResponseFromText = async (
break
}
}
}
}
// If none of the regexes match, we can search for labels immediately
if (!responseConfig.triggers && !flags.textRegexesOnly) {
logger.debug('No match from before regexes, doing NLP')
const scan = await api.client.parseText(content)
if (scan.labels.length) {
const matchedLabel = scan.labels[0]!
logger.debug(
`Message matched label with confidence: ${matchedLabel.name}, ${matchedLabel.confidence}`,
)
// If none of the regexes match, we can search for labels immediately
if (!responseConfig.triggers && !flags.textRegexesOnly) {
logger.debug('No match from before regexes, doing NLP')
const scan = await api.client.parseText(content)
if (scan.labels.length) {
const matchedLabel = scan.labels[0]!
logger.debug(`Message matched label with confidence: ${matchedLabel.name}, ${matchedLabel.confidence}`)
let trigger: ConfigMessageScanResponseLabelConfig | undefined
const response = responses.find(x => {
const config = x.triggers.text!.find(
(x): x is ConfigMessageScanResponseLabelConfig =>
'label' in x && x.label === matchedLabel.name,
)
if (config) trigger = config
return config
})
let trigger: ConfigMessageScanResponseLabelConfig | undefined
const response = responses.find(x => {
const config = x.triggers.text!.find(
(x): x is ConfigMessageScanResponseLabelConfig => 'label' in x && x.label === matchedLabel.name,
)
if (config) trigger = config
return config
})
if (!response) {
logger.warn(`No response config found for label ${matchedLabel.name}`)
// This returns the default value set in line 17, which means no response matched
return responseConfig
}
if (matchedLabel.confidence >= trigger!.threshold) {
logger.debug('Label confidence is enough')
responseConfig = { ...responseConfig, ...response, label: trigger!.label }
}
}
if (!response) {
logger.warn(`No response config found for label ${matchedLabel.name}`)
// This returns the default value set in line 17, which means no response matched
return responseConfig
}
// If we still don't have a response config, we can match all regexes after the initial label trigger
if (!responseConfig.triggers && !flags.imageTriggersOnly) {
logger.debug('No match from NLP, doing after regexes')
for (let i = 0; i < responses.length; i++) {
const {
triggers: { text: textTriggers },
} = responses[i]!
const firstLabelIndex = firstLabelIndexes[i] ?? -1
if (matchedLabel.confidence >= trigger!.threshold) {
logger.debug('Label confidence is enough')
responseConfig = { ...responseConfig, ...response, label: trigger!.label }
}
}
}
for (let j = firstLabelIndex + 1; j < textTriggers!.length; j++) {
const trigger = textTriggers![j]!
// If we still don't have a response config, we can match all regexes after the initial label trigger
if (!responseConfig.triggers && !flags.imageTriggersOnly) {
logger.debug('No match from NLP, doing after regexes')
for (let i = 0; i < responses.length; i++) {
const {
triggers: { text: textTriggers },
} = responses[i]!
const firstLabelIndex = firstLabelIndexes[i] ?? -1
if (trigger instanceof RegExp) {
if (trigger.test(content)) {
logger.debug(`Message matched regex (after mode): ${trigger.source}`)
responseConfig = responses[i]!
break
}
}
for (let j = firstLabelIndex + 1; j < textTriggers!.length; j++) {
const trigger = textTriggers![j]!
if (trigger instanceof RegExp) {
if (trigger.test(content)) {
logger.debug(`Message matched regex (after mode): ${trigger.source}`)
responseConfig = responses[i]!
break
}
}
}
@@ -163,14 +161,41 @@ export const handleUserResponseCorrection = async (
})
.where(eq(responses.replyId, response.replyId))
await reply.edit({
return void (await reply.edit({
...correctLabelResponse.response,
embeds: correctLabelResponse.response.embeds?.map(createMessageScanResponseEmbed),
})
components: [],
}))
}
await api.client.trainMessage(response.content, label)
logger.debug(`User ${user.id} trained message ${response.replyId} as ${label} (positive)`)
await reply.reactions.removeAll()
await reply.edit({
components: [],
})
}
export const createMessageScanResponseComponents = (reply: Message<true>) => [
{
type: ComponentType.ActionRow,
components: [
{
type: ComponentType.Button,
style: ButtonStyle.Secondary,
emoji: {
id: '👍',
},
custom_id: `train:${reply.id}`,
},
{
type: ComponentType.Button,
style: ButtonStyle.Secondary,
emoji: {
id: '🔧',
},
custom_id: `edit:${reply.id}`,
},
],
} as APIActionRowComponent<APIButtonComponent>,
]

BIN
bun.lockb

Binary file not shown.

View File

@@ -30,22 +30,22 @@
"packageManager": "bun@1.1.20",
"devDependencies": {
"@anolilab/multi-semantic-release": "^1.1.3",
"@biomejs/biome": "^1.8.3",
"@biomejs/biome": "^1.9.2",
"@codedependant/semantic-release-docker": "^5.0.3",
"@commitlint/cli": "^19.4.0",
"@commitlint/config-conventional": "^19.2.2",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"@saithodev/semantic-release-backmerge": "^4.0.1",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/exec": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@tsconfig/strictest": "^2.0.5",
"@types/bun": "^1.1.6",
"@types/bun": "^1.1.10",
"conventional-changelog-conventionalcommits": "^7.0.2",
"lefthook": "^1.7.14",
"lefthook": "^1.7.15",
"portainer-service-webhook": "https://github.com/newarifrh/portainer-service-webhook#v1",
"semantic-release": "^24.1.0",
"turbo": "^2.0.14",
"typescript": "^5.5.4"
"semantic-release": "^24.1.1",
"turbo": "^2.1.2",
"typescript": "^5.6.2"
},
"trustedDependencies": [
"@biomejs/biome",