Compare commits

..

17 Commits

Author SHA1 Message Date
semantic-release-bot
9fe6b4ca70 chore(release): 1.0.0-dev.15 [skip ci]
# @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](763ef253f9))

### Features

* **bots/discord:** add sticky messages ([bf66155](bf661556e1))
2024-07-31 19:31:21 +00:00
PalmDevs
bf661556e1 feat(bots/discord): add sticky messages 2024-08-01 02:29:49 +07:00
PalmDevs
763ef253f9 fix(bots/discord): import config from context 2024-07-31 21:25:12 +07:00
semantic-release-bot
561426028c chore(release): 1.0.0-dev.14 [skip ci]
# @revanced/discord-bot [1.0.0-dev.14](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.13...@revanced/discord-bot@1.0.0-dev.14) (2024-07-31)

### Bug Fixes

* **bots/discord:** always true check causing no messages to be scanned ([98ec37b](98ec37b5d1))
* other small issues ([bc437a5](bc437a5ec7))

### Features

* **bots/discord:** add more options for curing, fix default regex ([1a4ec1e](1a4ec1ece8))
* **bots/discord:** allow admins to bypass permission checks ([620f933](620f9339f0))
2024-07-31 12:36:12 +00:00
semantic-release-bot
b726c40fd4 chore(release): 1.0.0-dev.8 [skip ci]
# @revanced/bot-websocket-api [1.0.0-dev.8](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.7...@revanced/bot-websocket-api@1.0.0-dev.8) (2024-07-31)

### Bug Fixes

* other small issues ([bc437a5](bc437a5ec7))
2024-07-31 12:35:31 +00:00
PalmDevs
bc437a5ec7 fix: other small issues 2024-07-31 19:34:12 +07:00
PalmDevs
620f9339f0 feat(bots/discord): allow admins to bypass permission checks 2024-07-31 19:34:11 +07:00
PalmDevs
1a4ec1ece8 feat(bots/discord): add more options for curing, fix default regex 2024-07-31 19:34:10 +07:00
PalmDevs
98ec37b5d1 fix(bots/discord): always true check causing no messages to be scanned 2024-07-31 19:34:10 +07:00
PalmDevs
711f57f4a1 fix(packages/api): null errors being thrown 2024-07-31 19:34:09 +07:00
PalmDevs
e29e9c3dd1 fix(packages/api): properly await failed packets 2024-07-31 19:34:08 +07:00
semantic-release-bot
b832311f7e chore(release): 1.0.0-dev.13 [skip ci]
# @revanced/discord-bot [1.0.0-dev.13](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.12...@revanced/discord-bot@1.0.0-dev.13) (2024-07-30)

### Bug Fixes

* **bots/discord:** broken regex when prefix set to special characters ([ab62e55](ab62e55e76))
2024-07-30 19:14:27 +00:00
semantic-release-bot
887ee85e41 chore(release): 1.0.0-dev.7 [skip ci]
# @revanced/bot-websocket-api [1.0.0-dev.7](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.6...@revanced/bot-websocket-api@1.0.0-dev.7) (2024-07-30)
2024-07-30 19:13:45 +00:00
PalmDevs
c9b788dc51 build(Needs bump): do not minify builds 2024-07-31 02:12:31 +07:00
PalmDevs
ab62e55e76 fix(bots/discord): broken regex when prefix set to special characters 2024-07-31 02:12:30 +07:00
semantic-release-bot
8f83687b7c chore(release): 1.0.0-dev.12 [skip ci]
# @revanced/discord-bot [1.0.0-dev.12](https://github.com/revanced/revanced-helper/compare/@revanced/discord-bot@1.0.0-dev.11...@revanced/discord-bot@1.0.0-dev.12) (2024-07-30)

### Bug Fixes

