Compare commits

...

16 Commits

Author SHA1 Message Date
semantic-release-bot
14d301eeb4 chore(release): 1.0.0-dev.35 [skip ci]
# @revanced/discord-bot [1.0.0-dev.35](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.34...@revanced/discord-bot@1.0.0-dev.35) (2024-10-17)

### Bug Fixes

* **bots/discord:** fix freeze on prod builds ([8efb549](8efb549453))
2024-10-17 18:34:04 +00:00
PalmDevs
8efb549453 fix(bots/discord): fix freeze on prod builds 2024-10-18 01:32:42 +07:00
PalmDevs
79fea8b286 fix: update patches for dependencies 2024-10-18 00:02:06 +07:00
semantic-release-bot
e798a9ef32 chore(release): 1.0.0-dev.34 [skip ci]
# @revanced/discord-bot [1.0.0-dev.34](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.33...@revanced/discord-bot@1.0.0-dev.34) (2024-10-17)

### Bug Fixes

* **bots/discord:** attempt to fix stuck sticky message timeouts ([3ed5bd1](3ed5bd11ac))
* **bots/discord:** fix reload not working ([11582d5](11582d5034))

### Features

* **bots/discord:** add default durations for moderation commands ([27d3b39](27d3b39209))
* **bots/discord:** cure on every event ([8ff6086](8ff6086028))
2024-10-17 16:56:34 +00:00
PalmDevs
7b5d4fa1a2 chore: update dependencies 2024-10-17 23:55:17 +07:00
PalmDevs
11582d5034 fix(bots/discord): fix reload not working 2024-10-17 23:20:02 +07:00
PalmDevs
488d37e65b fix(packages/shareed): add missing imports 2024-10-17 21:47:14 +07:00
PalmDevs
3ed5bd11ac fix(bots/discord): attempt to fix stuck sticky message timeouts 2024-10-17 21:40:41 +07:00
PalmDevs
8ff6086028 feat(bots/discord): cure on every event 2024-10-17 21:39:05 +07:00
PalmDevs
27d3b39209 feat(bots/discord): add default durations for moderation commands 2024-10-17 21:38:54 +07:00
semantic-release-bot
6e181c0e7f chore(release): 1.0.0-dev.33 [skip ci]
# @revanced/discord-bot [1.0.0-dev.33](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.32...@revanced/discord-bot@1.0.0-dev.33) (2024-09-25)

### Features

* **bots/discord:** add trigger to context for eval ([b5f4097](b5f4097538))
2024-09-25 06:02:32 +00:00
PalmDevs
b5f4097538 feat(bots/discord): add trigger to context for eval 2024-09-25 13:00:53 +07:00
semantic-release-bot
f6d2e25130 chore(release): 1.0.0-dev.32 [skip ci]
# @revanced/discord-bot [1.0.0-dev.32](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.31...@revanced/discord-bot@1.0.0-dev.32) (2024-09-25)

### Bug Fixes

* **bots/discord:** contextify object before sandboxing ([062735f](062735f6d5))
2024-09-25 05:50:49 +00:00
PalmDevs
062735f6d5 fix(bots/discord): contextify object before sandboxing 2024-09-25 12:49:29 +07:00
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
22 changed files with 154 additions and 103 deletions

View File

@@ -28,13 +28,13 @@
"homepage": "https://github.com/revanced/revanced-helper#readme",
"dependencies": {
"@revanced/bot-shared": "workspace:*",
"@sapphire/async-queue": "^1.5.2",
"@sapphire/async-queue": "^1.5.3",
"chalk": "^5.3.0",
"tesseract.js": "^5.1.0",
"ws": "^8.17.1"
"tesseract.js": "^5.1.1",
"ws": "^8.18.0"
},
"devDependencies": {
"@types/ws": "^8.5.10",
"@types/ws": "^8.5.12",
"typed-emitter": "^2.1.0"
}
}
}

View File

