Compare commits

..

4 Commits

Author SHA1 Message Date
semantic-release-bot
82fac783ea chore(release): 1.0.0-dev.22 [skip ci]
# @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](6c8dce0593))
* **bots/discord:** provide discord token for `reload` command ([dd21a5a](dd21a5abad))

### Features

* **bots/discord:** add code to actually scan text files correctly ([80aeb19](80aeb19020))
2024-08-10 15:31:57 +00:00
PalmDevs
dd21a5abad fix(bots/discord): provide discord token for reload command 2024-08-10 22:30:45 +07:00
PalmDevs
80aeb19020 feat(bots/discord): add code to actually scan text files correctly 2024-08-10 22:30:45 +07:00
PalmDevs
6c8dce0593 fix(bots/discord): parse larger units of durations, fix wrong timestamp in mod embed 2024-08-10 22:30:44 +07:00
10 changed files with 58 additions and 28 deletions

View File

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

View File

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

View File

@@ -27,7 +27,9 @@ export default new AdminCommand({
logger.info('Reinitializing Discord client to reload configuration...')
await discord.client.destroy()
await discord.client.login()
// 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' })

View File

@@ -60,7 +60,7 @@ export default new ModerationCommand({
await applyRolePreset(member, 'mute', expires)
await sendModerationReplyAndLogs(
interaction,
createModerationActionEmbed('Muted', user, executor.user, reason, duration),
createModerationActionEmbed('Muted', user, executor.user, reason, Math.ceil(expires / 1000)),
)
if (duration)

View File

@@ -83,6 +83,6 @@ export default new ModerationCommand({
removeRolePreset(member, preset)
}, expires)
await sendPresetReplyAndLogs(apply ? 'apply' : 'remove', trigger, executor, user, preset, expires)
await sendPresetReplyAndLogs(apply ? 'apply' : 'remove', trigger, executor, user, preset, expires ? Math.ceil(expires / 1000) : undefined)
},
})

View File

@@ -59,26 +59,38 @@ withContext(on, 'messageCreate', async (context, msg) => {
}
}
if (msg.attachments.size > 0 && config.attachments?.scanAttachments) {
if (msg.attachments.size && config.attachments?.scanAttachments) {
logger.debug(`Classifying message attachments for ${msg.id}`)
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(attachment.contentType!)
!config.attachments.allowedMimeTypes.includes(mimeType)
) {
logger.debug(`Disallowed MIME type for attachment: ${attachment.url}, ${attachment.contentType}`)
logger.debug(`Disallowed MIME type for attachment: ${attachment.url}, ${mimeType}`)
continue
}
if (attachment.contentType?.startsWith('text/') && attachment.size > (config.attachments.maxTextFileSize ?? 512 * 1000)) {
logger.debug(`Attachment ${attachment.url} is too large be to scanned, size is ${attachment.size}`)
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 {
const { text: content } = await api.client.parseImage(attachment.url)
const { response } = await getResponseFromText(content, filteredResponses, context, true)
let response: Awaited<ReturnType<typeof getResponseFromText>>['response'] | undefined
if (isTextFile) {
const content = await (await fetch(attachment.url)).text()
response = await getResponseFromText(content, filteredResponses, context, { skipApiRequest: true }).then(it => it.response)
} else {
const { text: content } = await api.client.parseImage(attachment.url)
response = await getResponseFromText(content, filteredResponses, context, { onlyImageTriggers: true }).then(it => it.response)
}
if (response) {
logger.debug(`Response found for attachment: ${attachment.url}`)
@@ -89,8 +101,8 @@ withContext(on, 'messageCreate', async (context, msg) => {
break
}
} catch {
logger.error(`Failed to parse image: ${attachment.url}`)
} catch (e) {
logger.error(`Failed to parse attachment: ${attachment.url}`, e)
}
}
}

View File

@@ -9,7 +9,7 @@ export const getResponseFromText = async (
responses: ConfigMessageScanResponse[],
// Just to be safe that we will never use data from the context parameter
{ api, logger }: Omit<typeof import('src/context'), 'config'>,
ocrMode = false,
flags: { onlyImageTriggers?: boolean; skipApiRequest?: boolean } = {}
): Promise<
Omit<ConfigMessageScanResponse, 'triggers'> & { label?: string; triggers?: ConfigMessageScanResponse['triggers'] }
> => {
@@ -31,7 +31,7 @@ export const getResponseFromText = async (
triggers: { text: textTriggers, image: imageTriggers },
} = trigger
if (ocrMode) {
if (flags.onlyImageTriggers) {
if (imageTriggers)
for (const regex of imageTriggers)
if (regex.test(content)) {
@@ -57,7 +57,7 @@ export const getResponseFromText = async (
}
// If none of the regexes match, we can search for labels immediately
if (!responseConfig.triggers && !ocrMode) {
if (!responseConfig.triggers && !flags.onlyImageTriggers && !flags.skipApiRequest) {
logger.debug('No match from before regexes, doing NLP')
const scan = await api.client.parseText(content)
if (scan.labels.length) {
@@ -87,7 +87,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.triggers && ocrMode) {
if (!responseConfig.triggers && flags.onlyImageTriggers) {
logger.debug('No match from NLP, doing after regexes')
for (let i = 0; i < responses.length; i++) {
const {

View File

@@ -1,6 +1,6 @@
import { config, logger } from '$/context'
import decancer from 'decancer'
import type { ChatInputCommandInteraction, EmbedBuilder, Guild, GuildMember, Message, User } from 'discord.js'
import type { CommandInteraction, EmbedBuilder, Guild, GuildMember, Message, User } from 'discord.js'
import { applyReferenceToModerationActionEmbed, createModerationActionEmbed } from './embeds'
const PresetLogAction = {
@@ -10,7 +10,7 @@ const PresetLogAction = {
export const sendPresetReplyAndLogs = (
action: keyof typeof PresetLogAction,
interaction: ChatInputCommandInteraction | Message,
interaction: CommandInteraction | Message,
executor: GuildMember,
user: User,
preset: string,
@@ -24,7 +24,7 @@ export const sendPresetReplyAndLogs = (
)
export const sendModerationReplyAndLogs = async (
interaction: ChatInputCommandInteraction | Message,
interaction: CommandInteraction | Message,
embed: EmbedBuilder,
) => {
const reply = await interaction.reply({ embeds: [embed] }).then(it => it.fetch())

View File

@@ -6,9 +6,9 @@ import { and, eq } from 'drizzle-orm'
// TODO: Fix this type
type PresetKey = string
export const applyRolePreset = async (member: GuildMember, presetName: PresetKey, untilMs: number) => {
export const applyRolePreset = async (member: GuildMember, presetName: PresetKey, expires: number) => {
const afterInsert = await applyRolesUsingPreset(presetName, member, true)
const until = untilMs === Infinity ? null : Math.ceil(untilMs / 1000)
const until = expires === Infinity ? null : Math.ceil(expires / 1000)
await database
.insert(appliedPresets)

View File

@@ -1,13 +1,16 @@
export const parseDuration = (duration: string) => {
if (!duration.length) return Number.NaN
const matches = duration.match(/(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?/)!
const matches = duration.match(/(?:(\d+y)?(\d+M)?(\d+w)?(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)/)!
const [, days, hours, minutes, seconds] = matches.map(Number)
const [, years, months, weeks, days, hours, minutes, seconds] = matches.map(Number)
return (
(days || 0) * 24 * 60 * 60 * 1000 +
(hours || 0) * 60 * 60 * 1000 +
(minutes || 0) * 60 * 1000 +
(seconds || 0) * 1000
(years || 0) * 290304e5 +
(months || 0) * 24192e5 +
(weeks || 0) * 6048e5 +
(days || 0) * 864e5 +
(hours || 0) * 36e5 +
(minutes || 0) * 6e4 +
(seconds || 0) * 1e3
)
}