mirror of
https://github.com/ReVanced/revanced-bots.git
synced 2026-01-12 06:06:21 +00:00
Compare commits
204 Commits
@revanced/
...
@revanced/
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6885e18976 | ||
|
|
42038e6b38 | ||
|
|
51c0252b44 | ||
|
|
399c201f8c | ||
|
|
0a5a9c3e27 | ||
|
|
50a205c430 | ||
|
|
dd3e7d2ee0 | ||
|
|
567c5d2c7f | ||
|
|
8cc2377cbf | ||
|
|
f3c199d573 | ||
|
|
42c0facef1 | ||
|
|
96a9b83c48 | ||
|
|
fbd9480036 | ||
|
|
cc02c0a775 | ||
|
|
c83e219088 | ||
|
|
6164e6c1a5 | ||
|
|
47d2f8c015 | ||
|
|
c68cfd1c01 | ||
|
|
2b1928e116 | ||
|
|
670cc70057 | ||
|
|
439f301872 | ||
|
|
aeccf12906 | ||
|
|
b4ac8433f4 | ||
|
|
b01a4accee | ||
|
|
858e989bdc | ||
|
|
3a0f0fe786 | ||
|
|
409e850768 | ||
|
|
6e89b874cd | ||
|
|
b4a5c62549 | ||
|
|
495f686292 | ||
|
|
71eb11b67f | ||
|
|
04ce8252c0 | ||
|
|
27e06db1d9 | ||
|
|
3908854fe0 | ||
|
|
0c1382c558 | ||
|
|
410d289297 | ||
|
|
31e5cf7fc5 | ||
|
|
4e797a2cfd | ||
|
|
cb4dc42dfa | ||
|
|
33ba5b1f61 | ||
|
|
247a00f57f | ||
|
|
0da3c989cd | ||
|
|
16d97f409c | ||
|
|
539025f2d4 | ||
|
|
9d705e580c | ||
|
|
aa7501c309 | ||
|
|
00118b4a1b | ||
|
|
65288ec424 | ||
|
|
a5067889b2 | ||
|
|
8efa9091a4 | ||
|
|
0e44bb5ffe | ||
|
|
8942d27453 | ||
|
|
ca3ac64390 | ||
|
|
5c2429aed7 | ||
|
|
7564b1a8f0 | ||
|
|
5c9f4c6638 | ||
|
|
69de750e6a | ||
|
|
83f9780f9c | ||
|
|
5d862401a0 | ||
|
|
91bac934ab | ||
|
|
d74fba4092 | ||
|
|
ce76c5f08e | ||
|
|
bb2182e707 | ||
|
|
9b2888b944 | ||
|
|
ba1a467e20 | ||
|
|
c97fffb32f | ||
|
|
d138af46d1 | ||
|
|
75a57b0e16 | ||
|
|
c06033e573 | ||
|
|
d290417ff3 | ||
|
|
a21aa348d7 | ||
|
|
479812e199 | ||
|
|
f6119946f8 | ||
|
|
5d1af3c31c | ||
|
|
14c98e87df | ||
|
|
8e3946a666 | ||
|
|
c2009ca6d4 | ||
|
|
22d3eea88d | ||
|
|
14d301eeb4 | ||
|
|
8efb549453 | ||
|
|
79fea8b286 | ||
|
|
e798a9ef32 | ||
|
|
7b5d4fa1a2 | ||
|
|
11582d5034 | ||
|
|
488d37e65b | ||
|
|
3ed5bd11ac | ||
|
|
8ff6086028 | ||
|
|
27d3b39209 | ||
|
|
6e181c0e7f | ||
|
|
b5f4097538 | ||
|
|
f6d2e25130 | ||
|
|
062735f6d5 | ||
|
|
8aefcdb2e8 | ||
|
|
5b4965dcc7 | ||
|
|
37e64a2eb8 | ||
|
|
59dd803529 | ||
|
|
2ef66fbc87 | ||
|
|
0346741188 | ||
|
|
e0e40237fa | ||
|
|
d3c56222be | ||
|
|
3261294822 | ||
|
|
f035994f9e | ||
|
|
4abac0c890 | ||
|
|
8c0dd67d03 | ||
|
|
7a379a2cae | ||
|
|
dd8872c027 | ||
|
|
33a0e18e7b | ||
|
|
522ad28fd8 | ||
|
|
94c4fedc06 | ||
|
|
e3dcbab508 | ||
|
|
96065ff175 | ||
|
|
845dd5d914 | ||
|
|
99f65f07f5 | ||
|
|
51f877f321 | ||
|
|
031fd26b26 | ||
|
|
ef07039083 | ||
|
|
6dc7f0211e | ||
|
|
ee90ef247b | ||
|
|
97f2795df4 | ||
|
|
82fac783ea | ||
|
|
dd21a5abad | ||
|
|
80aeb19020 | ||
|
|
6c8dce0593 | ||
|
|
9897f244e0 | ||
|
|
eaa25f2eb5 | ||
|
|
a976dd2acc | ||
|
|
c567ef25c6 | ||
|
|
de8bef6520 | ||
|
|
98dea81eeb | ||
|
|
9f3295cc0f | ||
|
|
4da6175cf5 | ||
|
|
d90ad5c955 | ||
|
|
65add4dfee | ||
|
|
2c2f6b76d4 | ||
|
|
49c29bebfb | ||
|
|
4e889d4991 | ||
|
|
6d463df586 | ||
|
|
2d8688bd4c | ||
|
|
bc9951c9b5 | ||
|
|
a7688fa9b9 | ||
|
|
5925d90209 | ||
|
|
5506518635 | ||
|
|
b9d08fff64 | ||
|
|
6875b32fd0 | ||
|
|
c36684091d | ||
|
|
f5939e2528 | ||
|
|
412e00317d | ||
|
|
8fe78e424e | ||
|
|
9fe6b4ca70 | ||
|
|
bf661556e1 | ||
|
|
763ef253f9 | ||
|
|
561426028c | ||
|
|
b726c40fd4 | ||
|
|
bc437a5ec7 | ||
|
|
620f9339f0 | ||
|
|
1a4ec1ece8 | ||
|
|
98ec37b5d1 | ||
|
|
711f57f4a1 | ||
|
|
e29e9c3dd1 | ||
|
|
b832311f7e | ||
|
|
887ee85e41 | ||
|
|
c9b788dc51 | ||
|
|
ab62e55e76 | ||
|
|
8f83687b7c | ||
|
|
a60c60c0f9 | ||
|
|
95a122a225 | ||
|
|
d234d79310 | ||
|
|
3188f8dbed | ||
|
|
9b9bb1e1e6 | ||
|
|
d31616ebcb | ||
|
|
2efedc47df | ||
|
|
646ec8da87 | ||
|
|
a848a9c896 | ||
|
|
8168f79ac6 | ||
|
|
38c06997b4 | ||
|
|
cdb6001955 | ||
|
|
e748a4da92 | ||
|
|
300e5cff3b | ||
|
|
6685ffb855 | ||
|
|
cbf91162e2 | ||
|
|
bd906fbf54 | ||
|
|
27662ed91a | ||
|
|
d0acab1915 | ||
|
|
e86180fe29 | ||
|
|
1f5c5a92a6 | ||
|
|
b79a1c7575 | ||
|
|
3559ed1cb5 | ||
|
|
042b155b5e | ||
|
|
673aa189be | ||
|
|
c503a86c53 | ||
|
|
1bd973ea6c | ||
|
|
4bb965e9ff | ||
|
|
a8ceeb29ae | ||
|
|
96a6540434 | ||
|
|
e02c86a9c4 | ||
|
|
e82f2ab34b | ||
|
|
2a6f3c3013 | ||
|
|
875bd209b2 | ||
|
|
2b601b1a1d | ||
|
|
164570d176 | ||
|
|
0d4898dae8 | ||
|
|
38e00eb4e5 | ||
|
|
3117af5497 | ||
|
|
6a87464b40 |
31
.github/workflows/release.yml
vendored
31
.github/workflows/release.yml
vendored
@@ -12,22 +12,20 @@ jobs:
|
|||||||
name: Release
|
name: Release
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: write # to be able to publish a GitHub release
|
||||||
packages: write
|
issues: write # to be able to comment on released issues
|
||||||
|
pull-requests: write # to be able to comment on released pull requests
|
||||||
|
packages: write # to be able to publish GitHub packages
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
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
|
- name: Cache dependencies
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: '**/node_modules'
|
path: '**/node_modules'
|
||||||
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lockb') }}
|
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
|
||||||
restore-keys: ${{ runner.os }}-bun-
|
restore-keys: ${{ runner.os }}-bun-
|
||||||
|
|
||||||
- name: Setup Bun
|
- name: Setup Bun
|
||||||
@@ -47,22 +45,11 @@ jobs:
|
|||||||
- name: Setup Docker Buildx
|
- name: Setup Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Build and release
|
- name: Build, release, publish
|
||||||
env:
|
env:
|
||||||
RELEASE_WORKFLOW_STEP: release
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
GITHUB_TOKEN: ${{ secrets.REPOSITORY_PUSH_ACCESS }}
|
|
||||||
DOCKER_REGISTRY_USER: ${{ github.repository_owner }}
|
DOCKER_REGISTRY_USER: ${{ github.repository_owner }}
|
||||||
DOCKER_REGISTRY_PASSWORD: ${{ secrets.REPOSITORY_PUSH_ACCESS }}
|
DOCKER_REGISTRY_PASSWORD: ${{ secrets.GITHUB_TOKEN }}
|
||||||
DEBUG: semantic-release:*
|
|
||||||
run: bunx multi-semantic-release --debug
|
|
||||||
|
|
||||||
# We call multi-semantic-release twice to publish in a different step
|
|
||||||
# An environment variable determines which plugins in the config to run
|
|
||||||
- name: Trigger Portainer webhooks
|
|
||||||
if: github.ref == 'refs/heads/main'
|
|
||||||
env:
|
|
||||||
RELEASE_WORKFLOW_STEP: publish
|
|
||||||
GITHUB_TOKEN: ${{ secrets.REPOSITORY_PUSH_ACCESS }}
|
|
||||||
WEBSOCKET_API_PORTAINER_WEBHOOK_URL: ${{ secrets.WEBSOCKET_API_PORTAINER_WEBHOOK_URL }}
|
WEBSOCKET_API_PORTAINER_WEBHOOK_URL: ${{ secrets.WEBSOCKET_API_PORTAINER_WEBHOOK_URL }}
|
||||||
DISCORD_BOT_PORTAINER_WEBHOOK_URL: ${{ secrets.DISCORD_BOT_PORTAINER_WEBHOOK_URL }}
|
DISCORD_BOT_PORTAINER_WEBHOOK_URL: ${{ secrets.DISCORD_BOT_PORTAINER_WEBHOOK_URL }}
|
||||||
run: bunx multi-semantic-release
|
run: bunx multi-semantic-release
|
||||||
|
|||||||
@@ -58,7 +58,7 @@
|
|||||||
Continuing the legacy of Vanced
|
Continuing the legacy of Vanced
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
# 🤖 ReVanced Helper
|
# 🤖 ReVanced Bots
|
||||||
|
|
||||||
Bots assisting ReVanced on multiple platforms.
|
Bots assisting ReVanced on multiple platforms.
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,7 @@
|
|||||||
import defineSubprojectReleaseConfig from '../../semantic-release-config.js'
|
import defineSubprojectReleaseConfig from '../../semantic-release-config.js'
|
||||||
|
|
||||||
export default defineSubprojectReleaseConfig({
|
export default defineSubprojectReleaseConfig({
|
||||||
plugins:
|
plugins: [
|
||||||
process.env.RELEASE_WORKFLOW_STEP === 'publish'
|
|
||||||
? [
|
|
||||||
[
|
|
||||||
'@semantic-release/exec',
|
|
||||||
{
|
|
||||||
publishCmd: 'bun run scripts/trigger-portainer-webhook.ts',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
]
|
|
||||||
: [
|
|
||||||
[
|
[
|
||||||
'@codedependant/semantic-release-docker',
|
'@codedependant/semantic-release-docker',
|
||||||
{
|
{
|
||||||
@@ -28,5 +18,11 @@ export default defineSubprojectReleaseConfig({
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
'@semantic-release/exec',
|
||||||
|
{
|
||||||
|
successCmd: 'bun run scripts/trigger-portainer-webhook.ts',
|
||||||
|
},
|
||||||
|
],
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,3 +1,115 @@
|
|||||||
|
# @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)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** attempt to fix sticky messages again ([7564b1a](https://github.com/revanced/revanced-bots/commit/7564b1a8f066183df390887ddfd4d73e0baa87ac))
|
||||||
|
|
||||||
|
## @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)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** attempt to fix sticky messages again ([7564b1a](https://github.com/revanced/revanced-bots/commit/7564b1a8f066183df390887ddfd4d73e0baa87ac))
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api 1.0.0 (2025-04-04)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **apis/websocket:** also include tesseract core files in build ([7dfbf6c](https://github.com/revanced/revanced-bots/commit/7dfbf6c92c49100954fa4aca471dce4ab9fd9565))
|
||||||
|
* **apis/websocket:** attempt to fix missing remote address ([9b2888b](https://github.com/revanced/revanced-bots/commit/9b2888b944ea1d61d31aa5df3536768e9a2dadf8))
|
||||||
|
* **apis/websocket:** build and runtime issues ([89d8ab1](https://github.com/revanced/revanced-bots/commit/89d8ab1ee58278a9a96cdc31c679d0a0a0d865af))
|
||||||
|
* **apis/websocket:** builds not working due to dynamic import requirement ([fc7be22](https://github.com/revanced/revanced-bots/commit/fc7be22c6c15974c7394790e93de2a23a6627153))
|
||||||
|
* **apis/websocket:** don't bundle `tesseract.js` ([51a6fb6](https://github.com/revanced/revanced-bots/commit/51a6fb65f0df3409eacffb297430840a0e326989))
|
||||||
|
* **apis/websocket:** fix forever stuck Promise ([168f40d](https://github.com/revanced/revanced-bots/commit/168f40def64ca213cd2b549f4bafed4c0e1e3695))
|
||||||
|
* **apis/websocket:** fix undefined error ([2f03800](https://github.com/revanced/revanced-bots/commit/2f03800c61c00e59e512567d273a195e605d6736))
|
||||||
|
* **apis/websocket:** hardcoded paths in tesseract worker builds ([38e00eb](https://github.com/revanced/revanced-bots/commit/38e00eb4e59c763bd74d27b9b9b482ea66e4dcf4))
|
||||||
|
* **apis/websocket:** improve logging and error handling ([b6cbe9d](https://github.com/revanced/revanced-bots/commit/b6cbe9d64c01ff11feab8351fb801bc1aee48325))
|
||||||
|
* **bots/discord:** hanging process when disconnecting from API too many times ([d31616e](https://github.com/revanced/revanced-bots/commit/d31616ebcba6f1dcd8bde183bcb8d1adb1501b61))
|
||||||
|
* fix typings and formatting ([479812e](https://github.com/revanced/revanced-bots/commit/479812e199b52cdb295a5746e0767306afab3413))
|
||||||
|
* other small issues ([bc437a5](https://github.com/revanced/revanced-bots/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
|
||||||
|
* remove error cb handling for `socket.send()` calls ([29544d4](https://github.com/revanced/revanced-bots/commit/29544d4e0127173465796b7e3c62161f4db59c8b))
|
||||||
|
* run projects with `--bun` ([bb2182e](https://github.com/revanced/revanced-bots/commit/bb2182e707fa40c555d56138972eeea28f1b3cf9))
|
||||||
|
* **types:** fix issues with typings ([669e24c](https://github.com/revanced/revanced-bots/commit/669e24ca8103ea051b4e61160dd0f978e36707ea))
|
||||||
|
* update repo url ([a21aa34](https://github.com/revanced/revanced-bots/commit/a21aa348d7f32cd0ee65b371e9594520c0a9d3f1))
|
||||||
|
|
||||||
|
|
||||||
|
### chore
|
||||||
|
|
||||||
|
* fix more build issues ([77fefb9](https://github.com/revanced/revanced-bots/commit/77fefb9bef286a22f40a4d76b79c64fcc5a2467f))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **apis/websocket:** clear old client sessions and instances ([43bd0a0](https://github.com/revanced/revanced-bots/commit/43bd0a021cd885a3d74a1f307ec2935e81d17458))
|
||||||
|
* **apis/websocket:** return `true` for data on a `TrainedMessage` packet ([65add4d](https://github.com/revanced/revanced-bots/commit/65add4dfeed2fa067c2c8e2377f7d01d505ade54))
|
||||||
|
* **packages/shared:** add logger factory ([17c6be7](https://github.com/revanced/revanced-bots/commit/17c6be7bee5b5c24fd4a5279e73374b0bb7a6229))
|
||||||
|
|
||||||
|
|
||||||
|
### BREAKING CHANGES
|
||||||
|
|
||||||
|
* In `@revanced/discord-bot`, its environment variable
|
||||||
|
`DATABASE_URL` has been renamed to `DATABASE_PATH`
|
||||||
|
and the `file:` prefix is no longer needed
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.11](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.0-dev.10...@revanced/bot-websocket-api@1.0.0-dev.11) (2025-04-04)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **apis/websocket:** attempt to fix missing remote address ([9b2888b](https://github.com/revanced/revanced-bots/commit/9b2888b944ea1d61d31aa5df3536768e9a2dadf8))
|
||||||
|
* run projects with `--bun` ([bb2182e](https://github.com/revanced/revanced-bots/commit/bb2182e707fa40c555d56138972eeea28f1b3cf9))
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.10](https://github.com/revanced/revanced-bots/compare/@revanced/bot-websocket-api@1.0.0-dev.9...@revanced/bot-websocket-api@1.0.0-dev.10) (2025-03-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* fix typings and formatting ([479812e](https://github.com/revanced/revanced-bots/commit/479812e199b52cdb295a5746e0767306afab3413))
|
||||||
|
* update repo url ([a21aa34](https://github.com/revanced/revanced-bots/commit/a21aa348d7f32cd0ee65b371e9594520c0a9d3f1))
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.9](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.8...@revanced/bot-websocket-api@1.0.0-dev.9) (2024-08-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **apis/websocket:** return `true` for data on a `TrainedMessage` packet ([65add4d](https://github.com/revanced/revanced-helper/commit/65add4dfeed2fa067c2c8e2377f7d01d505ade54))
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.8](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.7...@revanced/bot-websocket-api@1.0.0-dev.8) (2024-07-31)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* other small issues ([bc437a5](https://github.com/revanced/revanced-helper/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.7](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.6...@revanced/bot-websocket-api@1.0.0-dev.7) (2024-07-30)
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.6](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.5...@revanced/bot-websocket-api@1.0.0-dev.6) (2024-07-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** hanging process when disconnecting from API too many times ([d31616e](https://github.com/revanced/revanced-helper/commit/d31616ebcba6f1dcd8bde183bcb8d1adb1501b61))
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.5](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.4...@revanced/bot-websocket-api@1.0.0-dev.5) (2024-07-23)
|
||||||
|
|
||||||
|
# @revanced/bot-websocket-api [1.0.0-dev.4](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.3...@revanced/bot-websocket-api@1.0.0-dev.4) (2024-07-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **apis/websocket:** hardcoded paths in tesseract worker builds ([38e00eb](https://github.com/revanced/revanced-helper/commit/38e00eb4e59c763bd74d27b9b9b482ea66e4dcf4))
|
||||||
|
|
||||||
# @revanced/bot-websocket-api [1.0.0-dev.3](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.2...@revanced/bot-websocket-api@1.0.0-dev.3) (2024-07-23)
|
# @revanced/bot-websocket-api [1.0.0-dev.3](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.2...@revanced/bot-websocket-api@1.0.0-dev.3) (2024-07-23)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ FROM base AS build
|
|||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN bun install --frozen-lockfile
|
RUN bun install --frozen-lockfile
|
||||||
RUN cd apis/websocket && bun --bun run build
|
RUN cd apis/websocket && bun run build
|
||||||
|
|
||||||
FROM base AS release
|
FROM base AS release
|
||||||
|
|
||||||
@@ -14,4 +14,4 @@ WORKDIR /app
|
|||||||
COPY --from=build /build/apis/websocket/dist /app
|
COPY --from=build /build/apis/websocket/dist /app
|
||||||
USER 1000:1000
|
USER 1000:1000
|
||||||
|
|
||||||
ENTRYPOINT [ "bun", "run", "index.js" ]
|
ENTRYPOINT [ "bun", "--bun", "run", "index.js" ]
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "@revanced/bot-websocket-api",
|
"name": "@revanced/bot-websocket-api",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.0.0-dev.3",
|
"version": "1.1.0",
|
||||||
"description": "🧦 WebSocket API server for bots assisting ReVanced",
|
"description": "🧦 WebSocket API server for bots assisting ReVanced",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/revanced/revanced-helper.git",
|
"url": "git+https://github.com/revanced/revanced-bots.git",
|
||||||
"directory": "apis/websocket"
|
"directory": "apis/websocket"
|
||||||
},
|
},
|
||||||
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
||||||
@@ -23,18 +23,18 @@
|
|||||||
],
|
],
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/revanced/revanced-helper/issues"
|
"url": "https://github.com/revanced/revanced-bots/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
"homepage": "https://github.com/revanced/revanced-bots#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@revanced/bot-shared": "workspace:*",
|
"@revanced/bot-shared": "workspace:*",
|
||||||
"@sapphire/async-queue": "^1.5.2",
|
"@sapphire/async-queue": "^1.5.5",
|
||||||
"chalk": "^5.3.0",
|
"chalk": "^5.6.2",
|
||||||
"tesseract.js": "^5.1.0",
|
"tesseract.js": "^6.0.1",
|
||||||
"ws": "^8.17.1"
|
"ws": "^8.18.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/ws": "^8.5.10",
|
"@types/ws": "^8.18.1",
|
||||||
"typed-emitter": "^2.1.0"
|
"typed-emitter": "^2.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,26 +1,25 @@
|
|||||||
import { createLogger } from '@revanced/bot-shared'
|
import { createLogger } from '@revanced/bot-shared'
|
||||||
import { cp, rm } from 'fs/promises'
|
import { cp, exists, rm } from 'fs/promises'
|
||||||
|
|
||||||
const logger = createLogger()
|
const logger = createLogger()
|
||||||
|
|
||||||
logger.info('Cleaning previous build...')
|
logger.info('Cleaning previous build...')
|
||||||
await rm('./dist', { recursive: true })
|
if (await exists('./dist')) await rm('./dist', { recursive: true })
|
||||||
|
|
||||||
logger.info('Building WebSocket API...')
|
logger.info('Building WebSocket API...')
|
||||||
await Bun.build({
|
await Bun.build({
|
||||||
entrypoints: ['./src/index.ts'],
|
entrypoints: ['./src/index.ts'],
|
||||||
outdir: './dist',
|
outdir: './dist',
|
||||||
target: 'bun',
|
target: 'bun',
|
||||||
minify: true,
|
|
||||||
sourcemap: 'external',
|
sourcemap: 'external',
|
||||||
})
|
})
|
||||||
|
|
||||||
logger.info('Building Tesseract.js worker...')
|
logger.info('Building Tesseract.js worker...')
|
||||||
await Bun.build({
|
await Bun.build({
|
||||||
entrypoints: ['../../node_modules/tesseract.js/src/worker-script/node/index.js'],
|
entrypoints: ['../../node_modules/tesseract.js/src/worker-script/node/index.js'],
|
||||||
|
external: ['tesseract.js-core/*'],
|
||||||
target: 'bun',
|
target: 'bun',
|
||||||
outdir: './dist/worker',
|
outdir: './dist/worker',
|
||||||
minify: true,
|
|
||||||
sourcemap: 'external',
|
sourcemap: 'external',
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
import { EventEmitter } from 'events'
|
|
||||||
import {
|
import {
|
||||||
ClientOperation,
|
ClientOperation,
|
||||||
DisconnectReason,
|
DisconnectReason,
|
||||||
type Packet,
|
|
||||||
ServerOperation,
|
|
||||||
deserializePacket,
|
deserializePacket,
|
||||||
isClientPacket,
|
isClientPacket,
|
||||||
|
type Packet,
|
||||||
|
ServerOperation,
|
||||||
serializePacket,
|
serializePacket,
|
||||||
uncapitalize,
|
uncapitalize,
|
||||||
} from '@revanced/bot-shared'
|
} from '@revanced/bot-shared'
|
||||||
|
import { EventEmitter } from 'events'
|
||||||
import type TypedEmitter from 'typed-emitter'
|
import type TypedEmitter from 'typed-emitter'
|
||||||
import type { RawData, WebSocket } from 'ws'
|
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
|
// @ts-expect-error TypeScript doesn't know that the above line will negate the type enough
|
||||||
packet,
|
packet,
|
||||||
)
|
)
|
||||||
} catch (e) {
|
} catch (_e) {
|
||||||
// TODO: add error fields to sent packet so we can log what went wrong
|
// TODO: add error fields to sent packet so we can log what went wrong
|
||||||
this.disconnect(DisconnectReason.InvalidPacket)
|
this.disconnect(DisconnectReason.InvalidPacket)
|
||||||
}
|
}
|
||||||
@@ -110,7 +109,7 @@ export default class Client {
|
|||||||
protected _toBuffer(data: RawData) {
|
protected _toBuffer(data: RawData) {
|
||||||
if (data instanceof Buffer) return data
|
if (data instanceof Buffer) return data
|
||||||
if (data instanceof ArrayBuffer) return Buffer.from(data)
|
if (data instanceof ArrayBuffer) return Buffer.from(data)
|
||||||
return Buffer.concat(data)
|
return Buffer.concat(data as Uint8Array[])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 { createLogger } from '@revanced/bot-shared'
|
||||||
import { exists as pathExists } from 'fs/promises'
|
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'
|
import { getConfig } from './utils/config'
|
||||||
|
|
||||||
export const config = getConfig()
|
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})`)
|
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) {
|
message(text: string) {
|
||||||
return this.fetch(`/message?q=${encodeURIComponent(text)}&n=8`) as Promise<WitMessageResponse>
|
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', {
|
await this.fetch('/utterances', {
|
||||||
body: JSON.stringify([
|
body: JSON.stringify([
|
||||||
{
|
{
|
||||||
@@ -42,7 +41,14 @@ export const wit = {
|
|||||||
method: 'POST',
|
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 {
|
export interface WitMessageResponse {
|
||||||
text: string
|
text: string
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import type { ClientOperation } from '@revanced/bot-shared'
|
import type { ClientOperation, Logger } from '@revanced/bot-shared'
|
||||||
import type { Logger } from '@revanced/bot-shared'
|
|
||||||
import type { Worker as TesseractWorker } from 'tesseract.js'
|
import type { Worker as TesseractWorker } from 'tesseract.js'
|
||||||
import type { ClientPacketObject } from '../classes/Client'
|
import type { ClientPacketObject } from '../classes/Client'
|
||||||
import type { WitMessageResponse } from '../context'
|
import type { Wit } from '../context'
|
||||||
import type { Config } from '../utils/config'
|
import type { Config } from '../utils/config'
|
||||||
|
|
||||||
export { default as parseTextEventHandler } from './parseText'
|
|
||||||
export { default as parseImageEventHandler } from './parseImage'
|
export { default as parseImageEventHandler } from './parseImage'
|
||||||
|
export { default as parseTextEventHandler } from './parseText'
|
||||||
export { default as trainMessageEventHandler } from './trainMessage'
|
export { default as trainMessageEventHandler } from './trainMessage'
|
||||||
|
|
||||||
export type EventHandler<POp extends ClientOperation> = (
|
export type EventHandler<POp extends ClientOperation> = (
|
||||||
@@ -15,10 +14,7 @@ export type EventHandler<POp extends ClientOperation> = (
|
|||||||
) => void | Promise<void>
|
) => void | Promise<void>
|
||||||
|
|
||||||
export type EventContext = {
|
export type EventContext = {
|
||||||
wit: {
|
wit: Wit
|
||||||
train(text: string, label: string): Promise<void>
|
|
||||||
message(text: string): Promise<WitMessageResponse>
|
|
||||||
}
|
|
||||||
tesseract: TesseractWorker
|
tesseract: TesseractWorker
|
||||||
logger: Logger
|
logger: Logger
|
||||||
config: Config
|
config: Config
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
|
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
|
||||||
import { AsyncQueue } from '@sapphire/async-queue'
|
import { AsyncQueue } from '@sapphire/async-queue'
|
||||||
|
|
||||||
import type { EventHandler } from '.'
|
import type { EventHandler } from '.'
|
||||||
|
|
||||||
const queue = new AsyncQueue()
|
const queue = new AsyncQueue()
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
|
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
|
||||||
|
|
||||||
import type { EventHandler } from '.'
|
import type { EventHandler } from '.'
|
||||||
|
|
||||||
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (packet, { wit, logger }) => {
|
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (packet, { wit, logger }) => {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
|
import { type ClientOperation, ServerOperation } from '@revanced/bot-shared'
|
||||||
|
|
||||||
import type { EventHandler } from '.'
|
import type { EventHandler } from '.'
|
||||||
|
|
||||||
const trainMessageEventHandler: EventHandler<ClientOperation.TrainMessage> = async (packet, { wit, logger }) => {
|
const trainMessageEventHandler: EventHandler<ClientOperation.TrainMessage> = async (packet, { wit, logger }) => {
|
||||||
@@ -11,14 +10,14 @@ const trainMessageEventHandler: EventHandler<ClientOperation.TrainMessage> = asy
|
|||||||
const nextSeq = client.currentSequence++
|
const nextSeq = client.currentSequence++
|
||||||
const actualText = text.slice(0, 279)
|
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 {
|
try {
|
||||||
await wit.train(actualText, label)
|
await wit.train(actualText, label)
|
||||||
client.send(
|
client.send(
|
||||||
{
|
{
|
||||||
op: ServerOperation.TrainedMessage,
|
op: ServerOperation.TrainedMessage,
|
||||||
d: null,
|
d: true,
|
||||||
},
|
},
|
||||||
nextSeq,
|
nextSeq,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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 { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
|
||||||
|
|
||||||
import { createServer } from 'http'
|
import { createServer } from 'http'
|
||||||
|
import { inspect as inspectObject } from 'util'
|
||||||
import { type WebSocket, WebSocketServer } from 'ws'
|
import { type WebSocket, WebSocketServer } from 'ws'
|
||||||
|
import Client from './classes/Client'
|
||||||
import { config, logger, tesseract, wit } from './context'
|
import { config, logger, tesseract, wit } from './context'
|
||||||
|
import { type EventContext, parseImageEventHandler, parseTextEventHandler, trainMessageEventHandler } from './events'
|
||||||
|
|
||||||
// Load config, init logger, check environment
|
// Load config, init logger, check environment
|
||||||
|
|
||||||
@@ -56,12 +52,13 @@ const wss = new WebSocketServer({
|
|||||||
|
|
||||||
wss.on('connection', async (socket, request) => {
|
wss.on('connection', async (socket, request) => {
|
||||||
try {
|
try {
|
||||||
if (!request.socket.remoteAddress) {
|
const addrInfo = request.socket.address()
|
||||||
|
if (!('address' in addrInfo)) {
|
||||||
socket.close()
|
socket.close()
|
||||||
return logger.warn('Connection failed because client is missing remote address')
|
return logger.warn('Connection failed because client is missing remote address. addrInfo =', addrInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = `${request.socket.remoteAddress}:${request.socket.remotePort}`
|
const id = `${addrInfo.address}:${addrInfo.port}`
|
||||||
|
|
||||||
if (clientIds.has(id)) {
|
if (clientIds.has(id)) {
|
||||||
logger.warn(`Client ${id} already connected, disconnecting old session`)
|
logger.warn(`Client ${id} already connected, disconnecting old session`)
|
||||||
|
|||||||
38
biome.json
38
biome.json
@@ -1,6 +1,20 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://biomejs.dev/schemas/1.8.2/schema.json",
|
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
|
||||||
|
"assist": {
|
||||||
|
"actions": {
|
||||||
|
"source": {
|
||||||
"organizeImports": {
|
"organizeImports": {
|
||||||
|
"level": "on",
|
||||||
|
"options": {
|
||||||
|
"groups": [
|
||||||
|
{
|
||||||
|
"type": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"enabled": true
|
"enabled": true
|
||||||
},
|
},
|
||||||
"linter": {
|
"linter": {
|
||||||
@@ -21,7 +35,18 @@
|
|||||||
},
|
},
|
||||||
"useNodejsImportProtocol": {
|
"useNodejsImportProtocol": {
|
||||||
"level": "off"
|
"level": "off"
|
||||||
}
|
},
|
||||||
|
"useNumberNamespace": {
|
||||||
|
"level": "off"
|
||||||
|
},
|
||||||
|
"noParameterAssign": "error",
|
||||||
|
"useAsConstAssertion": "error",
|
||||||
|
"useDefaultParameterLast": "error",
|
||||||
|
"useSelfClosingElements": "error",
|
||||||
|
"useSingleVarDeclarator": "error",
|
||||||
|
"noUnusedTemplateLiteral": "error",
|
||||||
|
"noInferrableTypes": "error",
|
||||||
|
"noUselessElse": "error"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -51,7 +76,12 @@
|
|||||||
},
|
},
|
||||||
"files": {
|
"files": {
|
||||||
"ignoreUnknown": true,
|
"ignoreUnknown": true,
|
||||||
"include": ["*.js", "*.json", "*.ts"],
|
"includes": [
|
||||||
"ignore": ["dist/**/*", "node_modules/**/*"]
|
"**/*.js",
|
||||||
|
"**/*.json",
|
||||||
|
"**/*.ts",
|
||||||
|
"!**/dist/**/*",
|
||||||
|
"!**/node_modules/**/*"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3
bots/discord/.gitignore
vendored
3
bots/discord/.gitignore
vendored
@@ -174,9 +174,6 @@ dist
|
|||||||
# Finder (MacOS) folder config
|
# Finder (MacOS) folder config
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
# Config
|
|
||||||
config.ts
|
|
||||||
|
|
||||||
# DB
|
# DB
|
||||||
*.db
|
*.db
|
||||||
*.sqlite
|
*.sqlite
|
||||||
|
|||||||
@@ -1,17 +1,7 @@
|
|||||||
import defineSubprojectReleaseConfig from '../../semantic-release-config.js'
|
import defineSubprojectReleaseConfig from '../../semantic-release-config.js'
|
||||||
|
|
||||||
export default defineSubprojectReleaseConfig({
|
export default defineSubprojectReleaseConfig({
|
||||||
plugins:
|
plugins: [
|
||||||
process.env.RELEASE_WORKFLOW_STEP === 'publish'
|
|
||||||
? [
|
|
||||||
[
|
|
||||||
'@semantic-release/exec',
|
|
||||||
{
|
|
||||||
publishCmd: 'bun run scripts/trigger-portainer-webhook.ts',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
]
|
|
||||||
: [
|
|
||||||
[
|
[
|
||||||
'@codedependant/semantic-release-docker',
|
'@codedependant/semantic-release-docker',
|
||||||
{
|
{
|
||||||
@@ -28,5 +18,11 @@ export default defineSubprojectReleaseConfig({
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
'@semantic-release/exec',
|
||||||
|
{
|
||||||
|
successCmd: 'bun run scripts/trigger-portainer-webhook.ts',
|
||||||
|
},
|
||||||
|
],
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,3 +1,612 @@
|
|||||||
|
## @revanced/discord-bot [1.5.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.5.0...@revanced/discord-bot@1.5.1) (2025-09-13)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** only fetch reference when it exists when `respondToReply` is set ([42038e6](https://github.com/revanced/revanced-bots/commit/42038e6b38983fefe79481359bad300dcb5e83b4))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.5.0](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.4.1...@revanced/discord-bot@1.5.0) (2025-09-13)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add additional options for `respondToReply` ([399c201](https://github.com/revanced/revanced-bots/commit/399c201f8c3e9e116050b49c2ffccdd79b02f39b))
|
||||||
|
|
||||||
|
## @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)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** attempt to fix sticky messages one last time ([65288ec](https://github.com/revanced/revanced-bots/commit/65288ec4242b32d0b5e213b3d7af602bb9a829ca))
|
||||||
|
|
||||||
|
## @revanced/discord-bot [1.0.2](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.1...@revanced/discord-bot@1.0.2) (2025-04-09)
|
||||||
|
|
||||||
|
## @revanced/discord-bot [1.0.1](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.0...@revanced/discord-bot@1.0.1) (2025-04-09)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** attempt to fix sticky messages again ([7564b1a](https://github.com/revanced/revanced-bots/commit/7564b1a8f066183df390887ddfd4d73e0baa87ac))
|
||||||
|
|
||||||
|
# @revanced/discord-bot 1.0.0 (2025-04-04)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bot/discord:** start remove preset timeout for `role-preset` command ([cbf9116](https://github.com/revanced/revanced-bots/commit/cbf91162e27dd4c1ecb976927ab708f1d882abca))
|
||||||
|
* **bots/discord/commands/eval:** evaluate in current context ([5925d90](https://github.com/revanced/revanced-bots/commit/5925d902095acef5f6396ca03583a9cbb0862498))
|
||||||
|
* **bots/discord/commands/mute:** use existing `parseDuration` util function' ([3e07429](https://github.com/revanced/revanced-bots/commit/3e07429664f7dbb6ce653083e0adb1a232737fde))
|
||||||
|
* **bots/discord/commands/unmute:** fix option description and embeds ([7fdf8c0](https://github.com/revanced/revanced-bots/commit/7fdf8c0dc722e21fe5a3ad6ef8d3a306ef85f532))
|
||||||
|
* **bots/discord/commands:** minor issues ([3b2596e](https://github.com/revanced/revanced-bots/commit/3b2596e748cf2cde1500ef2ded55f0faabc2c272))
|
||||||
|
* **bots/discord/commands:** refactor and add checks ([a2bf3ea](https://github.com/revanced/revanced-bots/commit/a2bf3eade99b46f9ffb55d45b8caf1bcf3d22a9b))
|
||||||
|
* **bots/discord/database:** fix schema for role presets ([4aa138a](https://github.com/revanced/revanced-bots/commit/4aa138a9af8db7093ef637470fcfdea1f5341236))
|
||||||
|
* **bots/discord/scripts/build:** check if dist dir exists before cleaning ([c06033e](https://github.com/revanced/revanced-bots/commit/c06033e5730f82438e8052b9b519a8f8e2d25437))
|
||||||
|
* **bots/discord/scripts:** unintentional escaping on windows ([09dc706](https://github.com/revanced/revanced-bots/commit/09dc70632da0597fdb26677acee3f6fccbb2b9b5))
|
||||||
|
* **bots/discord/utils/discord/embeds:** set thumbnail on moderation embeds ([b056291](https://github.com/revanced/revanced-bots/commit/b056291ad0f2e2eac5eec8aa71f15dbc769aa0f9))
|
||||||
|
* **bots/discord/utils/discord/rolePresets:** correct property access for presets ([4c6ad11](https://github.com/revanced/revanced-bots/commit/4c6ad11be30c1d6af97c4ae40fc62d05fa7bdd57))
|
||||||
|
* **bots/discord/utils/discord:** add `moderation` module related functions ([7e8270f](https://github.com/revanced/revanced-bots/commit/7e8270f7d260322e1950e058b221ab088bd595d0))
|
||||||
|
* **bots/discord/utils/duration:** fix empty string returning with duration is 0 ([83c314e](https://github.com/revanced/revanced-bots/commit/83c314ef5f721abc355272db0e4c182dcfe5d943))
|
||||||
|
* **bots/discord/utils/duration:** fix specified default unit not working ([d138af4](https://github.com/revanced/revanced-bots/commit/d138af46d1f25a11b6f8ab3790ecaa70b1d716a9))
|
||||||
|
* **bots/discord/utils/duration:** make second the default unit ([5d1af3c](https://github.com/revanced/revanced-bots/commit/5d1af3c31c3379b6a13684dfb07583737908c8aa))
|
||||||
|
* **bots/discord:** add GuildMember partial ([8e3946a](https://github.com/revanced/revanced-bots/commit/8e3946a66602838715787090008c7bfaf72b67e9))
|
||||||
|
* **bots/discord:** allow access to `context` in `/eval` and await result ([99f65f0](https://github.com/revanced/revanced-bots/commit/99f65f07f5f8830c6e8ea4ae171e986af4d3f1f6))
|
||||||
|
* **bots/discord:** always true check causing no messages to be scanned ([98ec37b](https://github.com/revanced/revanced-bots/commit/98ec37b5d18cade85270ab83b0ed0abe41244dd9))
|
||||||
|
* **bots/discord:** apply active role presets if members rejoin ([f50b26b](https://github.com/revanced/revanced-bots/commit/f50b26b82d66c88fd1dbb8c07d77c177c0e781df))
|
||||||
|
* **bots/discord:** attempt to fix stuck sticky message timeouts ([3ed5bd1](https://github.com/revanced/revanced-bots/commit/3ed5bd11acc3b4fbd57b0d632c68eb9f77365b8a))
|
||||||
|
* **bots/discord:** await when putting entries into db ([4da6175](https://github.com/revanced/revanced-bots/commit/4da6175cf58b1fa6144bdc71ec806766d32c1025))
|
||||||
|
* **bots/discord:** broken regex when prefix set to special characters ([ab62e55](https://github.com/revanced/revanced-bots/commit/ab62e55e76005f5999d7413d1158e54053f28d1f))
|
||||||
|
* **bots/discord:** check token before connecting to bot api ([f3e4408](https://github.com/revanced/revanced-bots/commit/f3e4408aa28fb6a9d21365af8c1bea3d07b481de))
|
||||||
|
* **bots/discord:** ci issues causing database to not be auto generated ([673aa18](https://github.com/revanced/revanced-bots/commit/673aa189bef1009a3e32ba3b1291a5ee84f2def3))
|
||||||
|
* **bots/discord:** clear role presets after they expire ([faa81f4](https://github.com/revanced/revanced-bots/commit/faa81f4d887eaeae809651f5b68187d033a260f2))
|
||||||
|
* **bots/discord:** connect to discord API even if initial bot API connection fails ([6658b58](https://github.com/revanced/revanced-bots/commit/6658b582dbeba7e072a7a04c4efa255e7f634aef))
|
||||||
|
* **bots/discord:** contextify object before sandboxing ([062735f](https://github.com/revanced/revanced-bots/commit/062735f6d552890404d6192244c51a11b0709580))
|
||||||
|
* **bots/discord:** correct permission check logic ([dd8872c](https://github.com/revanced/revanced-bots/commit/dd8872c027c7e7e1a00f38d659b4d6e79274238c))
|
||||||
|
* **bots/discord:** correct sticky messages logic ([de8bef6](https://github.com/revanced/revanced-bots/commit/de8bef6520d53a1299f0478458320a7eb75c5e1d))
|
||||||
|
* **bots/discord:** correct timer active condition for sticky messages ([96065ff](https://github.com/revanced/revanced-bots/commit/96065ff17584ff99a56ca5008327863ca5a7852b))
|
||||||
|
* **bots/discord:** correct whitelist logic ([49c29be](https://github.com/revanced/revanced-bots/commit/49c29bebfbe348ae4e2cc1b3a83bfa41eb26ccd1))
|
||||||
|
* **bots/discord:** cross-device link build errors ([38c0699](https://github.com/revanced/revanced-bots/commit/38c06997b4d0f7bb3f1e62618a5e3f088c522e30))
|
||||||
|
* **bots/discord:** decrease length of an option in `ban` command ([22d3eea](https://github.com/revanced/revanced-bots/commit/22d3eea88d532792c1237d1a1ab18bc02e57816a))
|
||||||
|
* **bots/discord:** delete expired appliedPresets entries after unapplying ([14c98e8](https://github.com/revanced/revanced-bots/commit/14c98e87df1ec4fd762bbc48ca4c06470cb110a2))
|
||||||
|
* **bots/discord:** deployment runtime errors due to minification ([a60c60c](https://github.com/revanced/revanced-bots/commit/a60c60c0f994a4c256b7d0582e99a1731209cf49))
|
||||||
|
* **bots/discord:** do decancer after resetting nickname ([0303fe3](https://github.com/revanced/revanced-bots/commit/0303fe3e367c07e92f831365d5548ca5b03435b2))
|
||||||
|
* **bots/discord:** do not remove unrelated reactions ([031fd26](https://github.com/revanced/revanced-bots/commit/031fd26b2619ecafeff3964e50accacb87de6108))
|
||||||
|
* **bots/discord:** don't refresh timer if force timer is active for sticky messages ([4abac0c](https://github.com/revanced/revanced-bots/commit/4abac0c890c0548e14cb56723cae919353a8e726))
|
||||||
|
* **bots/discord:** filter out text triggers correctly from image-only scans ([8c0dd67](https://github.com/revanced/revanced-bots/commit/8c0dd67d03d5a1747993da08a5bf82a39de43789))
|
||||||
|
* **bots/discord:** fix freeze on prod builds ([8efb549](https://github.com/revanced/revanced-bots/commit/8efb549453a04fab1ac6414a7f7f8bf702df3c93))
|
||||||
|
* **bots/discord:** fix get response logic ([3261294](https://github.com/revanced/revanced-bots/commit/3261294822b0a9faec094536ed5be2d3e1d5e17b))
|
||||||
|
* **bots/discord:** fix reload not working ([11582d5](https://github.com/revanced/revanced-bots/commit/11582d50345cae9fb645a65ca4e621596de6a408))
|
||||||
|
* **bots/discord:** follow-up if reply is already sent when error ([f75060b](https://github.com/revanced/revanced-bots/commit/f75060bc9cda44902cf872def73c116a6df039d7))
|
||||||
|
* **bots/discord:** give only removed roles for role presets ([522ad28](https://github.com/revanced/revanced-bots/commit/522ad28fd83565e9ca411dbce86c8447574288fd))
|
||||||
|
* **bots/discord:** hanging process when disconnecting from API too many times ([d31616e](https://github.com/revanced/revanced-bots/commit/d31616ebcba6f1dcd8bde183bcb8d1adb1501b61))
|
||||||
|
* **bots/discord:** import `config` from context ([763ef25](https://github.com/revanced/revanced-bots/commit/763ef253f9d4ff70a8b79969a7f4f41cba7f3c59))
|
||||||
|
* **bots/discord:** make `/eval` work ([eaa25f2](https://github.com/revanced/revanced-bots/commit/eaa25f2eb58a9e2d25bb98633ad668485e099714))
|
||||||
|
* **bots/discord:** messed up file name for `unmute` command ([399dca7](https://github.com/revanced/revanced-bots/commit/399dca71538fe5c8831977694a97058254a17578))
|
||||||
|
* **bots/discord:** only check for member permissions when specified while correcting responses ([b79a1c7](https://github.com/revanced/revanced-bots/commit/b79a1c7575e94c3e62654c87775cac497be4a50a))
|
||||||
|
* **bots/discord:** open database as read-write ([c366840](https://github.com/revanced/revanced-bots/commit/c36684091dddf67880505dc459e4334a8a5492f4))
|
||||||
|
* **bots/discord:** owners cannot bypass checks on some commands ([39cba97](https://github.com/revanced/revanced-bots/commit/39cba973418027ba6ed67e1ae5ab5c6458807562))
|
||||||
|
* **bots/discord:** parse larger units of durations, fix wrong timestamp in mod embed ([6c8dce0](https://github.com/revanced/revanced-bots/commit/6c8dce059366a6ef85f5b8b1794c056515b9f5b6))
|
||||||
|
* **bots/discord:** persist changes in context for eval command ([5b4965d](https://github.com/revanced/revanced-bots/commit/5b4965dcc7285676b2b3b6756c249bd56eaf8485))
|
||||||
|
* **bots/discord:** provide discord token for `reload` command ([dd21a5a](https://github.com/revanced/revanced-bots/commit/dd21a5abad560f3d00b8c58912786d4b6bd520e9))
|
||||||
|
* **bots/discord:** remove auto-generated files ([fb8af00](https://github.com/revanced/revanced-bots/commit/fb8af008661bf37389e01cba19d64a8b4fc82139))
|
||||||
|
* **bots/discord:** remove bad text channel checks ([f5939e2](https://github.com/revanced/revanced-bots/commit/f5939e25288fea2022fdeec9085ecb9ffada6111))
|
||||||
|
* **bots/discord:** remove redundant footer for response embeds ([412e003](https://github.com/revanced/revanced-bots/commit/412e00317d1eaca23e9c1375e16f94a5f2fa8d86))
|
||||||
|
* **bots/discord:** remove usage of macros ([7f27c56](https://github.com/revanced/revanced-bots/commit/7f27c5607ceeeef56d67097e88f68caa1b8791b3))
|
||||||
|
* **bots/discord:** remove useless feature ([d830e48](https://github.com/revanced/revanced-bots/commit/d830e48bc2de7aa457eab3a5f96ae652a93178f9))
|
||||||
|
* **bots/discord:** replace duration parser with a library ([94c4fed](https://github.com/revanced/revanced-bots/commit/94c4fedc06e20051e4123508e3134b97eb84782a))
|
||||||
|
* **bots/discord:** reset counter when reconnected to api, redo message scan filter logic ([d234d79](https://github.com/revanced/revanced-bots/commit/d234d79310caed9c43e14a905f9ef46a110e071d))
|
||||||
|
* **bots/discord:** revert dist denesting, fixes config not found ([0d4898d](https://github.com/revanced/revanced-bots/commit/0d4898dae8b26f8466d3f6b8f62875866f581644))
|
||||||
|
* **bots/discord:** send right response for after regexes ([a7688fa](https://github.com/revanced/revanced-bots/commit/a7688fa9b91919a87f74071b502cd0a87cd1c1fa))
|
||||||
|
* **bots/discord:** set the `label` property correctly for message scans ([6d463df](https://github.com/revanced/revanced-bots/commit/6d463df586dee5dd8fe8d6cff1c5316f7809b32a))
|
||||||
|
* **bots/discord:** set timeout for eligible mutes to unmute faster ([1f5c5a9](https://github.com/revanced/revanced-bots/commit/1f5c5a92a639973b83a1204355538936e69a4454))
|
||||||
|
* **bots/discord:** some configuration values not applying after running `/reload` ([a976dd2](https://github.com/revanced/revanced-bots/commit/a976dd2accc4b74914651245acde0979c30c92f5))
|
||||||
|
* **bots/discord:** use `APIEmbed` for response config ([35b9448](https://github.com/revanced/revanced-bots/commit/35b944800a3943c187d5b0e0d3e465ad7d2056fe))
|
||||||
|
* **bots/discord:** use env for initializing database ([af3759c](https://github.com/revanced/revanced-bots/commit/af3759caf428fada3b3f4a51852543d6fb280018))
|
||||||
|
* **bots/discord:** wrong command file path being imported ([fa0159c](https://github.com/revanced/revanced-bots/commit/fa0159c3a8dd4dad8778ccdb75b9e7c02ebbb64f))
|
||||||
|
* **bots/discord:** wrong database schema path ([875bd20](https://github.com/revanced/revanced-bots/commit/875bd209b252566414bf89349839cabc01697e1c))
|
||||||
|
* config file not being read ([474a8be](https://github.com/revanced/revanced-bots/commit/474a8be4af4eb2bae6e80a893439d846ad4f7503))
|
||||||
|
* **discord-bot:** also execute slash commands ([f0d45b2](https://github.com/revanced/revanced-bots/commit/f0d45b2c926ed753e2d21f2e06e24d7e6c43880a))
|
||||||
|
* **discord-bot:** check for role position ([d332043](https://github.com/revanced/revanced-bots/commit/d332043b1a4bb7ac9698a2fc912832e184130b4b))
|
||||||
|
* **discord-bot:** check if the member has the role ([9bff68c](https://github.com/revanced/revanced-bots/commit/9bff68c8c40c692764e4dec15a058e35059efbc9))
|
||||||
|
* **discord-bot:** not executing slash commands ([aa08087](https://github.com/revanced/revanced-bots/commit/aa0808768b90844c5fbd3e75d9f2d01c723b0151))
|
||||||
|
* **discord-bot:** only send lowercased text ([7803758](https://github.com/revanced/revanced-bots/commit/78037580dc92883f5ca21157e45268850cb5db90))
|
||||||
|
* dislike button not working properly ([85eba55](https://github.com/revanced/revanced-bots/commit/85eba554247738066af72a8efd0de215ec1164dc))
|
||||||
|
* fix deprecation ([4373ede](https://github.com/revanced/revanced-bots/commit/4373ede855333f209676551162a525238656e1f8))
|
||||||
|
* fix the fiter for the interaction collector ([a9ff003](https://github.com/revanced/revanced-bots/commit/a9ff00394a73f68a6793c2b35ff184675ee5a72c))
|
||||||
|
* fix typings and formatting ([479812e](https://github.com/revanced/revanced-bots/commit/479812e199b52cdb295a5746e0767306afab3413))
|
||||||
|
* ignore message if there's no content ([3cbebc2](https://github.com/revanced/revanced-bots/commit/3cbebc284277808495e64cf0fb47c555924ad9c5))
|
||||||
|
* move modules to `/bots` ([cd7156e](https://github.com/revanced/revanced-bots/commit/cd7156e792e65777ad1ab5a6f5d828b9ef6a9754))
|
||||||
|
* other small issues ([bc437a5](https://github.com/revanced/revanced-bots/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
|
||||||
|
* run projects with `--bun` ([bb2182e](https://github.com/revanced/revanced-bots/commit/bb2182e707fa40c555d56138972eeea28f1b3cf9))
|
||||||
|
* trainAI not using the bin location ([bd29943](https://github.com/revanced/revanced-bots/commit/bd2994388bc65f720120ef49edb6ba8163260309))
|
||||||
|
* update repo url ([a21aa34](https://github.com/revanced/revanced-bots/commit/a21aa348d7f32cd0ee65b371e9594520c0a9d3f1))
|
||||||
|
|
||||||
|
|
||||||
|
### chore
|
||||||
|
|
||||||
|
* fix more build issues ([77fefb9](https://github.com/revanced/revanced-bots/commit/77fefb9bef286a22f40a4d76b79c64fcc5a2467f))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add wit.ai support ([1909e2c](https://github.com/revanced/revanced-bots/commit/1909e2c42148d635dcd045c738d88f65c8be16e3))
|
||||||
|
* **bots/discord/commands/reply:** send stacktrace when failed ([9f1ac37](https://github.com/revanced/revanced-bots/commit/9f1ac379276c11da65235577a9c6717e01cb02eb))
|
||||||
|
* **bots/discord/commands:** add `ban` and `unban` commands ([dc4863d](https://github.com/revanced/revanced-bots/commit/dc4863dc208b3fede4d4def323306ab58daffe04))
|
||||||
|
* **bots/discord/commands:** add `eval` command ([e64d1da](https://github.com/revanced/revanced-bots/commit/e64d1da00cc2ba718da5a4b0da141fe86a0e48d2))
|
||||||
|
* **bots/discord/commands:** add `mute` and `unmute` commands ([c0fa2fe](https://github.com/revanced/revanced-bots/commit/c0fa2fe1c36acdc7c52cde277aa7da867065f55e))
|
||||||
|
* **bots/discord/commands:** add `purge` and `role-preset` commands ([fb01ce5](https://github.com/revanced/revanced-bots/commit/fb01ce57400130c93751a11573eb444c0ba103eb))
|
||||||
|
* **bots/discord/commands:** add `reload` command ([6875b32](https://github.com/revanced/revanced-bots/commit/6875b32fd0c6ce3034da9dc6c704d425afb26f2e))
|
||||||
|
* **bots/discord/commands:** allow process exception in `exception-test` ([ca47535](https://github.com/revanced/revanced-bots/commit/ca475356ad95fec86e8e8b5bf4bbf17b70add5fe))
|
||||||
|
* **bots/discord/utils/discord/embeds:** expose `applyCommonEmbedStyles` fn ([2d794ed](https://github.com/revanced/revanced-bots/commit/2d794ede7d7a208bd3616c45e8e6d2a2cd83e9ed))
|
||||||
|
* **bots/discord/utils/embeds:** make title parameter nullable ([ee885ca](https://github.com/revanced/revanced-bots/commit/ee885ca7585a55fdc31e137ae29dc13a37ce2fb2))
|
||||||
|
* **bots/discord/utils/fs:** use `recursive` option for listing files ([da21e1a](https://github.com/revanced/revanced-bots/commit/da21e1a6f76deaeb477203b04263bd170863825b))
|
||||||
|
* **bots/discord/utils:** add duration utility ([a9add9e](https://github.com/revanced/revanced-bots/commit/a9add9ea9affb42bdfcb17cf4b268feec5729854))
|
||||||
|
* **bots/discord/utils:** add functions for role presets ([fb32a04](https://github.com/revanced/revanced-bots/commit/fb32a04ad38be8d0836dc99259b6ef05a0825830))
|
||||||
|
* **bots/discord/utils:** allow loading commands from custom dir ([8b690b8](https://github.com/revanced/revanced-bots/commit/8b690b879bb5c6023c8fc863afbd9fd1d02719bb))
|
||||||
|
* **bots/discord:** add `api.disconnectRetryInterval` config ([2f86586](https://github.com/revanced/revanced-bots/commit/2f8658617923c07f6847cbf1fdfc5f5379d95b6c))
|
||||||
|
* **bots/discord:** add `moderation.roles` config to be used in `moderation` commands ([39d5b3a](https://github.com/revanced/revanced-bots/commit/39d5b3a479b4d856aabe12cc31177c24f88ae23e))
|
||||||
|
* **bots/discord:** add `ocrTriggers` resp config, embed footer scan mode ([744a56a](https://github.com/revanced/revanced-bots/commit/744a56a4fdc8844e37959a88bcf81ee39fe726ef))
|
||||||
|
* **bots/discord:** add `replyToReplied` option in response config ([27662ed](https://github.com/revanced/revanced-bots/commit/27662ed91a79bfac7d3f091834e859a7b57366ce))
|
||||||
|
* **bots/discord:** add `train` commands ([ee90ef2](https://github.com/revanced/revanced-bots/commit/ee90ef247b4bf2b3c0698606b947116f2dc1b868))
|
||||||
|
* **bots/discord:** add a better way to manage databases ([a68d726](https://github.com/revanced/revanced-bots/commit/a68d72687584332587455962b0202a306288057d))
|
||||||
|
* **bots/discord:** add code to actually scan text files correctly ([80aeb19](https://github.com/revanced/revanced-bots/commit/80aeb1902063140a2e78cfaed9424e5101ab03f1))
|
||||||
|
* **bots/discord:** add default durations for moderation commands ([27d3b39](https://github.com/revanced/revanced-bots/commit/27d3b392092141a1e3b4b0298131ff7817458dc1))
|
||||||
|
* **bots/discord:** add more fallbacks for decancering ([2e1e009](https://github.com/revanced/revanced-bots/commit/2e1e009b4272495798313bd3bd61f258875c62e1))
|
||||||
|
* **bots/discord:** add more month aliases to duration parser ([c2009ca](https://github.com/revanced/revanced-bots/commit/c2009ca6d42e4387bc5f375d76ecf72991b7fe32))
|
||||||
|
* **bots/discord:** add more options for curing, fix default regex ([1a4ec1e](https://github.com/revanced/revanced-bots/commit/1a4ec1ece80becd9156582cc490f6681cb2a1f39))
|
||||||
|
* **bots/discord:** add source ([f9d50a0](https://github.com/revanced/revanced-bots/commit/f9d50a0a6bef8beaa428a0a555bfa4f879f685f1))
|
||||||
|
* **bots/discord:** add sticky messages ([bf66155](https://github.com/revanced/revanced-bots/commit/bf661556e131bf0ef24e47f658fbcd701960e312))
|
||||||
|
* **bots/discord:** add trigger to context for eval ([b5f4097](https://github.com/revanced/revanced-bots/commit/b5f40975386677ffff343c42f8ffac21f847a0b7))
|
||||||
|
* **bots/discord:** allow admins to bypass permission checks ([620f933](https://github.com/revanced/revanced-bots/commit/620f9339f0737b79d72c66d90ffa42ea3f987710))
|
||||||
|
* **bots/discord:** blacklist and whitelist for filters ([cdb6001](https://github.com/revanced/revanced-bots/commit/cdb600195520dba33110c40841629259e317055e))
|
||||||
|
* **bots/discord:** cure on every event ([8ff6086](https://github.com/revanced/revanced-bots/commit/8ff6086028132cc4b49ee60846e8d6ef909f5a89))
|
||||||
|
* **bots/discord:** don't nest builds in src directory, autogen db when missing ([4834685](https://github.com/revanced/revanced-bots/commit/48346851864c4d4b6276388644dd24ce16222b3e))
|
||||||
|
* **bots/discord:** framework changes and new features ([646ec8d](https://github.com/revanced/revanced-bots/commit/646ec8da87617e6c8f48a89e8054e2cba91da549))
|
||||||
|
* **bots/discord:** improve admin commands ([0346741](https://github.com/revanced/revanced-bots/commit/03467411882b8598e2c06f389a09ef2e201bb43f))
|
||||||
|
* **bots/discord:** improve logs ([6abb740](https://github.com/revanced/revanced-bots/commit/6abb7409945c10bd3af451fb45ef4b4d4ebe9489))
|
||||||
|
* **bots/discord:** sanitize `BasicDatabase` inputs ([fd76e0a](https://github.com/revanced/revanced-bots/commit/fd76e0af72fe28b414ae3b5e8d3886e58561e57e))
|
||||||
|
* **bots/discord:** support nickname decancering ([1723e8c](https://github.com/revanced/revanced-bots/commit/1723e8cacf96e8c6bdee22cfd30e89524fdcef74))
|
||||||
|
* **bots/discord:** switch to `drizzle-orm` ([e204b7b](https://github.com/revanced/revanced-bots/commit/e204b7b7566fd7fa423baef32977a8575d44a9e0))
|
||||||
|
* **bots/discord:** update config ([197d2ac](https://github.com/revanced/revanced-bots/commit/197d2acea89c38e43858d52736508d449152e804))
|
||||||
|
* **bots/discord:** update example config file ([bc9951c](https://github.com/revanced/revanced-bots/commit/bc9951c9b5e007c3e1b3076aa0966ccf29bb18bc))
|
||||||
|
* **bots/discord:** update to newer command definition framework ([97f2795](https://github.com/revanced/revanced-bots/commit/97f2795df4ede4d12a08193dba453c1bc765a4c2))
|
||||||
|
* discord bot scanning messages ([d1bd3b2](https://github.com/revanced/revanced-bots/commit/d1bd3b2b7e4985a64e9b070ab006cc6f3508c46e))
|
||||||
|
* **discord-bot:** a way to train AI ([355a508](https://github.com/revanced/revanced-bots/commit/355a50803adc85b5579155b55ddbba4fa0449237))
|
||||||
|
* **discord-bot:** command handler and train cmd ([6aee8a4](https://github.com/revanced/revanced-bots/commit/6aee8a4c63eb108800fcb0a23ca61f200d8f1f2a))
|
||||||
|
* **discord-bot:** event handler ([0ad5ece](https://github.com/revanced/revanced-bots/commit/0ad5ece08593c0db111fa4a592b42c6e0348fd1c))
|
||||||
|
* GODEL AI ([0ba525c](https://github.com/revanced/revanced-bots/commit/0ba525c4a5802106d582c75f713728accf2f151a))
|
||||||
|
* initalize discord bot ([bb4a5a7](https://github.com/revanced/revanced-bots/commit/bb4a5a77eefbc7ac88536f73a111df1050b235e7))
|
||||||
|
* initialize helper client ([7f9ca77](https://github.com/revanced/revanced-bots/commit/7f9ca77e0331ec143160ee51ed7c3aa9e4e70b9c))
|
||||||
|
* message buttons for training ([6551ca9](https://github.com/revanced/revanced-bots/commit/6551ca9dadc2e3ddfe98875e80ed61f7d71a1651))
|
||||||
|
* platform specific responses ([18e57b0](https://github.com/revanced/revanced-bots/commit/18e57b0c320732a937bb60db11c5d6794ed11522))
|
||||||
|
* prettier and eslint ([1c27ccb](https://github.com/revanced/revanced-bots/commit/1c27ccb17c85f0f6982db45de426181d2c231d0e))
|
||||||
|
* refactor and new features ([#7](https://github.com/revanced/revanced-bots/issues/7)) ([8b9f45d](https://github.com/revanced/revanced-bots/commit/8b9f45dc22de29dc2ccb1cfab9a026db00457e25))
|
||||||
|
* run bots in one process ([d26d533](https://github.com/revanced/revanced-bots/commit/d26d53317440c64fb775cea609a87d29be6c8b40))
|
||||||
|
* training and replies changed ([715aa91](https://github.com/revanced/revanced-bots/commit/715aa918cf84213c9b19591a398d7532eb3f232a))
|
||||||
|
* **utils/discord/embeds:** allow adding extra fields for moderation embeds ([49ce9a7](https://github.com/revanced/revanced-bots/commit/49ce9a7ca3d8558b73a9b94dfe7a01d809db6fff))
|
||||||
|
|
||||||
|
|
||||||
|
### BREAKING CHANGES
|
||||||
|
|
||||||
|
* In `@revanced/discord-bot`, its environment variable
|
||||||
|
`DATABASE_URL` has been renamed to `DATABASE_PATH`
|
||||||
|
and the `file:` prefix is no longer needed
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.38](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.0-dev.37...@revanced/discord-bot@1.0.0-dev.38) (2025-04-04)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* run projects with `--bun` ([bb2182e](https://github.com/revanced/revanced-bots/commit/bb2182e707fa40c555d56138972eeea28f1b3cf9))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.37](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.0-dev.36...@revanced/discord-bot@1.0.0-dev.37) (2025-03-08)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord/utils/duration:** fix specified default unit not working ([d138af4](https://github.com/revanced/revanced-bots/commit/d138af46d1f25a11b6f8ab3790ecaa70b1d716a9))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.36](https://github.com/revanced/revanced-bots/compare/@revanced/discord-bot@1.0.0-dev.35...@revanced/discord-bot@1.0.0-dev.36) (2025-03-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord/scripts/build:** check if dist dir exists before cleaning ([c06033e](https://github.com/revanced/revanced-bots/commit/c06033e5730f82438e8052b9b519a8f8e2d25437))
|
||||||
|
* **bots/discord/utils/duration:** make second the default unit ([5d1af3c](https://github.com/revanced/revanced-bots/commit/5d1af3c31c3379b6a13684dfb07583737908c8aa))
|
||||||
|
* **bots/discord:** add GuildMember partial ([8e3946a](https://github.com/revanced/revanced-bots/commit/8e3946a66602838715787090008c7bfaf72b67e9))
|
||||||
|
* **bots/discord:** decrease length of an option in `ban` command ([22d3eea](https://github.com/revanced/revanced-bots/commit/22d3eea88d532792c1237d1a1ab18bc02e57816a))
|
||||||
|
* **bots/discord:** delete expired appliedPresets entries after unapplying ([14c98e8](https://github.com/revanced/revanced-bots/commit/14c98e87df1ec4fd762bbc48ca4c06470cb110a2))
|
||||||
|
* fix typings and formatting ([479812e](https://github.com/revanced/revanced-bots/commit/479812e199b52cdb295a5746e0767306afab3413))
|
||||||
|
* update repo url ([a21aa34](https://github.com/revanced/revanced-bots/commit/a21aa348d7f32cd0ee65b371e9594520c0a9d3f1))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add more month aliases to duration parser ([c2009ca](https://github.com/revanced/revanced-bots/commit/c2009ca6d42e4387bc5f375d76ecf72991b7fe32))
|
||||||
|
|
||||||
|
# @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)
|
||||||
|
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** don't refresh timer if force timer is active for sticky messages ([4abac0c](https://github.com/revanced/revanced-helper/commit/4abac0c890c0548e14cb56723cae919353a8e726))
|
||||||
|
* **bots/discord:** filter out text triggers correctly from image-only scans ([8c0dd67](https://github.com/revanced/revanced-helper/commit/8c0dd67d03d5a1747993da08a5bf82a39de43789))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.27](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.26...@revanced/discord-bot@1.0.0-dev.27) (2024-09-05)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** correct permission check logic ([dd8872c](https://github.com/revanced/revanced-helper/commit/dd8872c027c7e7e1a00f38d659b4d6e79274238c))
|
||||||
|
* **bots/discord:** give only removed roles for role presets ([522ad28](https://github.com/revanced/revanced-helper/commit/522ad28fd83565e9ca411dbce86c8447574288fd))
|
||||||
|
* **bots/discord:** replace duration parser with a library ([94c4fed](https://github.com/revanced/revanced-helper/commit/94c4fedc06e20051e4123508e3134b97eb84782a))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.27](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.26...@revanced/discord-bot@1.0.0-dev.27) (2024-08-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** give only removed roles for role presets ([522ad28](https://github.com/revanced/revanced-helper/commit/522ad28fd83565e9ca411dbce86c8447574288fd))
|
||||||
|
* **bots/discord:** replace duration parser with a library ([94c4fed](https://github.com/revanced/revanced-helper/commit/94c4fedc06e20051e4123508e3134b97eb84782a))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.26](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.25...@revanced/discord-bot@1.0.0-dev.26) (2024-08-15)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** correct timer active condition for sticky messages ([96065ff](https://github.com/revanced/revanced-helper/commit/96065ff17584ff99a56ca5008327863ca5a7852b))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.25](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.24...@revanced/discord-bot@1.0.0-dev.25) (2024-08-15)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** allow access to `context` in `/eval` and await result ([99f65f0](https://github.com/revanced/revanced-helper/commit/99f65f07f5f8830c6e8ea4ae171e986af4d3f1f6))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.24](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.23...@revanced/discord-bot@1.0.0-dev.24) (2024-08-14)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** do not remove unrelated reactions ([031fd26](https://github.com/revanced/revanced-helper/commit/031fd26b2619ecafeff3964e50accacb87de6108))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.23](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.22...@revanced/discord-bot@1.0.0-dev.23) (2024-08-13)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add `train` commands ([ee90ef2](https://github.com/revanced/revanced-helper/commit/ee90ef247b4bf2b3c0698606b947116f2dc1b868))
|
||||||
|
* **bots/discord:** update to newer command definition framework ([97f2795](https://github.com/revanced/revanced-helper/commit/97f2795df4ede4d12a08193dba453c1bc765a4c2))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.22](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.21...@revanced/discord-bot@1.0.0-dev.22) (2024-08-10)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** parse larger units of durations, fix wrong timestamp in mod embed ([6c8dce0](https://github.com/revanced/revanced-helper/commit/6c8dce059366a6ef85f5b8b1794c056515b9f5b6))
|
||||||
|
* **bots/discord:** provide discord token for `reload` command ([dd21a5a](https://github.com/revanced/revanced-helper/commit/dd21a5abad560f3d00b8c58912786d4b6bd520e9))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add code to actually scan text files correctly ([80aeb19](https://github.com/revanced/revanced-helper/commit/80aeb1902063140a2e78cfaed9424e5101ab03f1))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.21](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.20...@revanced/discord-bot@1.0.0-dev.21) (2024-08-04)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** correct sticky messages logic ([de8bef6](https://github.com/revanced/revanced-helper/commit/de8bef6520d53a1299f0478458320a7eb75c5e1d))
|
||||||
|
* **bots/discord:** make `/eval` work ([eaa25f2](https://github.com/revanced/revanced-helper/commit/eaa25f2eb58a9e2d25bb98633ad668485e099714))
|
||||||
|
* **bots/discord:** some configuration values not applying after running `/reload` ([a976dd2](https://github.com/revanced/revanced-helper/commit/a976dd2accc4b74914651245acde0979c30c92f5))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.20](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.19...@revanced/discord-bot@1.0.0-dev.20) (2024-08-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** await when putting entries into db ([4da6175](https://github.com/revanced/revanced-helper/commit/4da6175cf58b1fa6144bdc71ec806766d32c1025))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.19](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.18...@revanced/discord-bot@1.0.0-dev.19) (2024-08-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** correct whitelist logic ([49c29be](https://github.com/revanced/revanced-helper/commit/49c29bebfbe348ae4e2cc1b3a83bfa41eb26ccd1))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.18](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.17...@revanced/discord-bot@1.0.0-dev.18) (2024-08-03)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** set the `label` property correctly for message scans ([6d463df](https://github.com/revanced/revanced-helper/commit/6d463df586dee5dd8fe8d6cff1c5316f7809b32a))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.17](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.16...@revanced/discord-bot@1.0.0-dev.17) (2024-08-02)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord/commands/eval:** evaluate in current context ([5925d90](https://github.com/revanced/revanced-helper/commit/5925d902095acef5f6396ca03583a9cbb0862498))
|
||||||
|
* **bots/discord:** send right response for after regexes ([a7688fa](https://github.com/revanced/revanced-helper/commit/a7688fa9b91919a87f74071b502cd0a87cd1c1fa))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** update example config file ([bc9951c](https://github.com/revanced/revanced-helper/commit/bc9951c9b5e007c3e1b3076aa0966ccf29bb18bc))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.16](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.15...@revanced/discord-bot@1.0.0-dev.16) (2024-08-02)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** open database as read-write ([c366840](https://github.com/revanced/revanced-helper/commit/c36684091dddf67880505dc459e4334a8a5492f4))
|
||||||
|
* **bots/discord:** remove bad text channel checks ([f5939e2](https://github.com/revanced/revanced-helper/commit/f5939e25288fea2022fdeec9085ecb9ffada6111))
|
||||||
|
* **bots/discord:** remove redundant footer for response embeds ([412e003](https://github.com/revanced/revanced-helper/commit/412e00317d1eaca23e9c1375e16f94a5f2fa8d86))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord/commands:** add `reload` command ([6875b32](https://github.com/revanced/revanced-helper/commit/6875b32fd0c6ce3034da9dc6c704d425afb26f2e))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.15](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.14...@revanced/discord-bot@1.0.0-dev.15) (2024-07-31)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** import `config` from context ([763ef25](https://github.com/revanced/revanced-helper/commit/763ef253f9d4ff70a8b79969a7f4f41cba7f3c59))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add sticky messages ([bf66155](https://github.com/revanced/revanced-helper/commit/bf661556e131bf0ef24e47f658fbcd701960e312))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.14](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.13...@revanced/discord-bot@1.0.0-dev.14) (2024-07-31)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** always true check causing no messages to be scanned ([98ec37b](https://github.com/revanced/revanced-helper/commit/98ec37b5d18cade85270ab83b0ed0abe41244dd9))
|
||||||
|
* other small issues ([bc437a5](https://github.com/revanced/revanced-helper/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add more options for curing, fix default regex ([1a4ec1e](https://github.com/revanced/revanced-helper/commit/1a4ec1ece80becd9156582cc490f6681cb2a1f39))
|
||||||
|
* **bots/discord:** allow admins to bypass permission checks ([620f933](https://github.com/revanced/revanced-helper/commit/620f9339f0737b79d72c66d90ffa42ea3f987710))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.13](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.12...@revanced/discord-bot@1.0.0-dev.13) (2024-07-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** broken regex when prefix set to special characters ([ab62e55](https://github.com/revanced/revanced-helper/commit/ab62e55e76005f5999d7413d1158e54053f28d1f))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.12](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.11...@revanced/discord-bot@1.0.0-dev.12) (2024-07-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** deployment runtime errors due to minification ([a60c60c](https://github.com/revanced/revanced-helper/commit/a60c60c0f994a4c256b7d0582e99a1731209cf49))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.11](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.10...@revanced/discord-bot@1.0.0-dev.11) (2024-07-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** reset counter when reconnected to api, redo message scan filter logic ([d234d79](https://github.com/revanced/revanced-helper/commit/d234d79310caed9c43e14a905f9ef46a110e071d))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.10](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.9...@revanced/discord-bot@1.0.0-dev.10) (2024-07-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** hanging process when disconnecting from API too many times ([d31616e](https://github.com/revanced/revanced-helper/commit/d31616ebcba6f1dcd8bde183bcb8d1adb1501b61))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.9](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.8...@revanced/discord-bot@1.0.0-dev.9) (2024-07-30)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** framework changes and new features ([646ec8d](https://github.com/revanced/revanced-helper/commit/646ec8da87617e6c8f48a89e8054e2cba91da549))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.8](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.7...@revanced/discord-bot@1.0.0-dev.8) (2024-07-28)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** cross-device link build errors ([38c0699](https://github.com/revanced/revanced-helper/commit/38c06997b4d0f7bb3f1e62618a5e3f088c522e30))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** blacklist and whitelist for filters ([cdb6001](https://github.com/revanced/revanced-helper/commit/cdb600195520dba33110c40841629259e317055e))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.7](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.6...@revanced/discord-bot@1.0.0-dev.7) (2024-07-25)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bot/discord:** start remove preset timeout for `role-preset` command ([cbf9116](https://github.com/revanced/revanced-helper/commit/cbf91162e27dd4c1ecb976927ab708f1d882abca))
|
||||||
|
* **bots/discord:** only check for member permissions when specified while correcting responses ([b79a1c7](https://github.com/revanced/revanced-helper/commit/b79a1c7575e94c3e62654c87775cac497be4a50a))
|
||||||
|
* **bots/discord:** set timeout for eligible mutes to unmute faster ([1f5c5a9](https://github.com/revanced/revanced-helper/commit/1f5c5a92a639973b83a1204355538936e69a4454))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** add `replyToReplied` option in response config ([27662ed](https://github.com/revanced/revanced-helper/commit/27662ed91a79bfac7d3f091834e859a7b57366ce))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.6](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.5...@revanced/discord-bot@1.0.0-dev.6) (2024-07-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** ci issues causing database to not be auto generated ([673aa18](https://github.com/revanced/revanced-helper/commit/673aa189bef1009a3e32ba3b1291a5ee84f2def3))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.5](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.4...@revanced/discord-bot@1.0.0-dev.5) (2024-07-23)
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.4](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.3...@revanced/discord-bot@1.0.0-dev.4) (2024-07-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** wrong database schema path ([875bd20](https://github.com/revanced/revanced-helper/commit/875bd209b252566414bf89349839cabc01697e1c))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.3](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.2...@revanced/discord-bot@1.0.0-dev.3) (2024-07-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **bots/discord:** revert dist denesting, fixes config not found ([0d4898d](https://github.com/revanced/revanced-helper/commit/0d4898dae8b26f8466d3f6b8f62875866f581644))
|
||||||
|
|
||||||
|
# @revanced/discord-bot [1.0.0-dev.2](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.1...@revanced/discord-bot@1.0.0-dev.2) (2024-07-23)
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* **bots/discord:** don't nest builds in src directory, autogen db when missing ([4834685](https://github.com/revanced/revanced-helper/commit/48346851864c4d4b6276388644dd24ce16222b3e))
|
||||||
|
|
||||||
# @revanced/discord-bot 1.0.0-dev.1 (2024-07-22)
|
# @revanced/discord-bot 1.0.0-dev.1 (2024-07-22)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ FROM base AS build
|
|||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN bun install --frozen-lockfile
|
RUN bun install --frozen-lockfile
|
||||||
RUN cd bots/discord && bun --bun run build
|
RUN cd bots/discord && bun run build
|
||||||
|
|
||||||
FROM base AS release
|
FROM base AS release
|
||||||
|
|
||||||
@@ -15,4 +15,4 @@ COPY --from=build /build/bots/discord/dist /app
|
|||||||
|
|
||||||
USER 1000:1000
|
USER 1000:1000
|
||||||
|
|
||||||
ENTRYPOINT [ "bun", "run", "index.js" ]
|
ENTRYPOINT [ "bun", "--bun", "run", "src/index.js" ]
|
||||||
|
|||||||
@@ -4,10 +4,28 @@
|
|||||||
* @type {import('./config.schema').Config}
|
* @type {import('./config.schema').Config}
|
||||||
*/
|
*/
|
||||||
export default {
|
export default {
|
||||||
owners: ['USER_ID_HERE'],
|
prefix: '!',
|
||||||
guilds: ['GUILD_ID_HERE'],
|
admin: {
|
||||||
|
users: ['USER_ID_HERE'],
|
||||||
|
roles: {
|
||||||
|
GUILD_ID_HERE: ['ROLE_ID_HERE'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
stickyMessages: {
|
||||||
|
GUILD_ID_HERE: {
|
||||||
|
CHANNEL_ID_HERE: {
|
||||||
|
message: {
|
||||||
|
content: 'This is a sticky message!',
|
||||||
|
},
|
||||||
|
timeout: 60000,
|
||||||
|
forceSendTimeout: 300000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
moderation: {
|
moderation: {
|
||||||
cure: {
|
cure: {
|
||||||
|
minimumNameLength: 3,
|
||||||
|
removeCharactersRegex: /[^a-zA-Z0-9 \-_]/g,
|
||||||
defaultName: 'Server member',
|
defaultName: 'Server member',
|
||||||
},
|
},
|
||||||
roles: ['ROLE_ID_HERE'],
|
roles: ['ROLE_ID_HERE'],
|
||||||
@@ -33,14 +51,21 @@ export default {
|
|||||||
checkExpiredEvery: 3600,
|
checkExpiredEvery: 3600,
|
||||||
},
|
},
|
||||||
messageScan: {
|
messageScan: {
|
||||||
|
scanBots: false,
|
||||||
|
scanOutsideGuilds: false,
|
||||||
filter: {
|
filter: {
|
||||||
|
whitelist: {
|
||||||
channels: ['CHANNEL_ID_HERE'],
|
channels: ['CHANNEL_ID_HERE'],
|
||||||
roles: ['ROLE_ID_HERE'],
|
roles: ['ROLE_ID_HERE'],
|
||||||
users: ['USER_ID_HERE'],
|
users: ['USER_ID_HERE'],
|
||||||
whitelist: false,
|
},
|
||||||
|
blacklist: {
|
||||||
|
channels: ['CHANNEL_ID_HERE'],
|
||||||
|
roles: ['ROLE_ID_HERE'],
|
||||||
|
users: ['USER_ID_HERE'],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
humanCorrections: {
|
humanCorrections: {
|
||||||
falsePositiveLabel: 'false_positive',
|
|
||||||
allow: {
|
allow: {
|
||||||
members: {
|
members: {
|
||||||
permissions: 8n,
|
permissions: 8n,
|
||||||
@@ -48,13 +73,31 @@ export default {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
allowedAttachmentMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
|
attachments: {
|
||||||
|
scanAttachments: true,
|
||||||
|
allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp', 'text/plain'],
|
||||||
|
maxTextFileSize: 512000,
|
||||||
|
},
|
||||||
responses: [
|
responses: [
|
||||||
{
|
{
|
||||||
|
filterOverride: {
|
||||||
|
whitelist: {
|
||||||
|
channels: ['CHANNEL_ID_HERE'],
|
||||||
|
roles: ['ROLE_ID_HERE'],
|
||||||
|
users: ['USER_ID_HERE'],
|
||||||
|
},
|
||||||
|
blacklist: {
|
||||||
|
channels: ['CHANNEL_ID_HERE'],
|
||||||
|
roles: ['ROLE_ID_HERE'],
|
||||||
|
users: ['USER_ID_HERE'],
|
||||||
|
},
|
||||||
|
},
|
||||||
triggers: {
|
triggers: {
|
||||||
text: [/^regexp?$/, { label: 'label', threshold: 0.85 }],
|
text: [/^regexp?$/, { label: 'label', threshold: 0.85 }],
|
||||||
},
|
},
|
||||||
response: {
|
response: {
|
||||||
|
embeds: [
|
||||||
|
{
|
||||||
title: 'Embed title',
|
title: 'Embed title',
|
||||||
description: 'Embed description',
|
description: 'Embed description',
|
||||||
fields: [
|
fields: [
|
||||||
@@ -64,6 +107,8 @@ export default {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import type { APIEmbed } from 'discord.js'
|
import type { BaseMessageOptions } from 'discord.js'
|
||||||
|
|
||||||
export type Config = {
|
export type Config = {
|
||||||
owners: string[]
|
prefix?: string
|
||||||
guilds: string[]
|
admin?: {
|
||||||
|
users?: string[]
|
||||||
|
roles?: Record<string, string[]>
|
||||||
|
}
|
||||||
|
stickyMessages?: Record<string, Record<string, StickyMessageConfig>>
|
||||||
moderation?: {
|
moderation?: {
|
||||||
roles: string[]
|
roles: string[]
|
||||||
cure?: {
|
cure?: {
|
||||||
|
minimumNameLength?: number
|
||||||
|
removeCharactersRegex?: RegExp
|
||||||
defaultName: string
|
defaultName: string
|
||||||
}
|
}
|
||||||
log?: {
|
log?: {
|
||||||
@@ -18,15 +24,18 @@ export type Config = {
|
|||||||
guilds: Record<string, Record<string, RolePresetConfig>>
|
guilds: Record<string, Record<string, RolePresetConfig>>
|
||||||
}
|
}
|
||||||
messageScan?: {
|
messageScan?: {
|
||||||
allowedAttachmentMimeTypes: string[]
|
scanBots?: boolean
|
||||||
filter: {
|
scanOutsideGuilds?: boolean
|
||||||
roles?: string[]
|
attachments?: {
|
||||||
users?: string[]
|
scanAttachments?: boolean
|
||||||
channels?: string[]
|
allowedMimeTypes?: string[]
|
||||||
whitelist: boolean
|
maxTextFileSize?: number
|
||||||
|
}
|
||||||
|
filter?: {
|
||||||
|
whitelist?: Filter
|
||||||
|
blacklist?: Filter
|
||||||
}
|
}
|
||||||
humanCorrections: {
|
humanCorrections: {
|
||||||
falsePositiveLabel: string
|
|
||||||
allow?: {
|
allow?: {
|
||||||
users?: string[]
|
users?: string[]
|
||||||
members?: {
|
members?: {
|
||||||
@@ -45,6 +54,12 @@ export type Config = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type StickyMessageConfig = {
|
||||||
|
timeout: number
|
||||||
|
forceSendTimeout?: number
|
||||||
|
message: BaseMessageOptions
|
||||||
|
}
|
||||||
|
|
||||||
export type RolePresetConfig = {
|
export type RolePresetConfig = {
|
||||||
give: string[]
|
give: string[]
|
||||||
take: string[]
|
take: string[]
|
||||||
@@ -56,7 +71,8 @@ export type ConfigMessageScanResponse = {
|
|||||||
image?: Array<RegExp>
|
image?: Array<RegExp>
|
||||||
}
|
}
|
||||||
filterOverride?: NonNullable<Config['messageScan']>['filter']
|
filterOverride?: NonNullable<Config['messageScan']>['filter']
|
||||||
response: ConfigMessageScanResponseMessage | null
|
response: ConfigMessageScanResponseMessage
|
||||||
|
respondToReply?: boolean | 'only_regex' | 'only_labeled'
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ConfigMessageScanResponseLabelConfig = {
|
export type ConfigMessageScanResponseLabelConfig = {
|
||||||
@@ -70,4 +86,10 @@ export type ConfigMessageScanResponseLabelConfig = {
|
|||||||
threshold: number
|
threshold: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ConfigMessageScanResponseMessage = APIEmbed
|
export type Filter = {
|
||||||
|
roles?: string[]
|
||||||
|
users?: string[]
|
||||||
|
channels?: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ConfigMessageScanResponseMessage = BaseMessageOptions
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ To deploy the bot, you'll need to:
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd /usr/src/discord-bot
|
cd /usr/src/discord-bot
|
||||||
bun run index.js
|
bun run src/index.js
|
||||||
```
|
```
|
||||||
|
|
||||||
## ⏭️ What's next
|
## ⏭️ What's next
|
||||||
|
|||||||
@@ -35,8 +35,6 @@ export default {
|
|||||||
data: new SlashCommandBuilder()
|
data: new SlashCommandBuilder()
|
||||||
.setName("my-command")
|
.setName("my-command")
|
||||||
.setDescription("My cool command")
|
.setDescription("My cool command")
|
||||||
// Allowing this command to be used in DMs
|
|
||||||
.setDMPermission(true)
|
|
||||||
// DO NOT forget this line!
|
// DO NOT forget this line!
|
||||||
.toJSON(),
|
.toJSON(),
|
||||||
|
|
||||||
|
|||||||
@@ -2,20 +2,19 @@
|
|||||||
"name": "@revanced/discord-bot",
|
"name": "@revanced/discord-bot",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.0.0-dev.1",
|
"version": "1.5.1",
|
||||||
"description": "🤖 Discord bot assisting ReVanced",
|
"description": "🤖 Discord bot assisting ReVanced",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"register": "bun run scripts/reload-slash-commands.ts",
|
|
||||||
"start": "bun prepare && bun run src/index.ts",
|
"start": "bun prepare && bun run src/index.ts",
|
||||||
"dev": "bun prepare && bun --watch src/index.ts",
|
"dev": "bun prepare && bun --watch src/index.ts",
|
||||||
"build": "bun prepare && bun run scripts/build.ts",
|
"build": "bun prepare && bun run scripts/build.ts",
|
||||||
"watch": "bun dev",
|
"watch": "bun dev",
|
||||||
"prepare": "bun run scripts/generate-indexes.ts && drizzle-kit generate --name=schema"
|
"prepare": "bun run scripts/generate-indexes.ts && bunx --bun drizzle-kit generate --name=schema"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/revanced/revanced-helper.git",
|
"url": "git+https://github.com/revanced/revanced-bots.git",
|
||||||
"directory": "bots/discord"
|
"directory": "bots/discord"
|
||||||
},
|
},
|
||||||
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
||||||
@@ -25,22 +24,23 @@
|
|||||||
],
|
],
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/revanced/revanced-helper/issues"
|
"url": "https://github.com/revanced/revanced-bots/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
"homepage": "https://github.com/revanced/revanced-bots#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@discordjs/builders": "^1.8.2",
|
"@discordjs/builders": "^1.11.3",
|
||||||
"@discordjs/rest": "^2.3.0",
|
"@discordjs/rest": "^2.6.0",
|
||||||
"@revanced/bot-api": "workspace:*",
|
"@revanced/bot-api": "workspace:*",
|
||||||
"@revanced/bot-shared": "workspace:*",
|
"@revanced/bot-shared": "workspace:*",
|
||||||
"chalk": "^5.3.0",
|
"@sapphire/duration": "^1.2.0",
|
||||||
"decancer": "^3.2.3",
|
"chalk": "^5.6.2",
|
||||||
"discord.js": "^14.15.3",
|
"decancer": "^3.3.3",
|
||||||
"drizzle-orm": "^0.31.4"
|
"discord.js": "^14.22.1",
|
||||||
|
"drizzle-orm": "^0.44.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@libsql/client": "^0.7.0",
|
"@libsql/client": "^0.15.15",
|
||||||
"discord-api-types": "^0.37.92",
|
"discord-api-types": "^0.38.24",
|
||||||
"drizzle-kit": "^0.22.8"
|
"drizzle-kit": "^0.31.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,23 @@
|
|||||||
import { createLogger } from '@revanced/bot-shared'
|
import { createLogger } from '@revanced/bot-shared'
|
||||||
import { cp, rm } from 'fs/promises'
|
import { cp, exists, rm } from 'fs/promises'
|
||||||
|
|
||||||
const logger = createLogger()
|
const logger = createLogger()
|
||||||
|
|
||||||
logger.warn('Cleaning previous build...')
|
logger.warn('Cleaning previous build...')
|
||||||
await rm('./dist', { recursive: true })
|
if (await exists('./dist')) await rm('./dist', { recursive: true })
|
||||||
await rm('./.drizzle', { recursive: true })
|
|
||||||
|
|
||||||
logger.info('Building bot...')
|
logger.info('Building bot...')
|
||||||
await Bun.build({
|
await Bun.build({
|
||||||
entrypoints: ['./src/index.ts'],
|
entrypoints: ['./src/index.ts'],
|
||||||
outdir: './dist',
|
outdir: './dist/src',
|
||||||
target: 'bun',
|
target: 'bun',
|
||||||
external: ['./config.js'],
|
external: ['./config.js'],
|
||||||
minify: true,
|
|
||||||
sourcemap: 'external',
|
sourcemap: 'external',
|
||||||
})
|
})
|
||||||
|
|
||||||
logger.info('Copying config...')
|
logger.info('Copying config...')
|
||||||
await cp('config.js', 'dist/config.js')
|
await cp('./config.js', './dist/config.js')
|
||||||
|
|
||||||
logger.info('Copying database schema...')
|
logger.info('Copying database schema...')
|
||||||
await cp('.drizzle', 'dist/.drizzle', { recursive: true })
|
await cp('./.drizzle', './dist/.drizzle', { recursive: true })
|
||||||
|
await rm('./.drizzle', { recursive: true })
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
import { REST } from '@discordjs/rest'
|
|
||||||
import { getMissingEnvironmentVariables } from '@revanced/bot-shared'
|
|
||||||
import { Routes } from 'discord-api-types/v9'
|
|
||||||
import type {
|
|
||||||
RESTGetCurrentApplicationResult,
|
|
||||||
RESTPutAPIApplicationCommandsResult,
|
|
||||||
RESTPutAPIApplicationGuildCommandsResult,
|
|
||||||
} from 'discord.js'
|
|
||||||
import { config, discord, logger } from '../src/context'
|
|
||||||
|
|
||||||
// Check if token exists
|
|
||||||
|
|
||||||
const missingEnvs = getMissingEnvironmentVariables(['DISCORD_TOKEN'])
|
|
||||||
if (missingEnvs.length) {
|
|
||||||
for (const env of missingEnvs) logger.fatal(`${env} is not defined in environment variables`)
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Group commands by global and guild
|
|
||||||
|
|
||||||
const { global: globalCommands = [], guild: guildCommands = [] } = Object.groupBy(Object.values(discord.commands), c =>
|
|
||||||
c.global ? 'global' : 'guild',
|
|
||||||
)
|
|
||||||
|
|
||||||
// Set commands
|
|
||||||
|
|
||||||
const rest = new REST({ version: '10' }).setToken(process.env['DISCORD_TOKEN']!)
|
|
||||||
|
|
||||||
try {
|
|
||||||
const app = (await rest.get(Routes.currentApplication())) as RESTGetCurrentApplicationResult
|
|
||||||
const data = (await rest.put(Routes.applicationCommands(app.id), {
|
|
||||||
body: globalCommands.map(({ data }) => {
|
|
||||||
if (!data.dm_permission) data.dm_permission = true
|
|
||||||
logger.warn(`Command ${data.name} has no dm_permission set, forcing to true as it is a global command`)
|
|
||||||
return data
|
|
||||||
}),
|
|
||||||
})) as RESTPutAPIApplicationCommandsResult
|
|
||||||
|
|
||||||
logger.info(`Reloaded ${data.length} global commands`)
|
|
||||||
|
|
||||||
for (const guildId of config.guilds) {
|
|
||||||
const data = (await rest.put(Routes.applicationGuildCommands(app.id, guildId), {
|
|
||||||
body: guildCommands.map(x => x.data),
|
|
||||||
})) as RESTPutAPIApplicationGuildCommandsResult
|
|
||||||
|
|
||||||
logger.info(`Reloaded ${data.length} guild commands for guild ${guildId}`)
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.fatal(e)
|
|
||||||
}
|
|
||||||
725
bots/discord/src/classes/Command.ts
Normal file
725
bots/discord/src/classes/Command.ts
Normal file
@@ -0,0 +1,725 @@
|
|||||||
|
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,
|
||||||
|
Channel,
|
||||||
|
ChatInputCommandInteraction,
|
||||||
|
CommandInteraction,
|
||||||
|
CommandInteractionOption,
|
||||||
|
GuildMember,
|
||||||
|
Message,
|
||||||
|
MessageContextMenuCommandInteraction,
|
||||||
|
RESTPostAPIApplicationCommandsJSONBody,
|
||||||
|
RESTPostAPIChatInputApplicationCommandsJSONBody,
|
||||||
|
Role,
|
||||||
|
User,
|
||||||
|
UserContextMenuCommandInteraction,
|
||||||
|
UserResolvable,
|
||||||
|
} from 'discord.js'
|
||||||
|
|
||||||
|
export enum CommandType {
|
||||||
|
ChatGlobal = 1,
|
||||||
|
ChatGuild,
|
||||||
|
ContextMenuUser,
|
||||||
|
ContextMenuMessage,
|
||||||
|
ContextMenuGuildMessage,
|
||||||
|
ContextMenuGuildMember,
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Command<
|
||||||
|
const Type extends CommandType = CommandType.ChatGuild,
|
||||||
|
const Options extends If<IsContextMenu<Type>, undefined, CommandOptionsOptions | undefined> = undefined,
|
||||||
|
const AllowMessageCommand extends If<IsContextMenu<Type>, false, boolean> = false,
|
||||||
|
> {
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
requirements?: CommandRequirements
|
||||||
|
options?: Options
|
||||||
|
type: Type
|
||||||
|
allowMessageCommand: AllowMessageCommand
|
||||||
|
#execute: CommandExecuteFunction<Type, Options, AllowMessageCommand>
|
||||||
|
|
||||||
|
static OptionType = ApplicationCommandOptionType
|
||||||
|
static Type = CommandType
|
||||||
|
|
||||||
|
constructor({
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
requirements,
|
||||||
|
options,
|
||||||
|
type,
|
||||||
|
allowMessageCommand,
|
||||||
|
execute,
|
||||||
|
}: CommandOptions<Type, Options, AllowMessageCommand>) {
|
||||||
|
this.name = name
|
||||||
|
this.description = description!
|
||||||
|
this.requirements = requirements
|
||||||
|
this.options = options
|
||||||
|
// @ts-expect-error: Default is `CommandType.GuildOnly`, it makes sense
|
||||||
|
this.type = type ?? CommandType.ChatGuild
|
||||||
|
// @ts-expect-error: Default is `false`, it makes sense
|
||||||
|
this.allowMessageCommand = allowMessageCommand ?? false
|
||||||
|
this.#execute = execute
|
||||||
|
}
|
||||||
|
|
||||||
|
isGuildSpecific(): this is Command<
|
||||||
|
CommandType.ChatGuild | CommandType.ContextMenuGuildMember | CommandType.ContextMenuGuildMessage,
|
||||||
|
Options,
|
||||||
|
AllowMessageCommand
|
||||||
|
> {
|
||||||
|
return [
|
||||||
|
CommandType.ChatGuild,
|
||||||
|
CommandType.ContextMenuGuildMessage,
|
||||||
|
CommandType.ContextMenuGuildMember,
|
||||||
|
].includes(this.type)
|
||||||
|
}
|
||||||
|
|
||||||
|
isContextMenuSpecific(): this is Command<
|
||||||
|
| CommandType.ContextMenuGuildMessage
|
||||||
|
| CommandType.ContextMenuGuildMember
|
||||||
|
| CommandType.ContextMenuUser
|
||||||
|
| CommandType.ContextMenuMessage,
|
||||||
|
undefined,
|
||||||
|
false
|
||||||
|
> {
|
||||||
|
return [
|
||||||
|
CommandType.ContextMenuMessage,
|
||||||
|
CommandType.ContextMenuUser,
|
||||||
|
CommandType.ContextMenuGuildMessage,
|
||||||
|
CommandType.ContextMenuGuildMember,
|
||||||
|
].includes(this.type)
|
||||||
|
}
|
||||||
|
|
||||||
|
isGuildContextMenuSpecific(): this is Command<
|
||||||
|
CommandType.ContextMenuGuildMessage | CommandType.ContextMenuGuildMember,
|
||||||
|
undefined,
|
||||||
|
false
|
||||||
|
> {
|
||||||
|
return [CommandType.ContextMenuGuildMessage, CommandType.ContextMenuGuildMember].includes(this.type)
|
||||||
|
}
|
||||||
|
|
||||||
|
async onContextMenuInteraction(
|
||||||
|
context: typeof import('../context'),
|
||||||
|
interaction: If<
|
||||||
|
Extends<Type, CommandType.ContextMenuGuildMessage>,
|
||||||
|
MessageContextMenuCommandInteraction<ToCacheType<Type>>,
|
||||||
|
UserContextMenuCommandInteraction<ToCacheType<Type>>
|
||||||
|
>,
|
||||||
|
): Promise<unknown> {
|
||||||
|
if (!this.isGuildSpecific() && !interaction.inGuild())
|
||||||
|
throw new CommandError(CommandErrorType.InteractionNotInGuild)
|
||||||
|
|
||||||
|
const executor = await this.#fetchInteractionExecutor(interaction)
|
||||||
|
const target =
|
||||||
|
this.type === CommandType.ContextMenuGuildMember
|
||||||
|
? this.isGuildSpecific()
|
||||||
|
? fetchMember(interaction as CommandInteraction<'raw' | 'cached'>, interaction.targetId)
|
||||||
|
: interaction.client.users.fetch(interaction.targetId)
|
||||||
|
: interaction.channel?.messages.fetch(interaction.targetId)
|
||||||
|
|
||||||
|
if (!target) throw new CommandError(CommandErrorType.FetchManagerNotFound)
|
||||||
|
|
||||||
|
// @ts-expect-error: Type mismatch (again!) because TypeScript is not smart enough
|
||||||
|
return await this.#execute({ ...context, executor, target }, interaction, undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
async onMessage(
|
||||||
|
context: typeof import('../context'),
|
||||||
|
msg: Message<IsGuildSpecific<Type>>,
|
||||||
|
args: CommandArguments,
|
||||||
|
): Promise<unknown> {
|
||||||
|
if (!this.allowMessageCommand) return
|
||||||
|
if (!this.isGuildSpecific() && !msg.guildId) throw new CommandError(CommandErrorType.InteractionNotInGuild)
|
||||||
|
|
||||||
|
const executor = this.isGuildSpecific()
|
||||||
|
? await msg.guild?.members.fetch(msg.author)!
|
||||||
|
: await msg.client.users.fetch(msg.author)
|
||||||
|
if (!(await this.canExecute(executor))) throw new CommandError(CommandErrorType.RequirementsNotMet)
|
||||||
|
|
||||||
|
const options = this.options
|
||||||
|
? ((await this.#resolveMessageOptions(msg, this.options, args)) as CommandExecuteFunctionOptionsParameter<
|
||||||
|
NonNullable<Options>
|
||||||
|
>)
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
// @ts-expect-error: Type mismatch (again!) because TypeScript is not smart enough
|
||||||
|
return await this.#execute({ ...context, executor }, msg, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
async #resolveMessageOptions(msg: Message, options: CommandOptionsOptions, args: CommandArguments) {
|
||||||
|
const iterableOptions = Object.entries(options)
|
||||||
|
const _options = {} as unknown
|
||||||
|
|
||||||
|
for (let i = 0; i < iterableOptions.length; i++) {
|
||||||
|
const [name, option] = iterableOptions[i]!
|
||||||
|
const { type, required, description } = option
|
||||||
|
const isSubcommandLikeOption =
|
||||||
|
type === ApplicationCommandOptionType.Subcommand ||
|
||||||
|
type === ApplicationCommandOptionType.SubcommandGroup
|
||||||
|
|
||||||
|
const arg = args[i]
|
||||||
|
|
||||||
|
const expectedType = `${ApplicationCommandOptionType[type]}${required ? '' : '?'}`
|
||||||
|
const argExplainationString = `\n-# **${name}**: ${description}`
|
||||||
|
const choicesString =
|
||||||
|
'choices' in option && option.choices
|
||||||
|
? `\n\n-# **AVAILABLE CHOICES**\n${option.choices.map(({ value }) => `- ${value}`).join('\n')}`
|
||||||
|
: ''
|
||||||
|
|
||||||
|
if (isSubcommandLikeOption && !arg)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.MissingArgument,
|
||||||
|
`Missing required subcommand.\n\n-# **AVAILABLE SUBCOMMANDS**\n${iterableOptions.map(([name, { description }]) => `- **${name}**: ${description}`).join('\n')}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (required && !arg)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.MissingArgument,
|
||||||
|
`Missing required argument **${name}** with type **${expectedType}**.${argExplainationString}${choicesString}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (typeof arg === 'object' && arg.type !== type)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Invalid type for argument **${name}**.${argExplainationString}\n\nExpected type: **${expectedType}**\nGot type: **${ApplicationCommandOptionType[arg.type]}**${choicesString}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const argValue = typeof arg === 'string' ? arg : arg?.id
|
||||||
|
|
||||||
|
if (
|
||||||
|
'choices' in option &&
|
||||||
|
option.choices &&
|
||||||
|
!option.choices.some(({ value }) => value === (typeof value === 'number' ? Number(argValue) : argValue))
|
||||||
|
)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Invalid choice for argument **${name}**.\n${argExplainationString}${choicesString}\n`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (argValue && arg) {
|
||||||
|
if (isSubcommandLikeOption) {
|
||||||
|
const [subcommandName, subcommandOption] = iterableOptions.find(([name]) => name === argValue)!
|
||||||
|
|
||||||
|
// @ts-expect-error: Not smart enough, TypeScript :(
|
||||||
|
_options[subcommandName] = await this.#resolveMessageOptions(
|
||||||
|
msg,
|
||||||
|
(subcommandOption as CommandSubcommandLikeOption).options,
|
||||||
|
args.slice(i + 1),
|
||||||
|
)
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
type === ApplicationCommandOptionType.String &&
|
||||||
|
((typeof option.minLength === 'number' && argValue.length < option.minLength) ||
|
||||||
|
(typeof option.maxLength === 'number' && argValue.length > option.maxLength))
|
||||||
|
)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Invalid string length for argument **${name}**.\nLengths allowed: ${option.minLength ?? '(any)'} - ${option.maxLength ?? '(any)'}.${argExplainationString}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (
|
||||||
|
(type === ApplicationCommandOptionType.Channel ||
|
||||||
|
type === ApplicationCommandOptionType.User ||
|
||||||
|
type === ApplicationCommandOptionType.Role) &&
|
||||||
|
Number.isNaN(Number(argValue))
|
||||||
|
)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Malformed ID for argument **${name}**.${argExplainationString}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (type === ApplicationCommandOptionType.Number || type === ApplicationCommandOptionType.Integer) {
|
||||||
|
if (Number.isNaN(Number(argValue)))
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Invalid number for argument **${name}**.${argExplainationString}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (
|
||||||
|
(typeof option.min === 'number' && Number(argValue) < option.min) ||
|
||||||
|
(typeof option.max === 'number' && Number(argValue) > option.max)
|
||||||
|
)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Number out of range for argument **${name}**.\nRange allowed: ${option.min ?? '(any)'} - ${option.max ?? '(any)'}.${argExplainationString}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
type === ApplicationCommandOptionType.Boolean &&
|
||||||
|
!['true', 'false', 'yes', 'no', 'y', 'n', 't', 'f'].includes(argValue)
|
||||||
|
)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`Invalid boolean for argument **${name}**.${argExplainationString}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
// @ts-expect-error: Not smart enough, TypeScript :(
|
||||||
|
_options[name] =
|
||||||
|
type === ApplicationCommandOptionType.Number || type === ApplicationCommandOptionType.Integer
|
||||||
|
? Number(argValue)
|
||||||
|
: type === ApplicationCommandOptionType.Boolean
|
||||||
|
? ['t', 'y', 'yes', 'true'].some(value => value === argValue.toLowerCase())
|
||||||
|
: type === ApplicationCommandOptionType.Channel
|
||||||
|
? await msg.client.channels.fetch(argValue)
|
||||||
|
: type === ApplicationCommandOptionType.User
|
||||||
|
? await msg.client.users.fetch(argValue)
|
||||||
|
: type === ApplicationCommandOptionType.Role
|
||||||
|
? await msg.guild?.roles.fetch(argValue)
|
||||||
|
: argValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _options
|
||||||
|
}
|
||||||
|
|
||||||
|
#fetchInteractionExecutor(interaction: CommandInteraction) {
|
||||||
|
return this.isGuildSpecific()
|
||||||
|
? fetchMember(interaction as CommandInteraction<'raw' | 'cached'>)
|
||||||
|
: fetchUser(interaction)
|
||||||
|
}
|
||||||
|
|
||||||
|
async onInteraction(
|
||||||
|
context: typeof import('../context'),
|
||||||
|
interaction: ChatInputCommandInteraction,
|
||||||
|
): Promise<unknown> {
|
||||||
|
if (interaction.commandName !== this.name)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InteractionDataMismatch,
|
||||||
|
'The interaction command name does not match the expected command name.',
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!this.isGuildSpecific() && !interaction.inGuild())
|
||||||
|
throw new CommandError(CommandErrorType.InteractionNotInGuild)
|
||||||
|
|
||||||
|
const executor = await this.#fetchInteractionExecutor(interaction)
|
||||||
|
if (!(await this.canExecute(executor))) throw new CommandError(CommandErrorType.RequirementsNotMet)
|
||||||
|
|
||||||
|
const options = this.options
|
||||||
|
? ((await this.#resolveInteractionOptions(interaction)) as CommandExecuteFunctionOptionsParameter<
|
||||||
|
NonNullable<Options>
|
||||||
|
>)
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
if (options === null)
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InteractionDataMismatch,
|
||||||
|
'The registered interaction command option type does not match the expected command option type.',
|
||||||
|
)
|
||||||
|
|
||||||
|
// @ts-expect-error: Type mismatch (again!) because TypeScript is not smart enough
|
||||||
|
return await this.#execute({ ...context, executor }, interaction, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
async #resolveInteractionOptions(
|
||||||
|
interaction: ChatInputCommandInteraction,
|
||||||
|
options: readonly CommandInteractionOption[] = interaction.options.data,
|
||||||
|
) {
|
||||||
|
const _options = {} as unknown
|
||||||
|
|
||||||
|
if (this.options)
|
||||||
|
for (const { name, type, value } of options) {
|
||||||
|
if (this.options[name]?.type !== type) return null
|
||||||
|
|
||||||
|
if (
|
||||||
|
type === ApplicationCommandOptionType.Subcommand ||
|
||||||
|
type === ApplicationCommandOptionType.SubcommandGroup
|
||||||
|
) {
|
||||||
|
const subOptions = Object.entries((this.options[name] as CommandSubcommandLikeOption).options)
|
||||||
|
|
||||||
|
// @ts-expect-error: Not smart enough, TypeScript :(
|
||||||
|
_options[name] = await this.#resolveInteractionOptions(interaction, subOptions)
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value) continue
|
||||||
|
|
||||||
|
// @ts-expect-error: Not smart enough, TypeScript :(
|
||||||
|
_options[name] =
|
||||||
|
type === ApplicationCommandOptionType.Channel
|
||||||
|
? await interaction.client.channels.fetch(value as string)
|
||||||
|
: type === ApplicationCommandOptionType.User
|
||||||
|
? await interaction.client.users.fetch(value as string)
|
||||||
|
: type === ApplicationCommandOptionType.Role
|
||||||
|
? await interaction.guild?.roles.fetch(value as string)
|
||||||
|
: value
|
||||||
|
}
|
||||||
|
|
||||||
|
return _options
|
||||||
|
}
|
||||||
|
|
||||||
|
async canExecute(executor: User | GuildMember): Promise<boolean> {
|
||||||
|
if (!this.requirements) return false
|
||||||
|
|
||||||
|
const isExecutorAdmin = isAdmin(executor)
|
||||||
|
if (isExecutorAdmin) return true
|
||||||
|
|
||||||
|
const {
|
||||||
|
adminOnly,
|
||||||
|
roles,
|
||||||
|
permissions,
|
||||||
|
users,
|
||||||
|
mode = 'all',
|
||||||
|
defaultCondition = 'fail',
|
||||||
|
memberRequirementsForUsers = 'pass',
|
||||||
|
} = this.requirements
|
||||||
|
|
||||||
|
const member = this.isGuildSpecific() ? (executor as GuildMember) : null
|
||||||
|
const boolDefaultCondition = defaultCondition !== 'fail'
|
||||||
|
const boolMemberRequirementsForUsers = memberRequirementsForUsers !== 'fail'
|
||||||
|
|
||||||
|
const conditions = [
|
||||||
|
adminOnly ? isExecutorAdmin : boolDefaultCondition,
|
||||||
|
users ? users.includes(executor.id) : boolDefaultCondition,
|
||||||
|
member
|
||||||
|
? roles
|
||||||
|
? roles.some(role => member.roles.cache.has(role))
|
||||||
|
: boolDefaultCondition
|
||||||
|
: boolMemberRequirementsForUsers,
|
||||||
|
member
|
||||||
|
? permissions
|
||||||
|
? member.permissions.has(permissions)
|
||||||
|
: boolDefaultCondition
|
||||||
|
: boolMemberRequirementsForUsers,
|
||||||
|
]
|
||||||
|
|
||||||
|
if (mode === 'all' && conditions.some(condition => !condition)) return false
|
||||||
|
if (mode === 'any' && conditions.every(condition => !condition)) return false
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
get json(): RESTPostAPIApplicationCommandsJSONBody {
|
||||||
|
// @ts-expect-error: I hate union types in TypeScript
|
||||||
|
const base: RESTPostAPIApplicationCommandsJSONBody = {
|
||||||
|
name: this.name,
|
||||||
|
type:
|
||||||
|
this.type === CommandType.ContextMenuGuildMessage || this.type === CommandType.ContextMenuMessage
|
||||||
|
? ApplicationCommandType.Message
|
||||||
|
: this.type === CommandType.ContextMenuGuildMember || this.type === CommandType.ContextMenuUser
|
||||||
|
? ApplicationCommandType.User
|
||||||
|
: ApplicationCommandType.ChatInput,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isContextMenuSpecific()) return base
|
||||||
|
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
description: this.description,
|
||||||
|
options: this.options ? this.#transformOptions(this.options) : undefined,
|
||||||
|
// https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-interaction-context-types
|
||||||
|
contexts: this.isGuildSpecific() ? [0] : [0, 1, 2],
|
||||||
|
} as RESTPostAPIChatInputApplicationCommandsJSONBody & { contexts: Array<0 | 1 | 2> }
|
||||||
|
}
|
||||||
|
|
||||||
|
#transformOptions(optionsObject: Record<string, CommandOption>) {
|
||||||
|
const options: RESTPostAPIChatInputApplicationCommandsJSONBody['options'] = []
|
||||||
|
|
||||||
|
for (const [name, option] of Object.entries(optionsObject)) {
|
||||||
|
options.push({
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: Good enough work here
|
||||||
|
type: option.type as any,
|
||||||
|
name,
|
||||||
|
description: option.description,
|
||||||
|
required: option.required,
|
||||||
|
...(option.type === ApplicationCommandOptionType.Subcommand ||
|
||||||
|
option.type === ApplicationCommandOptionType.SubcommandGroup
|
||||||
|
? {
|
||||||
|
options: this.#transformOptions((option as CommandSubcommandLikeOption).options),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(option.type === ApplicationCommandOptionType.Channel ? { channel_types: option.types } : {}),
|
||||||
|
...(option.type === ApplicationCommandOptionType.Integer ||
|
||||||
|
option.type === ApplicationCommandOptionType.Number
|
||||||
|
? {
|
||||||
|
min_value: option.min,
|
||||||
|
max_value: option.max,
|
||||||
|
choices: option.choices,
|
||||||
|
autocomplete: option.autocomplete,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(option.type === ApplicationCommandOptionType.String
|
||||||
|
? {
|
||||||
|
min_length: option.minLength,
|
||||||
|
max_length: option.maxLength,
|
||||||
|
choices: option.choices,
|
||||||
|
autocomplete: option.autocomplete,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ModerationCommand<
|
||||||
|
Options extends CommandOptionsOptions,
|
||||||
|
AllowMessageCommand extends boolean = true,
|
||||||
|
> extends Command<CommandType.ChatGuild, Options, AllowMessageCommand> {
|
||||||
|
constructor(options: ExtendedCommandOptions<CommandType.ChatGuild, Options, AllowMessageCommand>) {
|
||||||
|
super({
|
||||||
|
...options,
|
||||||
|
requirements: {
|
||||||
|
...options.requirements,
|
||||||
|
defaultCondition: 'pass',
|
||||||
|
roles: (config.moderation?.roles ?? []).concat(options.requirements?.roles ?? []),
|
||||||
|
},
|
||||||
|
// @ts-expect-error: No thanks
|
||||||
|
allowMessageCommand: options.allowMessageCommand ?? true,
|
||||||
|
type: CommandType.ChatGuild,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AdminCommand<
|
||||||
|
Options extends CommandOptionsOptions,
|
||||||
|
AllowMessageCommand extends boolean = true,
|
||||||
|
> extends Command<CommandType.ChatGlobal, Options, AllowMessageCommand> {
|
||||||
|
constructor(options: ExtendedCommandOptions<CommandType.ChatGlobal, Options, AllowMessageCommand>) {
|
||||||
|
super({
|
||||||
|
...options,
|
||||||
|
requirements: {
|
||||||
|
...options.requirements,
|
||||||
|
adminOnly: true,
|
||||||
|
defaultCondition: 'pass',
|
||||||
|
},
|
||||||
|
allowMessageCommand: options.allowMessageCommand ?? (true as AllowMessageCommand),
|
||||||
|
type: CommandType.ChatGlobal,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchMember = async (
|
||||||
|
interaction: CommandInteraction<'raw' | 'cached'>,
|
||||||
|
source: UserResolvable = interaction.user,
|
||||||
|
manager = interaction.guild?.members,
|
||||||
|
) => {
|
||||||
|
const _manager = manager ?? (await interaction.client.guilds.fetch(interaction.guildId).then(it => it.members))
|
||||||
|
if (!_manager) throw new CommandError(CommandErrorType.FetchManagerNotFound, 'Cannot fetch member.')
|
||||||
|
return await _manager.fetch(source)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchUser = (interaction: CommandInteraction, source: UserResolvable = interaction.user) => {
|
||||||
|
return interaction.client.users.fetch(source)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* TODO:
|
||||||
|
APIApplicationCommandAttachmentOption
|
||||||
|
APIApplicationCommandMentionableOption
|
||||||
|
APIApplicationCommandRoleOption
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type CommandOptions<
|
||||||
|
Type extends CommandType,
|
||||||
|
Options extends CommandOptionsOptions | undefined,
|
||||||
|
AllowMessageCommand extends boolean,
|
||||||
|
> = {
|
||||||
|
name: string
|
||||||
|
requirements?: CommandRequirements
|
||||||
|
options?: Options
|
||||||
|
execute: CommandExecuteFunction<Type, Options, AllowMessageCommand>
|
||||||
|
type?: Type
|
||||||
|
allowMessageCommand?: AllowMessageCommand
|
||||||
|
} & If<IsContextMenu<Type>, { description?: never }, { description: string }>
|
||||||
|
|
||||||
|
export type CommandArguments = Array<string | CommandSpecialArgument>
|
||||||
|
export type CommandSpecialArgument = {
|
||||||
|
type: (typeof CommandSpecialArgumentType)[keyof typeof CommandSpecialArgumentType]
|
||||||
|
id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
//! If things ever get minified, this will most likely break property access via string names
|
||||||
|
export const CommandSpecialArgumentType = {
|
||||||
|
Channel: ApplicationCommandOptionType.Channel,
|
||||||
|
Role: ApplicationCommandOptionType.Role,
|
||||||
|
User: ApplicationCommandOptionType.User,
|
||||||
|
}
|
||||||
|
|
||||||
|
type ExtendedCommandOptions<
|
||||||
|
Type extends CommandType,
|
||||||
|
Options extends CommandOptionsOptions,
|
||||||
|
AllowMessageCommand extends boolean,
|
||||||
|
> = Omit<CommandOptions<Type, Options, AllowMessageCommand>, 'type'> & {
|
||||||
|
requirements?: Omit<CommandOptions<Type, Options, AllowMessageCommand>['requirements'], 'defaultCondition'>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CommandOptionsOptions = Record<string, CommandOption>
|
||||||
|
|
||||||
|
type ToCacheType<Type extends CommandType> = If<IsGuildSpecific<Type>, 'raw' | 'cached', CacheType>
|
||||||
|
|
||||||
|
type CommandExecuteFunction<
|
||||||
|
Type extends CommandType,
|
||||||
|
Options extends CommandOptionsOptions | undefined,
|
||||||
|
AllowMessageCommand extends boolean,
|
||||||
|
> = (
|
||||||
|
context: CommandContext<Type>,
|
||||||
|
trigger: If<
|
||||||
|
AllowMessageCommand,
|
||||||
|
Message<IsGuildSpecific<Type>> | CommandTypeToInteractionMap<ToCacheType<Type>>[Type],
|
||||||
|
CommandTypeToInteractionMap<ToCacheType<Type>>[Type]
|
||||||
|
>,
|
||||||
|
options: Options extends CommandOptionsOptions ? CommandExecuteFunctionOptionsParameter<Options> : never,
|
||||||
|
) => Promise<unknown> | unknown
|
||||||
|
|
||||||
|
type CommandTypeToInteractionMap<CT extends CacheType> = {
|
||||||
|
[CommandType.ChatGlobal]: ChatInputCommandInteraction<CT>
|
||||||
|
[CommandType.ChatGuild]: ChatInputCommandInteraction<CT>
|
||||||
|
[CommandType.ContextMenuUser]: UserContextMenuCommandInteraction<CT>
|
||||||
|
[CommandType.ContextMenuMessage]: MessageContextMenuCommandInteraction<CT>
|
||||||
|
[CommandType.ContextMenuGuildMessage]: MessageContextMenuCommandInteraction<CT>
|
||||||
|
[CommandType.ContextMenuGuildMember]: MessageContextMenuCommandInteraction<CT>
|
||||||
|
}
|
||||||
|
|
||||||
|
type IsContextMenu<Type extends CommandType> = Extends<
|
||||||
|
Type,
|
||||||
|
| CommandType.ContextMenuGuildMessage
|
||||||
|
| CommandType.ContextMenuGuildMember
|
||||||
|
| CommandType.ContextMenuMessage
|
||||||
|
| CommandType.ContextMenuUser
|
||||||
|
>
|
||||||
|
|
||||||
|
type IsGuildSpecific<Type extends CommandType> = Extends<
|
||||||
|
Type,
|
||||||
|
CommandType.ChatGuild | CommandType.ContextMenuGuildMember | CommandType.ContextMenuGuildMessage
|
||||||
|
>
|
||||||
|
|
||||||
|
type Extends<T, U> = T extends U ? true : false
|
||||||
|
type If<T extends boolean | undefined, U, V> = T extends true ? U : V
|
||||||
|
// type InvertBoolean<T extends boolean> = If<T, false, true>
|
||||||
|
|
||||||
|
type CommandExecuteFunctionOptionsParameter<Options extends CommandOptionsOptions> = {
|
||||||
|
[K in keyof Options]: Options[K]['type'] extends
|
||||||
|
| ApplicationCommandOptionType.Subcommand
|
||||||
|
| ApplicationCommandOptionType.SubcommandGroup
|
||||||
|
? // @ts-expect-error: Shut up, it works
|
||||||
|
CommandExecuteFunctionOptionsParameter<Options[K]['options']> | undefined
|
||||||
|
: If<
|
||||||
|
Options[K]['required'],
|
||||||
|
CommandOptionValueMap[Options[K]['type']],
|
||||||
|
CommandOptionValueMap[Options[K]['type']] | undefined
|
||||||
|
>
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandContext<Type extends CommandType> = typeof import('../context') & {
|
||||||
|
executor: CommandExecutor<Type>
|
||||||
|
target: If<
|
||||||
|
Extends<Type, CommandType.ContextMenuGuildMember>,
|
||||||
|
GuildMember,
|
||||||
|
If<Extends<Type, CommandType.ContextMenuGuildMessage>, Message<true>, never>
|
||||||
|
>
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandOptionValueMap = {
|
||||||
|
[ApplicationCommandOptionType.Boolean]: boolean
|
||||||
|
[ApplicationCommandOptionType.Channel]: Channel
|
||||||
|
[ApplicationCommandOptionType.Integer]: number
|
||||||
|
[ApplicationCommandOptionType.Number]: number
|
||||||
|
[ApplicationCommandOptionType.String]: string
|
||||||
|
[ApplicationCommandOptionType.User]: User
|
||||||
|
[ApplicationCommandOptionType.Role]: Role
|
||||||
|
[ApplicationCommandOptionType.Subcommand]: never
|
||||||
|
[ApplicationCommandOptionType.SubcommandGroup]: never
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandOption =
|
||||||
|
| CommandBooleanOption
|
||||||
|
| CommandChannelOption
|
||||||
|
| CommandIntegerOption
|
||||||
|
| CommandNumberOption
|
||||||
|
| CommandStringOption
|
||||||
|
| CommandUserOption
|
||||||
|
| CommandRoleOption
|
||||||
|
| CommandSubcommandOption
|
||||||
|
| CommandSubcommandGroupOption
|
||||||
|
|
||||||
|
type CommandExecutor<Type extends CommandType> = If<IsGuildSpecific<Type>, GuildMember, User>
|
||||||
|
|
||||||
|
type CommandOptionBase<Type extends ApplicationCommandOptionType> = {
|
||||||
|
type: Type
|
||||||
|
description: string
|
||||||
|
required?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandBooleanOption = CommandOptionBase<ApplicationCommandOptionType.Boolean>
|
||||||
|
|
||||||
|
type CommandChannelOption = CommandOptionBase<ApplicationCommandOptionType.Channel> & {
|
||||||
|
types: APIApplicationCommandChannelOption['channel_types']
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CommandOptionChoice<ValueType = number | string> {
|
||||||
|
name: string
|
||||||
|
value: ValueType
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandOptionWithAutocompleteOrChoicesWrapper<
|
||||||
|
Base extends CommandOptionBase<ApplicationCommandOptionType>,
|
||||||
|
ChoiceType extends CommandOptionChoice,
|
||||||
|
> =
|
||||||
|
| (Base & {
|
||||||
|
autocomplete: true
|
||||||
|
choices?: never
|
||||||
|
})
|
||||||
|
| (Base & {
|
||||||
|
autocomplete?: false
|
||||||
|
choices?: ChoiceType[] | readonly ChoiceType[]
|
||||||
|
})
|
||||||
|
|
||||||
|
type CommandIntegerOption = CommandOptionWithAutocompleteOrChoicesWrapper<
|
||||||
|
CommandOptionBase<ApplicationCommandOptionType.Integer>,
|
||||||
|
CommandOptionChoice<number>
|
||||||
|
> & {
|
||||||
|
min?: number
|
||||||
|
max?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandNumberOption = CommandOptionWithAutocompleteOrChoicesWrapper<
|
||||||
|
CommandOptionBase<ApplicationCommandOptionType.Number>,
|
||||||
|
CommandOptionChoice<number>
|
||||||
|
> & {
|
||||||
|
min?: number
|
||||||
|
max?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandStringOption = CommandOptionWithAutocompleteOrChoicesWrapper<
|
||||||
|
CommandOptionBase<ApplicationCommandOptionType.String>,
|
||||||
|
CommandOptionChoice<string>
|
||||||
|
> & {
|
||||||
|
minLength?: number
|
||||||
|
maxLength?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandUserOption = CommandOptionBase<ApplicationCommandOptionType.User>
|
||||||
|
|
||||||
|
type CommandRoleOption = CommandOptionBase<ApplicationCommandOptionType.Role>
|
||||||
|
|
||||||
|
type SubcommandLikeApplicationCommandOptionType =
|
||||||
|
| ApplicationCommandOptionType.Subcommand
|
||||||
|
| ApplicationCommandOptionType.SubcommandGroup
|
||||||
|
|
||||||
|
interface CommandSubcommandLikeOption<
|
||||||
|
Type extends SubcommandLikeApplicationCommandOptionType = SubcommandLikeApplicationCommandOptionType,
|
||||||
|
> extends CommandOptionBase<Type> {
|
||||||
|
options: CommandOptionsOptions
|
||||||
|
required?: never
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandSubcommandOption = CommandSubcommandLikeOption<ApplicationCommandOptionType.Subcommand>
|
||||||
|
type CommandSubcommandGroupOption = CommandSubcommandLikeOption<ApplicationCommandOptionType.SubcommandGroup>
|
||||||
|
|
||||||
|
export type CommandRequirements = {
|
||||||
|
users?: string[]
|
||||||
|
roles?: string[]
|
||||||
|
permissions?: bigint
|
||||||
|
adminOnly?: boolean
|
||||||
|
defaultCondition?: 'fail' | 'pass'
|
||||||
|
memberRequirementsForUsers?: 'fail' | 'pass'
|
||||||
|
mode?: 'all' | 'any'
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { createErrorEmbed } from '$/utils/discord/embeds'
|
import { createErrorEmbed } from '../utils/discord/embeds'
|
||||||
|
|
||||||
export default class CommandError extends Error {
|
export default class CommandError extends Error {
|
||||||
type: CommandErrorType
|
type: CommandErrorType
|
||||||
|
|
||||||
constructor(type: CommandErrorType, message?: string) {
|
constructor(type: CommandErrorType, message: string = ErrorMessageMap[type]) {
|
||||||
super(message)
|
super(message)
|
||||||
this.name = 'CommandError'
|
this.name = 'CommandError'
|
||||||
this.type = type
|
this.type = type
|
||||||
@@ -15,17 +15,34 @@ export default class CommandError extends Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export enum CommandErrorType {
|
export enum CommandErrorType {
|
||||||
Generic,
|
Generic = 1,
|
||||||
|
InteractionNotInGuild,
|
||||||
|
InteractionDataMismatch,
|
||||||
|
FetchManagerNotFound,
|
||||||
|
FetchNotFound,
|
||||||
|
RequirementsNotMet = 100,
|
||||||
MissingArgument,
|
MissingArgument,
|
||||||
InvalidUser,
|
InvalidArgument,
|
||||||
InvalidChannel,
|
|
||||||
InvalidDuration,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const ErrorTitleMap: Record<CommandErrorType, string> = {
|
const ErrorTitleMap: Record<CommandErrorType, string> = {
|
||||||
[CommandErrorType.Generic]: 'An exception was thrown',
|
[CommandErrorType.Generic]: 'An exception was thrown',
|
||||||
|
[CommandErrorType.InteractionNotInGuild]: 'This command can only be used in servers',
|
||||||
|
[CommandErrorType.InteractionDataMismatch]: 'Command data mismatch',
|
||||||
|
[CommandErrorType.FetchManagerNotFound]: 'Cannot fetch data (manager not found)',
|
||||||
|
[CommandErrorType.FetchNotFound]: 'Cannot fetch data (source not found)',
|
||||||
|
[CommandErrorType.RequirementsNotMet]: 'Command requirements not met',
|
||||||
[CommandErrorType.MissingArgument]: 'Missing argument',
|
[CommandErrorType.MissingArgument]: 'Missing argument',
|
||||||
[CommandErrorType.InvalidUser]: 'Invalid user',
|
[CommandErrorType.InvalidArgument]: 'Invalid argument',
|
||||||
[CommandErrorType.InvalidChannel]: 'Invalid channel',
|
}
|
||||||
[CommandErrorType.InvalidDuration]: 'Invalid duration',
|
|
||||||
|
const ErrorMessageMap: Record<CommandErrorType, string> = {
|
||||||
|
[CommandErrorType.Generic]: 'An generic exception was thrown.',
|
||||||
|
[CommandErrorType.InteractionNotInGuild]: 'This command can only be used in servers.',
|
||||||
|
[CommandErrorType.InteractionDataMismatch]: 'Interaction command data does not match the expected command data.',
|
||||||
|
[CommandErrorType.FetchManagerNotFound]: 'Cannot fetch required data.',
|
||||||
|
[CommandErrorType.FetchNotFound]: 'Cannot fetch target.',
|
||||||
|
[CommandErrorType.RequirementsNotMet]: 'You do not meet the requirements to use this command.',
|
||||||
|
[CommandErrorType.MissingArgument]: 'You are missing a required argument.',
|
||||||
|
[CommandErrorType.InvalidArgument]: 'You provided an invalid argument.',
|
||||||
}
|
}
|
||||||
|
|||||||
94
bots/discord/src/commands/admin/eval.ts
Normal file
94
bots/discord/src/commands/admin/eval.ts
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
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 { AdminCommand } from '$/classes/Command'
|
||||||
|
import { createSuccessEmbed } from '$/utils/discord/embeds'
|
||||||
|
import { parseDuration } from '$/utils/duration'
|
||||||
|
|
||||||
|
export default new AdminCommand({
|
||||||
|
name: 'eval',
|
||||||
|
description: 'Make the bot less sentient by evaluating code',
|
||||||
|
options: {
|
||||||
|
code: {
|
||||||
|
description: 'The code to evaluate',
|
||||||
|
type: ApplicationCommandOptionType.String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
['show-hidden']: {
|
||||||
|
description: 'Show hidden properties',
|
||||||
|
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, 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,
|
||||||
|
createContext({
|
||||||
|
...globalThis,
|
||||||
|
context,
|
||||||
|
trigger,
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
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({
|
||||||
|
embeds: [embed],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
files,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (files.length) unlinkSync(filepath)
|
||||||
|
},
|
||||||
|
})
|
||||||
23
bots/discord/src/commands/admin/exception-test.ts
Normal file
23
bots/discord/src/commands/admin/exception-test.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApplicationCommandOptionType } from 'discord.js'
|
||||||
|
import { AdminCommand } from '$/classes/Command'
|
||||||
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
|
|
||||||
|
export default new AdminCommand({
|
||||||
|
name: 'exception-test',
|
||||||
|
description: 'Makes the bot intentionally hate you by throwing an exception',
|
||||||
|
options: {
|
||||||
|
type: {
|
||||||
|
description: 'The type of exception to throw',
|
||||||
|
type: ApplicationCommandOptionType.String,
|
||||||
|
required: true,
|
||||||
|
choices: [
|
||||||
|
{ name: 'Process', value: 'Process' },
|
||||||
|
...Object.keys(CommandErrorType).map(k => ({ name: k, value: k })),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute(_, __, { type }) {
|
||||||
|
if (type === 'Process') throw new Error('Intentional process exception')
|
||||||
|
throw new CommandError(CommandErrorType[type as keyof typeof CommandErrorType], 'Intentional bot design') // ;)
|
||||||
|
},
|
||||||
|
})
|
||||||
39
bots/discord/src/commands/admin/reload.ts
Normal file
39
bots/discord/src/commands/admin/reload.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { type CommandInteraction, MessageFlags } from 'discord.js'
|
||||||
|
import { AdminCommand } from '$/classes/Command'
|
||||||
|
|
||||||
|
export default new AdminCommand({
|
||||||
|
name: 'reload',
|
||||||
|
description: 'Reload configuration',
|
||||||
|
async execute(context, trigger) {
|
||||||
|
const { api, logger, discord } = context
|
||||||
|
logger.info(`Reload triggered by ${context.executor.tag} (${context.executor.id})`)
|
||||||
|
|
||||||
|
logger.debug('Invalidating previous config...')
|
||||||
|
context.config.invalidate()
|
||||||
|
|
||||||
|
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(
|
||||||
|
{
|
||||||
|
url: context.config.api.url,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
api.intentionallyDisconnecting = true
|
||||||
|
api.client.disconnect(true)
|
||||||
|
api.disconnectCount = 0
|
||||||
|
api.intentionallyDisconnecting = false
|
||||||
|
api.client.connect()
|
||||||
|
|
||||||
|
logger.info('Reinitializing Discord client to reload configuration...')
|
||||||
|
await discord.client.destroy()
|
||||||
|
// discord.client.token only gets set whenever a new Client is intialized
|
||||||
|
// so that's why we need to provide the token here :/
|
||||||
|
await discord.client.login(process.env['DISCORD_TOKEN'])
|
||||||
|
|
||||||
|
// @ts-expect-error: TypeScript dum
|
||||||
|
await trigger['deferReply' in trigger ? 'editReply' : 'reply']({ content: 'Reloaded configuration' })
|
||||||
|
},
|
||||||
|
})
|
||||||
91
bots/discord/src/commands/admin/slash-commands.ts
Normal file
91
bots/discord/src/commands/admin/slash-commands.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
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 = {
|
||||||
|
where: {
|
||||||
|
description: 'Where to register the commands',
|
||||||
|
type: ApplicationCommandOptionType.String,
|
||||||
|
choices: [
|
||||||
|
{ name: 'globally', value: 'global' },
|
||||||
|
{ name: 'this server', value: 'server' },
|
||||||
|
],
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export default new AdminCommand({
|
||||||
|
name: 'slash-commands',
|
||||||
|
description: 'Register or delete slash commands',
|
||||||
|
options: {
|
||||||
|
register: {
|
||||||
|
description: 'Register slash commands',
|
||||||
|
type: ApplicationCommandOptionType.Subcommand,
|
||||||
|
options: SubcommandOptions,
|
||||||
|
},
|
||||||
|
delete: {
|
||||||
|
description: 'Delete slash commands',
|
||||||
|
type: ApplicationCommandOptionType.Subcommand,
|
||||||
|
options: SubcommandOptions,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
allowMessageCommand: true,
|
||||||
|
async execute(context, trigger, { delete: deleteOption, register }) {
|
||||||
|
const action = register ? 'register' : 'delete'
|
||||||
|
const { where } = (deleteOption ?? register)!
|
||||||
|
|
||||||
|
if (!trigger.inGuild())
|
||||||
|
throw new CommandError(CommandErrorType.Generic, 'This command can only be used in a server.')
|
||||||
|
|
||||||
|
const { global: globalCommands, guild: guildCommands } = Object.groupBy(
|
||||||
|
Object.values(context.discord.commands),
|
||||||
|
cmd => (cmd.isGuildSpecific() ? 'guild' : 'global'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const {
|
||||||
|
client,
|
||||||
|
client: { rest },
|
||||||
|
} = trigger
|
||||||
|
|
||||||
|
let response: string | undefined
|
||||||
|
|
||||||
|
switch (action) {
|
||||||
|
case 'register':
|
||||||
|
if (where === 'global') {
|
||||||
|
response = 'Registered global slash commands'
|
||||||
|
|
||||||
|
await rest.put(Routes.applicationCommands(client.application.id), {
|
||||||
|
body: globalCommands?.map(c => c.json),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
response = 'Registered slash commands on this server'
|
||||||
|
|
||||||
|
await rest.put(Routes.applicationGuildCommands(client.application.id, trigger.guildId), {
|
||||||
|
body: guildCommands?.map(c => c.json),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'delete':
|
||||||
|
if (where === 'global') {
|
||||||
|
response = 'Deleted global slash commands'
|
||||||
|
|
||||||
|
await rest.put(Routes.applicationCommands(client.application.id), {
|
||||||
|
body: [],
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
response = 'Deleted slash commands on this server'
|
||||||
|
|
||||||
|
await rest.put(Routes.applicationGuildCommands(client.application.id, trigger.guildId), {
|
||||||
|
body: [],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
await trigger.reply({ embeds: [createSuccessEmbed(response!)] })
|
||||||
|
},
|
||||||
|
})
|
||||||
25
bots/discord/src/commands/admin/stop.ts
Normal file
25
bots/discord/src/commands/admin/stop.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { MessageFlags } from 'discord.js'
|
||||||
|
import { AdminCommand } from '$/classes/Command'
|
||||||
|
|
||||||
|
export default new AdminCommand({
|
||||||
|
name: 'stop',
|
||||||
|
description: "You don't want to run this unless the bot starts to go insane, and like, you really need to stop it.",
|
||||||
|
async execute({ api, logger, executor }, trigger) {
|
||||||
|
api.intentionallyDisconnecting = true
|
||||||
|
|
||||||
|
logger.fatal('Stopping bot...')
|
||||||
|
trigger.reply({
|
||||||
|
content: 'Stopping... (I will go offline once done)',
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!api.client.disconnected) api.client.disconnect()
|
||||||
|
logger.warn('Disconnected from API')
|
||||||
|
|
||||||
|
trigger.client.destroy()
|
||||||
|
logger.warn('Disconnected from Discord API')
|
||||||
|
|
||||||
|
logger.info(`Bot stopped, requested by ${executor.id}`)
|
||||||
|
process.exit(0)
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { inspect } from 'util'
|
|
||||||
import { SlashCommandBuilder } from 'discord.js'
|
|
||||||
|
|
||||||
import { createSuccessEmbed } from '$/utils/discord/embeds'
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
data: new SlashCommandBuilder()
|
|
||||||
.setName('eval')
|
|
||||||
.setDescription('Make the bot less sentient by evaluating code')
|
|
||||||
.addStringOption(option => option.setName('code').setDescription('The code to evaluate').setRequired(true))
|
|
||||||
.setDMPermission(true)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
ownerOnly: true,
|
|
||||||
global: true,
|
|
||||||
|
|
||||||
async execute(_, interaction) {
|
|
||||||
const code = interaction.options.getString('code', true)
|
|
||||||
|
|
||||||
await interaction.reply({
|
|
||||||
ephemeral: true,
|
|
||||||
embeds: [
|
|
||||||
createSuccessEmbed('Evaluate', `\`\`\`js\n${code}\`\`\``).addFields({
|
|
||||||
name: 'Result',
|
|
||||||
// biome-ignore lint/security/noGlobalEval: Deal with it
|
|
||||||
value: `\`\`\`js\n${inspect(eval(code), { depth: 1 })}\`\`\``,
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
},
|
|
||||||
} satisfies Command
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
|
||||||
|
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
data: new SlashCommandBuilder()
|
|
||||||
.setName('exception-test')
|
|
||||||
.setDescription('Makes the bot intentionally hate you by throwing an exception')
|
|
||||||
.addStringOption(option =>
|
|
||||||
option
|
|
||||||
.setName('type')
|
|
||||||
.setDescription('The type of exception to throw')
|
|
||||||
.setRequired(true)
|
|
||||||
.addChoices(
|
|
||||||
Object.keys(CommandErrorType).map(
|
|
||||||
k =>
|
|
||||||
({
|
|
||||||
name: k,
|
|
||||||
value: k,
|
|
||||||
}) as const,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.setDMPermission(true)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
ownerOnly: true,
|
|
||||||
global: true,
|
|
||||||
|
|
||||||
async execute(_, interaction) {
|
|
||||||
const type = interaction.options.getString('type', true)
|
|
||||||
if (type === 'Process') throw new Error('Intentional process exception')
|
|
||||||
throw new CommandError(CommandErrorType[type as keyof typeof CommandErrorType], 'Intentional bot design') // ;)
|
|
||||||
},
|
|
||||||
} satisfies Command
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
|
||||||
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
data: new SlashCommandBuilder()
|
|
||||||
.setName('stop')
|
|
||||||
.setDescription(
|
|
||||||
"You don't want to run this unless the bot starts to go insane, and like, you really need to stop it.",
|
|
||||||
)
|
|
||||||
.setDMPermission(true)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
ownerOnly: true,
|
|
||||||
global: true,
|
|
||||||
|
|
||||||
async execute({ api, logger }, interaction) {
|
|
||||||
api.isStopping = true
|
|
||||||
|
|
||||||
logger.fatal('Stopping bot...')
|
|
||||||
await interaction.reply({
|
|
||||||
content: 'Stopping... (I will go offline once done)',
|
|
||||||
ephemeral: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
api.client.disconnect()
|
|
||||||
logger.warn('Disconnected from API')
|
|
||||||
|
|
||||||
await interaction.client.destroy()
|
|
||||||
logger.warn('Disconnected from Discord API')
|
|
||||||
|
|
||||||
logger.info(`Bot stopped, requested by ${interaction.user.id}`)
|
|
||||||
process.exit(0)
|
|
||||||
},
|
|
||||||
} satisfies Command
|
|
||||||
@@ -1,32 +1,37 @@
|
|||||||
|
import { EmbedBuilder, MessageFlags } from 'discord.js'
|
||||||
|
import Command from '$/classes/Command'
|
||||||
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
|
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
|
||||||
|
|
||||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'
|
export default new Command({
|
||||||
|
name: 'coinflip',
|
||||||
import type { Command } from '../types'
|
description: 'Do a coinflip!',
|
||||||
|
type: Command.Type.ChatGlobal,
|
||||||
export default {
|
requirements: {
|
||||||
data: new SlashCommandBuilder().setName('coinflip').setDescription('Do a coinflip!').setDMPermission(true).toJSON(),
|
defaultCondition: 'pass',
|
||||||
global: true,
|
},
|
||||||
|
allowMessageCommand: true,
|
||||||
async execute(_, interaction) {
|
async execute(_, trigger) {
|
||||||
const result = Math.random() < 0.5 ? ('heads' as const) : ('tails' as const)
|
const result = Math.random() < 0.5 ? ('heads' as const) : ('tails' as const)
|
||||||
const embed = applyCommonEmbedStyles(new EmbedBuilder().setTitle('Flipping... 🪙'), true, false, false)
|
const embed = applyCommonEmbedStyles(new EmbedBuilder().setTitle('Flipping... 🪙'), false, false, true)
|
||||||
|
|
||||||
await interaction.reply({
|
const reply = await trigger
|
||||||
|
.reply({
|
||||||
embeds: [embed.toJSON()],
|
embeds: [embed.toJSON()],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
})
|
})
|
||||||
|
.then(it => it.fetch())
|
||||||
|
|
||||||
embed.setTitle(`The coin landed on... **${result.toUpperCase()}**! ${EmojiMap[result]}`)
|
embed.setTitle(`The coin landed on... **${result.toUpperCase()}**! ${EmojiMap[result]}`)
|
||||||
|
|
||||||
setTimeout(
|
setTimeout(
|
||||||
() =>
|
() =>
|
||||||
interaction.editReply({
|
reply.edit({
|
||||||
embeds: [embed.toJSON()],
|
embeds: [embed.toJSON()],
|
||||||
}),
|
}),
|
||||||
1500,
|
1500,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|
||||||
const EmojiMap: Record<'heads' | 'tails', string> = {
|
const EmojiMap: Record<'heads' | 'tails', string> = {
|
||||||
heads: '🤯',
|
heads: '🤯',
|
||||||
|
|||||||
@@ -1,44 +1,46 @@
|
|||||||
import { SlashCommandBuilder, type TextBasedChannel } from 'discord.js'
|
import { ApplicationCommandOptionType, Message, MessageFlags } from 'discord.js'
|
||||||
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
|
import { ModerationCommand } from '../../classes/Command'
|
||||||
|
|
||||||
import { config } from '$/context'
|
export default new ModerationCommand({
|
||||||
import type { Command } from '../types'
|
name: 'reply',
|
||||||
|
description: 'Send a message as the bot',
|
||||||
export default {
|
options: {
|
||||||
data: new SlashCommandBuilder()
|
message: {
|
||||||
.setName('reply')
|
description: 'The message to send',
|
||||||
.setDescription('Send a message as the bot')
|
required: true,
|
||||||
.addStringOption(option => option.setName('message').setDescription('The message to send').setRequired(true))
|
type: ApplicationCommandOptionType.String,
|
||||||
.addStringOption(option =>
|
|
||||||
option
|
|
||||||
.setName('reference')
|
|
||||||
.setDescription('The message ID to reply to (use `latest` to reply to the latest message)')
|
|
||||||
.setRequired(false),
|
|
||||||
)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
memberRequirements: {
|
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
reference: {
|
||||||
|
description: 'The message ID to reply to (use `latest` to reply to the latest message)',
|
||||||
|
required: false,
|
||||||
|
type: ApplicationCommandOptionType.String,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
allowMessageCommand: false,
|
||||||
|
async execute({ logger, executor }, trigger, { reference: ref, message: msg }) {
|
||||||
|
if (trigger instanceof Message) return
|
||||||
|
|
||||||
global: false,
|
const channel = await trigger.guild!.channels.fetch(trigger.channelId)
|
||||||
|
if (!channel?.isTextBased())
|
||||||
async execute({ logger }, interaction) {
|
throw new CommandError(
|
||||||
const msg = interaction.options.getString('message', true)
|
CommandErrorType.InvalidArgument,
|
||||||
const ref = interaction.options.getString('reference')
|
'This command can only be used in or on text channels',
|
||||||
|
)
|
||||||
const channel = (await interaction.guild!.channels.fetch(interaction.channelId)) as TextBasedChannel
|
const refMsg = ref?.startsWith('latest')
|
||||||
const refMsg = ref?.startsWith('latest') ? (await channel.messages.fetch({ limit: 1 })).at(0)?.id : ref
|
? await channel.messages.fetch({ limit: 1 }).then(it => it.first())
|
||||||
|
: ref
|
||||||
|
|
||||||
await channel.send({
|
await channel.send({
|
||||||
content: msg,
|
content: msg,
|
||||||
reply: refMsg ? { messageReference: refMsg, failIfNotExists: true } : undefined,
|
reply: refMsg ? { messageReference: refMsg, failIfNotExists: true } : undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
logger.info(`User ${interaction.user.tag} made the bot say: ${msg}`)
|
logger.info(`User ${executor.user.tag} made the bot say: ${msg}`)
|
||||||
|
|
||||||
await interaction.reply({
|
await trigger.reply({
|
||||||
content: 'OK!',
|
content: 'OK!',
|
||||||
ephemeral: true,
|
flags: MessageFlags.Ephemeral,
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,58 +1,59 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
import { config } from '$/context'
|
|
||||||
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
||||||
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
||||||
import { parseDuration } from '$/utils/duration'
|
import { parseDuration } from '$/utils/duration'
|
||||||
|
|
||||||
export default {
|
export default new ModerationCommand({
|
||||||
data: new SlashCommandBuilder()
|
name: 'ban',
|
||||||
.setName('ban')
|
description: 'Ban a user',
|
||||||
.setDescription('Ban a user')
|
options: {
|
||||||
.addUserOption(option => option.setName('user').setRequired(true).setDescription('The user to ban'))
|
user: {
|
||||||
.addStringOption(option => option.setName('reason').setDescription('The reason for banning the user'))
|
description: 'The user to ban',
|
||||||
.addStringOption(option =>
|
required: true,
|
||||||
option.setName('dmd').setDescription('Duration to delete messages (must be from 0 to 7 days)'),
|
type: ModerationCommand.OptionType.User,
|
||||||
)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
memberRequirements: {
|
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
reason: {
|
||||||
|
description: 'The reason for banning the user',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
dmt: {
|
||||||
|
description:
|
||||||
|
'Time duration to delete messages (default time unit is days, must be from 0s to 7d, default is 0s)',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
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)
|
||||||
|
|
||||||
global: false,
|
if (member) {
|
||||||
|
if (!member.bannable)
|
||||||
async execute({ logger }, interaction) {
|
throw new CommandError(CommandErrorType.Generic, 'This user cannot be banned by the bot.')
|
||||||
const user = interaction.options.getUser('user', true)
|
|
||||||
const reason = interaction.options.getString('reason') ?? 'No reason provided'
|
|
||||||
const dmd = interaction.options.getString('dmd')
|
|
||||||
|
|
||||||
const member = await interaction.guild!.members.fetch(user.id)
|
|
||||||
const moderator = await interaction.guild!.members.fetch(interaction.user.id)
|
|
||||||
|
|
||||||
if (member.bannable) throw new CommandError(CommandErrorType.Generic, 'This user cannot be banned by the bot.')
|
|
||||||
|
|
||||||
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
|
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidUser,
|
CommandErrorType.InvalidArgument,
|
||||||
'You cannot ban a user with a role equal to or higher than yours.',
|
'You cannot ban a user with a role equal to or higher than yours.',
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
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, {
|
await interaction.guild!.members.ban(user, {
|
||||||
reason: `Banned by moderator ${interaction.user.tag} (${interaction.user.id}): ${reason}`,
|
reason: `Banned by moderator ${executor.user.tag} (${executor.id}): ${reason}`,
|
||||||
deleteMessageSeconds: dms,
|
deleteMessageSeconds: dms,
|
||||||
})
|
})
|
||||||
|
|
||||||
await sendModerationReplyAndLogs(
|
await sendModerationReplyAndLogs(
|
||||||
interaction,
|
interaction,
|
||||||
createModerationActionEmbed('Banned', user, interaction.user, reason),
|
createModerationActionEmbed('Banned', user, executor.user, reason),
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
`${interaction.user.tag} (${interaction.user.id}) banned ${user.tag} (${user.id}) because ${reason}, deleting their messages sent in the previous ${dms}s`,
|
`${executor.user.tag} (${executor.id}) banned ${user.tag} (${user.id}) because ${reason}, deleting their messages sent in the previous ${dms}s`,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,31 +1,25 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
import { MessageFlags } from 'discord.js'
|
||||||
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
import { config } from '$/context'
|
|
||||||
import { createSuccessEmbed } from '$/utils/discord/embeds'
|
import { createSuccessEmbed } from '$/utils/discord/embeds'
|
||||||
import { cureNickname } from '$/utils/discord/moderation'
|
import { cureNickname } from '$/utils/discord/moderation'
|
||||||
|
|
||||||
export default {
|
export default new ModerationCommand({
|
||||||
data: new SlashCommandBuilder()
|
name: 'cure',
|
||||||
.setName('cure')
|
description: "Cure a member's nickname",
|
||||||
.setDescription("Cure a member's nickname")
|
options: {
|
||||||
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to cure'))
|
member: {
|
||||||
.toJSON(),
|
description: 'The member to cure',
|
||||||
|
required: true,
|
||||||
memberRequirements: {
|
type: ModerationCommand.OptionType.User,
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
},
|
||||||
global: false,
|
async execute(_, interaction, { member: user }) {
|
||||||
|
const guild = await interaction.client.guilds.fetch(interaction.guildId)
|
||||||
async execute(_, interaction) {
|
const member = await guild.members.fetch(user)
|
||||||
const user = interaction.options.getUser('member', true)
|
|
||||||
const member = await interaction.guild!.members.fetch(user.id)
|
|
||||||
await cureNickname(member)
|
await cureNickname(member)
|
||||||
await interaction.reply({
|
await interaction.reply({
|
||||||
embeds: [createSuccessEmbed(null, `Cured nickname for ${member.toString()}`)],
|
embeds: [createSuccessEmbed(null, `Cured nickname for ${member.toString()}`)],
|
||||||
ephemeral: true,
|
flags: MessageFlags.Ephemeral,
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,67 +1,75 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
|
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
import { applyRolePreset } from '$/utils/discord/rolePresets'
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
import { config } from '$/context'
|
|
||||||
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
||||||
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
||||||
import { parseDuration } from '$/utils/duration'
|
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
|
||||||
|
import { isSafeTimeoutDuration, parseDuration } from '$/utils/duration'
|
||||||
|
|
||||||
export default {
|
export default new ModerationCommand({
|
||||||
data: new SlashCommandBuilder()
|
name: 'mute',
|
||||||
.setName('mute')
|
description: 'Mute a member',
|
||||||
.setDescription('Mute a member')
|
options: {
|
||||||
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to mute'))
|
member: {
|
||||||
.addStringOption(option => option.setName('reason').setDescription('The reason for muting the member'))
|
description: 'The member to mute',
|
||||||
.addStringOption(option => option.setName('duration').setDescription('The duration of the mute'))
|
required: true,
|
||||||
.toJSON(),
|
type: ModerationCommand.OptionType.User,
|
||||||
|
|
||||||
memberRequirements: {
|
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
duration: {
|
||||||
|
description: 'The duration of the mute (default time unit is minutes)',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
reason: {
|
||||||
|
description: 'The reason for muting the member',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute(
|
||||||
|
{ logger, executor },
|
||||||
|
interaction,
|
||||||
|
{ member: user, reason = 'No reason provided', duration: durationInput },
|
||||||
|
) {
|
||||||
|
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, 'm') : Infinity
|
||||||
|
|
||||||
global: false,
|
if (Number.isInteger(duration) && duration! < 1)
|
||||||
|
|
||||||
async execute({ logger }, interaction, { userIsOwner }) {
|
|
||||||
const user = interaction.options.getUser('member', true)
|
|
||||||
const reason = interaction.options.getString('reason') ?? 'No reason provided'
|
|
||||||
const duration = interaction.options.getString('duration')
|
|
||||||
const durationMs = duration ? parseDuration(duration) : null
|
|
||||||
|
|
||||||
if (Number.isInteger(durationMs) && durationMs! < 1)
|
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidDuration,
|
CommandErrorType.InvalidArgument,
|
||||||
'The duration must be at least 1 millisecond long.',
|
'The duration must be at least 1 millisecond long.',
|
||||||
)
|
)
|
||||||
|
|
||||||
const expires = durationMs ? Date.now() + durationMs : null
|
const expires = Math.max(duration, Date.now() + duration)
|
||||||
const moderator = await interaction.guild!.members.fetch(interaction.user.id)
|
|
||||||
const member = await interaction.guild!.members.fetch(user.id)
|
|
||||||
if (!member)
|
if (!member)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidUser,
|
CommandErrorType.InvalidArgument,
|
||||||
'The provided member is not in the server or does not exist.',
|
'The provided member is not in the server or does not exist.',
|
||||||
)
|
)
|
||||||
|
|
||||||
if (!member.manageable)
|
if (!member.manageable)
|
||||||
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
|
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
|
||||||
|
|
||||||
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0 && !userIsOwner)
|
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidUser,
|
CommandErrorType.InvalidArgument,
|
||||||
'You cannot mute a user with a role equal to or higher than yours.',
|
'You cannot mute a user with a role equal to or higher than yours.',
|
||||||
)
|
)
|
||||||
|
|
||||||
await applyRolePreset(member, 'mute', durationMs ? Date.now() + durationMs : null)
|
await applyRolePreset(member, 'mute', expires)
|
||||||
await sendModerationReplyAndLogs(
|
await sendModerationReplyAndLogs(
|
||||||
interaction,
|
interaction,
|
||||||
createModerationActionEmbed('Muted', user, interaction.user, reason, durationMs),
|
createModerationActionEmbed('Muted', user, executor.user, reason, Math.ceil(expires / 1000)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (isSafeTimeoutDuration(duration))
|
||||||
|
setTimeout(() => {
|
||||||
|
removeRolePreset(member, 'mute')
|
||||||
|
}, duration)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
`Moderator ${interaction.user.tag} (${interaction.user.id}) muted ${user.tag} (${user.id}) until ${expires} because ${reason}`,
|
`Moderator ${executor.user.tag} (${executor.user.id}) muted ${user.tag} (${user.id}) until ${expires} because ${reason}`,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,43 +1,37 @@
|
|||||||
import { EmbedBuilder, GuildChannel, SlashCommandBuilder } from 'discord.js'
|
import { EmbedBuilder } from 'discord.js'
|
||||||
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
import { config } from '$/context'
|
|
||||||
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
|
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
|
||||||
|
|
||||||
import type { Command } from '../types'
|
export default new ModerationCommand({
|
||||||
|
name: 'purge',
|
||||||
export default {
|
description: 'Purge messages from a channel',
|
||||||
data: new SlashCommandBuilder()
|
options: {
|
||||||
.setName('purge')
|
amount: {
|
||||||
.setDescription('Purge messages from a channel')
|
description: 'The amount of messages to remove',
|
||||||
.addIntegerOption(option =>
|
required: false,
|
||||||
option.setName('amount').setDescription('The amount of messages to remove').setMaxValue(100).setMinValue(1),
|
type: ModerationCommand.OptionType.Integer,
|
||||||
)
|
min: 1,
|
||||||
.addUserOption(option =>
|
max: 100,
|
||||||
option.setName('user').setDescription('The user to remove messages from (needs `until`)'),
|
|
||||||
)
|
|
||||||
.addStringOption(option =>
|
|
||||||
option.setName('until').setDescription('The message ID to remove messages until (overrides `amount`)'),
|
|
||||||
)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
memberRequirements: {
|
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
user: {
|
||||||
global: false,
|
description: 'The user to remove messages from (needs `until`)',
|
||||||
|
required: false,
|
||||||
async execute({ logger }, interaction) {
|
type: ModerationCommand.OptionType.User,
|
||||||
const amount = interaction.options.getInteger('amount')
|
},
|
||||||
const user = interaction.options.getUser('user')
|
until: {
|
||||||
const until = interaction.options.getString('until')
|
description: 'The message ID to remove messages until (overrides `amount`)',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute({ logger, executor }, interaction, { amount, user, until }) {
|
||||||
if (!amount && !until)
|
if (!amount && !until)
|
||||||
throw new CommandError(CommandErrorType.MissingArgument, 'Either `amount` or `until` must be provided.')
|
throw new CommandError(CommandErrorType.MissingArgument, 'Either `amount` or `until` must be provided.')
|
||||||
|
|
||||||
const channel = interaction.channel!
|
const channel = interaction.channel!
|
||||||
if (!(channel.isTextBased() && channel instanceof GuildChannel))
|
if (!channel.isTextBased())
|
||||||
throw new CommandError(CommandErrorType.InvalidChannel, 'The supplied channel is not a text channel.')
|
throw new CommandError(CommandErrorType.InvalidArgument, 'The supplied channel is not a text channel.')
|
||||||
|
|
||||||
const embed = applyCommonEmbedStyles(
|
const embed = applyCommonEmbedStyles(
|
||||||
new EmbedBuilder({
|
new EmbedBuilder({
|
||||||
@@ -59,8 +53,9 @@ export default {
|
|||||||
await channel.bulkDelete(messages, true)
|
await channel.bulkDelete(messages, true)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
`Moderator ${interaction.user.tag} (${interaction.user.id}) purged ${messages.size} messages in #${channel.name} (${channel.id})`,
|
`Moderator ${executor.user.tag} (${executor.id}) purged ${messages.size} messages in #${channel.name} (${channel.id})`,
|
||||||
)
|
)
|
||||||
|
|
||||||
await reply.edit({
|
await reply.edit({
|
||||||
embeds: [
|
embeds: [
|
||||||
embed.setTitle('Purged messages').setDescription(null).addFields({
|
embed.setTitle('Purged messages').setDescription(null).addFields({
|
||||||
@@ -70,4 +65,4 @@ export default {
|
|||||||
],
|
],
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,84 +1,95 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
|
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
import { sendPresetReplyAndLogs } from '$/utils/discord/moderation'
|
import { sendPresetReplyAndLogs } from '$/utils/discord/moderation'
|
||||||
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
|
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
|
||||||
import { parseDuration } from '$/utils/duration'
|
import { isSafeTimeoutDuration, parseDuration } from '$/utils/duration'
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
export default {
|
const SubcommandOptions = {
|
||||||
data: new SlashCommandBuilder()
|
member: {
|
||||||
.setName('role-preset')
|
description: 'The member to manage',
|
||||||
.setDescription('Manage role presets for a member')
|
required: true,
|
||||||
.addStringOption(option =>
|
type: ModerationCommand.OptionType.User,
|
||||||
option
|
|
||||||
.setName('action')
|
|
||||||
.setRequired(true)
|
|
||||||
.setDescription('The action to perform')
|
|
||||||
.addChoices([
|
|
||||||
{ name: 'apply', value: 'apply' },
|
|
||||||
{ name: 'remove', value: 'remove' },
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to manage'))
|
|
||||||
.addStringOption(option =>
|
|
||||||
option.setName('preset').setRequired(true).setDescription('The preset to apply or remove'),
|
|
||||||
)
|
|
||||||
.addStringOption(option =>
|
|
||||||
option.setName('duration').setDescription('The duration to apply the preset for (only for apply action)'),
|
|
||||||
)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
memberRequirements: {
|
|
||||||
roles: ['955220417969262612', '973886585294704640'],
|
|
||||||
},
|
},
|
||||||
|
preset: {
|
||||||
|
description: 'The preset to manage',
|
||||||
|
required: true,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
duration: {
|
||||||
|
description: 'The duration to apply the preset for (only for apply action, default time unit is minutes)',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.String,
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
global: false,
|
export default new ModerationCommand({
|
||||||
|
name: 'role-preset',
|
||||||
|
description: 'Manage role presets for a member',
|
||||||
|
options: {
|
||||||
|
apply: {
|
||||||
|
description: 'Apply a role preset to a member',
|
||||||
|
type: ModerationCommand.OptionType.Subcommand,
|
||||||
|
options: SubcommandOptions,
|
||||||
|
},
|
||||||
|
remove: {
|
||||||
|
description: 'Remove a role preset from a member',
|
||||||
|
type: ModerationCommand.OptionType.Subcommand,
|
||||||
|
options: SubcommandOptions,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute({ logger, executor }, trigger, { apply, remove }) {
|
||||||
|
let expires: number | undefined
|
||||||
|
const { member: user, duration: durationInput, preset } = (apply ?? remove)!
|
||||||
|
const moderator = await trigger.guild!.members.fetch(executor.user.id)
|
||||||
|
const member = await trigger.guild!.members.fetch(user.id)
|
||||||
|
|
||||||
async execute({ logger }, interaction, { userIsOwner }) {
|
|
||||||
const action = interaction.options.getString('action', true) as 'apply' | 'remove'
|
|
||||||
const user = interaction.options.getUser('member', true)
|
|
||||||
const preset = interaction.options.getString('preset', true)
|
|
||||||
const duration = interaction.options.getString('duration')
|
|
||||||
|
|
||||||
let expires: number | null | undefined = undefined
|
|
||||||
const moderator = await interaction.guild!.members.fetch(interaction.user.id)
|
|
||||||
const member = await interaction.guild!.members.fetch(user.id)
|
|
||||||
if (!member)
|
if (!member)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidUser,
|
CommandErrorType.InvalidArgument,
|
||||||
'The provided member is not in the server or does not exist.',
|
'The provided member is not in the server or does not exist.',
|
||||||
)
|
)
|
||||||
|
|
||||||
if (!member.manageable)
|
if (!member.manageable)
|
||||||
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
|
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
|
||||||
|
|
||||||
if (action === 'apply') {
|
if (apply) {
|
||||||
const durationMs = duration ? parseDuration(duration) : null
|
const duration = durationInput ? parseDuration(durationInput, 'm') : Infinity
|
||||||
if (Number.isInteger(durationMs) && durationMs! < 1)
|
if (Number.isInteger(duration) && duration! < 1)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidDuration,
|
CommandErrorType.InvalidArgument,
|
||||||
'The duration must be at least 1 millisecond long.',
|
'The duration must be at least 1 millisecond long.',
|
||||||
)
|
)
|
||||||
|
|
||||||
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0 && !userIsOwner)
|
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidUser,
|
CommandErrorType.InvalidArgument,
|
||||||
'You cannot apply a role preset to a user with a role equal to or higher than yours.',
|
'You cannot apply a role preset to a user with a role equal to or higher than yours.',
|
||||||
)
|
)
|
||||||
|
|
||||||
expires = durationMs ? Date.now() + durationMs : null
|
expires = Math.max(duration, Date.now() + duration)
|
||||||
await applyRolePreset(member, preset, expires)
|
await applyRolePreset(member, preset, expires)
|
||||||
logger.info(
|
logger.info(
|
||||||
`Moderator ${interaction.user.tag} (${interaction.user.id}) applied role preset ${preset} to ${user.id} until ${expires}`,
|
`Moderator ${executor.user.tag} (${executor.user.id}) applied role preset ${preset} to ${user.id} until ${expires}`,
|
||||||
)
|
)
|
||||||
} else if (action === 'remove') {
|
} else if (remove) {
|
||||||
await removeRolePreset(member, preset)
|
await removeRolePreset(member, preset)
|
||||||
logger.info(
|
logger.info(
|
||||||
`Moderator ${interaction.user.tag} (${interaction.user.id}) removed role preset ${preset} from ${user.id}`,
|
`Moderator ${executor.user.tag} (${executor.user.id}) removed role preset ${preset} from ${user.id}`,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
await sendPresetReplyAndLogs(action, interaction, user, preset, expires)
|
if (expires && isSafeTimeoutDuration(expires))
|
||||||
|
setTimeout(() => {
|
||||||
|
removeRolePreset(member, preset)
|
||||||
|
}, expires)
|
||||||
|
|
||||||
|
await sendPresetReplyAndLogs(
|
||||||
|
apply ? 'apply' : 'remove',
|
||||||
|
trigger,
|
||||||
|
executor,
|
||||||
|
user,
|
||||||
|
preset,
|
||||||
|
expires ? Math.ceil(expires / 1000) : undefined,
|
||||||
|
)
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,55 +1,40 @@
|
|||||||
|
import { ChannelType } from 'discord.js'
|
||||||
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
import { createSuccessEmbed } from '$/utils/discord/embeds'
|
import { createSuccessEmbed } from '$/utils/discord/embeds'
|
||||||
import { durationToString, parseDuration } from '$/utils/duration'
|
import { durationToString, parseDuration } from '$/utils/duration'
|
||||||
|
|
||||||
import { SlashCommandBuilder } from 'discord.js'
|
export default new ModerationCommand({
|
||||||
|
name: 'slowmode',
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
description: 'Set a slowmode for a channel',
|
||||||
import { config } from '$/context'
|
options: {
|
||||||
import type { Command } from '../types'
|
duration: {
|
||||||
|
description: 'The duration to set (default time unit is seconds)',
|
||||||
export default {
|
required: true,
|
||||||
data: new SlashCommandBuilder()
|
type: ModerationCommand.OptionType.String,
|
||||||
.setName('slowmode')
|
|
||||||
.setDescription('Set a slowmode for the current channel')
|
|
||||||
.addStringOption(option => option.setName('duration').setDescription('The duration to set').setRequired(true))
|
|
||||||
.addStringOption(option =>
|
|
||||||
option
|
|
||||||
.setName('channel')
|
|
||||||
.setDescription('The channel to set the slowmode on (defaults to current channel)')
|
|
||||||
.setRequired(false),
|
|
||||||
)
|
|
||||||
.toJSON(),
|
|
||||||
|
|
||||||
memberRequirements: {
|
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
channel: {
|
||||||
|
description: 'The channel to set the slowmode on (defaults to current channel)',
|
||||||
|
required: false,
|
||||||
|
type: ModerationCommand.OptionType.Channel,
|
||||||
|
types: [ChannelType.GuildText],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute({ logger, executor }, interaction, { duration: durationInput, channel: channelInput }) {
|
||||||
|
const channel = channelInput ?? (await interaction.guild!.channels.fetch(interaction.channelId))
|
||||||
|
const duration = parseDuration(durationInput, 's')
|
||||||
|
|
||||||
global: false,
|
if (!channel?.isTextBased() || channel.isDMBased())
|
||||||
|
throw new CommandError(CommandErrorType.InvalidArgument, 'The supplied channel is not a text channel.')
|
||||||
|
|
||||||
async execute({ logger }, interaction) {
|
if (Number.isNaN(duration)) throw new CommandError(CommandErrorType.InvalidArgument, 'Invalid duration.')
|
||||||
const durationStr = interaction.options.getString('duration', true)
|
|
||||||
const id = interaction.options.getChannel('channel')?.id ?? interaction.channelId
|
|
||||||
|
|
||||||
const duration = parseDuration(durationStr)
|
|
||||||
const channel = await interaction.guild!.channels.fetch(id)
|
|
||||||
|
|
||||||
if (!channel?.isTextBased())
|
|
||||||
throw new CommandError(
|
|
||||||
CommandErrorType.InvalidChannel,
|
|
||||||
'The supplied channel is not a text channel or does not exist.',
|
|
||||||
)
|
|
||||||
|
|
||||||
if (Number.isNaN(duration)) throw new CommandError(CommandErrorType.InvalidDuration, 'Invalid duration.')
|
|
||||||
if (duration < 0 || duration > 36e4)
|
if (duration < 0 || duration > 36e4)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidDuration,
|
CommandErrorType.InvalidArgument,
|
||||||
'Duration out of range, must be between 0s and 6h.',
|
'Duration out of range, must be between 0s and 6h.',
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.info(`Setting slowmode to ${duration}ms on ${channel.id}`)
|
await channel.setRateLimitPerUser(duration / 1000, `Set by ${executor.user.tag} (${executor.id})`)
|
||||||
|
|
||||||
await channel.setRateLimitPerUser(duration / 1000, `Set by ${interaction.user.tag} (${interaction.user.id})`)
|
|
||||||
|
|
||||||
await interaction.reply({
|
await interaction.reply({
|
||||||
embeds: [
|
embeds: [
|
||||||
createSuccessEmbed(
|
createSuccessEmbed(
|
||||||
@@ -59,7 +44,7 @@ export default {
|
|||||||
})
|
})
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
`${interaction.user.tag} (${interaction.user.id}) set the slowmode on ${channel.name} (${channel.id}) to ${duration}ms`,
|
`${executor.user.tag} (${executor.id}) set the slowmode on ${channel.name} (${channel.id}) to ${duration}ms`,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
@@ -1,33 +1,21 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
import { config } from '$/context'
|
|
||||||
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
||||||
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
||||||
|
|
||||||
export default {
|
export default new ModerationCommand({
|
||||||
data: new SlashCommandBuilder()
|
name: 'unban',
|
||||||
.setName('unban')
|
description: 'Unban a user',
|
||||||
.setDescription('Unban a user')
|
options: {
|
||||||
.addUserOption(option => option.setName('user').setRequired(true).setDescription('The user to unban'))
|
user: {
|
||||||
.toJSON(),
|
description: 'The user to unban',
|
||||||
|
required: true,
|
||||||
memberRequirements: {
|
type: ModerationCommand.OptionType.User,
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
|
||||||
global: false,
|
|
||||||
|
|
||||||
async execute({ logger }, interaction) {
|
|
||||||
const user = interaction.options.getUser('user', true)
|
|
||||||
|
|
||||||
await interaction.guild!.members.unban(
|
|
||||||
user,
|
|
||||||
`Unbanned by moderator ${interaction.user.tag} (${interaction.user.id})`,
|
|
||||||
)
|
|
||||||
|
|
||||||
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unbanned', user, interaction.user))
|
|
||||||
logger.info(`${interaction.user.tag} (${interaction.user.id}) unbanned ${user.tag} (${user.id})`)
|
|
||||||
},
|
},
|
||||||
} satisfies Command
|
async execute({ logger, executor }, interaction, { user }) {
|
||||||
|
await interaction.guild!.members.unban(user, `Unbanned by moderator ${executor.user.tag} (${executor.id})`)
|
||||||
|
|
||||||
|
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unbanned', user, executor.user))
|
||||||
|
logger.info(`${executor.user.tag} (${executor.id}) unbanned ${user.tag} (${user.id})`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,33 +1,26 @@
|
|||||||
import { SlashCommandBuilder } from 'discord.js'
|
import { and, eq } from 'drizzle-orm'
|
||||||
|
import { ModerationCommand } from '$/classes/Command'
|
||||||
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
import { config } from '$/context'
|
|
||||||
import { appliedPresets } from '$/database/schemas'
|
import { appliedPresets } from '$/database/schemas'
|
||||||
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
import { createModerationActionEmbed } from '$/utils/discord/embeds'
|
||||||
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
|
||||||
import { removeRolePreset } from '$/utils/discord/rolePresets'
|
import { removeRolePreset } from '$/utils/discord/rolePresets'
|
||||||
import { and, eq } from 'drizzle-orm'
|
|
||||||
import type { Command } from '../types'
|
|
||||||
|
|
||||||
export default {
|
export default new ModerationCommand({
|
||||||
data: new SlashCommandBuilder()
|
name: 'unmute',
|
||||||
.setName('unmute')
|
description: 'Unmute a member',
|
||||||
.setDescription('Unmute a member')
|
options: {
|
||||||
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to unmute'))
|
member: {
|
||||||
.toJSON(),
|
description: 'The member to unmute',
|
||||||
|
required: true,
|
||||||
memberRequirements: {
|
type: ModerationCommand.OptionType.User,
|
||||||
roles: config.moderation?.roles ?? [],
|
|
||||||
},
|
},
|
||||||
|
},
|
||||||
global: false,
|
async execute({ logger, database, executor }, interaction, { member: user }) {
|
||||||
|
|
||||||
async execute({ logger, database }, interaction) {
|
|
||||||
const user = interaction.options.getUser('member', true)
|
|
||||||
const member = await interaction.guild!.members.fetch(user.id)
|
const member = await interaction.guild!.members.fetch(user.id)
|
||||||
if (!member)
|
if (!member)
|
||||||
throw new CommandError(
|
throw new CommandError(
|
||||||
CommandErrorType.InvalidUser,
|
CommandErrorType.InvalidArgument,
|
||||||
'The provided member is not in the server or does not exist.',
|
'The provided member is not in the server or does not exist.',
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -39,8 +32,8 @@ export default {
|
|||||||
throw new CommandError(CommandErrorType.Generic, 'This user is not muted.')
|
throw new CommandError(CommandErrorType.Generic, 'This user is not muted.')
|
||||||
|
|
||||||
await removeRolePreset(member, 'mute')
|
await removeRolePreset(member, 'mute')
|
||||||
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unmuted', user, interaction.user))
|
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unmuted', user, executor.user))
|
||||||
|
|
||||||
logger.info(`Moderator ${interaction.user.tag} (${interaction.user.id}) unmuted ${user.tag} (${user.id})`)
|
logger.info(`Moderator ${executor.user.tag} (${executor.id}) unmuted ${user.tag} (${user.id})`)
|
||||||
},
|
},
|
||||||
} satisfies Command
|
})
|
||||||
|
|||||||
76
bots/discord/src/commands/support/train/chat.ts
Normal file
76
bots/discord/src/commands/support/train/chat.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
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 { 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 to a specific label',
|
||||||
|
type: Command.Type.ChatGuild,
|
||||||
|
requirements: {
|
||||||
|
users: msRcConfig?.users,
|
||||||
|
roles: msRcConfig?.members?.roles,
|
||||||
|
permissions: msRcConfig?.members?.permissions,
|
||||||
|
mode: 'any',
|
||||||
|
memberRequirementsForUsers: 'fail',
|
||||||
|
defaultCondition: 'fail',
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
message: {
|
||||||
|
description: 'The message to train (use `latest` to train the latest message)',
|
||||||
|
type: Command.OptionType.String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
label: {
|
||||||
|
description: 'The label to train the message as (leave empty for out of scope)',
|
||||||
|
type: Command.OptionType.String,
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
allowMessageCommand: true,
|
||||||
|
async execute(context, trigger, { label, message: ref }) {
|
||||||
|
const { logger, config } = context
|
||||||
|
const { messageScan: msConfig } = config
|
||||||
|
|
||||||
|
// If there's no config, we can't do anything
|
||||||
|
if (!msConfig?.humanCorrections) throw new CommandError(CommandErrorType.Generic, 'Response correction is off.')
|
||||||
|
const labels = msConfig.responses?.flatMap(r =>
|
||||||
|
r.triggers.text!.filter((t): t is ConfigMessageScanResponseLabelConfig => 'label' in t).map(t => t.label),
|
||||||
|
)
|
||||||
|
|
||||||
|
const channel = await trigger.guild!.channels.fetch(trigger.channelId)
|
||||||
|
if (!channel?.isTextBased())
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
'This command can only be used in or on text channels',
|
||||||
|
)
|
||||||
|
|
||||||
|
if (label && !labels.includes(label))
|
||||||
|
throw new CommandError(
|
||||||
|
CommandErrorType.InvalidArgument,
|
||||||
|
`The provided label is invalid.\nValid labels are:${labels.map(l => `\n- \`${l}\``).join('')}`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const refMsg = await channel.messages.fetch(
|
||||||
|
(ref.startsWith('latest') ? { limit: 1 } : ref) as MessageResolvable | FetchMessageOptions,
|
||||||
|
)
|
||||||
|
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 ?? '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 ? `\`${label}\`` : 'out of scope'}. Thank you for your contribution!`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
55
bots/discord/src/commands/support/train/context-menu.ts
Normal file
55
bots/discord/src/commands/support/train/context-menu.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { type APIStringSelectComponent, ComponentType, MessageFlags } from 'discord.js'
|
||||||
|
import Command from '$/classes/Command'
|
||||||
|
import CommandError, { CommandErrorType } from '$/classes/CommandError'
|
||||||
|
import { config } from '../../../context'
|
||||||
|
import type { ConfigMessageScanResponseLabelConfig } from 'config.schema'
|
||||||
|
|
||||||
|
const msRcConfig = config.messageScan?.humanCorrections?.allow
|
||||||
|
|
||||||
|
export default new Command({
|
||||||
|
name: 'Train Message',
|
||||||
|
type: Command.Type.ContextMenuGuildMessage,
|
||||||
|
requirements: {
|
||||||
|
users: msRcConfig?.users,
|
||||||
|
roles: msRcConfig?.members?.roles,
|
||||||
|
permissions: msRcConfig?.members?.permissions,
|
||||||
|
mode: 'any',
|
||||||
|
memberRequirementsForUsers: 'fail',
|
||||||
|
defaultCondition: 'fail',
|
||||||
|
},
|
||||||
|
async execute(context, trigger) {
|
||||||
|
const { logger, config } = context
|
||||||
|
const { messageScan: msConfig } = config
|
||||||
|
|
||||||
|
// If there's no config, we can't do anything
|
||||||
|
if (!msConfig?.humanCorrections) throw new CommandError(CommandErrorType.Generic, 'Response correction is off.')
|
||||||
|
|
||||||
|
logger.debug(`User ${context.executor.id} is training message ${trigger.targetId}`)
|
||||||
|
|
||||||
|
const labels = msConfig.responses.flatMap(r =>
|
||||||
|
r.triggers.text!.filter((t): t is ConfigMessageScanResponseLabelConfig => 'label' in t).map(t => t.label),
|
||||||
|
)
|
||||||
|
|
||||||
|
await trigger.reply({
|
||||||
|
content: 'Select a label to train this message as:',
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
custom_id: `tr_${trigger.targetMessage.channelId}_${trigger.targetId}`,
|
||||||
|
options: [
|
||||||
|
...labels.map(label => ({ label, value: label })),
|
||||||
|
{ label: 'Out of scope', value: OutOfScopeLabel, emoji: { name: '❌' } },
|
||||||
|
],
|
||||||
|
type: ComponentType.StringSelect,
|
||||||
|
} satisfies APIStringSelectComponent,
|
||||||
|
],
|
||||||
|
type: ComponentType.ActionRow,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const OutOfScopeLabel = '<out of scope>'
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import type { SlashCommandBuilder } from '@discordjs/builders'
|
|
||||||
import type { ChatInputCommandInteraction } from 'discord.js'
|
|
||||||
|
|
||||||
// Temporary system
|
|
||||||
export type Command = {
|
|
||||||
data: ReturnType<SlashCommandBuilder['toJSON']>
|
|
||||||
// The function has to return void or Promise<void>
|
|
||||||
// because TS may complain about some code paths not returning a value
|
|
||||||
/**
|
|
||||||
* The function to execute when this command is triggered
|
|
||||||
* @param interaction The interaction that triggered this command
|
|
||||||
*/
|
|
||||||
execute: (
|
|
||||||
context: typeof import('../context'),
|
|
||||||
interaction: ChatInputCommandInteraction,
|
|
||||||
info: Info,
|
|
||||||
) => Promise<void> | void
|
|
||||||
memberRequirements?: {
|
|
||||||
/**
|
|
||||||
* The mode to use when checking for requirements.
|
|
||||||
* - `all` means that the user needs meet all requirements specified.
|
|
||||||
* - `any` means that the user needs to meet any of the requirements specified.
|
|
||||||
*
|
|
||||||
* @default "all"
|
|
||||||
*/
|
|
||||||
mode?: 'all' | 'any'
|
|
||||||
/**
|
|
||||||
* The permissions required to use this command (in BitFields).
|
|
||||||
*
|
|
||||||
* - **0n** means that everyone can use this command.
|
|
||||||
* - **-1n** means that only bot owners can use this command.
|
|
||||||
* @default -1n
|
|
||||||
*/
|
|
||||||
permissions?: bigint
|
|
||||||
/**
|
|
||||||
* The roles required to use this command.
|
|
||||||
* By default, this is set to `[]`.
|
|
||||||
*/
|
|
||||||
roles?: string[]
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Whether this command can only be used by bot owners.
|
|
||||||
* @default false
|
|
||||||
*/
|
|
||||||
ownerOnly?: boolean
|
|
||||||
/**
|
|
||||||
* Whether to register this command as a global slash command.
|
|
||||||
* This is set to `false` and commands will be registered in allowed guilds only by default.
|
|
||||||
* @default false
|
|
||||||
*/
|
|
||||||
global?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Info {
|
|
||||||
userIsOwner: boolean
|
|
||||||
}
|
|
||||||
28
bots/discord/src/config.ts
Normal file
28
bots/discord/src/config.ts
Normal 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
|
||||||
@@ -4,12 +4,6 @@ export const MessageScanLabeledResponseReactions = {
|
|||||||
delete: '❌',
|
delete: '❌',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export const MessageScanHumanizedMode = {
|
|
||||||
ocr: 'image recognition',
|
|
||||||
nlp: 'text analysis',
|
|
||||||
match: 'pattern matching',
|
|
||||||
} as const
|
|
||||||
|
|
||||||
export const DefaultEmbedColor = '#4E98F0'
|
export const DefaultEmbedColor = '#4E98F0'
|
||||||
export const ReVancedLogoURL =
|
export const ReVancedLogoURL =
|
||||||
'https://media.discordapp.net/attachments/1095487869923119144/1115436493050224660/revanced-logo.png'
|
'https://media.discordapp.net/attachments/1095487869923119144/1115436493050224660/revanced-logo.png'
|
||||||
|
|||||||
@@ -1,24 +1,22 @@
|
|||||||
import { Database } from 'bun:sqlite'
|
import { Database } from 'bun:sqlite'
|
||||||
import { existsSync, readFileSync, readdirSync } from 'fs'
|
|
||||||
import { join } from 'path'
|
|
||||||
import { Client as APIClient } from '@revanced/bot-api'
|
import { Client as APIClient } from '@revanced/bot-api'
|
||||||
import { createLogger } from '@revanced/bot-shared'
|
import { createLogger } from '@revanced/bot-shared'
|
||||||
import { ActivityType, Client as DiscordClient, Partials } from 'discord.js'
|
import { Client as DiscordClient, type Message, Options, Partials } from 'discord.js'
|
||||||
import { drizzle } from 'drizzle-orm/bun-sqlite'
|
import { drizzle } from 'drizzle-orm/bun-sqlite'
|
||||||
|
import { existsSync, readdirSync, readFileSync } from 'fs'
|
||||||
// Export config first, as commands require them
|
import { join } from 'path'
|
||||||
import config from '../config.js'
|
import { __getConfig, config } from './config'
|
||||||
export { config }
|
|
||||||
|
|
||||||
import * as commands from './commands'
|
|
||||||
import * as schemas from './database/schemas'
|
import * as schemas from './database/schemas'
|
||||||
|
import type { default as Command, CommandOptionsOptions, CommandType } from './classes/Command'
|
||||||
import type { Command } from './commands/types'
|
export { config, __getConfig }
|
||||||
|
|
||||||
export const logger = createLogger({
|
export const logger = createLogger({
|
||||||
level: config.logLevel === 'none' ? Number.MAX_SAFE_INTEGER : config.logLevel,
|
level: config.logLevel === 'none' ? Number.MAX_SAFE_INTEGER : config.logLevel,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Export a few things before we initialize commands
|
||||||
|
import * as commands from './commands'
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
client: new APIClient({
|
client: new APIClient({
|
||||||
api: {
|
api: {
|
||||||
@@ -27,12 +25,12 @@ export const api = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
isStopping: false,
|
intentionallyDisconnecting: false,
|
||||||
disconnectCount: 0,
|
disconnectCount: 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
const DatabasePath = process.env['DATABASE_PATH']
|
const DatabasePath = process.env['DATABASE_PATH']
|
||||||
const DatabaseSchemaDir = join(import.meta.dir, '.drizzle')
|
const DatabaseSchemaDir = join(import.meta.dir, '..', '.drizzle')
|
||||||
|
|
||||||
let dbSchemaFileName: string | undefined
|
let dbSchemaFileName: string | undefined
|
||||||
|
|
||||||
@@ -56,7 +54,7 @@ if (DatabasePath && !existsSync(DatabasePath)) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const db = new Database(DatabasePath)
|
const db = new Database(DatabasePath, { readwrite: true, create: true })
|
||||||
if (dbSchemaFileName) db.run(readFileSync(join(DatabaseSchemaDir, dbSchemaFileName)).toString())
|
if (dbSchemaFileName) db.run(readFileSync(join(DatabaseSchemaDir, dbSchemaFileName)).toString())
|
||||||
|
|
||||||
export const database = drizzle(db, {
|
export const database = drizzle(db, {
|
||||||
@@ -79,18 +77,77 @@ export const discord = {
|
|||||||
parse: ['users'],
|
parse: ['users'],
|
||||||
repliedUser: true,
|
repliedUser: true,
|
||||||
},
|
},
|
||||||
partials: [Partials.Message, Partials.Reaction],
|
sweepers: {
|
||||||
presence: {
|
...Options.DefaultSweeperSettings,
|
||||||
activities: [
|
messages: {
|
||||||
{
|
interval: 1_800, // Every 30m
|
||||||
type: ActivityType.Watching,
|
lifetime: 3_600, // Remove messages older than 1h
|
||||||
name: 'cat videos',
|
|
||||||
},
|
},
|
||||||
],
|
|
||||||
},
|
},
|
||||||
|
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,
|
||||||
}),
|
}),
|
||||||
commands: Object.fromEntries(Object.values<Command>(commands).map(cmd => [cmd.data.name, cmd])) as Record<
|
partials: [Partials.Message, Partials.Reaction, Partials.GuildMember, Partials.User],
|
||||||
|
}),
|
||||||
|
commands: Object.fromEntries(Object.values(commands).map(cmd => [cmd.name, cmd])) as Record<
|
||||||
string,
|
string,
|
||||||
Command
|
Command<CommandType, CommandOptionsOptions | undefined, boolean>
|
||||||
|
>,
|
||||||
|
stickyMessages: {} as Record<
|
||||||
|
string,
|
||||||
|
Record<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Chat is active, so force send timer is also active
|
||||||
|
*/
|
||||||
|
forceTimerActive: boolean
|
||||||
|
/**
|
||||||
|
* There was a message sent, so the timer is active
|
||||||
|
*/
|
||||||
|
timerActive: boolean
|
||||||
|
timerMs: number
|
||||||
|
forceTimerMs?: number
|
||||||
|
send: () => Promise<void>
|
||||||
|
currentMessage?: Message<true>
|
||||||
|
timer?: NodeJS.Timeout
|
||||||
|
forceTimer?: NodeJS.Timeout
|
||||||
|
}
|
||||||
|
>
|
||||||
>,
|
>,
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { InferSelectModel } from 'drizzle-orm'
|
|
||||||
import { integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'
|
import { integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'
|
||||||
|
import type { InferSelectModel } from 'drizzle-orm'
|
||||||
|
|
||||||
export const responses = sqliteTable('responses', {
|
export const responses = sqliteTable('responses', {
|
||||||
replyId: text('reply').primaryKey().notNull(),
|
replyId: text('reply').primaryKey().notNull(),
|
||||||
@@ -16,12 +16,11 @@ export const appliedPresets = sqliteTable(
|
|||||||
{
|
{
|
||||||
memberId: text('member').notNull(),
|
memberId: text('member').notNull(),
|
||||||
guildId: text('guild').notNull(),
|
guildId: text('guild').notNull(),
|
||||||
|
removedRoles: text('roles', { mode: 'json' }).notNull().$type<string[]>().default([]),
|
||||||
preset: text('preset').notNull(),
|
preset: text('preset').notNull(),
|
||||||
until: integer('until'),
|
until: integer('until'),
|
||||||
},
|
},
|
||||||
table => ({
|
table => [uniqueIndex('unique_composite').on(table.memberId, table.preset, table.guildId)],
|
||||||
uniqueComposite: uniqueIndex('unique_composite').on(table.memberId, table.preset, table.guildId),
|
|
||||||
}),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
export type Response = InferSelectModel<typeof responses>
|
export type Response = InferSelectModel<typeof responses>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { on, withContext } from '$utils/api/events'
|
|
||||||
import { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
|
import { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
|
||||||
|
import { on, withContext } from '$utils/api/events'
|
||||||
|
|
||||||
withContext(on, 'disconnect', ({ api, config, logger }, reason, msg) => {
|
withContext(on, 'disconnect', ({ api, config, logger }, reason, msg) => {
|
||||||
if (reason === DisconnectReason.PlannedDisconnect && api.isStopping) return
|
if (reason === DisconnectReason.PlannedDisconnect && api.intentionallyDisconnecting) return
|
||||||
|
|
||||||
const ws = api.client.ws
|
const ws = api.client.ws
|
||||||
if (!ws.disconnected) ws.disconnect()
|
if (!ws.disconnected) ws.disconnect()
|
||||||
@@ -16,7 +16,7 @@ withContext(on, 'disconnect', ({ api, config, logger }, reason, msg) => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
if (api.disconnectCount >= (config.api.disconnectLimit ?? 3)) {
|
if (api.disconnectCount >= (config.api.disconnectLimit ?? 3)) {
|
||||||
console.error('Disconnected from bot API too many times')
|
logger.fatal('Disconnected from bot API too many times')
|
||||||
// We don't want the process hanging
|
// We don't want the process hanging
|
||||||
process.exit(1)
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
import { on, withContext } from '$utils/api/events'
|
import { on, withContext } from '$utils/api/events'
|
||||||
|
|
||||||
withContext(on, 'ready', ({ logger }) => void logger.info('Connected to the bot API'))
|
withContext(on, 'ready', ({ api, logger }) => {
|
||||||
|
// Reset disconnect count, so it doesn't meet the threshold for an accidental disconnect
|
||||||
|
api.disconnectCount = 0
|
||||||
|
logger.info('Connected to the bot API')
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { on } from '$/utils/discord/events'
|
import { on } from '$/utils/discord/events'
|
||||||
import { cureNickname } from '$/utils/discord/moderation'
|
import { cureNickname } from '$/utils/discord/moderation'
|
||||||
|
|
||||||
on('guildMemberUpdate', async (oldMember, newMember) => {
|
on('guildMemberUpdate', (_, newMember) => {
|
||||||
if (newMember.user.bot) return
|
if (newMember.user.bot) return
|
||||||
if (oldMember.displayName !== newMember.displayName) await cureNickname(newMember)
|
cureNickname(newMember)
|
||||||
})
|
})
|
||||||
|
|
||||||
on('guildMemberAdd', member => {
|
on('guildMemberAdd', member => {
|
||||||
@@ -11,7 +11,7 @@ on('guildMemberAdd', member => {
|
|||||||
cureNickname(member)
|
cureNickname(member)
|
||||||
})
|
})
|
||||||
|
|
||||||
on('messageCreate', async msg => {
|
on('messageCreate', msg => {
|
||||||
if (msg.author.bot || !msg.member) return
|
if (msg.author.bot || !msg.member) return
|
||||||
await cureNickname(msg.member)
|
cureNickname(msg.member)
|
||||||
})
|
})
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
|
import { and, eq, gt } from 'drizzle-orm'
|
||||||
import { appliedPresets } from '$/database/schemas'
|
import { appliedPresets } from '$/database/schemas'
|
||||||
import { on, withContext } from '$/utils/discord/events'
|
import { on, withContext } from '$/utils/discord/events'
|
||||||
import { applyRolesUsingPreset } from '$/utils/discord/rolePresets'
|
import { applyRolesUsingPreset } from '$/utils/discord/rolePresets'
|
||||||
import { and, eq, gt } from 'drizzle-orm'
|
|
||||||
|
|
||||||
withContext(on, 'guildMemberAdd', async ({ database }, member) => {
|
withContext(on, 'guildMemberAdd', async ({ database }, member) => {
|
||||||
const applieds = await database.query.appliedPresets.findMany({
|
const applieds = await database.query.appliedPresets.findMany({
|
||||||
@@ -12,5 +12,5 @@ withContext(on, 'guildMemberAdd', async ({ database }, member) => {
|
|||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|
||||||
for (const { preset } of applieds) await applyRolesUsingPreset(preset, member, true)
|
for (const { preset } of applieds) await applyRolesUsingPreset(preset, member)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,80 +1,31 @@
|
|||||||
|
import { MessageFlags } from 'discord.js'
|
||||||
import CommandError from '$/classes/CommandError'
|
import CommandError from '$/classes/CommandError'
|
||||||
import { createErrorEmbed, createStackTraceEmbed } from '$utils/discord/embeds'
|
import { createStackTraceEmbed } from '$utils/discord/embeds'
|
||||||
import { on, withContext } from '$utils/discord/events'
|
import { on, withContext } from '$utils/discord/events'
|
||||||
|
|
||||||
withContext(on, 'interactionCreate', async (context, interaction) => {
|
withContext(on, 'interactionCreate', async (context, interaction) => {
|
||||||
if (!interaction.isChatInputCommand()) return
|
if (!interaction.isChatInputCommand()) return
|
||||||
|
|
||||||
const { logger, discord, config } = context
|
const { logger, discord } = context
|
||||||
const command = discord.commands[interaction.commandName]
|
const command = discord.commands[interaction.commandName]
|
||||||
|
|
||||||
logger.debug(`Command ${interaction.commandName} being invoked by ${interaction.user.tag}`)
|
logger.debug(`Command ${interaction.commandName} being invoked by ${interaction.user.tag} via chat`)
|
||||||
if (!command) return void logger.error(`Command ${interaction.commandName} not implemented but registered!!!`)
|
if (!command) return void logger.error(`Chat command ${interaction.commandName} not implemented but registered!!!`)
|
||||||
|
|
||||||
const isOwner = config.owners.includes(interaction.user.id)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Owner check
|
|
||||||
*/
|
|
||||||
if (command.ownerOnly && !isOwner)
|
|
||||||
return void (await interaction.reply({
|
|
||||||
embeds: [createErrorEmbed('Massive skill issue', 'This command can only be used by the bot owners.')],
|
|
||||||
ephemeral: true,
|
|
||||||
}))
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sanity check
|
|
||||||
*/
|
|
||||||
if (!command.global && !interaction.inGuild()) {
|
|
||||||
logger.error(`Command ${interaction.commandName} cannot be run in DMs, but was registered as global`)
|
|
||||||
await interaction.reply({
|
|
||||||
embeds: [createErrorEmbed('Cannot run that here', 'This command can only be used in a server.')],
|
|
||||||
ephemeral: true,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Permission checks
|
|
||||||
*/
|
|
||||||
if (interaction.inGuild()) {
|
|
||||||
// Bot owners get bypass
|
|
||||||
if (command.memberRequirements && !isOwner) {
|
|
||||||
const { permissions = 0n, roles = [], mode } = command.memberRequirements
|
|
||||||
|
|
||||||
const member = await interaction.guild!.members.fetch(interaction.user.id)
|
|
||||||
|
|
||||||
const [missingPermissions, missingRoles] = [
|
|
||||||
// This command is an owner-only command (the user is not an owner, checked above)
|
|
||||||
permissions <= 0n ||
|
|
||||||
// or the user doesn't have the required permissions
|
|
||||||
(permissions > 0n && !interaction.memberPermissions.has(permissions)),
|
|
||||||
|
|
||||||
// If not:
|
|
||||||
!roles.some(x => member.roles.cache.has(x)),
|
|
||||||
]
|
|
||||||
|
|
||||||
if ((mode === 'any' && missingPermissions && missingRoles) || missingPermissions || missingRoles)
|
|
||||||
return void interaction.reply({
|
|
||||||
embeds: [
|
|
||||||
createErrorEmbed(
|
|
||||||
'Missing roles or permissions',
|
|
||||||
"You don't have the required roles or permissions to use this command.",
|
|
||||||
),
|
|
||||||
],
|
|
||||||
ephemeral: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
logger.debug(`Command ${interaction.commandName} being executed`)
|
logger.debug(`Command ${interaction.commandName} being executed via chat`)
|
||||||
await command.execute(context, interaction, { userIsOwner: isOwner })
|
await command.onInteraction(context, interaction)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (!(err instanceof CommandError))
|
||||||
logger.error(`Error while executing command ${interaction.commandName}:`, err)
|
logger.error(`Error while executing command ${interaction.commandName}:`, err)
|
||||||
|
|
||||||
await interaction[interaction.replied ? 'followUp' : 'reply']({
|
await interaction[interaction.replied ? 'followUp' : 'reply']({
|
||||||
embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)],
|
embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)],
|
||||||
ephemeral: true,
|
flags: MessageFlags.Ephemeral,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 100 and up are user errors
|
||||||
|
if (err instanceof CommandError && err.type < 100)
|
||||||
|
logger.error(`Command ${interaction.commandName} internally failed with error:`, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { MessageFlags } from 'discord.js'
|
||||||
|
import CommandError from '$/classes/CommandError'
|
||||||
|
import { createStackTraceEmbed } from '$utils/discord/embeds'
|
||||||
|
import { on, withContext } from '$utils/discord/events'
|
||||||
|
|
||||||
|
withContext(on, 'interactionCreate', async (context, interaction) => {
|
||||||
|
if (!interaction.isContextMenuCommand()) return
|
||||||
|
|
||||||
|
const { logger, discord } = context
|
||||||
|
const command = discord.commands[interaction.commandName]
|
||||||
|
|
||||||
|
logger.debug(`Command ${interaction.commandName} being invoked by ${interaction.user.tag} via context menu`)
|
||||||
|
if (!command)
|
||||||
|
return void logger.error(`Context menu command ${interaction.commandName} not implemented but registered!!!`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.debug(`Command ${interaction.commandName} being executed via context menu`)
|
||||||
|
await command.onContextMenuInteraction(context, interaction)
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof CommandError))
|
||||||
|
logger.error(`Error while executing command ${interaction.commandName}:`, err)
|
||||||
|
await interaction[interaction.replied ? 'followUp' : 'reply']({
|
||||||
|
embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -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 { responses } from '$/database/schemas'
|
||||||
import { handleUserResponseCorrection } from '$/utils/discord/messageScan'
|
import { handleUserResponseCorrection } from '$/utils/discord/messageScan'
|
||||||
import { createErrorEmbed, createStackTraceEmbed, createSuccessEmbed } from '$utils/discord/embeds'
|
import { createErrorEmbed, createStackTraceEmbed, createSuccessEmbed } from '$utils/discord/embeds'
|
||||||
import { on, withContext } from '$utils/discord/events'
|
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
|
// No permission check required as it is already done when the user reacts to a bot response
|
||||||
withContext(on, 'interactionCreate', async (context, interaction) => {
|
withContext(on, 'interactionCreate', async (context, interaction) => {
|
||||||
const {
|
const {
|
||||||
@@ -18,25 +22,25 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
|
|||||||
if (!interaction.isStringSelectMenu() && !interaction.isButton()) return
|
if (!interaction.isStringSelectMenu() && !interaction.isButton()) return
|
||||||
if (!interaction.customId.startsWith('cr_')) return
|
if (!interaction.customId.startsWith('cr_')) return
|
||||||
|
|
||||||
const [, key, action] = interaction.customId.split('_') as ['cr', string, 'select' | 'cancel' | 'delete']
|
const [, msgId, action] = interaction.customId.split('_') as ['cr', string, 'select' | 'cancel' | 'delete']
|
||||||
if (!key || !action) return
|
if (!msgId || !action) return
|
||||||
|
|
||||||
const response = await db.query.responses.findFirst({ where: eq(responses.replyId, key) })
|
const response = await db.query.responses.findFirst({ where: eq(responses.replyId, msgId) })
|
||||||
// If the message isn't saved in my DB (unrelated message)
|
// If the message isn't saved in my DB (unrelated message)
|
||||||
if (!response)
|
if (!response)
|
||||||
return void (await interaction.reply({
|
return void (await interaction.reply({
|
||||||
content: "I don't recall having sent this response, so I cannot correct it.",
|
content: "I don't recall having sent this response, so I cannot correct it.",
|
||||||
ephemeral: true,
|
flags: MessageFlags.Ephemeral,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// We're gonna pretend reactionChannel is a text-based channel, but it can be many more
|
// We're gonna pretend reactionChannel is a text-based channel, but it can be many more
|
||||||
// But `messages` should always exist as a property
|
// But `messages` should always exist as a property
|
||||||
const reactionGuild = await interaction.client.guilds.fetch(response.guildId)
|
const guild = await interaction.client.guilds.fetch(response.guildId)
|
||||||
const reactionChannel = (await reactionGuild.channels.fetch(response.channelId)) as TextBasedChannel | null
|
const channel = (await guild.channels.fetch(response.channelId)) as TextBasedChannel | null
|
||||||
const reactionMessage = await reactionChannel?.messages.fetch(key)
|
const msg = await channel?.messages.fetch(msgId)
|
||||||
|
|
||||||
if (!reactionMessage) {
|
if (!msg) {
|
||||||
await interaction.deferUpdate()
|
await interaction.deferUpdate()
|
||||||
await interaction.message.edit({
|
await interaction.message.edit({
|
||||||
content: null,
|
content: null,
|
||||||
@@ -53,9 +57,9 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const editMessage = (content: string, description?: string) =>
|
const editMessage = (content: string, description?: string) =>
|
||||||
editInteractionMessage(interaction, reactionMessage.url, content, description)
|
editInteractionMessage(interaction, msg.url, content, description)
|
||||||
const handleCorrection = (label: string) =>
|
const handleCorrection = (label?: string) =>
|
||||||
handleUserResponseCorrection(context, response, reactionMessage, label, interaction.user)
|
handleUserResponseCorrection(context, response, msg, interaction.user, label)
|
||||||
|
|
||||||
if (response.correctedById)
|
if (response.correctedById)
|
||||||
return await editMessage(
|
return await editMessage(
|
||||||
@@ -78,7 +82,7 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
|
|||||||
await editMessage('Canceled', 'You canceled this interaction. 😞')
|
await editMessage('Canceled', 'You canceled this interaction. 😞')
|
||||||
break
|
break
|
||||||
case 'delete':
|
case 'delete':
|
||||||
await handleCorrection(msConfig.humanCorrections.falsePositiveLabel)
|
await handleCorrection()
|
||||||
await editMessage(
|
await editMessage(
|
||||||
'Marked as false positive',
|
'Marked as false positive',
|
||||||
'The response has been deleted and marked as a false positive. Thank you for your feedback. 🎉',
|
'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)
|
logger.error('Failed to handle correct response interaction:', e)
|
||||||
await interaction.reply({
|
await interaction.reply({
|
||||||
embeds: [createStackTraceEmbed(e)],
|
embeds: [createStackTraceEmbed(e)],
|
||||||
ephemeral: true,
|
flags: MessageFlags.Ephemeral,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
withContext(on, 'interactionCreate', async (context, interaction) => {
|
||||||
|
const {
|
||||||
|
logger,
|
||||||
|
config: { messageScan: msConfig },
|
||||||
|
} = context
|
||||||
|
|
||||||
|
if (!msConfig?.humanCorrections) return
|
||||||
|
if (!interaction.isStringSelectMenu()) return
|
||||||
|
if (!interaction.customId.startsWith('tr_')) return
|
||||||
|
|
||||||
|
const [, channelId, msgId] = interaction.customId.split('_') as ['tr', string, string]
|
||||||
|
if (!channelId || !msgId) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const channel = (await interaction.client.channels.fetch(channelId)) as TextBasedChannel | null
|
||||||
|
const msg = await channel?.messages.fetch(msgId)
|
||||||
|
|
||||||
|
if (!msg)
|
||||||
|
return void (await interaction.reply({
|
||||||
|
embeds: [
|
||||||
|
createErrorEmbed(
|
||||||
|
'Message not found',
|
||||||
|
'Thank you for your contribution! Unfortunately, the message could not be found.',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const selectedLabel = interaction.values[0]
|
||||||
|
await context.api.client.trainMessage(
|
||||||
|
msg.content,
|
||||||
|
selectedLabel === OutOfScopeLabel ? undefined : selectedLabel,
|
||||||
|
)
|
||||||
|
await interaction.reply({
|
||||||
|
embeds: [
|
||||||
|
createSuccessEmbed(
|
||||||
|
'Message being trained',
|
||||||
|
`Thank you for your contribution! The selected message is being trained as \`${selectedLabel}\`. 🎉`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('Failed to handle train message interaction:', e)
|
||||||
|
await interaction.reply({
|
||||||
|
embeds: [createStackTraceEmbed(e)],
|
||||||
|
flags: MessageFlags.Ephemeral,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { type CommandArguments, CommandSpecialArgumentType } from '$/classes/Command'
|
||||||
|
import CommandError from '$/classes/CommandError'
|
||||||
|
import { createStackTraceEmbed } from '$utils/discord/embeds'
|
||||||
|
import { on, withContext } from '$utils/discord/events'
|
||||||
|
|
||||||
|
withContext(on, 'messageCreate', async (context, msg) => {
|
||||||
|
const { logger, discord, config } = context
|
||||||
|
|
||||||
|
if (msg.author.bot) return
|
||||||
|
|
||||||
|
const regex = new RegExp(
|
||||||
|
`^(?:${config.prefix ? `${escapeRegexSpecials(config.prefix)}|` : ''}${msg.client.user.toString()}\\s*)([a-zA-Z-_]+)(?:\\s+)?(.+)?`,
|
||||||
|
)
|
||||||
|
const matches = msg.content.match(regex)
|
||||||
|
|
||||||
|
if (!matches) return
|
||||||
|
const [, commandName, argsString] = matches
|
||||||
|
if (!commandName) return
|
||||||
|
|
||||||
|
const command = discord.commands[commandName]
|
||||||
|
logger.debug(`Command ${commandName} being invoked by ${msg.author.id} via message`)
|
||||||
|
if (!command) return void logger.debug(`Message command ${commandName} not implemented`)
|
||||||
|
|
||||||
|
const argsRegex: RegExp = /[^\s"]+|"([^"]*)"/g
|
||||||
|
const args: CommandArguments = []
|
||||||
|
let match: RegExpExecArray | null
|
||||||
|
|
||||||
|
// biome-ignore lint/suspicious/noAssignInExpressions: nuh uh
|
||||||
|
while ((match = argsRegex.exec(argsString ?? '')) !== null) {
|
||||||
|
const arg = match[1] ? match[1] : match[0]
|
||||||
|
const mentionMatch = arg.match(/<(@(?:!|&)?|#)(.+?)>/)
|
||||||
|
|
||||||
|
if (mentionMatch) {
|
||||||
|
const [, prefix, id] = mentionMatch
|
||||||
|
|
||||||
|
if (!id || !prefix) {
|
||||||
|
args.push('')
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
args.push({
|
||||||
|
type: CommandSpecialArgumentType[prefix[1] === '&' ? 'Role' : prefix[0] === '#' ? 'Channel' : 'User'],
|
||||||
|
id,
|
||||||
|
})
|
||||||
|
} else args.push(arg)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.debug(`Command ${commandName} being executed via message`)
|
||||||
|
await command.onMessage(context, msg, args)
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof CommandError)) logger.error(`Error while executing command ${commandName}:`, err)
|
||||||
|
await msg.reply({ embeds: [err instanceof CommandError ? err.toEmbed() : createStackTraceEmbed(err)] })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const escapeRegexSpecials = (str: string): string => {
|
||||||
|
let escapedStr = ''
|
||||||
|
for (const char of str) {
|
||||||
|
if (['.', '+', '*', '?', '$', '(', ')', '[', ']', '{', '}', '|', '\\'].includes(char)) escapedStr += `\\${char}`
|
||||||
|
else escapedStr += char
|
||||||
|
}
|
||||||
|
return escapedStr
|
||||||
|
}
|
||||||
116
bots/discord/src/events/discord/messageCreate/messageScan.ts
Normal file
116
bots/discord/src/events/discord/messageCreate/messageScan.ts
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
import { MessageScanLabeledResponseReactions } from '$/constants'
|
||||||
|
import { responses } from '$/database/schemas'
|
||||||
|
import { getResponseFromText, messageMatchesFilter } from '$/utils/discord/messageScan'
|
||||||
|
import { createMessageScanResponseEmbed } from '$utils/discord/embeds'
|
||||||
|
import { on, withContext } from '$utils/discord/events'
|
||||||
|
|
||||||
|
withContext(on, 'messageCreate', async (context, msg) => {
|
||||||
|
const {
|
||||||
|
api,
|
||||||
|
config: { messageScan: config },
|
||||||
|
database: db,
|
||||||
|
logger,
|
||||||
|
} = context
|
||||||
|
|
||||||
|
if (!config || !config.responses) return
|
||||||
|
if (msg.author.bot && !config.scanBots) return
|
||||||
|
if (!msg.inGuild() && !config.scanOutsideGuilds) return
|
||||||
|
if (msg.inGuild() && msg.member?.partial) await msg.member.fetch()
|
||||||
|
|
||||||
|
const filteredResponses = config.responses.filter(x => messageMatchesFilter(msg, x.filterOverride ?? config.filter))
|
||||||
|
if (!filteredResponses.length) return
|
||||||
|
|
||||||
|
if (msg.content.length) {
|
||||||
|
try {
|
||||||
|
logger.debug(`Classifying message ${msg.id}, possible responses is ${filteredResponses.length}`)
|
||||||
|
|
||||||
|
const { response, label, respondToReply } = await getResponseFromText(
|
||||||
|
msg.content,
|
||||||
|
filteredResponses,
|
||||||
|
context,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (response) {
|
||||||
|
logger.debug('Response found')
|
||||||
|
|
||||||
|
const toReply = msg.reference?.messageId && (
|
||||||
|
respondToReply === true
|
||||||
|
? true
|
||||||
|
: (respondToReply === 'only_labeled' && label !== undefined) ||
|
||||||
|
(respondToReply === 'only_regex' && label === undefined)
|
||||||
|
)
|
||||||
|
? await msg.fetchReference()
|
||||||
|
: msg
|
||||||
|
|
||||||
|
const reply = await toReply.reply({
|
||||||
|
...response,
|
||||||
|
embeds: response.embeds?.map(createMessageScanResponseEmbed),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (label) {
|
||||||
|
await db.insert(responses).values({
|
||||||
|
replyId: reply.id,
|
||||||
|
channelId: reply.channel.id,
|
||||||
|
guildId: reply.guild!.id,
|
||||||
|
referenceId: msg.id,
|
||||||
|
label,
|
||||||
|
content: msg.content,
|
||||||
|
})
|
||||||
|
|
||||||
|
await Promise.all(Object.values(MessageScanLabeledResponseReactions).map(name => reply.react(name)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('Failed to classify message:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.attachments.size && config.attachments?.scanAttachments) {
|
||||||
|
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]
|
||||||
|
if (!mimeType) return void logger.warn(`No MIME type for attachment: ${attachment.url}`)
|
||||||
|
|
||||||
|
if (config.attachments.allowedMimeTypes && !config.attachments.allowedMimeTypes.includes(mimeType)) {
|
||||||
|
logger.debug(`Disallowed MIME type for attachment: ${attachment.url}, ${mimeType}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const isTextFile = mimeType.startsWith('text/')
|
||||||
|
|
||||||
|
if (isTextFile && attachment.size > (config.attachments.maxTextFileSize ?? 512 * 1000)) {
|
||||||
|
logger.debug(`Attachment ${attachment.url} is too large be to scanned, size is ${attachment.size}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let response: Awaited<ReturnType<typeof getResponseFromText>>['response'] | undefined
|
||||||
|
|
||||||
|
if (isTextFile) {
|
||||||
|
const content = await (await fetch(attachment.url)).text()
|
||||||
|
response = await getResponseFromText(content, filteredResponses, context, {
|
||||||
|
textRegexesOnly: true,
|
||||||
|
}).then(it => it.response)
|
||||||
|
} else {
|
||||||
|
const { text: content } = await api.client.parseImage(attachment.url)
|
||||||
|
response = await getResponseFromText(content, filteredResponses, context, {
|
||||||
|
imageTriggersOnly: true,
|
||||||
|
}).then(it => it.response)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response) {
|
||||||
|
logger.debug(`Response found for attachment: ${attachment.url}`)
|
||||||
|
await msg.reply({
|
||||||
|
...response,
|
||||||
|
embeds: response.embeds?.map(createMessageScanResponseEmbed),
|
||||||
|
})
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`Failed to parse attachment: ${attachment.url}`, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
import { MessageScanLabeledResponseReactions } from '$/constants'
|
|
||||||
import { responses } from '$/database/schemas'
|
|
||||||
import { getResponseFromText, shouldScanMessage } from '$/utils/discord/messageScan'
|
|
||||||
import { createMessageScanResponseEmbed } from '$utils/discord/embeds'
|
|
||||||
import { on, withContext } from '$utils/discord/events'
|
|
||||||
|
|
||||||
withContext(on, 'messageCreate', async (context, msg) => {
|
|
||||||
const {
|
|
||||||
api,
|
|
||||||
config: { messageScan: config },
|
|
||||||
database: db,
|
|
||||||
logger,
|
|
||||||
} = context
|
|
||||||
|
|
||||||
if (!config || !config.responses) return
|
|
||||||
|
|
||||||
const filteredResponses = config.responses.filter(x => shouldScanMessage(msg, x.filterOverride ?? config.filter))
|
|
||||||
if (!filteredResponses.length) return
|
|
||||||
|
|
||||||
if (msg.content.length) {
|
|
||||||
try {
|
|
||||||
logger.debug(`Classifying message ${msg.id}`)
|
|
||||||
|
|
||||||
const { response, label } = await getResponseFromText(msg.content, filteredResponses, context)
|
|
||||||
|
|
||||||
if (response) {
|
|
||||||
logger.debug('Response found')
|
|
||||||
|
|
||||||
const reply = await msg.reply({
|
|
||||||
embeds: [createMessageScanResponseEmbed(response, label ? 'nlp' : 'match')],
|
|
||||||
})
|
|
||||||
|
|
||||||
if (label)
|
|
||||||
db.insert(responses).values({
|
|
||||||
replyId: reply.id,
|
|
||||||
channelId: reply.channel.id,
|
|
||||||
guildId: reply.guild!.id,
|
|
||||||
referenceId: msg.id,
|
|
||||||
label,
|
|
||||||
content: msg.content,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (label) {
|
|
||||||
for (const reaction of Object.values(MessageScanLabeledResponseReactions)) {
|
|
||||||
await reply.react(reaction)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.error('Failed to classify message:', e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msg.attachments.size > 0) {
|
|
||||||
logger.debug(`Classifying message attachments for ${msg.id}`)
|
|
||||||
|
|
||||||
for (const attachment of msg.attachments.values()) {
|
|
||||||
if (attachment.contentType && !config.allowedAttachmentMimeTypes.includes(attachment.contentType)) continue
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { text: content } = await api.client.parseImage(attachment.url)
|
|
||||||
const { response } = await getResponseFromText(content, filteredResponses, context, true)
|
|
||||||
|
|
||||||
if (response) {
|
|
||||||
logger.debug(`Response found for attachment: ${attachment.url}`)
|
|
||||||
await msg.reply({
|
|
||||||
embeds: [createMessageScanResponseEmbed(response, 'ocr')],
|
|
||||||
})
|
|
||||||
|
|
||||||
break
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
logger.error(`Failed to parse image: ${attachment.url}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { on, withContext } from '$utils/discord/events'
|
||||||
|
|
||||||
|
withContext(on, 'messageCreate', async ({ discord, logger }, msg) => {
|
||||||
|
if (!msg.inGuild()) return
|
||||||
|
if (msg.author.id === msg.client.user.id) return
|
||||||
|
|
||||||
|
const store = discord.stickyMessages[msg.guildId]?.[msg.channelId]
|
||||||
|
if (!store) return
|
||||||
|
|
||||||
|
// 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`,
|
||||||
|
)
|
||||||
|
|
||||||
|
// (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
|
||||||
|
})
|
||||||
@@ -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 {
|
import {
|
||||||
ActionRowBuilder,
|
ActionRowBuilder,
|
||||||
ButtonBuilder,
|
ButtonBuilder,
|
||||||
@@ -9,11 +5,14 @@ import {
|
|||||||
StringSelectMenuBuilder,
|
StringSelectMenuBuilder,
|
||||||
StringSelectMenuOptionBuilder,
|
StringSelectMenuOptionBuilder,
|
||||||
} from 'discord.js'
|
} from 'discord.js'
|
||||||
|
|
||||||
import type { ConfigMessageScanResponseLabelConfig } from '$/../config.schema'
|
|
||||||
import { responses } from '$/database/schemas'
|
|
||||||
import { handleUserResponseCorrection } from '$/utils/discord/messageScan'
|
|
||||||
import { eq } from 'drizzle-orm'
|
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 type { ConfigMessageScanResponseLabelConfig } from '$/../config.schema'
|
||||||
|
|
||||||
const PossibleReactions = Object.values(Reactions) as string[]
|
const PossibleReactions = Object.values(Reactions) as string[]
|
||||||
|
|
||||||
@@ -31,13 +30,11 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
|
|||||||
|
|
||||||
if (reactionMessage.author.id !== reaction.client.user!.id) return
|
if (reactionMessage.author.id !== reaction.client.user!.id) return
|
||||||
if (!PossibleReactions.includes(reaction.emoji.name!)) return
|
if (!PossibleReactions.includes(reaction.emoji.name!)) return
|
||||||
|
await rct.users.remove(user.id)
|
||||||
|
|
||||||
if (!config.owners.includes(user.id)) {
|
if (!isAdmin(reactionMessage.member || reactionMessage.author)) {
|
||||||
// User is in guild, and config has member requirements
|
// User is in guild, and config has member requirements
|
||||||
if (
|
if (reactionMessage.inGuild() && msConfig.humanCorrections.allow) {
|
||||||
reactionMessage.inGuild() &&
|
|
||||||
(msConfig.humanCorrections.allow?.members || msConfig.humanCorrections.allow?.users)
|
|
||||||
) {
|
|
||||||
const {
|
const {
|
||||||
allow: { users: allowedUsers, members: allowedMembers },
|
allow: { users: allowedUsers, members: allowedMembers },
|
||||||
} = msConfig.humanCorrections
|
} = msConfig.humanCorrections
|
||||||
@@ -46,24 +43,28 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
|
|||||||
const member = await reactionMessage.guild.members.fetch(user.id)
|
const member = await reactionMessage.guild.members.fetch(user.id)
|
||||||
const { permissions, roles } = allowedMembers
|
const { permissions, roles } = allowedMembers
|
||||||
|
|
||||||
if (!(member.permissions.has(permissions ?? 0n) || roles?.some(role => member.roles.cache.has(role))))
|
if (
|
||||||
|
!(
|
||||||
|
(permissions ? member.permissions.has(permissions) : false) ||
|
||||||
|
roles?.some(role => member.roles.cache.has(role))
|
||||||
|
)
|
||||||
|
)
|
||||||
return
|
return
|
||||||
} else if (allowedUsers) {
|
} else if (!allowedUsers?.includes(user.id)) return
|
||||||
if (!allowedUsers.includes(user.id)) return
|
} else
|
||||||
} else {
|
|
||||||
return void logger.warn(
|
return void logger.warn(
|
||||||
'No member or user requirements set for human corrections, all requests will be ignored',
|
'No member or user requirements set for human corrections, all requests will be ignored',
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanity check
|
// Sanity check
|
||||||
const response = await db.query.responses.findFirst({ where: eq(responses.replyId, rct.message.id) })
|
const response = await db.query.responses.findFirst({ where: eq(responses.replyId, rct.message.id) })
|
||||||
if (!response || response.correctedById) return
|
if (!response || response.correctedById) return
|
||||||
|
|
||||||
const handleCorrection = (label: string) =>
|
logger.debug(`User ${user.id} is trying to correct the response ${rct.message.id}`)
|
||||||
handleUserResponseCorrection(context, response, reactionMessage, label, user)
|
|
||||||
|
const handleCorrection = (label?: string) =>
|
||||||
|
handleUserResponseCorrection(context, response, reactionMessage, user, label)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (reaction.emoji.name === Reactions.train) {
|
if (reaction.emoji.name === Reactions.train) {
|
||||||
@@ -105,7 +106,7 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
|
|||||||
.setCustomId(`${componentPrefix}_cancel`),
|
.setCustomId(`${componentPrefix}_cancel`),
|
||||||
new ButtonBuilder()
|
new ButtonBuilder()
|
||||||
.setEmoji(Reactions.delete)
|
.setEmoji(Reactions.delete)
|
||||||
.setLabel('Delete (mark as false positive)')
|
.setLabel('Delete (mark as out of scope)')
|
||||||
.setStyle(ButtonStyle.Danger)
|
.setStyle(ButtonStyle.Danger)
|
||||||
.setCustomId(`${componentPrefix}_delete`),
|
.setCustomId(`${componentPrefix}_delete`),
|
||||||
),
|
),
|
||||||
@@ -116,8 +117,8 @@ withContext(on, 'messageReactionAdd', async (context, rct, user) => {
|
|||||||
components: rows,
|
components: rows,
|
||||||
})
|
})
|
||||||
} else if (reaction.emoji.name === Reactions.delete) {
|
} else if (reaction.emoji.name === Reactions.delete) {
|
||||||
await handleCorrection(msConfig.humanCorrections.falsePositiveLabel)
|
await handleCorrection()
|
||||||
await user.send({ content: 'The response has been deleted and marked as a false positive.' })
|
await user.send({ content: 'The response has been deleted and marked as out of scope.' })
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error('Failed to correct response:', e)
|
logger.error('Failed to correct response:', e)
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
import { database, logger } from '$/context'
|
|
||||||
import { appliedPresets } from '$/database/schemas'
|
|
||||||
import { removeRolePreset } from '$/utils/discord/rolePresets'
|
|
||||||
import type { Client } from 'discord.js'
|
|
||||||
import { lt } from 'drizzle-orm'
|
|
||||||
import { on, withContext } from 'src/utils/discord/events'
|
|
||||||
|
|
||||||
export default withContext(on, 'ready', ({ config, 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 this is not expected, please run the /leave-unknowns command`,
|
|
||||||
)
|
|
||||||
|
|
||||||
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 {
|
|
||||||
const guild = await client.guilds.fetch(expired.guildId)
|
|
||||||
const member = await guild.members.fetch(expired.memberId)
|
|
||||||
|
|
||||||
logger.debug(`Removing role preset for ${expired.memberId} in ${expired.guildId}`)
|
|
||||||
await removeRolePreset(member, expired.preset)
|
|
||||||
} catch (e) {
|
|
||||||
logger.error(`Error while removing role preset for ${expired.memberId} in ${expired.guildId}: ${e}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
6
bots/discord/src/events/discord/ready/log.ts
Normal file
6
bots/discord/src/events/discord/ready/log.ts
Normal 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`)
|
||||||
|
})
|
||||||
@@ -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)))
|
||||||
|
}
|
||||||
|
}
|
||||||
68
bots/discord/src/events/discord/ready/stickyMessageSetup.ts
Normal file
68
bots/discord/src/events/discord/ready/stickyMessageSetup.ts
Normal 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { api, discord, logger } from '$/context'
|
|
||||||
import { getMissingEnvironmentVariables } from '@revanced/bot-shared'
|
import { getMissingEnvironmentVariables } from '@revanced/bot-shared'
|
||||||
|
import { api, discord, logger } from '$/context'
|
||||||
|
|
||||||
import './events/register'
|
import './events/register'
|
||||||
|
|
||||||
@@ -10,5 +10,10 @@ if (missingEnvs.length) {
|
|||||||
process.exit(1)
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle uncaught exceptions
|
||||||
|
|
||||||
|
process.on('uncaughtException', error => console.error('Uncaught exception:', error))
|
||||||
|
process.on('unhandledRejection', reason => console.error('Unhandled rejection:', reason))
|
||||||
|
|
||||||
api.client.connect()
|
api.client.connect()
|
||||||
discord.client.login()
|
discord.client.login()
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ClientWebSocketEvents } from '@revanced/bot-api'
|
|
||||||
import * as context from '../../context'
|
import * as context from '../../context'
|
||||||
|
import type { ClientWebSocketEvents } from '@revanced/bot-api'
|
||||||
|
|
||||||
const { client } = context.api
|
const { client } = context.api
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
import type { Command } from '$commands/types'
|
|
||||||
import { listAllFilesRecursive } from '$utils/fs'
|
|
||||||
|
|
||||||
export const loadCommands = async (dir: string) => {
|
|
||||||
const commandsMap: Record<string, Command> = {}
|
|
||||||
const files = listAllFilesRecursive(dir)
|
|
||||||
const commands = await Promise.all(
|
|
||||||
files.map(async file => {
|
|
||||||
const command = await import(file)
|
|
||||||
return command.default
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
for (const command of commands) {
|
|
||||||
if (command) commandsMap[command.data.name] = command
|
|
||||||
}
|
|
||||||
|
|
||||||
return commandsMap
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { DefaultEmbedColor, MessageScanHumanizedMode, ReVancedLogoURL } from '$/constants'
|
import { type APIEmbed, EmbedBuilder, type EmbedField, type JSONEncodable, type User } from 'discord.js'
|
||||||
import { EmbedBuilder, type EmbedField, type User } from 'discord.js'
|
import { DefaultEmbedColor, ReVancedLogoURL } from '$/constants'
|
||||||
import type { ConfigMessageScanResponseMessage } from '../../../config.schema'
|
import type { ConfigMessageScanResponseMessage } from '../../../config.schema'
|
||||||
|
|
||||||
export const createErrorEmbed = (title: string | null, description?: string) =>
|
export const createErrorEmbed = (title: string | null, description?: string) =>
|
||||||
@@ -24,21 +24,8 @@ export const createSuccessEmbed = (title: string | null, description?: string) =
|
|||||||
)
|
)
|
||||||
|
|
||||||
export const createMessageScanResponseEmbed = (
|
export const createMessageScanResponseEmbed = (
|
||||||
response: ConfigMessageScanResponseMessage,
|
response: NonNullable<ConfigMessageScanResponseMessage['embeds']>[number],
|
||||||
mode: 'ocr' | 'nlp' | 'match',
|
) => applyCommonEmbedStyles(response, true, true, true)
|
||||||
) => {
|
|
||||||
const embed = new EmbedBuilder().setTitle(response.title ?? null)
|
|
||||||
|
|
||||||
if (response.description) embed.setDescription(response.description)
|
|
||||||
if (response.fields) embed.addFields(response.fields)
|
|
||||||
|
|
||||||
embed.setFooter({
|
|
||||||
text: `ReVanced • Done via ${MessageScanHumanizedMode[mode]}`,
|
|
||||||
iconURL: ReVancedLogoURL,
|
|
||||||
})
|
|
||||||
|
|
||||||
return applyCommonEmbedStyles(embed, true, true, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
export const createModerationActionEmbed = (
|
export const createModerationActionEmbed = (
|
||||||
action: string,
|
action: string,
|
||||||
@@ -74,19 +61,23 @@ export const applyReferenceToModerationActionEmbed = (embed: EmbedBuilder, refer
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const applyCommonEmbedStyles = (
|
export const applyCommonEmbedStyles = (
|
||||||
embed: EmbedBuilder,
|
embed: EmbedBuilder | JSONEncodable<APIEmbed> | APIEmbed,
|
||||||
setThumbnail = false,
|
setThumbnail = false,
|
||||||
setFooter = false,
|
setFooter = false,
|
||||||
setColor = false,
|
setColor = false,
|
||||||
) => {
|
) => {
|
||||||
|
// biome-ignore lint/style/noParameterAssign: While this is confusing, it is fine for this purpose
|
||||||
|
if ('toJSON' in embed) embed = embed.toJSON()
|
||||||
|
const builder = new EmbedBuilder(embed)
|
||||||
|
|
||||||
if (setFooter)
|
if (setFooter)
|
||||||
embed.setFooter({
|
builder.setFooter({
|
||||||
text: 'ReVanced',
|
text: 'ReVanced',
|
||||||
iconURL: ReVancedLogoURL,
|
iconURL: ReVancedLogoURL,
|
||||||
})
|
})
|
||||||
|
|
||||||
if (setColor) embed.setColor(DefaultEmbedColor)
|
if (setColor) builder.setColor(DefaultEmbedColor)
|
||||||
if (setThumbnail) embed.setThumbnail(ReVancedLogoURL)
|
if (setThumbnail) builder.setThumbnail(ReVancedLogoURL)
|
||||||
|
|
||||||
return embed
|
return builder
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,25 @@
|
|||||||
import { type Response, responses } from '$/database/schemas'
|
import { ButtonStyle, ComponentType } from 'discord.js'
|
||||||
import type {
|
|
||||||
Config,
|
|
||||||
ConfigMessageScanResponse,
|
|
||||||
ConfigMessageScanResponseLabelConfig,
|
|
||||||
ConfigMessageScanResponseMessage,
|
|
||||||
} from 'config.schema'
|
|
||||||
import type { Message, PartialUser, User } from 'discord.js'
|
|
||||||
import { eq } from 'drizzle-orm'
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { type Response, responses } from '$/database/schemas'
|
||||||
import { createMessageScanResponseEmbed } from './embeds'
|
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 (
|
export const getResponseFromText = async (
|
||||||
content: string,
|
content: string,
|
||||||
responses: ConfigMessageScanResponse[],
|
responses: ConfigMessageScanResponse[],
|
||||||
// Just to be safe that we will never use data from the context parameter
|
// Just to be safe that we will never use data from the context parameter
|
||||||
{ api, logger }: Omit<typeof import('src/context'), 'config'>,
|
{ api, logger }: Omit<typeof import('src/context'), 'config'>,
|
||||||
ocrMode = false,
|
flags: { imageTriggersOnly?: boolean; textRegexesOnly?: boolean } = {},
|
||||||
) => {
|
): Promise<
|
||||||
let label: string | undefined
|
Omit<ConfigMessageScanResponse, 'triggers'> & { label?: string; triggers?: ConfigMessageScanResponse['triggers'] }
|
||||||
let response: ConfigMessageScanResponseMessage | undefined | null
|
> => {
|
||||||
|
type ResponseConfig = Awaited<ReturnType<typeof getResponseFromText>>
|
||||||
|
let responseConfig: Omit<ResponseConfig, 'triggers'> & { triggers?: ResponseConfig['triggers'] } = {
|
||||||
|
triggers: undefined,
|
||||||
|
response: null!,
|
||||||
|
}
|
||||||
|
|
||||||
const firstLabelIndexes: number[] = []
|
const firstLabelIndexes: number[] = []
|
||||||
|
|
||||||
// Test if all regexes before a label trigger is matched
|
// Test if all regexes before a label trigger is matched
|
||||||
@@ -25,29 +27,27 @@ export const getResponseFromText = async (
|
|||||||
const trigger = responses[i]!
|
const trigger = responses[i]!
|
||||||
|
|
||||||
// Filter override check is not neccessary here, we are already passing responses that match the filter
|
// Filter override check is not neccessary here, we are already passing responses that match the filter
|
||||||
// from the messageCreate handler
|
// from the messageCreate handler, see line 17 of messageCreate handler
|
||||||
const {
|
const {
|
||||||
triggers: { text: textTriggers, image: imageTriggers },
|
triggers: { text: textTriggers, image: imageTriggers },
|
||||||
response: resp,
|
|
||||||
} = trigger
|
} = trigger
|
||||||
if (response) break
|
|
||||||
|
|
||||||
if (ocrMode) {
|
if (flags.imageTriggersOnly) {
|
||||||
if (imageTriggers)
|
if (imageTriggers)
|
||||||
for (const regex of imageTriggers)
|
for (const regex of imageTriggers)
|
||||||
if (regex.test(content)) {
|
if (regex.test(content)) {
|
||||||
logger.debug(`Message matched regex (OCR mode): ${regex.source}`)
|
logger.debug(`Message matched regex (OCR mode): ${regex.source}`)
|
||||||
response = resp
|
responseConfig = trigger
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
} else
|
} else {
|
||||||
for (let j = 0; j < textTriggers!.length; j++) {
|
for (let j = 0; j < textTriggers!.length; j++) {
|
||||||
const trigger = textTriggers![j]!
|
const regex = textTriggers![j]!
|
||||||
|
|
||||||
if (trigger instanceof RegExp) {
|
if (regex instanceof RegExp) {
|
||||||
if (trigger.test(content)) {
|
if (regex.test(content)) {
|
||||||
logger.debug(`Message matched regex (before mode): ${trigger.source}`)
|
logger.debug(`Message matched regex (before mode): ${regex.source}`)
|
||||||
response = resp
|
responseConfig = trigger
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -56,54 +56,54 @@ export const getResponseFromText = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// If none of the regexes match, we can search for labels immediately
|
// If none of the regexes match, we can search for labels immediately
|
||||||
if (!response && !ocrMode) {
|
if (!responseConfig.triggers && !flags.textRegexesOnly) {
|
||||||
logger.debug('No match from before regexes, doing NLP')
|
logger.debug('No match from before regexes, doing NLP')
|
||||||
const scan = await api.client.parseText(content)
|
const scan = await api.client.parseText(content)
|
||||||
if (scan.labels.length) {
|
if (scan.labels.length) {
|
||||||
const matchedLabel = scan.labels[0]!
|
const matchedLabel = scan.labels[0]!
|
||||||
logger.debug(`Message matched label with confidence: ${matchedLabel.name}, ${matchedLabel.confidence}`)
|
logger.debug(`Message matched label with confidence: ${matchedLabel.name}, ${matchedLabel.confidence}`)
|
||||||
|
|
||||||
let triggerConfig: ConfigMessageScanResponseLabelConfig | undefined
|
let trigger: ConfigMessageScanResponseLabelConfig | undefined
|
||||||
const labelConfig = responses.find(x => {
|
const response = responses.find(x => {
|
||||||
const config = x.triggers.text!.find(
|
const config = x.triggers.text!.find(
|
||||||
(x): x is ConfigMessageScanResponseLabelConfig => 'label' in x && x.label === matchedLabel.name,
|
(x): x is ConfigMessageScanResponseLabelConfig => 'label' in x && x.label === matchedLabel.name,
|
||||||
)
|
)
|
||||||
if (config) triggerConfig = config
|
if (config) trigger = config
|
||||||
return config
|
return config
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!labelConfig) {
|
|
||||||
logger.warn(`No label config found for label ${matchedLabel.name}`)
|
|
||||||
return { response: null, label: undefined }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matchedLabel.confidence >= triggerConfig!.threshold) {
|
|
||||||
logger.debug('Label confidence is enough')
|
|
||||||
label = matchedLabel.name
|
|
||||||
response = labelConfig.response
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we still don't have a label, we can match all regexes after the initial label trigger
|
|
||||||
if (!response) {
|
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 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')
|
logger.debug('No match from NLP, doing after regexes')
|
||||||
for (let i = 0; i < responses.length; i++) {
|
for (let i = 0; i < responses.length; i++) {
|
||||||
const {
|
const {
|
||||||
triggers: { text: textTriggers },
|
triggers: { text: textTriggers },
|
||||||
response: resp,
|
|
||||||
} = responses[i]!
|
} = responses[i]!
|
||||||
const firstLabelIndex = firstLabelIndexes[i] ?? -1
|
const firstLabelIndex = firstLabelIndexes[i] ?? -1
|
||||||
|
|
||||||
for (let i = firstLabelIndex + 1; i < textTriggers!.length; i++) {
|
for (let j = firstLabelIndex + 1; j < textTriggers!.length; j++) {
|
||||||
const trigger = textTriggers![i]!
|
const trigger = textTriggers![j]!
|
||||||
|
|
||||||
if (trigger instanceof RegExp) {
|
if (trigger instanceof RegExp) {
|
||||||
if (trigger.test(content)) {
|
if (trigger.test(content)) {
|
||||||
logger.debug(`Message matched regex (after mode): ${trigger.source}`)
|
logger.debug(`Message matched regex (after mode): ${trigger.source}`)
|
||||||
response = resp
|
responseConfig = responses[i]!
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -111,45 +111,54 @@ export const getResponseFromText = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return responseConfig
|
||||||
response,
|
|
||||||
label,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const shouldScanMessage = (
|
export const messageMatchesFilter = (message: Message, filter: NonNullable<Config['messageScan']>['filter']) => {
|
||||||
message: Message,
|
|
||||||
filter: NonNullable<Config['messageScan']>['filter'],
|
|
||||||
): message is Message<true> => {
|
|
||||||
if (message.author.bot) return false
|
|
||||||
if (!message.guild) return false
|
|
||||||
if (!filter) return true
|
if (!filter) return true
|
||||||
|
|
||||||
const filters = [
|
const memberRoles = new Set(message.member?.roles.cache.keys())
|
||||||
filter.users?.includes(message.author.id),
|
const { blacklist, whitelist } = filter
|
||||||
message.member?.roles.cache.some(x => filter.roles?.includes(x.id)),
|
|
||||||
filter.channels?.includes(message.channel.id),
|
|
||||||
]
|
|
||||||
|
|
||||||
if (filter.whitelist && filters.every(x => !x)) return false
|
// If matches only blacklist, will return false
|
||||||
if (!filter.whitelist && filters.some(x => x)) return false
|
// If matches whitelist but also matches blacklist, will return false
|
||||||
|
// If matches only whitelist, will return true
|
||||||
return true
|
// If matches neither, will return true
|
||||||
|
return (
|
||||||
|
(whitelist
|
||||||
|
? whitelist.channels?.includes(message.channelId) ||
|
||||||
|
whitelist.roles?.some(role => memberRoles.has(role)) ||
|
||||||
|
whitelist.users?.includes(message.author.id)
|
||||||
|
: true) &&
|
||||||
|
!(
|
||||||
|
blacklist &&
|
||||||
|
(blacklist.channels?.includes(message.channelId) ||
|
||||||
|
blacklist.roles?.some(role => memberRoles.has(role)) ||
|
||||||
|
blacklist.users?.includes(message.author.id))
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const handleUserResponseCorrection = async (
|
export const handleUserResponseCorrection = async (
|
||||||
{ api, database: db, config: { messageScan: msConfig }, logger }: typeof import('$/context'),
|
{ api, database: db, config: { messageScan: msConfig }, logger }: typeof import('$/context'),
|
||||||
response: Response,
|
response: Response,
|
||||||
reply: Message,
|
reply: Message,
|
||||||
label: string,
|
|
||||||
user: User | PartialUser,
|
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 =>
|
const correctLabelResponse = msConfig!.responses!.find(r =>
|
||||||
r.triggers.text!.some(t => 'label' in t && t.label === label),
|
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) throw new Error('Cannot find label config for the selected label')
|
||||||
if (!correctLabelResponse.response) return void (await reply.delete())
|
|
||||||
|
|
||||||
if (response.label !== label) {
|
if (response.label !== label) {
|
||||||
db.update(responses)
|
db.update(responses)
|
||||||
@@ -158,13 +167,42 @@ export const handleUserResponseCorrection = async (
|
|||||||
correctedById: user.id,
|
correctedById: user.id,
|
||||||
})
|
})
|
||||||
.where(eq(responses.replyId, response.replyId))
|
.where(eq(responses.replyId, response.replyId))
|
||||||
await reply.edit({
|
|
||||||
embeds: [createMessageScanResponseEmbed(correctLabelResponse.response, 'nlp')],
|
return void (await reply.edit({
|
||||||
})
|
...correctLabelResponse.response,
|
||||||
|
embeds: correctLabelResponse.response.embeds?.map(createMessageScanResponseEmbed),
|
||||||
|
components: [],
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
await api.client.trainMessage(response.content, label)
|
await Promise.all([
|
||||||
logger.debug(`User ${user.id} trained message ${response.replyId} as ${label} (positive)`)
|
api.client.trainMessage(response.content, label),
|
||||||
|
reply.edit({
|
||||||
await reply.reactions.removeAll()
|
components: [],
|
||||||
|
}),
|
||||||
|
]).finally(() => logger.debug(`User ${user.id} trained message ${response.replyId} as ${label}`))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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>,
|
||||||
|
]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { config, logger } from '$/context'
|
|
||||||
import decancer from 'decancer'
|
import decancer from 'decancer'
|
||||||
import type { ChatInputCommandInteraction, EmbedBuilder, Guild, GuildMember, User } from 'discord.js'
|
import { config, logger } from '$/context'
|
||||||
import { applyReferenceToModerationActionEmbed, createModerationActionEmbed } from './embeds'
|
import { applyReferenceToModerationActionEmbed, createModerationActionEmbed } from './embeds'
|
||||||
|
import type { CommandInteraction, EmbedBuilder, Guild, GuildMember, Message, User } from 'discord.js'
|
||||||
|
|
||||||
const PresetLogAction = {
|
const PresetLogAction = {
|
||||||
apply: 'Applied role preset to',
|
apply: 'Applied role preset to',
|
||||||
@@ -10,19 +10,20 @@ const PresetLogAction = {
|
|||||||
|
|
||||||
export const sendPresetReplyAndLogs = (
|
export const sendPresetReplyAndLogs = (
|
||||||
action: keyof typeof PresetLogAction,
|
action: keyof typeof PresetLogAction,
|
||||||
interaction: ChatInputCommandInteraction,
|
interaction: CommandInteraction | Message,
|
||||||
|
executor: GuildMember,
|
||||||
user: User,
|
user: User,
|
||||||
preset: string,
|
preset: string,
|
||||||
expires?: number | null,
|
expires?: number | null,
|
||||||
) =>
|
) =>
|
||||||
sendModerationReplyAndLogs(
|
sendModerationReplyAndLogs(
|
||||||
interaction,
|
interaction,
|
||||||
createModerationActionEmbed(PresetLogAction[action], user, interaction.user, undefined, expires, [
|
createModerationActionEmbed(PresetLogAction[action], user, executor.user, undefined, expires, [
|
||||||
[{ name: 'Preset', value: preset, inline: true }],
|
[{ name: 'Preset', value: preset, inline: true }],
|
||||||
]),
|
]),
|
||||||
)
|
)
|
||||||
|
|
||||||
export const sendModerationReplyAndLogs = async (interaction: ChatInputCommandInteraction, embed: EmbedBuilder) => {
|
export const sendModerationReplyAndLogs = async (interaction: CommandInteraction | Message, embed: EmbedBuilder) => {
|
||||||
const reply = await interaction.reply({ embeds: [embed] }).then(it => it.fetch())
|
const reply = await interaction.reply({ embeds: [embed] }).then(it => it.fetch())
|
||||||
const logChannel = await getLogChannel(interaction.guild!)
|
const logChannel = await getLogChannel(interaction.guild!)
|
||||||
await logChannel?.send({ embeds: [applyReferenceToModerationActionEmbed(embed, reply.url)] })
|
await logChannel?.send({ embeds: [applyReferenceToModerationActionEmbed(embed, reply.url)] })
|
||||||
@@ -34,7 +35,7 @@ export const getLogChannel = async (guild: Guild) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const channel = await guild.channels.fetch(logConfig.thread ?? logConfig.channel)
|
const channel = await guild.channels.fetch(logConfig.thread ?? logConfig.channel)
|
||||||
if (!channel || !channel.isTextBased())
|
if (!channel?.isTextBased())
|
||||||
return void logger.warn('The moderation log channel does not exist, skipping logging')
|
return void logger.warn('The moderation log channel does not exist, skipping logging')
|
||||||
|
|
||||||
return channel
|
return channel
|
||||||
@@ -46,17 +47,17 @@ export const getLogChannel = async (guild: Guild) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const cureNickname = async (member: GuildMember) => {
|
export const cureNickname = async (member: GuildMember) => {
|
||||||
if (!member.manageable) throw new Error('Member is not manageable')
|
if (!member.manageable) return
|
||||||
const name = member.displayName
|
const name = member.displayName
|
||||||
let cured = decancer(name)
|
let cured = decancer(name)
|
||||||
.toString()
|
.toString()
|
||||||
.replace(/[^a-zA-Z0-9]/g, '')
|
.replace(new RegExp(config.moderation?.cure?.removeCharactersRegex ?? '[^a-zA-Z0-9 \\-_]', 'g'), '')
|
||||||
|
|
||||||
if (cured.length < 3 || !/^[a-zA-Z]/.test(cured))
|
if (cured.length < (config?.moderation?.cure?.minimumNameLength ?? 3))
|
||||||
cured =
|
cured =
|
||||||
member.user.username.length >= 3
|
member.user.username.length >= 3
|
||||||
? member.user.username
|
? member.user.username
|
||||||
: config.moderation?.cure?.defaultName ?? 'Server member'
|
: (config.moderation?.cure?.defaultName ?? 'Server member')
|
||||||
|
|
||||||
if (cured.toLowerCase() === name.toLowerCase()) return
|
if (cured.toLowerCase() === name.toLowerCase()) return
|
||||||
|
|
||||||
|
|||||||
14
bots/discord/src/utils/discord/permissions.ts
Normal file
14
bots/discord/src/utils/discord/permissions.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { GuildMember, type User } from 'discord.js'
|
||||||
|
import { config } from '../../context'
|
||||||
|
|
||||||
|
export const isAdmin = (userOrMember: User | GuildMember) => {
|
||||||
|
return (
|
||||||
|
config.admin?.users?.includes(userOrMember.id) ||
|
||||||
|
(userOrMember instanceof GuildMember && isMemberAdmin(userOrMember))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isMemberAdmin = (member: GuildMember) => {
|
||||||
|
const roles = new Set(member.roles.cache.keys())
|
||||||
|
return Boolean(config?.admin?.roles?.[member.guild.id]?.some(role => roles.has(role)))
|
||||||
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
|
import { and, eq } from 'drizzle-orm'
|
||||||
import { config, database } from '$/context'
|
import { config, database } from '$/context'
|
||||||
import { appliedPresets } from '$/database/schemas'
|
import { appliedPresets } from '$/database/schemas'
|
||||||
import type { GuildMember } from 'discord.js'
|
import type { GuildMember } from 'discord.js'
|
||||||
import { and, eq } from 'drizzle-orm'
|
|
||||||
|
|
||||||
// TODO: Fix this type
|
// TODO: Fix this type
|
||||||
type PresetKey = string
|
type PresetKey = string
|
||||||
|
|
||||||
export const applyRolePreset = async (member: GuildMember, presetName: PresetKey, untilMs: number | null) => {
|
export const applyRolePreset = async (member: GuildMember, presetName: PresetKey, expires: number) => {
|
||||||
const afterInsert = await applyRolesUsingPreset(presetName, member, true)
|
const { removed, callback } = await applyRolesUsingPreset(presetName, member)
|
||||||
const until = untilMs ? Math.ceil(untilMs / 1000) : null
|
const until = expires === Infinity ? null : Math.ceil(expires / 1000)
|
||||||
|
|
||||||
await database
|
await database
|
||||||
.insert(appliedPresets)
|
.insert(appliedPresets)
|
||||||
@@ -16,39 +16,60 @@ export const applyRolePreset = async (member: GuildMember, presetName: PresetKey
|
|||||||
memberId: member.id,
|
memberId: member.id,
|
||||||
guildId: member.guild.id,
|
guildId: member.guild.id,
|
||||||
preset: presetName,
|
preset: presetName,
|
||||||
|
removedRoles: removed,
|
||||||
until,
|
until,
|
||||||
})
|
})
|
||||||
.onConflictDoUpdate({
|
.onConflictDoUpdate({
|
||||||
target: [appliedPresets.memberId, appliedPresets.preset, appliedPresets.guildId],
|
target: [appliedPresets.memberId, appliedPresets.preset, appliedPresets.guildId],
|
||||||
set: { until },
|
set: { until },
|
||||||
})
|
})
|
||||||
.then(afterInsert)
|
.then(callback)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const removeRolePreset = async (member: GuildMember, presetName: PresetKey) => {
|
export const removeRolePreset = async (member: GuildMember, presetName: PresetKey) => {
|
||||||
const afterDelete = await applyRolesUsingPreset(presetName, member, false)
|
const where = and(
|
||||||
|
|
||||||
await database
|
|
||||||
.delete(appliedPresets)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(appliedPresets.memberId, member.id),
|
eq(appliedPresets.memberId, member.id),
|
||||||
eq(appliedPresets.preset, presetName),
|
eq(appliedPresets.preset, presetName),
|
||||||
eq(appliedPresets.guildId, member.guild.id),
|
eq(appliedPresets.guildId, member.guild.id),
|
||||||
),
|
|
||||||
)
|
)
|
||||||
.execute()
|
|
||||||
.then(afterDelete)
|
const data = await database.query.appliedPresets.findFirst({ where })
|
||||||
|
if (!data) return false
|
||||||
|
|
||||||
|
const { callback } = await applyRolesUsingPreset(presetName, member, data.removedRoles)
|
||||||
|
await database.delete(appliedPresets).where(where).execute().then(callback)
|
||||||
|
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
export const applyRolesUsingPreset = async (presetName: string, member: GuildMember, applying: boolean) => {
|
export const applyRolesUsingPreset = async (
|
||||||
|
presetName: string,
|
||||||
|
member: GuildMember,
|
||||||
|
removePresetGiveRoles?: string[],
|
||||||
|
) => {
|
||||||
const preset = config.rolePresets?.guilds[member.guild.id]?.[presetName]
|
const preset = config.rolePresets?.guilds[member.guild.id]?.[presetName]
|
||||||
if (!preset) throw new Error(`The preset "${presetName}" does not exist for this server`)
|
if (!preset) throw new Error(`The preset "${presetName}" does not exist for this server`)
|
||||||
|
|
||||||
const roles = new Set(member.roles.cache.keys())
|
const roles = new Set(member.roles.cache.keys())
|
||||||
|
const removed: string[] = []
|
||||||
|
|
||||||
for (const role of preset.give) roles[applying ? 'add' : 'delete'](role)
|
// If removePresetGiveRoles is not provided, we're applying a preset
|
||||||
for (const role of preset.take) roles[applying ? 'delete' : 'add'](role)
|
if (!removePresetGiveRoles) {
|
||||||
|
for (const role of preset.give) roles.add(role)
|
||||||
return () => member.roles.set(Array.from(roles))
|
for (const role of preset.take) {
|
||||||
|
if (roles.has(role)) {
|
||||||
|
roles.delete(role)
|
||||||
|
removed.push(role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const guildRoles = await member.guild.roles.fetch()
|
||||||
|
for (const role of preset.give) roles.delete(role)
|
||||||
|
for (const role of removePresetGiveRoles) if (guildRoles.has(role)) roles.add(role)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
removed,
|
||||||
|
callback: () => member.roles.set(Array.from(roles)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,44 @@
|
|||||||
export const parseDuration = (duration: string) => {
|
import { Duration, DurationFormatter } from '@sapphire/duration'
|
||||||
if (!duration.length) return Number.NaN
|
|
||||||
const matches = duration.match(/(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?/)!
|
|
||||||
|
|
||||||
const [, days, hours, minutes, seconds] = matches.map(Number)
|
const fmt = new DurationFormatter({
|
||||||
return (
|
year: {
|
||||||
(days || 0) * 24 * 60 * 60 * 1000 +
|
DEFAULT: 'y',
|
||||||
(hours || 0) * 60 * 60 * 1000 +
|
},
|
||||||
(minutes || 0) * 60 * 1000 +
|
month: {
|
||||||
(seconds || 0) * 1000
|
DEFAULT: 'M',
|
||||||
)
|
},
|
||||||
|
week: {
|
||||||
|
DEFAULT: 'w',
|
||||||
|
},
|
||||||
|
day: {
|
||||||
|
DEFAULT: 'd',
|
||||||
|
},
|
||||||
|
hour: {
|
||||||
|
DEFAULT: 'h',
|
||||||
|
},
|
||||||
|
minute: {
|
||||||
|
DEFAULT: 'm',
|
||||||
|
},
|
||||||
|
second: {
|
||||||
|
DEFAULT: 's',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
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) => {
|
export const durationToString = (duration: number) => {
|
||||||
if (duration === 0) return '0s'
|
return fmt.format(duration, undefined, {
|
||||||
|
left: '',
|
||||||
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)
|
export function isSafeTimeoutDuration(duration: number) {
|
||||||
|
return duration > 0 && duration < 2 ** 31 - 1
|
||||||
return `${days ? `${days}d` : ''}${hours ? `${hours}h` : ''}${minutes ? `${minutes}m` : ''}${
|
|
||||||
seconds ? `${seconds}s` : ''
|
|
||||||
}`
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,17 +7,27 @@ export const listAllFilesRecursive = (dir: string): string[] =>
|
|||||||
.filter(x => x.isFile())
|
.filter(x => x.isFile())
|
||||||
.map(x => join(x.parentPath, x.name).replaceAll(pathSep, posixPathSep))
|
.map(x => join(x.parentPath, x.name).replaceAll(pathSep, posixPathSep))
|
||||||
|
|
||||||
export const generateCommandsIndex = (dirPath: string) => generateIndexes(dirPath, x => !x.endsWith('types.ts'))
|
export const generateCommandsIndex = (dirPath: string) =>
|
||||||
|
generateIndexes(dirPath, (x, i) => `export { default as C${i} } from './${x}'`)
|
||||||
|
|
||||||
export const generateEventsIndex = (dirPath: string) => generateIndexes(dirPath)
|
export const generateEventsIndex = (dirPath: string) => generateIndexes(dirPath)
|
||||||
|
|
||||||
const generateIndexes = async (dirPath: string, pathFilter?: (path: string) => boolean) => {
|
const generateIndexes = async (
|
||||||
|
dirPath: string,
|
||||||
|
customMap?: (path: string, index: number) => string,
|
||||||
|
pathFilter?: (path: string) => boolean,
|
||||||
|
) => {
|
||||||
const files = listAllFilesRecursive(dirPath)
|
const files = listAllFilesRecursive(dirPath)
|
||||||
.filter(x => (x.endsWith('.ts') && !x.endsWith('index.ts') && pathFilter ? pathFilter(x) : true))
|
.filter(x => x.endsWith('.ts') && !x.endsWith('index.ts') && (pathFilter ? pathFilter(x) : true))
|
||||||
.map(x => relative(dirPath, x).replaceAll(pathSep, posixPathSep))
|
.map(x => relative(dirPath, x).replaceAll(pathSep, posixPathSep))
|
||||||
|
|
||||||
writeFileSync(
|
writeFileSync(
|
||||||
join(dirPath, 'index.ts'),
|
join(dirPath, 'index.ts'),
|
||||||
`// AUTO-GENERATED BY A SCRIPT, DON'T TOUCH\n\n${files.map(c => `import './${c.split('.').at(-2)}'`).join('\n')}`,
|
`// AUTO-GENERATED BY A SCRIPT, DON'T TOUCH\n\n${files
|
||||||
|
.map((c, i) => {
|
||||||
|
const path = c.split('.').at(-2)!
|
||||||
|
return customMap ? customMap(path, i) : `import './${path}'`
|
||||||
|
})
|
||||||
|
.join('\n')}`,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ To start developing, you'll need to set up the development environment first.
|
|||||||
2. Clone the mono-repository
|
2. Clone the mono-repository
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone https://github.com/revanced/revanced-helper.git &&
|
git clone https://github.com/revanced/revanced-bots.git &&
|
||||||
cd revanced-helper
|
cd revanced-bots
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Install dependencies
|
3. Install dependencies
|
||||||
|
|||||||
42
package.json
42
package.json
@@ -1,12 +1,16 @@
|
|||||||
{
|
{
|
||||||
"name": "revanced-helper",
|
"name": "revanced-bots",
|
||||||
"description": "🤖 Bots assisting ReVanced on multiple platforms",
|
"description": "🤖 Bots assisting ReVanced on multiple platforms",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
||||||
"workspaces": ["packages/*", "apis/*", "bots/*"],
|
"workspaces": [
|
||||||
|
"packages/*",
|
||||||
|
"apis/*",
|
||||||
|
"bots/*"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:all": "turbo run build",
|
"build:all": "turbo run build",
|
||||||
"build:packages": "turbo build --filter=\"./packages/*\"",
|
"build:packages": "turbo build --filter=\"./packages/*\"",
|
||||||
@@ -15,37 +19,37 @@
|
|||||||
"flint:check": "biome check .",
|
"flint:check": "biome check .",
|
||||||
"clint": "commitlint --edit"
|
"clint": "commitlint --edit"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
"homepage": "https://github.com/revanced/revanced-bots#readme",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/revanced/revanced-helper.git"
|
"url": "git+https://github.com/revanced/revanced-bots.git"
|
||||||
},
|
},
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/revanced/revanced-helper/issues"
|
"url": "https://github.com/revanced/revanced-bots/issues"
|
||||||
},
|
},
|
||||||
"contributors": [
|
"contributors": [
|
||||||
"Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
"Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
||||||
"ReVanced <nosupport@revanced.app> (https://revanced.app)"
|
"ReVanced <nosupport@revanced.app> (https://revanced.app)"
|
||||||
],
|
],
|
||||||
"packageManager": "bun@1.1.20",
|
"packageManager": "bun@1.2.17",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@anolilab/multi-semantic-release": "^1.1.3",
|
"@anolilab/multi-semantic-release": "^2.0.3",
|
||||||
"@biomejs/biome": "^1.8.3",
|
"@biomejs/biome": "^2.2.4",
|
||||||
"@codedependant/semantic-release-docker": "^5.0.3",
|
"@codedependant/semantic-release-docker": "^5.1.1",
|
||||||
"@commitlint/cli": "^19.3.0",
|
"@commitlint/cli": "^19.8.1",
|
||||||
"@commitlint/config-conventional": "^19.2.2",
|
"@commitlint/config-conventional": "^19.8.1",
|
||||||
"@saithodev/semantic-release-backmerge": "^4.0.1",
|
"@saithodev/semantic-release-backmerge": "^4.0.1",
|
||||||
"@semantic-release/changelog": "^6.0.3",
|
"@semantic-release/changelog": "^6.0.3",
|
||||||
"@semantic-release/exec": "^6.0.3",
|
"@semantic-release/exec": "^7.1.0",
|
||||||
"@semantic-release/git": "^10.0.1",
|
"@semantic-release/git": "^10.0.1",
|
||||||
"@tsconfig/strictest": "^2.0.5",
|
"@tsconfig/strictest": "^2.0.5",
|
||||||
"@types/bun": "^1.1.6",
|
"@types/bun": "^1.2.21",
|
||||||
"conventional-changelog-conventionalcommits": "^7.0.2",
|
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||||
"lefthook": "^1.7.5",
|
"lefthook": "^1.13.0",
|
||||||
"portainer-service-webhook": "https://github.com/newarifrh/portainer-service-webhook#v1",
|
"portainer-service-webhook": "https://github.com/newarifrh/portainer-service-webhook#v1",
|
||||||
"semantic-release": "^24.0.0",
|
"semantic-release": "^24.2.8",
|
||||||
"turbo": "^2.0.9",
|
"turbo": "^2.5.6",
|
||||||
"typescript": "^5.5.4"
|
"typescript": "^5.9.2"
|
||||||
},
|
},
|
||||||
"trustedDependencies": [
|
"trustedDependencies": [
|
||||||
"@biomejs/biome",
|
"@biomejs/biome",
|
||||||
@@ -54,6 +58,6 @@
|
|||||||
"lefthook"
|
"lefthook"
|
||||||
],
|
],
|
||||||
"patchedDependencies": {
|
"patchedDependencies": {
|
||||||
"@semantic-release/npm@12.0.1": "patches/@semantic-release%2Fnpm@12.0.1.patch"
|
"@semantic-release/npm@12.0.2": "patches/@semantic-release%2Fnpm@12.0.2.patch"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/revanced/revanced-helper.git",
|
"url": "git+https://github.com/revanced/revanced-bots.git",
|
||||||
"directory": "packages/api"
|
"directory": "packages/api"
|
||||||
},
|
},
|
||||||
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
||||||
@@ -23,15 +23,15 @@
|
|||||||
],
|
],
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/revanced/revanced-helper/issues"
|
"url": "https://github.com/revanced/revanced-bots/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
"homepage": "https://github.com/revanced/revanced-bots#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@revanced/bot-shared": "workspace:*",
|
"@revanced/bot-shared": "workspace:*",
|
||||||
"ws": "^8.17.1"
|
"ws": "^8.18.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/ws": "^8.5.10",
|
"@types/ws": "^8.18.1",
|
||||||
"typed-emitter": "^2.1.0"
|
"typed-emitter": "^2.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,17 +52,20 @@ export default class Client {
|
|||||||
// But if we add anything similar, this will cause another race condition
|
// But if we add anything similar, this will cause another race condition
|
||||||
// To fix this, we can try adding a instanced function that would return the currentSequence
|
// To fix this, we can try adding a instanced function that would return the currentSequence
|
||||||
// and it would be updated every time a "heartbeat ack" packet is received
|
// and it would be updated every time a "heartbeat ack" packet is received
|
||||||
return Promise.race([
|
const packet = await Promise.race([
|
||||||
this.#awaiter.await(ServerOperation.ParsedText, this.ws.currentSequence),
|
this.#awaiter.await(ServerOperation.ParsedText, this.ws.currentSequence),
|
||||||
this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.timeout + 5000),
|
this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.currentSequence, this.ws.timeout + 5000),
|
||||||
])
|
])
|
||||||
.then(pkt => {
|
.then(pkt => {
|
||||||
if (pkt.op === ServerOperation.ParsedText) return pkt.d
|
if (pkt.op === ServerOperation.ParsedText) return pkt.d
|
||||||
throw new Error('Failed to parse text, the API encountered an error')
|
return null
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
throw new Error('Failed to parse text, the API did not respond in time')
|
throw new Error('Failed to parse text, the API did not respond in time')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (!packet) throw new Error('Failed to parse text, the API encountered an error')
|
||||||
|
return packet
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,20 +85,23 @@ export default class Client {
|
|||||||
|
|
||||||
// See line 50
|
// See line 50
|
||||||
|
|
||||||
return Promise.race([
|
const packet = await Promise.race([
|
||||||
this.#awaiter.await(ServerOperation.ParsedImage, this.ws.currentSequence),
|
this.#awaiter.await(ServerOperation.ParsedImage, this.ws.currentSequence),
|
||||||
this.#awaiter.await(ServerOperation.ParseImageFailed, this.ws.timeout + 5000),
|
this.#awaiter.await(ServerOperation.ParseImageFailed, this.ws.currentSequence, this.ws.timeout + 5000),
|
||||||
])
|
])
|
||||||
.then(pkt => {
|
.then(pkt => {
|
||||||
if (pkt.op === ServerOperation.ParsedImage) return pkt.d
|
if (pkt.op === ServerOperation.ParsedImage) return pkt.d
|
||||||
throw new Error('Failed to parse image, the API encountered an error')
|
return null
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
throw new Error('Failed to parse image, the API did not respond in time')
|
throw new Error('Failed to parse image, the API did not respond in time')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (!packet) throw new Error('Failed to parse image, the API encountered an error')
|
||||||
|
return packet
|
||||||
}
|
}
|
||||||
|
|
||||||
async trainMessage(text: string, label: string) {
|
async trainMessage(text: string, label?: string) {
|
||||||
this.#throwIfNotReady()
|
this.#throwIfNotReady()
|
||||||
|
|
||||||
this.ws.send({
|
this.ws.send({
|
||||||
@@ -107,17 +113,20 @@ export default class Client {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// See line 50
|
// See line 50
|
||||||
return Promise.race([
|
const packet = await Promise.race([
|
||||||
this.#awaiter.await(ServerOperation.TrainedMessage, this.ws.currentSequence),
|
this.#awaiter.await(ServerOperation.TrainedMessage, this.ws.currentSequence),
|
||||||
this.#awaiter.await(ServerOperation.TrainMessageFailed, this.ws.timeout + 5000),
|
this.#awaiter.await(ServerOperation.TrainMessageFailed, this.ws.currentSequence, this.ws.timeout + 5000),
|
||||||
])
|
])
|
||||||
.then(pkt => {
|
.then(pkt => {
|
||||||
if (pkt.op === ServerOperation.TrainedMessage) return pkt.d
|
if (pkt.op === ServerOperation.TrainedMessage) return pkt.d
|
||||||
throw new Error('Failed to train message, the API encountered an error')
|
return null
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
throw new Error('Failed to train message, the API did not respond in time')
|
throw new Error('Failed to train message, the API did not respond in time')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (!packet) throw new Error('Failed to train message, the API encountered an error')
|
||||||
|
return packet
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -163,13 +172,17 @@ export default class Client {
|
|||||||
/**
|
/**
|
||||||
* Disconnects the client from the API
|
* Disconnects the client from the API
|
||||||
*/
|
*/
|
||||||
disconnect() {
|
disconnect(force?: boolean) {
|
||||||
this.ws.disconnect()
|
this.ws.disconnect(force)
|
||||||
}
|
}
|
||||||
|
|
||||||
#throwIfNotReady() {
|
#throwIfNotReady() {
|
||||||
if (!this.isReady()) throw new Error('Client is not ready')
|
if (!this.isReady()) throw new Error('Client is not ready')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get disconnected() {
|
||||||
|
return this.ws.disconnected
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ClientWebSocketPacketAwaiter {
|
export class ClientWebSocketPacketAwaiter {
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
import { EventEmitter } from 'events'
|
|
||||||
import {
|
import {
|
||||||
type ClientOperation,
|
type ClientOperation,
|
||||||
DisconnectReason,
|
DisconnectReason,
|
||||||
type Packet,
|
|
||||||
ServerOperation,
|
|
||||||
deserializePacket,
|
deserializePacket,
|
||||||
isServerPacket,
|
isServerPacket,
|
||||||
|
type Packet,
|
||||||
|
ServerOperation,
|
||||||
serializePacket,
|
serializePacket,
|
||||||
uncapitalize,
|
uncapitalize,
|
||||||
} from '@revanced/bot-shared'
|
} from '@revanced/bot-shared'
|
||||||
import type TypedEmitter from 'typed-emitter'
|
import { EventEmitter } from 'events'
|
||||||
import { type RawData, WebSocket } from 'ws'
|
import { type RawData, WebSocket } from 'ws'
|
||||||
|
import type TypedEmitter from 'typed-emitter'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The class that handles the WebSocket connection to the server.
|
* The class that handles the WebSocket connection to the server.
|
||||||
* This is the only relevant class for the time being. But in the future, there may be more classes to handle different protocols of the API.
|
* This is the only relevant class for the time being. But in the future, there may be more classes to handle different protocols of the API.
|
||||||
*/
|
*/
|
||||||
export class ClientWebSocketManager {
|
export class ClientWebSocketManager {
|
||||||
readonly url: string
|
url: string
|
||||||
timeout: number
|
timeout: number
|
||||||
|
|
||||||
connecting = false
|
connecting = false
|
||||||
@@ -33,6 +33,21 @@ export class ClientWebSocketManager {
|
|||||||
this.timeout = options.timeout ?? 10000
|
this.timeout = options.timeout ?? 10000
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the URL to connect to
|
||||||
|
*
|
||||||
|
* **Requires a reconnect to take effect**
|
||||||
|
*/
|
||||||
|
async setOptions({ url, timeout }: Partial<ClientWebSocketManagerOptions>, autoReconnect = true) {
|
||||||
|
if (url) this.url = url
|
||||||
|
this.timeout = timeout ?? this.timeout
|
||||||
|
|
||||||
|
if (autoReconnect) {
|
||||||
|
this.disconnect(true)
|
||||||
|
await this.connect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connects to the WebSocket API
|
* Connects to the WebSocket API
|
||||||
* @returns A promise that resolves when the client is ready
|
* @returns A promise that resolves when the client is ready
|
||||||
@@ -49,19 +64,13 @@ export class ClientWebSocketManager {
|
|||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
if (!this.ready) {
|
if (!this.ready) {
|
||||||
this.#socket?.close(DisconnectReason.TooSlow)
|
this.#socket?.close(DisconnectReason.TooSlow)
|
||||||
throw new Error('WebSocket connection was not readied in time')
|
this._handleDisconnect(DisconnectReason.TooSlow, 'WebSocket connection was not readied in time')
|
||||||
}
|
}
|
||||||
}, this.timeout)
|
}, this.timeout)
|
||||||
|
|
||||||
const errorBeforeReadyHandler = (err: Error) => {
|
|
||||||
cleanup()
|
|
||||||
throw err
|
|
||||||
}
|
|
||||||
|
|
||||||
const closeBeforeReadyHandler = (code: number, reason: Buffer) => {
|
const closeBeforeReadyHandler = (code: number, reason: Buffer) => {
|
||||||
clearTimeout(timeout)
|
|
||||||
this._handleDisconnect(code, reason.toString())
|
this._handleDisconnect(code, reason.toString())
|
||||||
throw new Error('WebSocket connection closed before ready')
|
cleanup()
|
||||||
}
|
}
|
||||||
|
|
||||||
const readyHandler = () => {
|
const readyHandler = () => {
|
||||||
@@ -71,20 +80,23 @@ export class ClientWebSocketManager {
|
|||||||
rs()
|
rs()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const socket = this.#socket
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
this.#socket.off('open', readyHandler)
|
socket.off('open', readyHandler)
|
||||||
this.#socket.off('close', closeBeforeReadyHandler)
|
socket.off('close', closeBeforeReadyHandler)
|
||||||
this.#socket.off('error', errorBeforeReadyHandler)
|
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
this.#socket.on('open', readyHandler)
|
this.#socket.on('open', readyHandler)
|
||||||
this.#socket.on('error', errorBeforeReadyHandler)
|
|
||||||
this.#socket.on('close', closeBeforeReadyHandler)
|
this.#socket.on('close', closeBeforeReadyHandler)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
rj(e)
|
rj(e)
|
||||||
}
|
}
|
||||||
}).finally(() => {
|
})
|
||||||
|
.then(() => {
|
||||||
|
this.#socket.on('close', (code, reason) => this._handleDisconnect(code, reason.toString()))
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
this.connecting = false
|
this.connecting = false
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -130,15 +142,15 @@ export class ClientWebSocketManager {
|
|||||||
this.currentSequence++
|
this.currentSequence++
|
||||||
|
|
||||||
this.#socket.send(serializePacket(packet), err => {
|
this.#socket.send(serializePacket(packet), err => {
|
||||||
throw err
|
if (err) throw err
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disconnects from the WebSocket API
|
* Disconnects from the WebSocket API
|
||||||
*/
|
*/
|
||||||
disconnect() {
|
disconnect(force?: boolean) {
|
||||||
this.#throwIfDisconnected('Cannot disconnect when already disconnected from the server')
|
if (!force) this.#throwIfDisconnected('Cannot disconnect when already disconnected from the server')
|
||||||
this._handleDisconnect(DisconnectReason.PlannedDisconnect)
|
this._handleDisconnect(DisconnectReason.PlannedDisconnect)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +207,7 @@ export class ClientWebSocketManager {
|
|||||||
protected _toBuffer(data: RawData) {
|
protected _toBuffer(data: RawData) {
|
||||||
if (data instanceof Buffer) return data
|
if (data instanceof Buffer) return data
|
||||||
if (data instanceof ArrayBuffer) return Buffer.from(data)
|
if (data instanceof ArrayBuffer) return Buffer.from(data)
|
||||||
return Buffer.concat(data)
|
return Buffer.concat(data as Uint8Array[])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
export { default as Client } from './Client'
|
|
||||||
export * from './Client'
|
export * from './Client'
|
||||||
|
export { default as Client } from './Client'
|
||||||
export * from './ClientWebSocket'
|
export * from './ClientWebSocket'
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/revanced/revanced-helper.git",
|
"url": "git+https://github.com/revanced/revanced-bots.git",
|
||||||
"directory": "packages/shared"
|
"directory": "packages/shared"
|
||||||
},
|
},
|
||||||
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
"author": "Palm <contact@palmdevs.me> (https://palmdevs.me)",
|
||||||
@@ -26,13 +26,13 @@
|
|||||||
],
|
],
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://github.com/revanced/revanced-helper/issues"
|
"url": "https://github.com/revanced/revanced-bots/issues"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
"homepage": "https://github.com/revanced/revanced-bots#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bson": "^6.7.0",
|
"bson": "^6.10.4",
|
||||||
"chalk": "^5.3.0",
|
"chalk": "^5.6.2",
|
||||||
"tracer": "^1.3.0",
|
"tracer": "^1.3.0",
|
||||||
"valibot": "^0.30.0"
|
"valibot": "^1.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import {
|
import {
|
||||||
url,
|
|
||||||
type AnySchema,
|
|
||||||
type NullSchema,
|
|
||||||
type ObjectSchema,
|
|
||||||
type Output,
|
|
||||||
array,
|
array,
|
||||||
|
boolean,
|
||||||
|
custom,
|
||||||
enum_,
|
enum_,
|
||||||
|
type InferOutput,
|
||||||
null_,
|
null_,
|
||||||
object,
|
object,
|
||||||
|
optional,
|
||||||
parse,
|
parse,
|
||||||
special,
|
pipe,
|
||||||
string,
|
string,
|
||||||
|
url,
|
||||||
// merge
|
// merge
|
||||||
} from 'valibot'
|
} from 'valibot'
|
||||||
import DisconnectReason from '../constants/DisconnectReason'
|
import DisconnectReason from '../constants/DisconnectReason'
|
||||||
@@ -19,15 +19,14 @@ import { ClientOperation, Operation, ServerOperation } from '../constants/Operat
|
|||||||
/**
|
/**
|
||||||
* Schema to validate packets
|
* Schema to validate packets
|
||||||
*/
|
*/
|
||||||
export const PacketSchema = special<Packet>(input => {
|
export const PacketSchema = custom<Packet>(input => {
|
||||||
if (
|
if (
|
||||||
typeof input === 'object' &&
|
typeof input === 'object' &&
|
||||||
input &&
|
input &&
|
||||||
'op' in input &&
|
'op' in input &&
|
||||||
typeof input.op === 'number' &&
|
typeof input.op === 'number' &&
|
||||||
input.op in Operation &&
|
input.op in Operation &&
|
||||||
'd' in input &&
|
'd' in input
|
||||||
typeof input.d === 'object'
|
|
||||||
) {
|
) {
|
||||||
if (input.op in ServerOperation && !('s' in input && typeof input.s === 'number')) return false
|
if (input.op in ServerOperation && !('s' in input && typeof input.s === 'number')) return false
|
||||||
|
|
||||||
@@ -50,7 +49,7 @@ export const PacketDataSchemas = {
|
|||||||
labels: array(
|
labels: array(
|
||||||
object({
|
object({
|
||||||
name: string(),
|
name: string(),
|
||||||
confidence: special<number>(input => typeof input === 'number' && input >= 0 && input <= 1),
|
confidence: custom<number>(input => typeof input === 'number' && input >= 0 && input <= 1),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
@@ -62,24 +61,20 @@ export const PacketDataSchemas = {
|
|||||||
[ServerOperation.Disconnect]: object({
|
[ServerOperation.Disconnect]: object({
|
||||||
reason: enum_(DisconnectReason),
|
reason: enum_(DisconnectReason),
|
||||||
}),
|
}),
|
||||||
[ServerOperation.TrainedMessage]: null_(),
|
[ServerOperation.TrainedMessage]: boolean(),
|
||||||
[ServerOperation.TrainMessageFailed]: null_(),
|
[ServerOperation.TrainMessageFailed]: null_(),
|
||||||
|
|
||||||
[ClientOperation.ParseText]: object({
|
[ClientOperation.ParseText]: object({
|
||||||
text: string(),
|
text: string(),
|
||||||
}),
|
}),
|
||||||
[ClientOperation.ParseImage]: object({
|
[ClientOperation.ParseImage]: object({
|
||||||
image_url: string([url()]),
|
image_url: pipe(string(), url()),
|
||||||
}),
|
}),
|
||||||
[ClientOperation.TrainMessage]: object({
|
[ClientOperation.TrainMessage]: object({
|
||||||
text: string(),
|
text: string(),
|
||||||
label: string(),
|
label: optional(string()),
|
||||||
}),
|
}),
|
||||||
} as const satisfies Record<
|
} as const
|
||||||
Operation,
|
|
||||||
// biome-ignore lint/suspicious/noExplicitAny: This is a schema, it's not possible to type it
|
|
||||||
ObjectSchema<any> | AnySchema | NullSchema
|
|
||||||
>
|
|
||||||
|
|
||||||
export type Packet<TOp extends Operation = Operation> = TOp extends ServerOperation
|
export type Packet<TOp extends Operation = Operation> = TOp extends ServerOperation
|
||||||
? PacketWithSequenceNumber<TOp>
|
? PacketWithSequenceNumber<TOp>
|
||||||
@@ -87,6 +82,6 @@ export type Packet<TOp extends Operation = Operation> = TOp extends ServerOperat
|
|||||||
|
|
||||||
type PacketWithSequenceNumber<TOp extends Operation> = {
|
type PacketWithSequenceNumber<TOp extends Operation> = {
|
||||||
op: TOp
|
op: TOp
|
||||||
d: Output<(typeof PacketDataSchemas)[TOp]>
|
d: InferOutput<(typeof PacketDataSchemas)[TOp]>
|
||||||
s: number
|
s: number
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Chalk, supportsColor, supportsColorStderr } from 'chalk'
|
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 chalk = new Chalk()
|
||||||
const DefaultConfig = {
|
const DefaultConfig = {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as BSON from 'bson'
|
import * as BSON from 'bson'
|
||||||
import { parse } from 'valibot'
|
import { parse } from 'valibot'
|
||||||
import type { Operation } from '../constants'
|
|
||||||
import { type Packet, PacketSchema } from '../schemas'
|
import { type Packet, PacketSchema } from '../schemas'
|
||||||
|
import type { Operation } from '../constants'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compresses a packet into a buffer
|
* Compresses a packet into a buffer
|
||||||
@@ -18,6 +18,6 @@ export function serializePacket<TOp extends Operation>(packet: Packet<TOp>) {
|
|||||||
* @returns A packet
|
* @returns A packet
|
||||||
*/
|
*/
|
||||||
export function deserializePacket(buffer: Buffer) {
|
export function deserializePacket(buffer: Buffer) {
|
||||||
const data = BSON.deserialize(buffer)
|
const data = BSON.deserialize(buffer as Uint8Array)
|
||||||
return parse(PacketSchema, data) as Packet
|
return parse(PacketSchema, data) as Packet
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
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
|
diff --git a/lib/prepare.js b/lib/prepare.js
|
||||||
index 3e76bec44cf595a1b4141728336bed904d4d518d..c6baf4e8de9bdf7536f9ad2e9eb9c360e031c7b5 100644
|
index 3e76bec44cf595a1b4141728336bed904d4d518d..4b25ca64879bbee2a600f2b23b738c86136ad9c6 100644
|
||||||
--- a/lib/prepare.js
|
--- a/lib/prepare.js
|
||||||
+++ b/lib/prepare.js
|
+++ b/lib/prepare.js
|
||||||
@@ -1,6 +1,7 @@
|
@@ -1,6 +1,7 @@
|
||||||
@@ -14,7 +11,7 @@ index 3e76bec44cf595a1b4141728336bed904d4d518d..c6baf4e8de9bdf7536f9ad2e9eb9c360
|
|||||||
|
|
||||||
export default async function (
|
export default async function (
|
||||||
npmrc,
|
npmrc,
|
||||||
@@ -11,19 +12,12 @@ export default async function (
|
@@ -11,19 +12,13 @@ export default async function (
|
||||||
|
|
||||||
logger.log("Write version %s to package.json in %s", version, basePath);
|
logger.log("Write version %s to package.json in %s", version, basePath);
|
||||||
|
|
||||||
@@ -36,10 +33,11 @@ index 3e76bec44cf595a1b4141728336bed904d4d518d..c6baf4e8de9bdf7536f9ad2e9eb9c360
|
|||||||
|
|
||||||
- await versionResult;
|
- await versionResult;
|
||||||
+ await writeFile(pkgJsonPath, JSON.stringify(pkgJson, null, detectIndent(pkgJsonRaw).indent))
|
+ await writeFile(pkgJsonPath, JSON.stringify(pkgJson, null, detectIndent(pkgJsonRaw).indent))
|
||||||
|
+ await execa("bun", ["install"]);
|
||||||
|
|
||||||
if (tarballDir) {
|
if (tarballDir) {
|
||||||
logger.log("Creating npm package version %s", version);
|
logger.log("Creating npm package version %s", version);
|
||||||
@@ -38,7 +32,7 @@ export default async function (
|
@@ -38,7 +33,7 @@ export default async function (
|
||||||
// Only move the tarball if we need to
|
// Only move the tarball if we need to
|
||||||
// Fixes: https://github.com/semantic-release/npm/issues/169
|
// Fixes: https://github.com/semantic-release/npm/issues/169
|
||||||
if (tarballSource !== tarballDestination) {
|
if (tarballSource !== tarballDestination) {
|
||||||
@@ -11,9 +11,7 @@ const Options = {
|
|||||||
prerelease: true,
|
prerelease: true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
plugins:
|
plugins: [
|
||||||
process.env['RELEASE_WORKFLOW_STEP'] !== 'publish'
|
|
||||||
? [
|
|
||||||
[
|
[
|
||||||
'@semantic-release/commit-analyzer',
|
'@semantic-release/commit-analyzer',
|
||||||
{
|
{
|
||||||
@@ -26,12 +24,12 @@ const Options = {
|
|||||||
'@semantic-release/npm',
|
'@semantic-release/npm',
|
||||||
{
|
{
|
||||||
npmPublish: false,
|
npmPublish: false,
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'@semantic-release/git',
|
'@semantic-release/git',
|
||||||
{
|
{
|
||||||
assets: ['CHANGELOG.md', 'package.json'],
|
assets: ['CHANGELOG.md', 'package.json', '../../bun.lockb'],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
@@ -58,8 +56,7 @@ const Options = {
|
|||||||
clearWorkspace: true,
|
clearWorkspace: true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
]
|
],
|
||||||
: [],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -70,6 +67,6 @@ export default function defineSubprojectReleaseConfig(subprojectOptions) {
|
|||||||
return {
|
return {
|
||||||
...Options,
|
...Options,
|
||||||
...subprojectOptions,
|
...subprojectOptions,
|
||||||
plugins: [...(subprojectOptions.plugins || []), ...(Options.plugins || [])],
|
plugins: [...(Options.plugins || []), ...(subprojectOptions.plugins || [])],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user