@@ -1,3 +1,45 @@
# @revanced/discord-bot [1.0.0-dev.35](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.34...@revanced/discord-bot@1.0.0-dev.35) (2024-10-17)
### Bug Fixes
* **bots/discord:** fix freeze on prod builds ([8efb549](https://github.com/revanced/revanced-helper/commit/8efb549453a04fab1ac6414a7f7f8bf702df3c93))
# @revanced/discord-bot [1.0.0-dev.34](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.33...@revanced/discord-bot@1.0.0-dev.34) (2024-10-17)
### Bug Fixes
* **bots/discord:** attempt to fix stuck sticky message timeouts ([3ed5bd1](https://github.com/revanced/revanced-helper/commit/3ed5bd11acc3b4fbd57b0d632c68eb9f77365b8a))
* **bots/discord:** fix reload not working ([11582d5](https://github.com/revanced/revanced-helper/commit/11582d50345cae9fb645a65ca4e621596de6a408))
### Features
* **bots/discord:** add default durations for moderation commands ([27d3b39](https://github.com/revanced/revanced-helper/commit/27d3b392092141a1e3b4b0298131ff7817458dc1))
* **bots/discord:** cure on every event ([8ff6086](https://github.com/revanced/revanced-helper/commit/8ff6086028132cc4b49ee60846e8d6ef909f5a89))
# @revanced/discord-bot [1.0.0-dev.33](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.32...@revanced/discord-bot@1.0.0-dev.33) (2024-09-25)
### Features
* **bots/discord:** add trigger to context for eval ([b5f4097](https://github.com/revanced/revanced-helper/commit/b5f40975386677ffff343c42f8ffac21f847a0b7))
# @revanced/discord-bot [1.0.0-dev.32](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.31...@revanced/discord-bot@1.0.0-dev.32) (2024-09-25)
### Bug Fixes
* **bots/discord:** contextify object before sandboxing ([062735f](https://github.com/revanced/revanced-helper/commit/062735f6d552890404d6192244c51a11b0709580))
# @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)

View File

@@ -2,7 +2,7 @@
"name": "@revanced/discord-bot",
"type": "module",
"private": true,
"version": "1.0.0-dev.30",
"version": "1.0.0-dev.35",
"description": "🤖 Discord bot assisting ReVanced",
"main": "src/index.ts",
"scripts": {
@@ -28,19 +28,19 @@
},
"homepage": "https://github.com/revanced/revanced-helper#readme",
"dependencies": {
"@discordjs/builders": "^1.8.2",
"@discordjs/rest": "^2.3.0",
"@discordjs/builders": "^1.9.0",
"@discordjs/rest": "^2.4.0",
"@revanced/bot-api": "workspace:*",
"@revanced/bot-shared": "workspace:*",
"chalk": "^5.3.0",
"decancer": "^3.2.4",
"discord.js": "^14.15.3",
"discord.js": "^14.16.3",
"drizzle-orm": "^0.31.4",
"parse-duration": "^1.1.0"
},
"devDependencies": {
"@libsql/client": "^0.7.0",
"discord-api-types": "^0.37.97",
"discord-api-types": "^0.37.102",
"drizzle-kit": "^0.22.8"
}
}

View File

@@ -1,7 +1,7 @@
import { unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { inspect } from 'util'
import { runInNewContext } from 'vm'
import { createContext, runInContext } from 'vm'
import { ApplicationCommandOptionType } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
@@ -41,12 +41,13 @@ export default new AdminCommand({
// 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 runInNewContext(
const output = await runInContext(
code,
{
createContext({
...globalThis,
context,
},
trigger,
}),
{
timeout: parseDuration(timeout ?? '10s'),
filename: 'eval',

View File

@@ -1,8 +1,5 @@
import { dirname, join } from 'path'
import { AdminCommand } from '$/classes/Command'
import type { Config } from 'config.schema'
export default new AdminCommand({
name: 'reload',
description: 'Reload configuration',
@@ -10,10 +7,8 @@ export default new AdminCommand({
const { api, logger, discord } = context
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
logger.debug('Invalidating previous config...')
context.config.invalidate()
if ('deferReply' in trigger) await trigger.deferReply({ ephemeral: true })
@@ -28,7 +23,7 @@ export default new AdminCommand({
api.client.disconnect(true)
api.disconnectCount = 0
api.intentionallyDisconnecting = false
await api.client.connect()
api.client.connect()
logger.info('Reinitializing Discord client to reload configuration...')
await discord.client.destroy()

View File

@@ -18,13 +18,14 @@ export default new ModerationCommand({
required: false,
type: ModerationCommand.OptionType.String,
},
dmd: {
description: 'Duration to delete messages (must be from 0 to 7 days)',
dmt: {
description:
'Time duration to delete messages (default time unit is days, must be from 0s to 7d, default value is 0s)',
required: false,
type: ModerationCommand.OptionType.String,
},
},
async execute({ logger, executor }, interaction, { user, reason, dmd }) {
async execute({ logger, executor }, interaction, { user, reason, dmt }) {
const guild = await interaction.client.guilds.fetch(interaction.guildId)
const member = await guild.members.fetch(user).catch(() => {})
const moderator = await guild.members.fetch(executor.user)
@@ -40,7 +41,7 @@ export default new ModerationCommand({
)
}
const dms = Math.floor(dmd ? parseDuration(dmd) : 0 / 1000)
const dms = Math.floor((dmt ? parseDuration(dmt, 'd') : 0) / 1000)
await interaction.guild!.members.ban(user, {
reason: `Banned by moderator ${executor.user.tag} (${executor.id}): ${reason}`,
deleteMessageSeconds: dms,

View File

@@ -14,13 +14,13 @@ export default new ModerationCommand({
required: true,
type: ModerationCommand.OptionType.User,
},
reason: {
description: 'The reason for muting the member',
duration: {
description: 'The duration of the mute (default time unit is minutes)',
required: false,
type: ModerationCommand.OptionType.String,
},
duration: {
description: 'The duration of the mute',
reason: {
description: 'The reason for muting the member',
required: false,
type: ModerationCommand.OptionType.String,
},
@@ -33,7 +33,7 @@ export default new ModerationCommand({
const guild = await interaction.client.guilds.fetch(interaction.guildId)
const member = await guild.members.fetch(user.id)
const moderator = await guild.members.fetch(executor.id)
const duration = durationInput ? parseDuration(durationInput) : Infinity
const duration = durationInput ? parseDuration(durationInput, 'm') : Infinity
if (Number.isInteger(duration) && duration! < 1)
throw new CommandError(

View File

@@ -11,12 +11,12 @@ const SubcommandOptions = {
type: ModerationCommand.OptionType.User,
},
preset: {
description: 'The preset to apply or remove',
description: 'The preset to manage',
required: true,
type: ModerationCommand.OptionType.String,
},
duration: {
description: 'The duration to apply the preset for (only for apply action)',
description: 'The duration to apply the preset for (only for apply action, default time unit is minutes)',
required: false,
type: ModerationCommand.OptionType.String,
},
@@ -53,7 +53,7 @@ export default new ModerationCommand({
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
if (apply) {
const duration = durationInput ? parseDuration(durationInput) : Infinity
const duration = durationInput ? parseDuration(durationInput, 'm') : Infinity
if (Number.isInteger(duration) && duration! < 1)
throw new CommandError(
CommandErrorType.InvalidArgument,
@@ -83,6 +83,13 @@ export default new ModerationCommand({
removeRolePreset(member, preset)
}, expires)
await sendPresetReplyAndLogs(apply ? 'apply' : 'remove', trigger, executor, user, preset, expires ? Math.ceil(expires / 1000) : undefined)
await sendPresetReplyAndLogs(
apply ? 'apply' : 'remove',
trigger,
executor,
user,
preset,
expires ? Math.ceil(expires / 1000) : undefined,
)
},
})

View File

@@ -10,7 +10,7 @@ export default new ModerationCommand({
description: 'Set a slowmode for a channel',
options: {
duration: {
description: 'The duration to set',
description: 'The duration to set (default time unit is seconds)',
required: true,
type: ModerationCommand.OptionType.String,
},
@@ -23,13 +23,10 @@ export default new ModerationCommand({
},
async execute({ logger, executor }, interaction, { duration: durationInput, channel: channelInput }) {
const channel = channelInput ?? (await interaction.guild!.channels.fetch(interaction.channelId))
const duration = parseDuration(durationInput)
const duration = parseDuration(durationInput, 's')
if (!channel?.isTextBased() || channel.isDMBased())
throw new CommandError(
CommandErrorType.InvalidArgument,
'The supplied channel is not a text channel.',
)
throw new CommandError(CommandErrorType.InvalidArgument, 'The supplied channel is not a text channel.')
if (Number.isNaN(duration)) throw new CommandError(CommandErrorType.InvalidArgument, 'Invalid duration.')
if (duration < 0 || duration > 36e4)

View File

@@ -0,0 +1,28 @@
import { dirname, join } from 'path'
import _firstConfig from '../config.js'
let currentConfig = _firstConfig
// Other parts of the code will access properties of this proxy, they don't care what the target looks like
export const config = new Proxy(
{
INSPECTION_WARNING: 'Run `context.__getConfig()` to inspect the latest config.',
} as unknown as typeof currentConfig,
{
get(_, p, receiver) {
if (p === 'invalidate')
return async () => {
const path = join(dirname(Bun.main), '..', 'config.js')
Loader.registry.delete(path)
currentConfig = (await import(path)).default
}
return Reflect.get(currentConfig, p, receiver)
},
set(_, p, newValue, receiver) {
return Reflect.set(currentConfig, p, newValue, receiver)
},
},
) as typeof _firstConfig & { invalidate(): void }
export const __getConfig = () => currentConfig

View File

@@ -6,18 +6,19 @@ import { createLogger } from '@revanced/bot-shared'
import { Client as DiscordClient, type Message, Partials } from 'discord.js'
import { drizzle } from 'drizzle-orm/bun-sqlite'
// Export some things first, as commands require them
import config from '../config.js'
export { config }
import * as schemas from './database/schemas'
import type { default as Command, CommandOptionsOptions, CommandType } from './classes/Command'
import { __getConfig, config } from './config'
export { config, __getConfig }
export const logger = createLogger({
level: config.logLevel === 'none' ? Number.MAX_SAFE_INTEGER : config.logLevel,
})
// Export a few things before we initialize commands
import * as commands from './commands'
import * as schemas from './database/schemas'
import type { default as Command, CommandOptionsOptions, CommandType } from './classes/Command'
export const api = {
client: new APIClient({

View File

@@ -1,9 +1,9 @@
import { on } from '$/utils/discord/events'
import { cureNickname } from '$/utils/discord/moderation'
on('guildMemberUpdate', async (oldMember, newMember) => {
on('guildMemberUpdate', (_, newMember) => {
if (newMember.user.bot) return
if (oldMember.displayName !== newMember.displayName) await cureNickname(newMember)
cureNickname(newMember)
})
on('guildMemberAdd', member => {
@@ -11,7 +11,7 @@ on('guildMemberAdd', member => {
cureNickname(member)
})
on('messageCreate', async msg => {
on('messageCreate', msg => {
if (msg.author.bot || !msg.member) return
await cureNickname(msg.member)
cureNickname(msg.member)
})

View File

@@ -7,41 +7,8 @@ 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
if (!store.timer) store.timer = setTimeout(store.send, store.timerMs) as NodeJS.Timeout
else {
/*
If:
- (negate carried) There's a timer
- The timer is not active
- The force timer is not active
Then:
- Restart the timer
*/
if (!timerPreviouslyActive && !store.forceTimerActive) store.timer.refresh()
/*
If:
- Any of:
- (negate carried) The timer is active
- (negate carried) The force timer is active
- The force timer is not active
Then:
- Start the force timer and clear the existing timer
*/ else if (!store.forceTimerActive && store.forceTimerMs) {
if (store.timerActive) {
if (!store.forceTimerActive && store.forceTimerMs) {
logger.debug(
`Channel ${msg.channelId} in guild ${msg.guildId} is active, starting force send timer and clearing existing timer`,
)
@@ -62,5 +29,8 @@ withContext(on, 'messageCreate', async ({ discord, logger }, msg) => {
) as NodeJS.Timeout
else store.forceTimer.refresh()
}
} else if (!store.forceTimerActive) {
store.timerActive = true
if (!store.timer) store.timer = setTimeout(store.send, store.timerMs) as NodeJS.Timeout
}
})

View File

@@ -60,7 +60,7 @@ export default withContext(on, 'ready', async ({ config, discord, logger }, clie
)
}
}
// Set up the store
discord.stickyMessages[guildId]![channelId] = {
forceTimerActive: false,
@@ -69,7 +69,7 @@ export default withContext(on, 'ready', async ({ config, discord, logger }, clie
timerMs: timeout,
send,
// If the store exists before the configuration refresh, take its current message
currentMessage: oldStore?.[channelId]?.currentMessage
currentMessage: oldStore?.[channelId]?.currentMessage,
}
// Send a new sticky message immediately, as well as deleting the old/outdated message, if it exists

View File

@@ -1,6 +1,15 @@
import parse from 'parse-duration'
export const parseDuration = (duration: string) => parse(duration, 'ms') ?? Number.NaN
const defaultUnitValue = parse['']!
export const parseDuration = (duration: string, defaultUnit?: parse.Units) => {
if (defaultUnit) parse[''] = parse[defaultUnit]!
return (
// biome-ignore lint/suspicious/noAssignInExpressions: Expression is ignored
// biome-ignore lint/style/noCommaOperator: The last expression (parse call) is returned, it is not confusing
(parse[''] = defaultUnitValue), parse(duration, 'ms') ?? Number.NaN
)
}
export const durationToString = (duration: number) => {
if (duration === 0) return '0s'

BIN
bun.lockb

Binary file not shown.

View File

@@ -30,7 +30,7 @@
"packageManager": "bun@1.1.20",
"devDependencies": {
"@anolilab/multi-semantic-release": "^1.1.3",
"@biomejs/biome": "^1.9.2",
"@biomejs/biome": "^1.9.3",
"@codedependant/semantic-release-docker": "^5.0.3",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
@@ -39,13 +39,13 @@
"@semantic-release/exec": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@tsconfig/strictest": "^2.0.5",
"@types/bun": "^1.1.10",
"@types/bun": "^1.1.11",
"conventional-changelog-conventionalcommits": "^7.0.2",
"lefthook": "^1.7.15",
"lefthook": "^1.7.21",
"portainer-service-webhook": "https://github.com/newarifrh/portainer-service-webhook#v1",
"semantic-release": "^24.1.1",
"turbo": "^2.1.2",
"typescript": "^5.6.2"
"semantic-release": "^24.1.2",
"turbo": "^2.1.3",
"typescript": "^5.6.3"
},
"trustedDependencies": [
"@biomejs/biome",
@@ -56,6 +56,6 @@
"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",
"decancer@3.2.3": "patches/decancer@3.2.3.patch"
"decancer@3.2.4": "patches/decancer@3.2.4.patch"
}
}

View File

@@ -28,10 +28,10 @@
"homepage": "https://github.com/revanced/revanced-helper#readme",
"dependencies": {
"@revanced/bot-shared": "workspace:*",
"ws": "^8.17.1"
"ws": "^8.18.0"
},
"devDependencies": {
"@types/ws": "^8.5.10",
"@types/ws": "^8.5.12",
"typed-emitter": "^2.1.0"
}
}

View File

@@ -35,7 +35,7 @@ export class ClientWebSocketManager {
/**
* Sets the URL to connect to
*
*
* **Requires a reconnect to take effect**
*/
async setOptions({ url, timeout }: Partial<ClientWebSocketManagerOptions>, autoReconnect = true) {

View File

@@ -30,7 +30,7 @@
},
"homepage": "https://github.com/revanced/revanced-helper#readme",
"dependencies": {
"bson": "^6.7.0",
"bson": "^6.8.0",
"chalk": "^5.3.0",
"tracer": "^1.3.0",
"valibot": "^0.30.0"

View File

@@ -1,18 +1,18 @@
import {
url,
type AnySchema,
type BooleanSchema,
type NullSchema,
type ObjectSchema,
type Output,
type BooleanSchema,
array,
boolean,
enum_,
null_,
object,
parse,
special,
string,
boolean,
url,
// merge
} from 'valibot'
import DisconnectReason from '../constants/DisconnectReason'