* **bots/discord:** deployment runtime errors due to minification ([a60c60c](a60c60c0f9))
2024-07-30 18:42:20 +00:00
PalmDevs
a60c60c0f9 fix(bots/discord): deployment runtime errors due to minification 2024-07-31 01:40:45 +07:00
25 changed files with 256 additions and 66 deletions

View File

@@ -1,3 +1,12 @@
# @revanced/bot-websocket-api [1.0.0-dev.8](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.7...@revanced/bot-websocket-api@1.0.0-dev.8) (2024-07-31)
### Bug Fixes
* other small issues ([bc437a5](https://github.com/revanced/revanced-helper/commit/bc437a5ec7ce1d339094d608e2a61ac5f460c163))
# @revanced/bot-websocket-api [1.0.0-dev.7](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.6...@revanced/bot-websocket-api@1.0.0-dev.7) (2024-07-30)
# @revanced/bot-websocket-api [1.0.0-dev.6](https://github.com/revanced/revanced-helper/compare/@revanced/bot-websocket-api@1.0.0-dev.5...@revanced/bot-websocket-api@1.0.0-dev.6) (2024-07-30)

View File

@@ -2,7 +2,7 @@
"name": "@revanced/bot-websocket-api",
"type": "module",
"private": true,
"version": "1.0.0-dev.6",
"version": "1.0.0-dev.8",
"description": "🧦 WebSocket API server for bots assisting ReVanced",
"main": "dist/index.js",
"scripts": {

View File

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

View File

@@ -1,3 +1,43 @@
# @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)

View File

@@ -6,9 +6,12 @@ export type Config = {
users?: string[]
roles?: Record<string, string[]>
}
stickyMessages?: Record<string, Record<string, StickyMessageConfig>>
moderation?: {
roles: string[]
cure?: {
minimumNameLength?: number
removeCharactersRegex?: RegExp
defaultName: string
}
log?: {
@@ -48,6 +51,12 @@ export type Config = {
}
}
export type StickyMessageConfig = {
timeout: number
forceSendTimeout?: number
message: BaseMessageOptions
}
export type RolePresetConfig = {
give: string[]
take: string[]

View File

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

View File

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

View File

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

View File

@@ -3,7 +3,7 @@ import { existsSync, readFileSync, readdirSync } from 'fs'
import { join } from 'path'
import { Client as APIClient } from '@revanced/bot-api'
import { createLogger } from '@revanced/bot-shared'
import { Client as DiscordClient, Partials } from 'discord.js'
import { Client as DiscordClient, type Message, Partials } from 'discord.js'
import { drizzle } from 'drizzle-orm/bun-sqlite'
// Export some things first, as commands require them
@@ -85,4 +85,19 @@ export const discord = {
string,
Command<boolean, CommandOptionsOptions | undefined, boolean>
>,
stickyMessages: {} as Record<
string,
Record<
string,
{
forceSendTimerActive?: boolean
timeoutMs: number
forceSendMs?: number
send: (forced?: boolean) => Promise<void>
currentMessage?: Message<true>
interval?: NodeJS.Timeout
forceSendInterval?: NodeJS.Timeout
}
>
>,
} as const

View File

@@ -9,7 +9,8 @@ withContext(on, 'interactionCreate', async (context, interaction) => {
const command = discord.commands[interaction.commandName]
logger.debug(`Command ${interaction.commandName} being invoked by ${interaction.user.tag}`)
if (!command) return void logger.error(`Command ${interaction.commandName} not implemented but registered!!!`)
if (!command)
return void logger.error(`Interaction command ${interaction.commandName} not implemented but registered!!!`)
try {
logger.debug(`Command ${interaction.commandName} being executed`)

View File

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

View File

@@ -33,7 +33,7 @@ withContext(on, 'messageCreate', async (context, msg) => {
if (response) {
logger.debug('Response found')
const toReply = replyToReplied ? await msg.fetchReference() : msg
const toReply = replyToReplied ? (msg.reference?.messageId ? await msg.fetchReference() : msg) : msg
const reply = await toReply.reply({
...response,
embeds: response.embeds?.map(it => createMessageScanResponseEmbed(it, label ? 'nlp' : 'match')),

View File

@@ -0,0 +1,30 @@
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
if (!store.interval) store.interval = setTimeout(store.send, store.timeoutMs) as NodeJS.Timeout
else {
store.interval.refresh()
if (!store.forceSendTimerActive && store.forceSendMs) {
logger.debug(`Channel ${msg.channelId} in guild ${msg.guildId} is active, starting force send timer`)
store.forceSendTimerActive = true
if (!store.forceSendInterval)
store.forceSendInterval = setTimeout(
() =>
store.send(true).then(() => {
store.forceSendTimerActive = false
}),
store.forceSendMs,
) as NodeJS.Timeout
else store.forceSendInterval.refresh()
}
}
})

View File

@@ -1,14 +1,68 @@
import { database, logger } from '$/context'
import { appliedPresets } from '$/database/schemas'
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
import { on, withContext } from '$/utils/discord/events'
import { removeRolePreset } from '$/utils/discord/rolePresets'
import 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) => {
import type { Client } from 'discord.js'
export default withContext(on, 'ready', async ({ config, discord, logger }, client) => {
logger.info(`Connected to Discord API, logged in as ${client.user.displayName} (@${client.user.tag})!`)
logger.info(`Bot is in ${client.guilds.cache.size} guilds`)
if (config.stickyMessages)
for (const [guildId, channels] of Object.entries(config.stickyMessages)) {
const guild = await client.guilds.fetch(guildId)
discord.stickyMessages[guildId] = {}
for (const [channelId, { message, timeout, forceSendTimeout }] of Object.entries(channels)) {
const channel = await guild.channels.fetch(channelId)
if (!channel?.isTextBased()) return
const send = async (forced = false) => {
try {
const msg = await channel.send({
...message,
embeds: message.embeds?.map(it => applyCommonEmbedStyles(it, true, true, true)),
})
const store = discord.stickyMessages[guildId]![channelId]
if (!store) return
await store.currentMessage?.delete().catch()
store.currentMessage = msg
if (!forced) {
clearTimeout(store.forceSendInterval)
logger.debug(
`Timeout ended for sticky message in channel ${channelId} in guild ${guildId}, channel is inactive`,
)
} else {
clearTimeout(store.interval)
logger.debug(
`Forced send timeout for sticky message in channel ${channelId} in guild ${guildId} ended, channel is too active`,
)
}
logger.debug(`Sent sticky message to channel ${channelId} in guild ${guildId}`)
} catch (e) {
logger.error(
`Error while sending sticky message to channel ${channelId} in guild ${guildId}:`,
e,
)
}
}
discord.stickyMessages[guildId]![channelId] = {
forceSendMs: forceSendTimeout,
timeoutMs: timeout,
send,
forceSendTimerActive: false,
}
}
}
if (config.rolePresets) {
removeExpiredPresets(client)
setTimeout(() => removeExpiredPresets(client), config.rolePresets.checkExpiredEvery)

View File

@@ -10,5 +10,10 @@ if (missingEnvs.length) {
process.exit(1)
}
// Handle uncaught exceptions
process.on('uncaughtException', error => console.error('Uncaught exception:', error))
process.on('unhandledRejection', reason => console.error('Unhandled rejection:', reason))
api.client.connect()
discord.client.login()

View File

@@ -1,5 +1,5 @@
import { DefaultEmbedColor, MessageScanHumanizedMode, ReVancedLogoURL } from '$/constants'
import { EmbedBuilder, type EmbedField, type User } from 'discord.js'
import { type APIEmbed, EmbedBuilder, type EmbedField, type JSONEncodable, type User } from 'discord.js'
import type { ConfigMessageScanResponseMessage } from '../../../config.schema'
export const createErrorEmbed = (title: string | null, description?: string) =>
@@ -26,23 +26,12 @@ export const createSuccessEmbed = (title: string | null, description?: string) =
export const createMessageScanResponseEmbed = (
response: NonNullable<ConfigMessageScanResponseMessage['embeds']>[number],
mode: 'ocr' | 'nlp' | 'match',
) => {
// biome-ignore lint/style/noParameterAssign: While this is confusing, it is fine for this purpose
if ('toJSON' in response) response = response.toJSON()
const embed = new EmbedBuilder().setTitle(response.title ?? null)
if (response.description) embed.setDescription(response.description)
if (response.fields) embed.addFields(response.fields)
embed.setFooter({
) =>
applyCommonEmbedStyles(response, true, true, true).setFooter({
text: `ReVanced • Via ${MessageScanHumanizedMode[mode]}`,
iconURL: ReVancedLogoURL,
})
return applyCommonEmbedStyles(embed, true, true, true)
}
export const createModerationActionEmbed = (
action: string,
user: User,
@@ -77,19 +66,23 @@ export const applyReferenceToModerationActionEmbed = (embed: EmbedBuilder, refer
}
export const applyCommonEmbedStyles = (
embed: EmbedBuilder,
embed: EmbedBuilder | JSONEncodable<APIEmbed> | APIEmbed,
setThumbnail = false,
setFooter = 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)
embed.setFooter({
builder.setFooter({
text: 'ReVanced',
iconURL: ReVancedLogoURL,
})
if (setColor) embed.setColor(DefaultEmbedColor)
if (setThumbnail) embed.setThumbnail(ReVancedLogoURL)
if (setColor) builder.setColor(DefaultEmbedColor)
if (setThumbnail) builder.setThumbnail(ReVancedLogoURL)
return embed
return builder
}

View File

@@ -10,9 +10,12 @@ export const getResponseFromText = async (
// Just to be safe that we will never use data from the context parameter
{ api, logger }: Omit<typeof import('src/context'), 'config'>,
ocrMode = false,
): Promise<ConfigMessageScanResponse & { label?: string }> => {
let responseConfig: Awaited<ReturnType<typeof getResponseFromText>> = {
triggers: {},
): Promise<
Omit<ConfigMessageScanResponse, 'triggers'> & { label?: string; triggers?: ConfigMessageScanResponse['triggers'] }
> => {
type ResponseConfig = Awaited<ReturnType<typeof getResponseFromText>>
let responseConfig: Omit<ResponseConfig, 'triggers'> & { triggers?: ResponseConfig['triggers'] } = {
triggers: undefined,
response: null,
}
@@ -27,7 +30,6 @@ export const getResponseFromText = async (
const {
triggers: { text: textTriggers, image: imageTriggers },
} = trigger
if (responseConfig) break
if (ocrMode) {
if (imageTriggers)
@@ -55,7 +57,7 @@ export const getResponseFromText = async (
}
// If none of the regexes match, we can search for labels immediately
if (!responseConfig && !ocrMode) {
if (!responseConfig.triggers && !ocrMode) {
logger.debug('No match from before regexes, doing NLP')
const scan = await api.client.parseText(content)
if (scan.labels.length) {
@@ -84,7 +86,7 @@ export const getResponseFromText = async (
}
// If we still don't have a response config, we can match all regexes after the initial label trigger
if (!responseConfig) {
if (!responseConfig.triggers) {
logger.debug('No match from NLP, doing after regexes')
for (let i = 0; i < responses.length; i++) {
const {
@@ -119,19 +121,17 @@ export const messageMatchesFilter = (message: Message, filter: NonNullable<Confi
// If matches whitelist but also matches blacklist, will return false
// If matches only whitelist, will return true
// If matches neither, will return true
return (
(whitelist
? whitelist.channels?.includes(message.channelId) ||
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))
)
)
return whitelist
? (whitelist.channels?.includes(message.channelId) ?? true) ||
(whitelist.roles?.some(role => memberRoles.has(role)) ?? true) ||
(whitelist.users?.includes(message.author.id) ?? true)
: true &&
!(
blacklist &&
(blacklist.channels?.includes(message.channelId) ||
blacklist.roles?.some(role => memberRoles.has(role)) ||
blacklist.users?.includes(message.author.id))
)
}
export const handleUserResponseCorrection = async (

View File

@@ -54,9 +54,9 @@ export const cureNickname = async (member: GuildMember) => {
const name = member.displayName
let cured = decancer(name)
.toString()
.replace(/[^a-zA-Z0-9]/g, '')
.replace(new RegExp(config.moderation?.cure?.removeCharactersRegex ?? '[^a-zA-Z0-9 \\-_]', 'g'), '')
if (cured.length < 3 || !/^[a-zA-Z]/.test(cured))
if (cured.length < (config?.moderation?.cure?.minimumNameLength ?? 3))
cured =
member.user.username.length >= 3
? member.user.username

View File

@@ -1,5 +1,5 @@
import { GuildMember, type User } from 'discord.js'
import config from '../../../config'
import { config } from '../../context'
export const isAdmin = (userOrMember: User | GuildMember) => {
return (

BIN
bun.lockb

Binary file not shown.

View File

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

View File

@@ -52,17 +52,20 @@ export default class Client {
// But if we add anything similar, this will cause another race condition
// To fix this, we can try adding a instanced function that would return the currentSequence
// and it would be updated every time a "heartbeat ack" packet is received
return Promise.race([
const packet = await Promise.race([
this.#awaiter.await(ServerOperation.ParsedText, this.ws.currentSequence),
this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.timeout + 5000),
this.#awaiter.await(ServerOperation.ParseTextFailed, this.ws.currentSequence, this.ws.timeout + 5000),
])
.then(pkt => {
if (pkt.op === ServerOperation.ParsedText) return pkt.d
throw new Error('Failed to parse text, the API encountered an error')
return null
})
.catch(() => {
throw new Error('Failed to parse text, the API did not respond in time')
})
if (!packet) throw new Error('Failed to parse text, the API encountered an error')
return packet
}
/**
@@ -82,17 +85,20 @@ export default class Client {
// See line 50
return Promise.race([
const packet = await Promise.race([
this.#awaiter.await(ServerOperation.ParsedImage, this.ws.currentSequence),
this.#awaiter.await(ServerOperation.ParseImageFailed, this.ws.timeout + 5000),
this.#awaiter.await(ServerOperation.ParseImageFailed, this.ws.currentSequence, this.ws.timeout + 5000),
])
.then(pkt => {
if (pkt.op === ServerOperation.ParsedImage) return pkt.d
throw new Error('Failed to parse image, the API encountered an error')
return null
})
.catch(() => {
throw new Error('Failed to parse image, the API did not respond in time')
})
if (!packet) throw new Error('Failed to parse image, the API encountered an error')
return packet
}
async trainMessage(text: string, label: string) {
@@ -107,17 +113,20 @@ export default class Client {
})
// See line 50
return Promise.race([
const packet = await Promise.race([
this.#awaiter.await(ServerOperation.TrainedMessage, this.ws.currentSequence),
this.#awaiter.await(ServerOperation.TrainMessageFailed, this.ws.timeout + 5000),
this.#awaiter.await(ServerOperation.TrainMessageFailed, this.ws.currentSequence, this.ws.timeout + 5000),
])
.then(pkt => {
if (pkt.op === ServerOperation.TrainedMessage) return pkt.d
throw new Error('Failed to train message, the API encountered an error')
return null
})
.catch(() => {
throw new Error('Failed to train message, the API did not respond in time')
})
if (!packet) throw new Error('Failed to train message, the API encountered an error')
return packet
}
/**

View File

@@ -123,7 +123,7 @@ export class ClientWebSocketManager {
this.currentSequence++
this.#socket.send(serializePacket(packet), err => {
throw err
if (err) throw err
})
}

View File

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