Compare commits

..

42 Commits

Author SHA1 Message Date
semantic-release-bot
0a5a9c3e27 chore(release): 1.4.1 [skip ci]
## @revanced/discord-bot [1.4.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.4.0...@revanced/discord-bot@1.4.1) (2025-09-13)

### Bug Fixes

* **bots/discord/database:** use non-deprecated way to create indexes ([8cc2377](8cc2377cbf))
* **bots/discord:** allow partial users ([dd3e7d2](dd3e7d2ee0))
* **bots/discord:** error in cache `keepOverLimit` comparison ([567c5d2](567c5d2c7f))
2025-09-13 12:28:35 +00:00
PalmDevs
50a205c430 chore: update dependencies 2025-09-13 19:27:45 +07:00
PalmDevs
dd3e7d2ee0 fix(bots/discord): allow partial users 2025-09-13 19:27:43 +07:00
PalmDevs
567c5d2c7f fix(bots/discord): error in cache keepOverLimit comparison 2025-09-13 19:27:42 +07:00
PalmDevs
8cc2377cbf fix(bots/discord/database): use non-deprecated way to create indexes 2025-09-13 19:27:41 +07:00
semantic-release-bot
f3c199d573 chore(release): 1.4.0 [skip ci]
# @revanced/discord-bot [1.4.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.3.0...@revanced/discord-bot@1.4.0) (2025-07-11)

### Bug Fixes

* **bots/discord:** pass non-empty out of scope label to discord ([fbd9480](fbd9480036))

### Features

* **bots/discord:** react to label classified response ([96a9b83](96a9b83c48))
2025-07-11 18:23:24 +00:00
PalmDevs
42c0facef1 chore: format 2025-07-12 01:22:30 +07:00
PalmDevs
96a9b83c48 feat(bots/discord): react to label classified response 2025-07-12 01:22:28 +07:00
PalmDevs
fbd9480036 fix(bots/discord): pass non-empty out of scope label to discord 2025-07-12 01:22:27 +07:00
semantic-release-bot
cc02c0a775 chore(release): 1.3.0 [skip ci]
# @revanced/discord-bot [1.3.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.3...@revanced/discord-bot@1.3.0) (2025-07-11)

### Features

* **bots/discord:** support training without label ([c68cfd1](c68cfd1c01))
2025-07-11 18:08:35 +00:00
semantic-release-bot
c83e219088 chore(release): 1.1.0 [skip ci]
# @revanced/bot-websocket-api [1.1.0](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.2...@revanced/bot-websocket-api@1.1.0) (2025-07-11)

### Features

* **apis/websocket:** support training without label ([670cc70](670cc70057))
2025-07-11 18:07:46 +00:00
PalmDevs
6164e6c1a5 chore: format 2025-07-12 01:06:45 +07:00
PalmDevs
47d2f8c015 chore: update dependencies and remove outdated patches 2025-07-12 01:06:43 +07:00
PalmDevs
c68cfd1c01 feat(bots/discord): support training without label 2025-07-12 01:06:41 +07:00
PalmDevs
2b1928e116 feat(packages/api): support training without label 2025-07-12 01:06:39 +07:00
PalmDevs
670cc70057 feat(apis/websocket): support training without label 2025-07-12 01:06:37 +07:00
Palm
439f301872 chore: merge dev to main 2025-07-11 21:05:10 +07:00
Pun Butrach
aeccf12906 ci: Use default fetch-depth of 1 for checkout step (#47) 2025-07-08 18:14:54 +02:00
semantic-release-bot
b4ac8433f4 chore(release): 1.2.3 [skip ci]
## @revanced/discord-bot [1.2.3](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.2...@revanced/discord-bot@1.2.3) (2025-06-23)

### Bug Fixes

* **bots/discord:** disable unneeded cache, enable message cache sweeping ([3a0f0fe](3a0f0fe786))
2025-06-23 13:33:41 +00:00
semantic-release-bot
b01a4accee chore(release): 1.0.2 [skip ci]
## @revanced/bot-websocket-api [1.0.2](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.1...@revanced/bot-websocket-api@1.0.2) (2025-06-23)
2025-06-23 13:32:58 +00:00
PalmDevs
858e989bdc build(Needs bump): update dependencies 2025-06-23 20:32:18 +07:00
PalmDevs
3a0f0fe786 fix(bots/discord): disable unneeded cache, enable message cache sweeping 2025-06-23 20:30:28 +07:00
semantic-release-bot
409e850768 chore(release): 1.2.2 [skip ci]
## @revanced/discord-bot [1.2.2](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.1...@revanced/discord-bot@1.2.2) (2025-06-10)

### Bug Fixes

* **bots/discord:** use intervals for checking expired presets ([6e89b87](6e89b874cd))
2025-06-10 17:40:44 +00:00
PalmDevs
6e89b874cd fix(bots/discord): use intervals for checking expired presets 2025-06-11 00:40:08 +07:00
semantic-release-bot
b4a5c62549 chore(release): 1.2.1 [skip ci]
## @revanced/discord-bot [1.2.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.0...@revanced/discord-bot@1.2.1) (2025-05-02)

### Bug Fixes

* **bots/discord:** fix timeout overflow check for role presets ([495f686](495f686292))
2025-05-02 16:11:20 +00:00
PalmDevs
495f686292 fix(bots/discord): fix timeout overflow check for role presets 2025-05-02 23:01:37 +07:00
semantic-release-bot
71eb11b67f chore(release): 1.2.0 [skip ci]
# @revanced/discord-bot [1.2.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.1.2...@revanced/discord-bot@1.2.0) (2025-05-02)

### Features

* **bots/discord:** switch duration parser to `@sapphire/duration` ([04ce825](04ce8252c0))
2025-05-02 15:58:00 +00:00
PalmDevs
04ce8252c0 feat(bots/discord): switch duration parser to @sapphire/duration 2025-05-02 22:57:13 +07:00
semantic-release-bot
27e06db1d9 chore(release): 1.1.2 [skip ci]
## @revanced/discord-bot [1.1.2](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.1.1...@revanced/discord-bot@1.1.2) (2025-04-16)

### Bug Fixes

* **bots/discord/commands/admin/reload:** fix type error ([3908854](3908854fe0))
* **bots/discord/commands/moderation:** check if timeout amount is safe in role-preset commands ([0c1382c](0c1382c558))
* **bots/discord:** replace use of deprecated `options.ephemeral` in replies ([31e5cf7](31e5cf7fc5))
2025-04-16 13:41:16 +00:00
PalmDevs
3908854fe0 fix(bots/discord/commands/admin/reload): fix type error 2025-04-16 20:40:16 +07:00
PalmDevs
0c1382c558 fix(bots/discord/commands/moderation): check if timeout amount is safe in role-preset commands 2025-04-16 20:40:14 +07:00
PalmDevs
410d289297 ci(release): hash new lockfile for dependency caching 2025-04-16 20:40:12 +07:00
PalmDevs
31e5cf7fc5 fix(bots/discord): replace use of deprecated options.ephemeral in replies 2025-04-16 20:40:11 +07:00
semantic-release-bot
4e797a2cfd chore(release): 1.1.1 [skip ci]
## @revanced/discord-bot [1.1.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.1.0...@revanced/discord-bot@1.1.1) (2025-04-14)

### Bug Fixes

* **bots/discord:** fix sticky msg force timer always starting, add more logging ([cb4dc42](cb4dc42dfa))
2025-04-14 14:09:38 +00:00
PalmDevs
cb4dc42dfa fix(bots/discord): fix sticky msg force timer always starting, add more logging 2025-04-14 21:08:47 +07:00
semantic-release-bot
33ba5b1f61 chore(release): 1.1.0 [skip ci]
# @revanced/discord-bot [1.1.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.4...@revanced/discord-bot@1.1.0) (2025-04-14)

### Features

* **bots/discord:** delete and send sticky msg concurrently, add more logging ([247a00f](247a00f57f))
2025-04-14 14:01:23 +00:00
PalmDevs
247a00f57f feat(bots/discord): delete and send sticky msg concurrently, add more logging 2025-04-14 21:00:24 +07:00
semantic-release-bot
0da3c989cd chore(release): 1.0.4 [skip ci]
## @revanced/discord-bot [1.0.4](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.3...@revanced/discord-bot@1.0.4) (2025-04-14)

### Bug Fixes

* **bots/discord:** fix sticky messages logic again ([aa7501c](aa7501c309))
* **bots/discord:** remove expired presets from db if unapplying is not possible ([9d705e5](9d705e580c))
2025-04-14 12:54:56 +00:00
PalmDevs
16d97f409c chore: format 2025-04-14 19:53:58 +07:00
PalmDevs
539025f2d4 chore(bots/discord): separate discord ready event handlers 2025-04-14 19:53:56 +07:00
PalmDevs
9d705e580c fix(bots/discord): remove expired presets from db if unapplying is not possible 2025-04-14 19:53:54 +07:00
PalmDevs
aa7501c309 fix(bots/discord): fix sticky messages logic again 2025-04-14 19:53:53 +07:00
66 changed files with 1347 additions and 644 deletions

View File

@@ -20,17 +20,12 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# Make sure the release step uses its own credentials:
# https://github.com/cycjimmy/semantic-release-action#private-packages
persist-credentials: false
fetch-depth: 0
- name: Cache dependencies
uses: actions/cache@v4
with:
path: '**/node_modules'
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: ${{ runner.os }}-bun-
- name: Setup Bun

View File

@@ -1,3 +1,12 @@
# @revanced/bot-websocket-api [1.1.0](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.2...@revanced/bot-websocket-api@1.1.0) (2025-07-11)
### Features
* **apis/websocket:** support training without label ([670cc70](https://github.com/revanced/revanced-bots/commit/670cc700570b32924738c3f24acb9f5312d2dcdb))
## @revanced/bot-websocket-api [1.0.2](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.1...@revanced/bot-websocket-api@1.0.2) (2025-06-23)
## @revanced/bot-websocket-api [1.0.1](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.0...@revanced/bot-websocket-api@1.0.1) (2025-04-09)

View File

@@ -2,7 +2,7 @@
"name": "@revanced/bot-websocket-api",
"type": "module",
"private": true,
"version": "1.0.1",
"version": "1.1.0",
"description": "🧦 WebSocket API server for bots assisting ReVanced",
"main": "dist/index.js",
"scripts": {
@@ -29,12 +29,12 @@
"dependencies": {
"@revanced/bot-shared": "workspace:*",
"@sapphire/async-queue": "^1.5.5",
"chalk": "^5.4.1",
"tesseract.js": "^5.1.1",
"ws": "^8.18.1"
"chalk": "^5.6.2",
"tesseract.js": "^6.0.1",
"ws": "^8.18.3"
},
"devDependencies": {
"@types/ws": "^8.18.1",
"typed-emitter": "^2.1.0"
}
}
}

View File

@@ -1,15 +1,14 @@
import { EventEmitter } from 'events'
import {
ClientOperation,
DisconnectReason,
type Packet,
ServerOperation,
deserializePacket,
isClientPacket,
type Packet,
ServerOperation,
serializePacket,
uncapitalize,
} from '@revanced/bot-shared'
import { EventEmitter } from 'events'
import type TypedEmitter from 'typed-emitter'
import type { RawData, WebSocket } from 'ws'
@@ -100,7 +99,7 @@ export default class Client {
// @ts-expect-error TypeScript doesn't know that the above line will negate the type enough
packet,
)
} catch (e) {
} catch (_e) {
// TODO: add error fields to sent packet so we can log what went wrong
this.disconnect(DisconnectReason.InvalidPacket)
}

View File

@@ -1,8 +1,7 @@
import { OEM, createWorker as createTesseractWorker } from 'tesseract.js'
import { join as joinPath } from 'path'
import { createLogger } from '@revanced/bot-shared'
import { exists as pathExists } from 'fs/promises'
import { join as joinPath } from 'path'
import { createWorker as createTesseractWorker, OEM } from 'tesseract.js'
import { getConfig } from './utils/config'
export const config = getConfig()
@@ -24,12 +23,12 @@ export const wit = {
if (!res.ok) throw new Error(`Failed to fetch from Wit.ai: ${res.statusText} (${res.status})`)
return await res.json()
return (await res.json()) as WitMessageResponse
},
message(text: string) {
return this.fetch(`/message?q=${encodeURIComponent(text)}&n=8`) as Promise<WitMessageResponse>
},
async train(text: string, label: string) {
async train(text: string, label?: string) {
await this.fetch('/utterances', {
body: JSON.stringify([
{
@@ -42,7 +41,14 @@ export const wit = {
method: 'POST',
})
},
} as const
} satisfies Wit
export interface Wit {
token: string
fetch(route: string, options?: RequestInit): Promise<WitMessageResponse>
message(text: string): Promise<WitMessageResponse>
train(text: string, label?: string): Promise<void>
}
export interface WitMessageResponse {
text: string

View File

@@ -1,12 +1,11 @@
import type { ClientOperation } from '@revanced/bot-shared'
import type { Logger } from '@revanced/bot-shared'
import type { ClientOperation, Logger } from '@revanced/bot-shared'
import type { Worker as TesseractWorker } from 'tesseract.js'
import type { ClientPacketObject } from '../classes/Client'
import type { WitMessageResponse } from '../context'
import type { Wit } from '../context'
import type { Config } from '../utils/config'
export { default as parseTextEventHandler } from './parseText'
export { default as parseImageEventHandler } from './parseImage'
export { default as parseTextEventHandler } from './parseText'
export { default as trainMessageEventHandler } from './trainMessage'
export type EventHandler<POp extends ClientOperation> = (
@@ -15,10 +14,7 @@ export type EventHandler<POp extends ClientOperation> = (
) => void | Promise<void>
export type EventContext = {
wit: {
train(text: string, label: string): Promise<void>
message(text: string): Promise<WitMessageResponse>
}
wit: Wit
tesseract: TesseractWorker
logger: Logger
config: Config

View File

@@ -1,6 +1,5 @@
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
import { AsyncQueue } from '@sapphire/async-queue'
import type { EventHandler } from '.'
const queue = new AsyncQueue()

View File

@@ -1,5 +1,4 @@
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
import type { EventHandler } from '.'
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (packet, { wit, logger }) => {

View File

@@ -1,5 +1,4 @@
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
import type { EventHandler } from '.'
const trainMessageEventHandler: EventHandler<ClientOperation.TrainMessage> = async (packet, { wit, logger }) => {
@@ -11,7 +10,7 @@ const trainMessageEventHandler: EventHandler<ClientOperation.TrainMessage> = asy
const nextSeq = client.currentSequence++
const actualText = text.slice(0, 279)
logger.debug(`${client.id} requested to train label ${label} (${nextSeq}) with:`, actualText)
logger.debug(`${client.id} requested to train label ${label ?? '<out of scope>'} (${nextSeq}) with:`, actualText)
try {
await wit.train(actualText, label)

View File

@@ -1,14 +1,10 @@
import { inspect as inspectObject } from 'util'
import Client from './classes/Client'
import { type EventContext, parseImageEventHandler, parseTextEventHandler, trainMessageEventHandler } from './events'
import { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
import { createServer } from 'http'
import { inspect as inspectObject } from 'util'
import { type WebSocket, WebSocketServer } from 'ws'
import Client from './classes/Client'
import { config, logger, tesseract, wit } from './context'
import { type EventContext, parseImageEventHandler, parseTextEventHandler, trainMessageEventHandler } from './events'
// Load config, init logger, check environment

View File

@@ -1,6 +1,20 @@
{
"$schema": "https://biomejs.dev/schemas/1.8.2/schema.json",
"organizeImports": {
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
"assist": {
"actions": {
"source": {
"organizeImports": {
"level": "on",
"options": {
"groups": [
{
"type": false
}
]
}
}
}
},
"enabled": true
},
"linter": {
@@ -24,7 +38,15 @@
},
"useNumberNamespace": {
"level": "off"
}
},
"noParameterAssign": "error",
"useAsConstAssertion": "error",
"useDefaultParameterLast": "error",
"useSelfClosingElements": "error",
"useSingleVarDeclarator": "error",
"noUnusedTemplateLiteral": "error",
"noInferrableTypes": "error",
"noUselessElse": "error"
}
}
},
@@ -54,7 +76,12 @@
},
"files": {
"ignoreUnknown": true,
"include": ["*.js", "*.json", "*.ts"],
"ignore": ["dist/**/*", "node_modules/**/*"]
"includes": [
"**/*.js",
"**/*.json",
"**/*.ts",
"!**/dist/**/*",
"!**/node_modules/**/*"
]
}
}

View File

@@ -1,3 +1,90 @@
## @revanced/discord-bot [1.4.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.4.0...@revanced/discord-bot@1.4.1) (2025-09-13)
### Bug Fixes
* **bots/discord/database:** use non-deprecated way to create indexes ([8cc2377](https://github.com/revanced/revanced-bots/commit/8cc2377cbfcc74c2c3228ed18da2495b4efd45aa))
* **bots/discord:** allow partial users ([dd3e7d2](https://github.com/revanced/revanced-bots/commit/dd3e7d2ee0cdf40e083af7f6db35ac3508ddf763))
* **bots/discord:** error in cache `keepOverLimit` comparison ([567c5d2](https://github.com/revanced/revanced-bots/commit/567c5d2c7f41dae7d7fec9946a7dd2ac1b10cc2a))
# @revanced/discord-bot [1.4.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.3.0...@revanced/discord-bot@1.4.0) (2025-07-11)
### Bug Fixes
* **bots/discord:** pass non-empty out of scope label to discord ([fbd9480](https://github.com/revanced/revanced-bots/commit/fbd948003631b48a1914eb7b2551ead4b05089b7))
### Features
* **bots/discord:** react to label classified response ([96a9b83](https://github.com/revanced/revanced-bots/commit/96a9b83c486fdc6e78f4c59e197fa6c1dab09161))
# @revanced/discord-bot [1.3.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.3...@revanced/discord-bot@1.3.0) (2025-07-11)
### Features
* **bots/discord:** support training without label ([c68cfd1](https://github.com/revanced/revanced-bots/commit/c68cfd1c01703fad17f233ad4e13cf81913afbb6))
## @revanced/discord-bot [1.2.3](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.2...@revanced/discord-bot@1.2.3) (2025-06-23)
### Bug Fixes
* **bots/discord:** disable unneeded cache, enable message cache sweeping ([3a0f0fe](https://github.com/revanced/revanced-bots/commit/3a0f0fe7861d73a4d81ecaba0e12bd60c06f8eb8))
## @revanced/discord-bot [1.2.2](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.1...@revanced/discord-bot@1.2.2) (2025-06-10)
### Bug Fixes
* **bots/discord:** use intervals for checking expired presets ([6e89b87](https://github.com/revanced/revanced-bots/commit/6e89b874cdfee8a1c215559271c741f43ba578ce))
## @revanced/discord-bot [1.2.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.2.0...@revanced/discord-bot@1.2.1) (2025-05-02)
### Bug Fixes
* **bots/discord:** fix timeout overflow check for role presets ([495f686](https://github.com/revanced/revanced-bots/commit/495f686292ebdcf51902c1dc75ac1510d7fdbd9c))
# @revanced/discord-bot [1.2.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.1.2...@revanced/discord-bot@1.2.0) (2025-05-02)
### Features
* **bots/discord:** switch duration parser to `@sapphire/duration` ([04ce825](https://github.com/revanced/revanced-bots/commit/04ce8252c05a23dbb4a91fded4f1a3d63b5c8a64))
## @revanced/discord-bot [1.1.2](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.1.1...@revanced/discord-bot@1.1.2) (2025-04-16)
### Bug Fixes
* **bots/discord/commands/admin/reload:** fix type error ([3908854](https://github.com/revanced/revanced-bots/commit/3908854fe090dda67b0d90225ab76f75e95db4c0))
* **bots/discord/commands/moderation:** check if timeout amount is safe in role-preset commands ([0c1382c](https://github.com/revanced/revanced-bots/commit/0c1382c55856ed1e54c9e53dbb37e9297c5da37c))
* **bots/discord:** replace use of deprecated `options.ephemeral` in replies ([31e5cf7](https://github.com/revanced/revanced-bots/commit/31e5cf7fc5c7cd0c6ca3b1f3b9410a88b95d8273))
## @revanced/discord-bot [1.1.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.1.0...@revanced/discord-bot@1.1.1) (2025-04-14)
### Bug Fixes
* **bots/discord:** fix sticky msg force timer always starting, add more logging ([cb4dc42](https://github.com/revanced/revanced-bots/commit/cb4dc42dfab8cf9821b03316cf56b405abd497ae))
# @revanced/discord-bot [1.1.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.4...@revanced/discord-bot@1.1.0) (2025-04-14)
### Features
* **bots/discord:** delete and send sticky msg concurrently, add more logging ([247a00f](https://github.com/revanced/revanced-bots/commit/247a00f57fc2a45fe828cc41e6f0e38e67e83a20))
## @revanced/discord-bot [1.0.4](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.3...@revanced/discord-bot@1.0.4) (2025-04-14)
### Bug Fixes
* **bots/discord:** fix sticky messages logic again ([aa7501c](https://github.com/revanced/revanced-bots/commit/aa7501c3097a790265e4ea624d07c4a9c3c1b908))
* **bots/discord:** remove expired presets from db if unapplying is not possible ([9d705e5](https://github.com/revanced/revanced-bots/commit/9d705e580c05d8b25df6f845d3aac747adaca116))
## @revanced/discord-bot [1.0.3](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.2...@revanced/discord-bot@1.0.3) (2025-04-09)

View File

@@ -66,7 +66,6 @@ export default {
},
},
humanCorrections: {
falsePositiveLabel: 'false_positive',
allow: {
members: {
permissions: 8n,

View File

@@ -36,7 +36,6 @@ export type Config = {
blacklist?: Filter
}
humanCorrections: {
falsePositiveLabel: string
allow?: {
users?: string[]
members?: {
@@ -72,7 +71,7 @@ export type ConfigMessageScanResponse = {
image?: Array<RegExp>
}
filterOverride?: NonNullable<Config['messageScan']>['filter']
response: ConfigMessageScanResponseMessage | null
response: ConfigMessageScanResponseMessage
respondToReply?: boolean
}

View File

@@ -2,7 +2,7 @@
"name": "@revanced/discord-bot",
"type": "module",
"private": true,
"version": "1.0.3",
"version": "1.4.1",
"description": "🤖 Discord bot assisting ReVanced",
"main": "src/index.ts",
"scripts": {
@@ -28,19 +28,19 @@
},
"homepage": "https://github.com/revanced/revanced-bots#readme",
"dependencies": {
"@discordjs/builders": "^1.10.1",
"@discordjs/rest": "^2.4.3",
"@discordjs/builders": "^1.11.3",
"@discordjs/rest": "^2.6.0",
"@revanced/bot-api": "workspace:*",
"@revanced/bot-shared": "workspace:*",
"chalk": "^5.4.1",
"decancer": "^3.2.8",
"discord.js": "^14.18.0",
"drizzle-orm": "^0.31.4",
"parse-duration": "^1.1.2"
"@sapphire/duration": "^1.2.0",
"chalk": "^5.6.2",
"decancer": "^3.3.3",
"discord.js": "^14.22.1",
"drizzle-orm": "^0.44.5"
},
"devDependencies": {
"@libsql/client": "^0.7.0",
"discord-api-types": "^0.37.119",
"drizzle-kit": "^0.22.8"
"@libsql/client": "^0.15.15",
"discord-api-types": "^0.38.24",
"drizzle-kit": "^0.31.4"
}
}

View File

@@ -1,8 +1,7 @@
import { ApplicationCommandOptionType, ApplicationCommandType } from 'discord.js'
import { config } from '../context'
import { isAdmin } from '../utils/discord/permissions'
import CommandError, { CommandErrorType } from './CommandError'
import type {
APIApplicationCommandChannelOption,
CacheType,
@@ -20,7 +19,6 @@ import type {
UserContextMenuCommandInteraction,
UserResolvable,
} from 'discord.js'
import { config } from '../context'
export enum CommandType {
ChatGlobal = 1,

View File

@@ -1,9 +1,8 @@
import { ApplicationCommandOptionType, MessageFlags } from 'discord.js'
import { unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { inspect } from 'util'
import { createContext, runInContext } from 'vm'
import { ApplicationCommandOptionType } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { parseDuration } from '$/utils/duration'
@@ -85,8 +84,8 @@ export default new AdminCommand({
})
await trigger.reply({
ephemeral: true,
embeds: [embed],
flags: MessageFlags.Ephemeral,
files,
})

View File

@@ -1,5 +1,4 @@
import { ApplicationCommandOptionType } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'

View File

@@ -1,3 +1,4 @@
import { type CommandInteraction, MessageFlags } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
export default new AdminCommand({
@@ -10,7 +11,8 @@ export default new AdminCommand({
logger.debug('Invalidating previous config...')
context.config.invalidate()
if ('deferReply' in trigger) await trigger.deferReply({ ephemeral: true })
if ((trigger as CommandInteraction).deferReply)
await (trigger as CommandInteraction).deferReply({ flags: MessageFlags.Ephemeral })
logger.info('Reinitializing API client to reload configuration...')
await api.client.ws.setOptions(

View File

@@ -1,8 +1,6 @@
import { ApplicationCommandOptionType, Routes } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { createSuccessEmbed } from '$/utils/discord/embeds'
const SubcommandOptions = {

View File

@@ -1,3 +1,4 @@
import { MessageFlags } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
export default new AdminCommand({
@@ -9,7 +10,7 @@ export default new AdminCommand({
logger.fatal('Stopping bot...')
trigger.reply({
content: 'Stopping... (I will go offline once done)',
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
if (!api.client.disconnected) api.client.disconnect()

View File

@@ -1,5 +1,4 @@
import { EmbedBuilder } from 'discord.js'
import { EmbedBuilder, MessageFlags } from 'discord.js'
import Command from '$/classes/Command'
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
@@ -18,6 +17,7 @@ export default new Command({
const reply = await trigger
.reply({
embeds: [embed.toJSON()],
flags: MessageFlags.Ephemeral,
})
.then(it => it.fetch())

View File

@@ -1,5 +1,5 @@
import { ApplicationCommandOptionType, Message, MessageFlags } from 'discord.js'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { ApplicationCommandOptionType, Message } from 'discord.js'
import { ModerationCommand } from '../../classes/Command'
export default new ModerationCommand({
@@ -40,7 +40,7 @@ export default new ModerationCommand({
await trigger.reply({
content: 'OK!',
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
},
})

View File

@@ -1,3 +1,4 @@
import { MessageFlags } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { cureNickname } from '$/utils/discord/moderation'
@@ -18,7 +19,7 @@ export default new ModerationCommand({
await cureNickname(member)
await interaction.reply({
embeds: [createSuccessEmbed(null, `Cured nickname for ${member.toString()}`)],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
},
})

View File

@@ -3,7 +3,7 @@ import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { createModerationActionEmbed } from '$/utils/discord/embeds'
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
import { parseDuration } from '$/utils/duration'
import { isSafeTimeoutDuration, parseDuration } from '$/utils/duration'
export default new ModerationCommand({
name: 'mute',
@@ -63,7 +63,7 @@ export default new ModerationCommand({
createModerationActionEmbed('Muted', user, executor.user, reason, Math.ceil(expires / 1000)),
)
if (duration)
if (isSafeTimeoutDuration(duration))
setTimeout(() => {
removeRolePreset(member, 'mute')
}, duration)

View File

@@ -1,5 +1,4 @@
import { EmbedBuilder } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'

View File

@@ -2,7 +2,7 @@ import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { sendPresetReplyAndLogs } from '$/utils/discord/moderation'
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
import { parseDuration } from '$/utils/duration'
import { isSafeTimeoutDuration, parseDuration } from '$/utils/duration'
const SubcommandOptions = {
member: {
@@ -78,7 +78,7 @@ export default new ModerationCommand({
)
}
if (expires)
if (expires && isSafeTimeoutDuration(expires))
setTimeout(() => {
removeRolePreset(member, preset)
}, expires)

View File

@@ -1,9 +1,8 @@
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { durationToString, parseDuration } from '$/utils/duration'
import { ChannelType } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { ChannelType } from 'discord.js'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { durationToString, parseDuration } from '$/utils/duration'
export default new ModerationCommand({
name: 'slowmode',

View File

@@ -1,10 +1,10 @@
import { and, eq } from 'drizzle-orm'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { appliedPresets } from '$/database/schemas'
import { createModerationActionEmbed } from '$/utils/discord/embeds'
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
import { removeRolePreset } from '$/utils/discord/rolePresets'
import { and, eq } from 'drizzle-orm'
export default new ModerationCommand({
name: 'unmute',

View File

@@ -1,15 +1,15 @@
import { type FetchMessageOptions, MessageFlags, type MessageResolvable } from 'discord.js'
import Command from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import type { ConfigMessageScanResponseLabelConfig } from 'config.schema'
import type { FetchMessageOptions, MessageResolvable } from 'discord.js'
import { config } from '../../../context'
import type { ConfigMessageScanResponseLabelConfig } from 'config.schema'
const msRcConfig = config.messageScan?.humanCorrections?.allow
export default new Command({
name: 'train',
description: 'Train a specific message or text to a specific label',
description: 'Train a specific message to a specific label',
type: Command.Type.ChatGuild,
requirements: {
users: msRcConfig?.users,
@@ -26,9 +26,9 @@ export default new Command({
required: true,
},
label: {
description: 'The label to train the message as',
description: 'The label to train the message as (leave empty for out of scope)',
type: Command.OptionType.String,
required: true,
required: false,
},
},
allowMessageCommand: true,
@@ -49,7 +49,7 @@ export default new Command({
'This command can only be used in or on text channels',
)
if (!labels.includes(label))
if (label && !labels.includes(label))
throw new CommandError(
CommandErrorType.InvalidArgument,
`The provided label is invalid.\nValid labels are:${labels.map(l => `\n- \`${l}\``).join('')}`,
@@ -60,17 +60,17 @@ export default new Command({
)
if (!refMsg) throw new CommandError(CommandErrorType.InvalidArgument, 'The provided message does not exist.')
logger.debug(`User ${context.executor.id} is training message ${refMsg?.id} as ${label}`)
logger.debug(`User ${context.executor.id} is training message ${refMsg?.id} as ${label ?? 'out of scope'}`)
await context.api.client.trainMessage(refMsg.content, label)
await trigger.reply({
embeds: [
createSuccessEmbed(
'Message trained',
`The provided message has been trained as \`${label}\`. Thank you for your contribution!`,
`The provided message has been trained as ${label ? `\`${label}\`` : 'out of scope'}. Thank you for your contribution!`,
),
],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
},
})

View File

@@ -1,8 +1,8 @@
import { type APIStringSelectComponent, ComponentType, MessageFlags } from 'discord.js'
import Command from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import type { ConfigMessageScanResponseLabelConfig } from 'config.schema'
import { type APIStringSelectComponent, ComponentType } from 'discord.js'
import { config } from '../../../context'
import type { ConfigMessageScanResponseLabelConfig } from 'config.schema'
const msRcConfig = config.messageScan?.humanCorrections?.allow
@@ -37,14 +37,19 @@ export default new Command({
components: [
{
custom_id: `tr_${trigger.targetMessage.channelId}_${trigger.targetId}`,
options: labels.map(label => ({ label, value: label })),
options: [
...labels.map(label => ({ label, value: label })),
{ label: 'Out of scope', value: OutOfScopeLabel, emoji: { name: '❌' } },
],
type: ComponentType.StringSelect,
} satisfies APIStringSelectComponent,
],
type: ComponentType.ActionRow,
},
],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
},
})
export const OutOfScopeLabel = '<out of scope>'

View File

@@ -1,16 +1,13 @@
import { Database } from 'bun:sqlite'
import { existsSync, readFileSync, readdirSync } from 'fs'
import { join } from 'path'
import { Client as APIClient } from '@revanced/bot-api'
import { createLogger } from '@revanced/bot-shared'
import { Client as DiscordClient, type Message, Partials } from 'discord.js'
import { Client as DiscordClient, type Message, Options, Partials } from 'discord.js'
import { drizzle } from 'drizzle-orm/bun-sqlite'
import * as schemas from './database/schemas'
import type { default as Command, CommandOptionsOptions, CommandType } from './classes/Command'
import { existsSync, readdirSync, readFileSync } from 'fs'
import { join } from 'path'
import { __getConfig, config } from './config'
import * as schemas from './database/schemas'
import type { default as Command, CommandOptionsOptions, CommandType } from './classes/Command'
export { config, __getConfig }
export const logger = createLogger({
@@ -80,7 +77,52 @@ export const discord = {
parse: ['users'],
repliedUser: true,
},
partials: [Partials.Message, Partials.Reaction, Partials.GuildMember],
sweepers: {
...Options.DefaultSweeperSettings,
messages: {
interval: 1_800, // Every 30m
lifetime: 3_600, // Remove messages older than 1h
},
},
makeCache: Options.cacheWithLimits({
...Options.DefaultMakeCacheSettings,
UserManager: 50,
GuildMemberManager: {
maxSize: 50,
// Always keep client guild member in cache
keepOverLimit: member => member.id === member.client.user.id,
},
ThreadManager: {
maxSize: 0,
// Always keep threads that are used for moderation logging
keepOverLimit: thread => config.moderation?.log?.thread === thread.id,
},
GuildMessageManager: {
maxSize: 0,
// Always keep messages posted by the client in cache
keepOverLimit: message => message.author?.id === message.client.user.id,
},
// Unneeded cache
MessageManager: 0,
ReactionManager: 0,
VoiceStateManager: 0,
ThreadMemberManager: 0,
StageInstanceManager: 0,
ReactionUserManager: 0,
PresenceManager: 0,
GuildTextThreadManager: 0,
GuildStickerManager: 0,
DMMessageManager: 0,
GuildEmojiManager: 0,
GuildBanManager: 0,
GuildScheduledEventManager: 0,
EntitlementManager: 0,
AutoModerationRuleManager: 0,
GuildForumThreadManager: 0,
BaseGuildEmojiManager: 0,
GuildInviteManager: 0,
}),
partials: [Partials.Message, Partials.Reaction, Partials.GuildMember, Partials.User],
}),
commands: Object.fromEntries(Object.values(commands).map(cmd => [cmd.name, cmd])) as Record<
string,
@@ -101,7 +143,7 @@ export const discord = {
timerActive: boolean
timerMs: number
forceTimerMs?: number
send: (forced?: boolean) => Promise<void>
send: () => Promise<void>
currentMessage?: Message<true>
timer?: NodeJS.Timeout
forceTimer?: NodeJS.Timeout

View File

@@ -1,5 +1,5 @@
import type { InferSelectModel } from 'drizzle-orm'
import { integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'
import type { InferSelectModel } from 'drizzle-orm'
export const responses = sqliteTable('responses', {
replyId: text('reply').primaryKey().notNull(),
@@ -20,9 +20,7 @@ export const appliedPresets = sqliteTable(
preset: text('preset').notNull(),
until: integer('until'),
},
table => ({
uniqueComposite: uniqueIndex('unique_composite').on(table.memberId, table.preset, table.guildId),
}),
table => [uniqueIndex('unique_composite').on(table.memberId, table.preset, table.guildId)],
)
export type Response = InferSelectModel<typeof responses>

View File

@@ -1,5 +1,5 @@
import { on, withContext } from '$utils/api/events'
import { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
import { on, withContext } from '$utils/api/events'
withContext(on, 'disconnect', ({ api, config, logger }, reason, msg) => {
if (reason === DisconnectReason.PlannedDisconnect && api.intentionallyDisconnecting) return

View File

@@ -1,7 +1,7 @@
import { and, eq, gt } from 'drizzle-orm'
import { appliedPresets } from '$/database/schemas'
import { on, withContext } from '$/utils/discord/events'
import { applyRolesUsingPreset } from '$/utils/discord/rolePresets'
import { and, eq, gt } from 'drizzle-orm'
withContext(on, 'guildMemberAdd', async ({ database }, member) => {
const applieds = await database.query.appliedPresets.findMany({

View File

@@ -1,3 +1,4 @@
import { MessageFlags } from 'discord.js'
import CommandError from '$/classes/CommandError'
import { createStackTraceEmbed } from '$utils/discord/embeds'
import { on, withContext } from '$utils/discord/events'
@@ -20,7 +21,7 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
await interaction[interaction.replied ? 'followUp' : 'reply']({
embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
// 100 and up are user errors

View File

@@ -1,3 +1,4 @@
import { MessageFlags } from 'discord.js'
import CommandError from '$/classes/CommandError'
import { createStackTraceEmbed } from '$utils/discord/embeds'
import { on, withContext } from '$utils/discord/events'
@@ -20,7 +21,7 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
logger.error(`Error while executing command ${interaction.commandName}:`, err)
await interaction[interaction.replied ? 'followUp' : 'reply']({
embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
}
})

View File

@@ -1,11 +1,15 @@
import {
type ButtonInteraction,
MessageFlags,
type StringSelectMenuInteraction,
type TextBasedChannel,
} from 'discord.js'
import { eq } from 'drizzle-orm'
import { responses } from '$/database/schemas'
import { handleUserResponseCorrection } from '$/utils/discord/messageScan'
import { createErrorEmbed, createStackTraceEmbed, createSuccessEmbed } from '$utils/discord/embeds'
import { on, withContext } from '$utils/discord/events'
import type { ButtonInteraction, StringSelectMenuInteraction, TextBasedChannel } from 'discord.js'
import { eq } from 'drizzle-orm'
// No permission check required as it is already done when the user reacts to a bot response
withContext(on, 'interactionCreate', async (context, interaction) => {
const {
@@ -26,7 +30,7 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
if (!response)
return void (await interaction.reply({
content: "I don't recall having sent this response, so I cannot correct it.",
ephemeral: true,
flags: MessageFlags.Ephemeral,
}))
try {
@@ -54,8 +58,8 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
const editMessage = (content: string, description?: string) =>
editInteractionMessage(interaction, msg.url, content, description)
const handleCorrection = (label: string) =>
handleUserResponseCorrection(context, response, msg, label, interaction.user)
const handleCorrection = (label?: string) =>
handleUserResponseCorrection(context, response, msg, interaction.user, label)
if (response.correctedById)
return await editMessage(
@@ -78,7 +82,7 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
await editMessage('Canceled', 'You canceled this interaction. 😞')
break
case 'delete':
await handleCorrection(msConfig.humanCorrections.falsePositiveLabel)
await handleCorrection()
await editMessage(
'Marked as false positive',
'The response has been deleted and marked as a false positive. Thank you for your feedback. 🎉',
@@ -91,7 +95,7 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
logger.error('Failed to handle correct response interaction:', e)
await interaction.reply({
embeds: [createStackTraceEmbed(e)],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
}
})

View File

@@ -1,8 +1,8 @@
import { MessageFlags, type TextBasedChannel } from 'discord.js'
import { OutOfScopeLabel } from '$/commands/support/train/context-menu'
import { createErrorEmbed, createStackTraceEmbed, createSuccessEmbed } from '$utils/discord/embeds'
import { on, withContext } from '$utils/discord/events'
import type { TextBasedChannel } from 'discord.js'
withContext(on, 'interactionCreate', async (context, interaction) => {
const {
logger,
@@ -28,11 +28,14 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
'Thank you for your contribution! Unfortunately, the message could not be found.',
),
],
ephemeral: true,
flags: MessageFlags.Ephemeral,
}))
const selectedLabel = interaction.values[0]!
await context.api.client.trainMessage(msg.content, selectedLabel)
const selectedLabel = interaction.values[0]
await context.api.client.trainMessage(
msg.content,
selectedLabel === OutOfScopeLabel ? undefined : selectedLabel,
)
await interaction.reply({
embeds: [
createSuccessEmbed(
@@ -40,13 +43,13 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
`Thank you for your contribution! The selected message is being trained as \`${selectedLabel}\`. 🎉`,
),
],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
} catch (e) {
logger.error('Failed to handle train message interaction:', e)
await interaction.reply({
embeds: [createStackTraceEmbed(e)],
ephemeral: true,
flags: MessageFlags.Ephemeral,
})
}
})

View File

@@ -1,3 +1,4 @@
import { MessageScanLabeledResponseReactions } from '$/constants'
import { responses } from '$/database/schemas'
import { getResponseFromText, messageMatchesFilter } from '$/utils/discord/messageScan'
import { createMessageScanResponseEmbed } from '$utils/discord/embeds'
@@ -47,6 +48,8 @@ withContext(on, 'messageCreate', async (context, msg) => {
label,
content: msg.content,
})
await Promise.all(Object.values(MessageScanLabeledResponseReactions).map(name => reply.react(name)))
}
}
} catch (e) {

View File

@@ -7,29 +7,22 @@ withContext(on, 'messageCreate', async ({ discord, logger }, msg) => {
const store = discord.stickyMessages[msg.guildId]?.[msg.channelId]
if (!store) return
if (store.timerActive) {
// Timer is already active, so we try to start the force timer
if (store.forceTimerMs && !store.forceTimerActive) {
// Force timer isn't active, so we start it
logger.debug(
`Channel ${msg.channelId} in guild ${msg.guildId} is active, starting force send timer and clearing existing timer`,
)
// Timer is already active from previous event, and force timer isn't active, so we start the latter
if (store.timerActive && store.forceTimerMs && !store.forceTimerActive) {
logger.debug(
`Channel ${msg.channelId} in guild ${msg.guildId} is very active, starting sticky message force timer`,
)
// Clear the timer
clearTimeout(store.timer)
store.timerActive = false
// Start the force timer
store.forceTimerActive = true
// biome-ignore lint/suspicious/noAssignInExpressions: This works fine
;(store.forceTimer ??= setTimeout(store.send, store.forceTimerMs)).refresh()
}
} else if (store.forceTimerActive) {
// Force timer is already active, so force send the message, and clear the force timer
store.send(true)
} else {
// Both timers aren't active, so we start the timer
store.timerActive = true
if (!store.timer) store.timer = setTimeout(store.send, store.timerMs) as NodeJS.Timeout
// (Re)start the force timer
store.forceTimerActive = true
if (store.forceTimer) store.forceTimer.refresh()
else store.forceTimer = setTimeout(store.send, store.forceTimerMs)
}
logger.debug(`Channel ${msg.channelId} in guild ${msg.guildId} is active, starting sticky message timer`)
// (Re)start the timer
store.timerActive = true
if (store.timer) store.timer.refresh()
else store.timer = setTimeout(store.send, store.timerMs) as NodeJS.Timeout
})

View File

@@ -1,7 +1,3 @@
import { MessageScanLabeledResponseReactions as Reactions } from '$/constants'
import { createErrorEmbed, createStackTraceEmbed, createSuccessEmbed } from '$/utils/discord/embeds'
import { on, withContext } from '$/utils/discord/events'
import {
ActionRowBuilder,
ButtonBuilder,
@@ -9,12 +5,14 @@ import {
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder,
} from 'discord.js'
import type { ConfigMessageScanResponseLabelConfig } from '$/../config.schema'
import { eq } from 'drizzle-orm'
import { MessageScanLabeledResponseReactions as Reactions } from '$/constants'
import { responses } from '$/database/schemas'
import { createErrorEmbed, createStackTraceEmbed, createSuccessEmbed } from '$/utils/discord/embeds'
import { on, withContext } from '$/utils/discord/events'
import { handleUserResponseCorrection } from '$/utils/discord/messageScan'
import { isAdmin } from '$/utils/discord/permissions'
import { eq } from 'drizzle-orm'
import type { ConfigMessageScanResponseLabelConfig } from '$/../config.schema'
const PossibleReactions = Object.values(Reactions) as string[]
@@ -65,8 +63,8 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
logger.debug(`User ${user.id} is trying to correct the response ${rct.message.id}`)
const handleCorrection = (label: string) =>
handleUserResponseCorrection(context, response, reactionMessage, label, user)
const handleCorrection = (label?: string) =>
handleUserResponseCorrection(context, response, reactionMessage, user, label)
try {
if (reaction.emoji.name === Reactions.train) {
@@ -108,7 +106,7 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
.setCustomId(`${componentPrefix}_cancel`),
new ButtonBuilder()
.setEmoji(Reactions.delete)
.setLabel('Delete (mark as false positive)')
.setLabel('Delete (mark as out of scope)')
.setStyle(ButtonStyle.Danger)
.setCustomId(`${componentPrefix}_delete`),
),
@@ -119,8 +117,8 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
components: rows,
})
} else if (reaction.emoji.name === Reactions.delete) {
await handleCorrection(msConfig.humanCorrections.falsePositiveLabel)
await user.send({ content: 'The response has been deleted and marked as a false positive.' })
await handleCorrection()
await user.send({ content: 'The response has been deleted and marked as out of scope.' })
}
} catch (e) {
logger.error('Failed to correct response:', e)

View File

@@ -1,107 +0,0 @@
import { database, logger } from '$/context'
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 { and, eq, lt } from 'drizzle-orm'
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(`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)
// In case of configuration refresh, this will not be nullable
const oldStore = discord.stickyMessages[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 void logger.warn(
`Channel ${channelId} in guild ${guildId} is not a text channel, sticky messages will not be sent`,
)
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
// Clear any remaining timers
clearTimeout(store.timer)
clearTimeout(store.forceTimer)
store.forceTimerActive = store.timerActive = false
if (!forced)
logger.debug(
`Timer ended for sticky message in channel ${channelId} in guild ${guildId}, channel is inactive`,
)
else
logger.debug(
`Force timer for sticky message in channel ${channelId} in guild ${guildId} hasn't ended but a message was sent, 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,
)
}
}
// Set up the store
discord.stickyMessages[guildId]![channelId] = {
forceTimerActive: false,
timerActive: false,
forceTimerMs: forceSendTimeout,
timerMs: timeout,
send,
// If the store exists before the configuration refresh, take its current message
currentMessage: oldStore?.[channelId]?.currentMessage,
}
// Send a new sticky message immediately, as well as deleting the old/outdated message, if it exists
await send()
}
}
if (config.rolePresets) {
removeExpiredPresets(client)
setTimeout(() => removeExpiredPresets(client), config.rolePresets.checkExpiredEvery)
}
})
const removeExpiredPresets = async (client: Client) => {
logger.debug('Checking for expired role presets...')
const expireds = await database.query.appliedPresets.findMany({
where: lt(appliedPresets.until, Math.floor(Date.now() / 1000)),
})
for (const expired of expireds)
try {
logger.debug(`Removing role preset for ${expired.memberId} in ${expired.guildId}`)
const guild = await client.guilds.fetch(expired.guildId)
const member = await guild.members.fetch(expired.memberId)
await removeRolePreset(member, expired.preset)
await database
.delete(appliedPresets)
.where(and(eq(appliedPresets.guildId, expired.guildId), eq(appliedPresets.memberId, expired.memberId)))
} catch (e) {
logger.error(`Error while removing role preset for ${expired.memberId} in ${expired.guildId}: ${e}`)
}
}

View File

@@ -0,0 +1,6 @@
import { on, withContext } from '$/utils/discord/events'
export default withContext(on, 'ready', async ({ logger }, client) => {
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`)
})

View File

@@ -0,0 +1,42 @@
import { type Client, DiscordAPIError } from 'discord.js'
import { and, eq, lt } from 'drizzle-orm'
import { database, logger } from '$/context'
import { appliedPresets } from '$/database/schemas'
import { on, withContext } from '$/utils/discord/events'
import { removeRolePreset } from '$/utils/discord/rolePresets'
export default withContext(on, 'ready', async ({ config }, client) => {
if (config.rolePresets) {
removeExpiredPresets(client)
setInterval(() => removeExpiredPresets(client), config.rolePresets.checkExpiredEvery)
}
})
async function removeExpiredPresets(client: Client) {
logger.debug('Checking for expired role presets...')
const expireds = await database.query.appliedPresets.findMany({
where: lt(appliedPresets.until, Math.floor(Date.now() / 1000)),
})
for (const expired of expireds) {
try {
logger.debug(`Removing role preset for ${expired.memberId} in ${expired.guildId}`)
const guild = await client.guilds.fetch(expired.guildId)
const member = await guild.members.fetch(expired.memberId)
await removeRolePreset(member, expired.preset)
} catch (e) {
// Unknown Member: https://discord.com/developers/docs/topics/opcodes-and-status-codes#json
if (!(e instanceof DiscordAPIError) || e.code !== 10007) {
logger.error(`Error while removing role preset for ${expired.memberId} in ${expired.guildId}: ${e}`)
continue
}
}
await database
.delete(appliedPresets)
.where(and(eq(appliedPresets.guildId, expired.guildId), eq(appliedPresets.memberId, expired.memberId)))
}
}

View File

@@ -0,0 +1,68 @@
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
import { on, withContext } from '$/utils/discord/events'
export default withContext(on, 'ready', async ({ config, discord, logger }, client) => {
if (config.stickyMessages)
for (const [guildId, channels] of Object.entries(config.stickyMessages)) {
const guild = await client.guilds.fetch(guildId)
// In case of configuration refresh, this will not be nullable
const oldStore = discord.stickyMessages[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 void logger.warn(
`Channel ${channelId} in guild ${guildId} is not a text channel, sticky messages will not be sent`,
)
// Set up the store
// biome-ignore lint/suspicious/noAssignInExpressions: don't care
const store = (discord.stickyMessages[guildId]![channelId] = {
forceTimerActive: false,
timerActive: false,
forceTimerMs: forceSendTimeout,
timerMs: timeout,
async send() {
try {
await Promise.all([
channel
.send({
...message,
embeds: message.embeds?.map(it => applyCommonEmbedStyles(it, true, true, true)),
})
.then(msg => {
this.currentMessage = msg
logger.debug(`Sent sticky message to channel ${channelId} in guild ${guildId}`)
}),
this.currentMessage
?.delete()
?.then(() =>
logger.debug(
`Deleted old sticky message from channel ${channelId} in guild ${guildId}`,
),
),
])
} catch (e) {
logger.error(
`Error while managing sticky message of channel ${channelId} in guild ${guildId}:`,
e,
)
} finally {
// Clear any remaining timers
clearTimeout(this.timer)
clearTimeout(this.forceTimer)
this.forceTimerActive = this.timerActive = false
logger.debug(`Cleared sticky message timer for channel ${channelId} in guild ${guildId}`)
}
},
// If the store exists before the configuration refresh, take its current message
currentMessage: oldStore?.[channelId]?.currentMessage,
})
// Send a new sticky message immediately, as well as deleting the old/outdated message, if it exists
await store.send()
}
}
})

View File

@@ -1,5 +1,5 @@
import { api, discord, logger } from '$/context'
import { getMissingEnvironmentVariables } from '@revanced/bot-shared'
import { api, discord, logger } from '$/context'
import './events/register'

View File

@@ -1,5 +1,5 @@
import type { ClientWebSocketEvents } from '@revanced/bot-api'
import * as context from '../../context'
import type { ClientWebSocketEvents } from '@revanced/bot-api'
const { client } = context.api

View File

@@ -1,5 +1,5 @@
import { DefaultEmbedColor, ReVancedLogoURL } from '$/constants'
import { type APIEmbed, EmbedBuilder, type EmbedField, type JSONEncodable, type User } from 'discord.js'
import { DefaultEmbedColor, ReVancedLogoURL } from '$/constants'
import type { ConfigMessageScanResponseMessage } from '../../../config.schema'
export const createErrorEmbed = (title: string | null, description?: string) =>

View File

@@ -1,9 +1,9 @@
import { type Response, responses } from '$/database/schemas'
import type { Config, ConfigMessageScanResponse, ConfigMessageScanResponseLabelConfig } from 'config.schema'
import { ButtonStyle, ComponentType } from 'discord.js'
import type { APIActionRowComponent, APIButtonComponent, Message, PartialUser, User } from 'discord.js'
import { eq } from 'drizzle-orm'
import { type Response, responses } from '$/database/schemas'
import { createMessageScanResponseEmbed } from './embeds'
import type { Config, ConfigMessageScanResponse, ConfigMessageScanResponseLabelConfig } from 'config.schema'
import type { APIActionRowComponent, APIButtonComponent, Message, PartialUser, User } from 'discord.js'
export const getResponseFromText = async (
content: string,
@@ -17,7 +17,7 @@ export const getResponseFromText = async (
type ResponseConfig = Awaited<ReturnType<typeof getResponseFromText>>
let responseConfig: Omit<ResponseConfig, 'triggers'> & { triggers?: ResponseConfig['triggers'] } = {
triggers: undefined,
response: null,
response: null!,
}
const firstLabelIndexes: number[] = []
@@ -143,15 +143,22 @@ export const handleUserResponseCorrection = async (
{ api, database: db, config: { messageScan: msConfig }, logger }: typeof import('$/context'),
response: Response,
reply: Message,
label: string,
user: User | PartialUser,
label?: string,
) => {
if (!label) {
await Promise.all([reply.delete(), api.client.trainMessage(response.content, label)]).finally(() =>
logger.debug(`User ${user.id} trained message ${response.replyId} as out of scope`),
)
return
}
const correctLabelResponse = msConfig!.responses!.find(r =>
r.triggers.text!.some(t => 'label' in t && t.label === label),
)
if (!correctLabelResponse) throw new Error('Cannot find label config for the selected label')
if (!correctLabelResponse.response) return void (await reply.delete())
if (response.label !== label) {
db.update(responses)
@@ -168,12 +175,12 @@ export const handleUserResponseCorrection = async (
}))
}
await api.client.trainMessage(response.content, label)
logger.debug(`User ${user.id} trained message ${response.replyId} as ${label} (positive)`)
await reply.edit({
components: [],
})
await Promise.all([
api.client.trainMessage(response.content, label),
reply.edit({
components: [],
}),
]).finally(() => logger.debug(`User ${user.id} trained message ${response.replyId} as ${label}`))
}
export const createMessageScanResponseComponents = (reply: Message<true>) => [

View File

@@ -1,7 +1,7 @@
import { config, logger } from '$/context'
import decancer from 'decancer'
import type { CommandInteraction, EmbedBuilder, Guild, GuildMember, Message, User } from 'discord.js'
import { config, logger } from '$/context'
import { applyReferenceToModerationActionEmbed, createModerationActionEmbed } from './embeds'
import type { CommandInteraction, EmbedBuilder, Guild, GuildMember, Message, User } from 'discord.js'
const PresetLogAction = {
apply: 'Applied role preset to',

View File

@@ -1,7 +1,7 @@
import { and, eq } from 'drizzle-orm'
import { config, database } from '$/context'
import { appliedPresets } from '$/database/schemas'
import type { GuildMember } from 'discord.js'
import { and, eq } from 'drizzle-orm'
// TODO: Fix this type
type PresetKey = string

View File

@@ -1,25 +1,44 @@
import parse from 'parse-duration'
import { Duration, DurationFormatter } from '@sapphire/duration'
parse[''] = parse['s']!
parse['mo'] = parse['M'] = parse['month']!
const fmt = new DurationFormatter({
year: {
DEFAULT: 'y',
},
month: {
DEFAULT: 'M',
},
week: {
DEFAULT: 'w',
},
day: {
DEFAULT: 'd',
},
hour: {
DEFAULT: 'h',
},
minute: {
DEFAULT: 'm',
},
second: {
DEFAULT: 's',
},
})
export const parseDuration = (duration: string, defaultUnit?: parse.Units) => {
const defaultUnitValue = parse['']!
if (defaultUnit) parse[''] = parse[defaultUnit]!
const result = parse(duration, 'ms') ?? Number.NaN
parse[''] = defaultUnitValue
return result
export const parseDuration = (duration: string, defaultUnit = 's') => {
// adds default unit to the end of the string if it doesn't have a unit
// 100 -> 100s
// 10m100 -> 10m100s
// biome-ignore lint/style/noParameterAssign: this is fine
if (/\d$/.test(duration)) duration += defaultUnit
return new Duration(duration).offset
}
export const durationToString = (duration: number) => {
if (duration === 0) return '0s'
const days = Math.floor(duration / (24 * 60 * 60 * 1000))
const hours = Math.floor((duration % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
const minutes = Math.floor((duration % (60 * 60 * 1000)) / (60 * 1000))
const seconds = Math.floor((duration % (60 * 1000)) / 1000)
return `${days ? `${days}d` : ''}${hours ? `${hours}h` : ''}${minutes ? `${minutes}m` : ''}${
seconds ? `${seconds}s` : ''
}`
return fmt.format(duration, undefined, {
left: '',
})
}
export function isSafeTimeoutDuration(duration: number) {
return duration > 0 && duration < 2 ** 31 - 1
}

1049
bun.lock

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,11 @@
"license": "GPL-3.0-or-later",
"type": "module",
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
"workspaces": ["packages/*", "apis/*", "bots/*"],
"workspaces": [
"packages/*",
"apis/*",
"bots/*"
],
"scripts": {
"build:all": "turbo run build",
"build:packages": "turbo build --filter=\"./packages/*\"",
@@ -27,25 +31,25 @@
"Palm <contact@palmdevs.me> (https://palmdevs.me)",
"ReVanced <nosupport@revanced.app> (https://revanced.app)"
],
"packageManager": "bun@1.1.20",
"packageManager": "bun@1.2.17",
"devDependencies": {
"@anolilab/multi-semantic-release": "^1.1.10",
"@biomejs/biome": "^1.9.4",
"@codedependant/semantic-release-docker": "^5.1.0",
"@commitlint/cli": "^19.8.0",
"@commitlint/config-conventional": "^19.8.0",
"@anolilab/multi-semantic-release": "^2.0.3",
"@biomejs/biome": "^2.2.4",
"@codedependant/semantic-release-docker": "^5.1.1",
"@commitlint/cli": "^19.8.1",
"@commitlint/config-conventional": "^19.8.1",
"@saithodev/semantic-release-backmerge": "^4.0.1",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/exec": "^6.0.3",
"@semantic-release/exec": "^7.1.0",
"@semantic-release/git": "^10.0.1",
"@tsconfig/strictest": "^2.0.5",
"@types/bun": "^1.2.8",
"conventional-changelog-conventionalcommits": "^7.0.2",
"lefthook": "^1.11.6",
"@types/bun": "^1.2.21",
"conventional-changelog-conventionalcommits": "^9.1.0",
"lefthook": "^1.13.0",
"portainer-service-webhook": "https://github.com/newarifrh/portainer-service-webhook#v1",
"semantic-release": "^24.2.3",
"turbo": "^2.5.0",
"typescript": "^5.8.2"
"semantic-release": "^24.2.8",
"turbo": "^2.5.6",
"typescript": "^5.9.2"
},
"trustedDependencies": [
"@biomejs/biome",
@@ -54,8 +58,6 @@
"lefthook"
],
"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.4": "patches/decancer@3.2.4.patch"
"@semantic-release/npm@12.0.2": "patches/@semantic-release%2Fnpm@12.0.2.patch"
}
}

View File

@@ -28,7 +28,7 @@
"homepage": "https://github.com/revanced/revanced-bots#readme",
"dependencies": {
"@revanced/bot-shared": "workspace:*",
"ws": "^8.18.1"
"ws": "^8.18.3"
},
"devDependencies": {
"@types/ws": "^8.18.1",

View File

@@ -101,7 +101,7 @@ export default class Client {
return packet
}
async trainMessage(text: string, label: string) {
async trainMessage(text: string, label?: string) {
this.#throwIfNotReady()
this.ws.send({

View File

@@ -1,16 +1,16 @@
import { EventEmitter } from 'events'
import {
type ClientOperation,
DisconnectReason,
type Packet,
ServerOperation,
deserializePacket,
isServerPacket,
type Packet,
ServerOperation,
serializePacket,
uncapitalize,
} from '@revanced/bot-shared'
import type TypedEmitter from 'typed-emitter'
import { EventEmitter } from 'events'
import { type RawData, WebSocket } from 'ws'
import type TypedEmitter from 'typed-emitter'
/**
* The class that handles the WebSocket connection to the server.

View File

@@ -1,3 +1,3 @@
export { default as Client } from './Client'
export * from './Client'
export { default as Client } from './Client'
export * from './ClientWebSocket'

View File

@@ -30,9 +30,9 @@
},
"homepage": "https://github.com/revanced/revanced-bots#readme",
"dependencies": {
"bson": "^6.10.3",
"chalk": "^5.4.1",
"bson": "^6.10.4",
"chalk": "^5.6.2",
"tracer": "^1.3.0",
"valibot": "^0.30.0"
"valibot": "^1.1.0"
}
}

View File

@@ -1,18 +1,16 @@
import {
url,
type AnySchema,
type BooleanSchema,
type NullSchema,
type ObjectSchema,
type Output,
array,
boolean,
custom,
enum_,
type InferOutput,
null_,
object,
optional,
parse,
special,
pipe,
string,
url,
// merge
} from 'valibot'
import DisconnectReason from '../constants/DisconnectReason'
@@ -21,7 +19,7 @@ import { ClientOperation, Operation, ServerOperation } from '../constants/Operat
/**
* Schema to validate packets
*/
export const PacketSchema = special<Packet>(input => {
export const PacketSchema = custom<Packet>(input => {
if (
typeof input === 'object' &&
input &&
@@ -51,7 +49,7 @@ export const PacketDataSchemas = {
labels: array(
object({
name: string(),
confidence: special<number>(input => typeof input === 'number' && input >= 0 && input <= 1),
confidence: custom<number>(input => typeof input === 'number' && input >= 0 && input <= 1),
}),
),
}),
@@ -70,17 +68,13 @@ export const PacketDataSchemas = {
text: string(),
}),
[ClientOperation.ParseImage]: object({
image_url: string([url()]),
image_url: pipe(string(), url()),
}),
[ClientOperation.TrainMessage]: object({
text: string(),
label: string(),
label: optional(string()),
}),
} as const satisfies Record<
Operation,
// biome-ignore lint/suspicious/noExplicitAny: This is a schema, it's not possible to type it
ObjectSchema<any> | AnySchema | NullSchema | BooleanSchema
>
} as const
export type Packet<TOp extends Operation = Operation> = TOp extends ServerOperation
? PacketWithSequenceNumber<TOp>
@@ -88,6 +82,6 @@ export type Packet<TOp extends Operation = Operation> = TOp extends ServerOperat
type PacketWithSequenceNumber<TOp extends Operation> = {
op: TOp
d: Output<(typeof PacketDataSchemas)[TOp]>
d: InferOutput<(typeof PacketDataSchemas)[TOp]>
s: number
}

View File

@@ -1,5 +1,5 @@
import { Chalk, supportsColor, supportsColorStderr } from 'chalk'
import { type Tracer, colorConsole, console as uncoloredConsole } from 'tracer'
import { colorConsole, type Tracer, console as uncoloredConsole } from 'tracer'
const chalk = new Chalk()
const DefaultConfig = {

View File

@@ -1,7 +1,7 @@
import * as BSON from 'bson'
import { parse } from 'valibot'
import type { Operation } from '../constants'
import { type Packet, PacketSchema } from '../schemas'
import type { Operation } from '../constants'
/**
* Compresses a packet into a buffer

View File

@@ -1,12 +1,3 @@
diff --git a/node_modules/@semantic-release/npm/.bun-tag-3853154e196b7721 b/.bun-tag-3853154e196b7721
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/@semantic-release/npm/.bun-tag-550461f23a8ec245 b/.bun-tag-550461f23a8ec245
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/node_modules/@semantic-release/npm/.bun-tag-c9c8130945517add b/.bun-tag-c9c8130945517add
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/lib/prepare.js b/lib/prepare.js
index 3e76bec44cf595a1b4141728336bed904d4d518d..4b25ca64879bbee2a600f2b23b738c86136ad9c6 100644
--- a/lib/prepare.js

View File

@@ -1,13 +0,0 @@
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}`)
}

View File

@@ -1,21 +0,0 @@
diff --git a/bin.cjs b/bin.cjs
index 142ed9c20f28dc1080bebfb52325fa308c6cb771..9d3bea0787f6c05df11567c6821bc85743286340 100644
--- a/bin.cjs
+++ b/bin.cjs
@@ -22053,7 +22053,7 @@ var init_sqliteImports = __esm({
const { unregister } = await safeRegister();
for (let i2 = 0; i2 < imports.length; i2++) {
const it = imports[i2];
- const i0 = require(`${it}`);
+ const i0 = await import(`${it}`);
const prepared = prepareFromExports3(i0);
tables.push(...prepared.tables);
}
@@ -129572,6 +129572,7 @@ var generateCommand = new Command("generate").option("--dialect <dialect>", "Dat
} else {
assertUnreachable(dialect7);
}
+ process.exit(0);
});
var migrateCommand = new Command("migrate").option(
"--config <config>",