[Snyk] Upgrade discord.js from 14.16.3 to 14.17.3 (#155)

This commit is contained in:
Jonathan Smoley
2025-01-31 16:23:31 -08:00
committed by GitHub
parent 2a39e20fee
commit 5b542aca1a
23 changed files with 324 additions and 316 deletions

96
package-lock.json generated
View File

@@ -9,7 +9,7 @@
"version": "0.8.2", "version": "0.8.2",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"discord.js": "^14.16.3", "discord.js": "^14.17.3",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"ollama": "^0.5.11", "ollama": "^0.5.11",
"redis": "^4.7.0" "redis": "^4.7.0"
@@ -123,32 +123,26 @@
} }
}, },
"node_modules/@discordjs/builders": { "node_modules/@discordjs/builders": {
"version": "1.9.0", "version": "1.10.0",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.9.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.10.0.tgz",
"integrity": "sha512-0zx8DePNVvQibh5ly5kCEei5wtPBIUbSoE9n+91Rlladz4tgtFbJ36PZMxxZrTEOQ7AHMZ/b0crT/0fCy6FTKg==", "integrity": "sha512-ikVZsZP+3shmVJ5S1oM+7SveUCK3L9fTyfA8aJ7uD9cNQlTqF+3Irbk2Y22KXTb3C3RNUahRkSInClJMkHrINg==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/formatters": "^0.5.0", "@discordjs/formatters": "^0.6.0",
"@discordjs/util": "^1.1.1", "@discordjs/util": "^1.1.1",
"@sapphire/shapeshift": "^4.0.0", "@sapphire/shapeshift": "^4.0.0",
"discord-api-types": "0.37.97", "discord-api-types": "^0.37.114",
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.4", "ts-mixer": "^6.0.4",
"tslib": "^2.6.3" "tslib": "^2.6.3"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=16.11.0"
}, },
"funding": { "funding": {
"url": "https://github.com/discordjs/discord.js?sponsor" "url": "https://github.com/discordjs/discord.js?sponsor"
} }
}, },
"node_modules/@discordjs/builders/node_modules/discord-api-types": {
"version": "0.37.97",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.97.tgz",
"integrity": "sha512-No1BXPcVkyVD4ZVmbNgDKaBoqgeQ+FJpzZ8wqHkfmBnTZig1FcH3iPPersiK1TUIAzgClh2IvOuVUYfcWLQAOA==",
"license": "MIT"
},
"node_modules/@discordjs/collection": { "node_modules/@discordjs/collection": {
"version": "1.5.3", "version": "1.5.3",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",
@@ -159,30 +153,24 @@
} }
}, },
"node_modules/@discordjs/formatters": { "node_modules/@discordjs/formatters": {
"version": "0.5.0", "version": "0.6.0",
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.5.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.0.tgz",
"integrity": "sha512-98b3i+Y19RFq1Xke4NkVY46x8KjJQjldHUuEbCqMvp1F5Iq9HgnGpu91jOi/Ufazhty32eRsKnnzS8n4c+L93g==", "integrity": "sha512-YIruKw4UILt/ivO4uISmrGq2GdMY6EkoTtD0oS0GvkJFRZbTSdPhzYiUILbJ/QslsvC9H9nTgGgnarnIl4jMfw==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"discord-api-types": "0.37.97" "discord-api-types": "^0.37.114"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=16.11.0"
}, },
"funding": { "funding": {
"url": "https://github.com/discordjs/discord.js?sponsor" "url": "https://github.com/discordjs/discord.js?sponsor"
} }
}, },
"node_modules/@discordjs/formatters/node_modules/discord-api-types": {
"version": "0.37.97",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.97.tgz",
"integrity": "sha512-No1BXPcVkyVD4ZVmbNgDKaBoqgeQ+FJpzZ8wqHkfmBnTZig1FcH3iPPersiK1TUIAzgClh2IvOuVUYfcWLQAOA==",
"license": "MIT"
},
"node_modules/@discordjs/rest": { "node_modules/@discordjs/rest": {
"version": "2.4.0", "version": "2.4.2",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.4.0.tgz", "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.4.2.tgz",
"integrity": "sha512-Xb2irDqNcq+O8F0/k/NaDp7+t091p+acb51iA4bCKfIn+WFWd6HrNvcsSbMMxIR9NjcMZS6NReTKygqiQN+ntw==", "integrity": "sha512-9bOvXYLQd5IBg/kKGuEFq3cstVxAMJ6wMxO2U3wjrgO+lHv8oNCT+BBRpuzVQh7BoXKvk/gpajceGvQUiRoJ8g==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/collection": "^2.1.1", "@discordjs/collection": "^2.1.1",
@@ -190,7 +178,7 @@
"@sapphire/async-queue": "^1.5.3", "@sapphire/async-queue": "^1.5.3",
"@sapphire/snowflake": "^3.5.3", "@sapphire/snowflake": "^3.5.3",
"@vladfrangu/async_event_emitter": "^2.4.6", "@vladfrangu/async_event_emitter": "^2.4.6",
"discord-api-types": "0.37.97", "discord-api-types": "^0.37.114",
"magic-bytes.js": "^1.10.0", "magic-bytes.js": "^1.10.0",
"tslib": "^2.6.3", "tslib": "^2.6.3",
"undici": "6.19.8" "undici": "6.19.8"
@@ -214,12 +202,6 @@
"url": "https://github.com/discordjs/discord.js?sponsor" "url": "https://github.com/discordjs/discord.js?sponsor"
} }
}, },
"node_modules/@discordjs/rest/node_modules/discord-api-types": {
"version": "0.37.97",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.97.tgz",
"integrity": "sha512-No1BXPcVkyVD4ZVmbNgDKaBoqgeQ+FJpzZ8wqHkfmBnTZig1FcH3iPPersiK1TUIAzgClh2IvOuVUYfcWLQAOA==",
"license": "MIT"
},
"node_modules/@discordjs/util": { "node_modules/@discordjs/util": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.1.1.tgz", "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.1.1.tgz",
@@ -233,20 +215,20 @@
} }
}, },
"node_modules/@discordjs/ws": { "node_modules/@discordjs/ws": {
"version": "1.1.1", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.1.1.tgz", "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.0.tgz",
"integrity": "sha512-PZ+vLpxGCRtmr2RMkqh8Zp+BenUaJqlS6xhgWKEZcgC/vfHLEzpHtKkB0sl3nZWpwtcKk6YWy+pU3okL2I97FA==", "integrity": "sha512-QH5CAFe3wHDiedbO+EI3OOiyipwWd+Q6BdoFZUw/Wf2fw5Cv2fgU/9UEtJRmJa9RecI+TAhdGPadMaEIur5yJg==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/collection": "^2.1.0", "@discordjs/collection": "^2.1.0",
"@discordjs/rest": "^2.3.0", "@discordjs/rest": "^2.4.1",
"@discordjs/util": "^1.1.0", "@discordjs/util": "^1.1.0",
"@sapphire/async-queue": "^1.5.2", "@sapphire/async-queue": "^1.5.2",
"@types/ws": "^8.5.10", "@types/ws": "^8.5.10",
"@vladfrangu/async_event_emitter": "^2.2.4", "@vladfrangu/async_event_emitter": "^2.2.4",
"discord-api-types": "0.37.83", "discord-api-types": "^0.37.114",
"tslib": "^2.6.2", "tslib": "^2.6.2",
"ws": "^8.16.0" "ws": "^8.17.0"
}, },
"engines": { "engines": {
"node": ">=16.11.0" "node": ">=16.11.0"
@@ -267,12 +249,6 @@
"url": "https://github.com/discordjs/discord.js?sponsor" "url": "https://github.com/discordjs/discord.js?sponsor"
} }
}, },
"node_modules/@discordjs/ws/node_modules/discord-api-types": {
"version": "0.37.83",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.83.tgz",
"integrity": "sha512-urGGYeWtWNYMKnYlZnOnDHm8fVRffQs3U0SpE8RHeiuLKb/u92APS8HoQnPTFbnXmY1vVnXjXO4dOxcAn3J+DA==",
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": { "node_modules/@esbuild/aix-ppc64": {
"version": "0.23.1", "version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.23.1.tgz", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.23.1.tgz",
@@ -1176,9 +1152,9 @@
} }
}, },
"node_modules/@types/ws": { "node_modules/@types/ws": {
"version": "8.5.13", "version": "8.5.14",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.13.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.14.tgz",
"integrity": "sha512-osM/gWBTPKgHV8XkTunnegTRIsvF6owmf5w+JtAfOw472dptdm0dlGv4xCt6GwQRcC2XVOvvRE/0bAoQcL2QkA==", "integrity": "sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/node": "*" "@types/node": "*"
@@ -1553,25 +1529,25 @@
} }
}, },
"node_modules/discord-api-types": { "node_modules/discord-api-types": {
"version": "0.37.100", "version": "0.37.118",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.100.tgz", "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.118.tgz",
"integrity": "sha512-a8zvUI0GYYwDtScfRd/TtaNBDTXwP5DiDVX7K5OmE+DRT57gBqKnwtOC5Ol8z0mRW8KQfETIgiB8U0YZ9NXiCA==", "integrity": "sha512-MQkHHZcytmNQ3nQOBj6a0z38swsmHiROX7hdayfd0eWVrLxaQp/6tWBZ7FO2MCKKsc+W3QWnnfOJTbtyk8C4TQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/discord.js": { "node_modules/discord.js": {
"version": "14.16.3", "version": "14.17.3",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.16.3.tgz", "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.17.3.tgz",
"integrity": "sha512-EPCWE9OkA9DnFFNrO7Kl1WHHDYFXu3CNVFJg63bfU7hVtjZGyhShwZtSBImINQRWxWP2tgo2XI+QhdXx28r0aA==", "integrity": "sha512-8/j8udc3CU7dz3Eqch64UaSHoJtUT6IXK4da5ixjbav4NAXJicloWswD/iwn1ImZEMoAV3LscsdO0zhBh6H+0Q==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@discordjs/builders": "^1.9.0", "@discordjs/builders": "^1.10.0",
"@discordjs/collection": "1.5.3", "@discordjs/collection": "1.5.3",
"@discordjs/formatters": "^0.5.0", "@discordjs/formatters": "^0.6.0",
"@discordjs/rest": "^2.4.0", "@discordjs/rest": "^2.4.2",
"@discordjs/util": "^1.1.1", "@discordjs/util": "^1.1.1",
"@discordjs/ws": "1.1.1", "@discordjs/ws": "^1.2.0",
"@sapphire/snowflake": "3.5.3", "@sapphire/snowflake": "3.5.3",
"discord-api-types": "0.37.100", "discord-api-types": "^0.37.114",
"fast-deep-equal": "3.1.3", "fast-deep-equal": "3.1.3",
"lodash.snakecase": "4.1.1", "lodash.snakecase": "4.1.1",
"tslib": "^2.6.3", "tslib": "^2.6.3",

View File

@@ -27,7 +27,7 @@
"author": "Kevin Dang", "author": "Kevin Dang",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"discord.js": "^14.16.3", "discord.js": "^14.17.3",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"ollama": "^0.5.11", "ollama": "^0.5.11",
"redis": "^4.7.0" "redis": "^4.7.0"

View File

@@ -22,7 +22,9 @@ export const Capacity: SlashCommand = {
if (!channel || !UserCommand.includes(channel.type)) return if (!channel || !UserCommand.includes(channel.type)) return
// set state of bot chat features // set state of bot chat features
openConfig(`${interaction.user.username}-config.json`, interaction.commandName, interaction.options.get('context-capacity')?.value) openConfig(`${interaction.user.username}-config.json`, interaction.commandName,
interaction.options.get('context-capacity')?.value
)
interaction.reply({ interaction.reply({
content: `Max message history is now set to \`${interaction.options.get('context-capacity')?.value}\``, content: `Max message history is now set to \`${interaction.options.get('context-capacity')?.value}\``,

View File

@@ -14,9 +14,11 @@ export const ClearUserChannelHistory: SlashCommand = {
if (!channel || !UserCommand.includes(channel.type)) return if (!channel || !UserCommand.includes(channel.type)) return
// clear channel info for user // clear channel info for user
const successfulWipe = await clearChannelInfo(interaction.channelId, const successfulWipe = await clearChannelInfo(
interaction.channelId,
interaction.channel as TextChannel, interaction.channel as TextChannel,
interaction.user.username) interaction.user.username
)
// check result of clearing history // check result of clearing history
if (successfulWipe) if (successfulWipe)

View File

@@ -31,10 +31,12 @@ export const Disable: SlashCommand = {
} }
// set state of bot chat features // set state of bot chat features
openConfig(`${interaction.guildId}-config.json`, interaction.commandName, interaction.options.get('enabled')?.value) openConfig(`${interaction.guildId}-config.json`, interaction.commandName,
interaction.options.get('enabled')?.value
)
interaction.reply({ interaction.reply({
content: `${client.user?.username} is now **${interaction.options.get('enabled')?.value ? "enabled" : "disabled" }**.`, content: `${client.user?.username} is now **${interaction.options.get('enabled')?.value ? "enabled" : "disabled"}**.`,
ephemeral: true ephemeral: true
}) })
} }

View File

@@ -22,7 +22,9 @@ export const MessageStream: SlashCommand = {
if (!channel || !UserCommand.includes(channel.type)) return if (!channel || !UserCommand.includes(channel.type)) return
// save value to json and write to it // save value to json and write to it
openConfig(`${interaction.user.username}-config.json`, interaction.commandName, interaction.options.get('stream')?.value) openConfig(`${interaction.user.username}-config.json`, interaction.commandName,
interaction.options.get('stream')?.value
)
interaction.reply({ interaction.reply({
content: `Message streaming is now set to: \`${interaction.options.get('stream')?.value}\``, content: `Message streaming is now set to: \`${interaction.options.get('stream')?.value}\``,

View File

@@ -28,6 +28,7 @@ export const Shutoff: SlashCommand = {
content: `${client.user?.tag} is shutting down.`, content: `${client.user?.tag} is shutting down.`,
ephemeral: true ephemeral: true
}) })
console.log(`[Command: shutoff] ${client.user?.tag} is shutting down.`) console.log(`[Command: shutoff] ${client.user?.tag} is shutting down.`)
// clean up client instance and stop // clean up client instance and stop

View File

@@ -31,20 +31,20 @@ export const SwitchModel: SlashCommand = {
// Phase 1: Switch to the model // Phase 1: Switch to the model
let switchSuccess = false let switchSuccess = false
await ollama.list() await ollama.list()
.then(response => { .then(response => {
for (const model in response.models) { for (const model in response.models) {
const currentModel: ModelResponse = response.models[model] const currentModel: ModelResponse = response.models[model]
if (currentModel.name.startsWith(modelInput)) { if (currentModel.name.startsWith(modelInput)) {
openConfig(`${interaction.user.username}-config.json`, interaction.commandName, modelInput) openConfig(`${interaction.user.username}-config.json`, interaction.commandName, modelInput)
// successful switch // successful switch
interaction.editReply({ interaction.editReply({
content: `Successfully switched to **${modelInput}** as the preferred model for ${interaction.user.username}.` content: `Successfully switched to **${modelInput}** as the preferred model for ${interaction.user.username}.`
}) })
switchSuccess = true switchSuccess = true
}
} }
} })
})
// todo: problem can be here if async messes up // todo: problem can be here if async messes up
if (switchSuccess) { if (switchSuccess) {
// set model now that it exists // set model now that it exists

View File

@@ -21,9 +21,7 @@ export const ThreadCreate: SlashCommand = {
thread.send(`Hello ${interaction.user} and others! \n\nIt's nice to meet you. Please talk to me by typing **@${client.user?.username}** with your message.`) thread.send(`Hello ${interaction.user} and others! \n\nIt's nice to meet you. Please talk to me by typing **@${client.user?.username}** with your message.`)
// handle storing this chat channel // handle storing this chat channel
openChannelInfo(thread.id, openChannelInfo(thread.id, thread as ThreadChannel, interaction.user.tag)
thread as ThreadChannel,
interaction.user.tag)
// user only reply // user only reply
return interaction.reply({ return interaction.reply({

View File

@@ -22,10 +22,7 @@ export const PrivateThreadCreate: SlashCommand = {
// handle storing this chat channel // handle storing this chat channel
// store: thread.id, thread.name // store: thread.id, thread.name
openChannelInfo(thread.id, openChannelInfo(thread.id, thread as ThreadChannel, interaction.user.tag)
thread as ThreadChannel,
interaction.user.tag
)
// user only reply // user only reply
return interaction.reply({ return interaction.reply({

View File

@@ -6,14 +6,15 @@ import commands from '../commands/index.js'
* @param interaction the interaction received from the server * @param interaction the interaction received from the server
*/ */
export default event(Events.InteractionCreate, async ({ log, client }, interaction) => { export default event(Events.InteractionCreate, async ({ log, client }, interaction) => {
if (!interaction.isCommand() || !interaction.isChatInputCommand()) return if (!interaction.isCommand() || !interaction.isChatInputCommand()) return
log(`Interaction called \'${interaction.commandName}\' from ${interaction.user.tag}.`) log(`Interaction called \'${interaction.commandName}\' from ${interaction.user.tag}.`)
// ensure command exists, otherwise kill event // ensure command exists, otherwise kill event
const command = commands.find(command => command.name === interaction.commandName) const command = commands.find(command => command.name === interaction.commandName)
if (!command) return if (!command) return
// the command exists, execute it // the command exists, execute it
command.run(client, interaction) command.run(client, interaction)
}) }
)

View File

@@ -1,6 +1,9 @@
import { TextChannel } from 'discord.js' import { TextChannel } from 'discord.js'
import { event, Events, normalMessage, UserMessage, clean, getTextFileAttachmentData } from '../utils/index.js' import { event, Events, normalMessage, UserMessage, clean } from '../utils/index.js'
import { getChannelInfo, getServerConfig, getUserConfig, openChannelInfo, openConfig, UserConfig, getAttachmentData } from '../utils/index.js' import {
getChannelInfo, getServerConfig, getUserConfig, openChannelInfo,
openConfig, UserConfig, getAttachmentData, getTextFileAttachmentData
} from '../utils/index.js'
/** /**
* Max Message length for free users is 2000 characters (bot or not). * Max Message length for free users is 2000 characters (bot or not).
@@ -13,129 +16,129 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
let cleanedMessage = clean(message.content, clientId) let cleanedMessage = clean(message.content, clientId)
log(`Message \"${cleanedMessage}\" from ${message.author.tag} in channel/thread ${message.channelId}.`) log(`Message \"${cleanedMessage}\" from ${message.author.tag} in channel/thread ${message.channelId}.`)
// Do not respond if bot talks in the chat // Do not respond if bot talks in the chat
if (message.author.username === message.client.user.username) return if (message.author.username === message.client.user.username) return
// Only respond if message mentions the bot // Only respond if message mentions the bot
if (!message.mentions.has(clientId)) return if (!message.mentions.has(clientId)) return
// default stream to false // default stream to false
let shouldStream = false let shouldStream = false
// Params for Preferences Fetching // Params for Preferences Fetching
const maxRetries = 3 const maxRetries = 3
const delay = 1000 // in millisecons const delay = 1000 // in millisecons
try { try {
// Retrieve Server/Guild Preferences // Retrieve Server/Guild Preferences
let attempt = 0 let attempt = 0
while (attempt < maxRetries) { while (attempt < maxRetries) {
try { try {
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
getServerConfig(`${message.guildId}-config.json`, (config) => { getServerConfig(`${message.guildId}-config.json`, (config) => {
// check if config.json exists // check if config.json exists
if (config === undefined) { if (config === undefined) {
// Allowing chat options to be available // Allowing chat options to be available
openConfig(`${message.guildId}-config.json`, 'toggle-chat', true) openConfig(`${message.guildId}-config.json`, 'toggle-chat', true)
reject(new Error('Failed to locate or create Server Preferences\n\nPlease try chatting again...')) reject(new Error('Failed to locate or create Server Preferences\n\nPlease try chatting again...'))
} }
// check if chat is disabled // check if chat is disabled
else if (!config.options['toggle-chat']) else if (!config.options['toggle-chat'])
reject(new Error('Admin(s) have disabled chat features.\n\n Please contact your server\'s admin(s).')) reject(new Error('Admin(s) have disabled chat features.\n\n Please contact your server\'s admin(s).'))
else else
resolve(config) resolve(config)
})
}) })
}) break // successful
break // successful } catch (error) {
} catch (error) { ++attempt
++attempt if (attempt < maxRetries) {
if (attempt < maxRetries) { log(`Attempt ${attempt} failed for Server Preferences. Retrying in ${delay}ms...`)
log(`Attempt ${attempt} failed for Server Preferences. Retrying in ${delay}ms...`) await new Promise(ret => setTimeout(ret, delay))
await new Promise(ret => setTimeout(ret, delay)) } else
} else throw new Error(`Could not retrieve Server Preferences, please try chatting again...`)
throw new Error(`Could not retrieve Server Preferences, please try chatting again...`)
}
}
// Reset attempts for User preferences
attempt = 0
let userConfig: UserConfig | undefined
while (attempt < maxRetries) {
try {
// Retrieve User Preferences
userConfig = await new Promise((resolve, reject) => {
getUserConfig(`${message.author.username}-config.json`, (config) => {
if (config === undefined) {
openConfig(`${message.author.username}-config.json`, 'message-style', false)
openConfig(`${message.author.username}-config.json`, 'switch-model', defaultModel)
reject(new Error('No User Preferences is set up.\n\nCreating preferences file with \`message-style\` set as \`false\` for regular message style.\nPlease try chatting again.'))
return
}
// check if there is a set capacity in config
else if (typeof config.options['modify-capacity'] !== 'number')
log(`Capacity is undefined, using default capacity of ${msgHist.capacity}.`)
else if (config.options['modify-capacity'] === msgHist.capacity)
log(`Capacity matches config as ${msgHist.capacity}, no changes made.`)
else {
log(`New Capacity found. Setting Context Capacity to ${config.options['modify-capacity']}.`)
msgHist.capacity = config.options['modify-capacity']
}
// set stream state
shouldStream = config.options['message-stream'] as boolean || false
if (typeof config.options['switch-model'] !== 'string')
reject(new Error(`No Model was set. Please set a model by running \`/switch-model <model of choice>\`.\n\nIf you do not have any models. Run \`/pull-model <model name>\`.`))
resolve(config)
})
})
break // successful
} catch (error) {
++attempt
if (attempt < maxRetries) {
log(`Attempt ${attempt} failed for User Preferences. Retrying in ${delay}ms...`)
await new Promise(ret => setTimeout(ret, delay))
} else
throw new Error(`Could not retrieve User Preferences, please try chatting again...`)
}
}
// need new check for "open/active" threads/channels here!
let chatMessages: UserMessage[] = await new Promise((resolve) => {
// set new queue to modify
getChannelInfo(`${message.channelId}-${message.author.username}.json`, (channelInfo) => {
if (channelInfo?.messages)
resolve(channelInfo.messages)
else {
log(`Channel/Thread ${message.channel}-${message.author.username} does not exist. File will be created shortly...`)
resolve([])
} }
}) }
})
if (chatMessages.length === 0) { // Reset attempts for User preferences
chatMessages = await new Promise((resolve, reject) => { attempt = 0
openChannelInfo(message.channelId, let userConfig: UserConfig | undefined
message.channel as TextChannel,
message.author.tag while (attempt < maxRetries) {
) try {
// Retrieve User Preferences
userConfig = await new Promise((resolve, reject) => {
getUserConfig(`${message.author.username}-config.json`, (config) => {
if (config === undefined) {
openConfig(`${message.author.username}-config.json`, 'message-style', false)
openConfig(`${message.author.username}-config.json`, 'switch-model', defaultModel)
reject(new Error('No User Preferences is set up.\n\nCreating preferences file with \`message-style\` set as \`false\` for regular message style.\nPlease try chatting again.'))
return
}
// check if there is a set capacity in config
else if (typeof config.options['modify-capacity'] !== 'number')
log(`Capacity is undefined, using default capacity of ${msgHist.capacity}.`)
else if (config.options['modify-capacity'] === msgHist.capacity)
log(`Capacity matches config as ${msgHist.capacity}, no changes made.`)
else {
log(`New Capacity found. Setting Context Capacity to ${config.options['modify-capacity']}.`)
msgHist.capacity = config.options['modify-capacity']
}
// set stream state
shouldStream = config.options['message-stream'] as boolean || false
if (typeof config.options['switch-model'] !== 'string')
reject(new Error(`No Model was set. Please set a model by running \`/switch-model <model of choice>\`.\n\nIf you do not have any models. Run \`/pull-model <model name>\`.`))
resolve(config)
})
})
break // successful
} catch (error) {
++attempt
if (attempt < maxRetries) {
log(`Attempt ${attempt} failed for User Preferences. Retrying in ${delay}ms...`)
await new Promise(ret => setTimeout(ret, delay))
} else
throw new Error(`Could not retrieve User Preferences, please try chatting again...`)
}
}
// need new check for "open/active" threads/channels here!
let chatMessages: UserMessage[] = await new Promise((resolve) => {
// set new queue to modify
getChannelInfo(`${message.channelId}-${message.author.username}.json`, (channelInfo) => { getChannelInfo(`${message.channelId}-${message.author.username}.json`, (channelInfo) => {
if (channelInfo?.messages) if (channelInfo?.messages)
resolve(channelInfo.messages) resolve(channelInfo.messages)
else { else {
log(`Channel/Thread ${message.channel}-${message.author.username} does not exist. File will be created shortly...`) log(`Channel/Thread ${message.channel}-${message.author.username} does not exist. File will be created shortly...`)
reject(new Error(`Failed to find ${message.author.username}'s history. Try chatting again.`)) resolve([])
} }
}) })
}) })
}
if (!userConfig) if (chatMessages.length === 0) {
throw new Error(`Failed to initialize User Preference for **${message.author.username}**.\n\nIt's likely you do not have a model set. Please use the \`switch-model\` command to do that.`) chatMessages = await new Promise((resolve, reject) => {
openChannelInfo(message.channelId,
message.channel as TextChannel,
message.author.tag
)
getChannelInfo(`${message.channelId}-${message.author.username}.json`, (channelInfo) => {
if (channelInfo?.messages)
resolve(channelInfo.messages)
else {
log(`Channel/Thread ${message.channel}-${message.author.username} does not exist. File will be created shortly...`)
reject(new Error(`Failed to find ${message.author.username}'s history. Try chatting again.`))
}
})
})
}
if (!userConfig)
throw new Error(`Failed to initialize User Preference for **${message.author.username}**.\n\nIt's likely you do not have a model set. Please use the \`switch-model\` command to do that.`)
// get message attachment if exists // get message attachment if exists
const attachment = message.attachments.first() const attachment = message.attachments.first()
@@ -148,43 +151,44 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
const model: string = userConfig.options['switch-model'] const model: string = userConfig.options['switch-model']
// set up new queue // set up new queue
msgHist.setQueue(chatMessages) msgHist.setQueue(chatMessages)
// check if we can push, if not, remove oldest // check if we can push, if not, remove oldest
while (msgHist.size() >= msgHist.capacity) msgHist.dequeue() while (msgHist.size() >= msgHist.capacity) msgHist.dequeue()
// push user response before ollama query // push user response before ollama query
msgHist.enqueue({ msgHist.enqueue({
role: 'user', role: 'user',
content: cleanedMessage, content: cleanedMessage,
images: messageAttachment || [] images: messageAttachment || []
}) })
// response string for ollama to put its response // response string for ollama to put its response
const response: string = await normalMessage(message, ollama, model, msgHist, shouldStream) const response: string = await normalMessage(message, ollama, model, msgHist, shouldStream)
// If something bad happened, remove user query and stop // If something bad happened, remove user query and stop
if (response == undefined) { msgHist.pop(); return } if (response == undefined) { msgHist.pop(); return }
// if queue is full, remove the oldest message // if queue is full, remove the oldest message
while (msgHist.size() >= msgHist.capacity) msgHist.dequeue() while (msgHist.size() >= msgHist.capacity) msgHist.dequeue()
// successful query, save it in context history // successful query, save it in context history
msgHist.enqueue({ msgHist.enqueue({
role: 'assistant', role: 'assistant',
content: response, content: response,
images: messageAttachment || [] images: messageAttachment || []
}) })
// only update the json on success // only update the json on success
openChannelInfo(message.channelId, openChannelInfo(message.channelId,
message.channel as TextChannel, message.channel as TextChannel,
message.author.tag, message.author.tag,
msgHist.getItems() msgHist.getItems()
) )
} catch (error: any) { } catch (error: any) {
msgHist.pop() // remove message because of failure msgHist.pop() // remove message because of failure
message.reply(`**Error Occurred:**\n\n**Reason:** *${error.message}*`) message.reply(`**Error Occurred:**\n\n**Reason:** *${error.message}*`)
}
} }
}) )

View File

@@ -4,14 +4,15 @@ import commands from '../commands/index.js'
// Log when the bot successfully logs in and export it // Log when the bot successfully logs in and export it
export default event(Events.ClientReady, ({ log }, client) => { export default event(Events.ClientReady, ({ log }, client) => {
// Register the commands associated with the bot upon loggin in // Register the commands associated with the bot upon loggin in
registerCommands(client, commands) registerCommands(client, commands)
// set status of the bot // set status of the bot
client.user.setActivity({ client.user.setActivity({
name: 'Powered by Ollama', name: 'Powered by Ollama',
type: ActivityType.Custom type: ActivityType.Custom
}) })
log(`Logged in as ${client.user.username}.`) log(`Logged in as ${client.user.username}.`)
}) }
)

View File

@@ -6,35 +6,36 @@ import fs from 'fs'
* Event to remove the associated .json file for a thread once deleted * Event to remove the associated .json file for a thread once deleted
*/ */
export default event(Events.ThreadDelete, async ({ log }, thread: ThreadChannel) => { export default event(Events.ThreadDelete, async ({ log }, thread: ThreadChannel) => {
// iterate through every guild member in the thread and delete their history, except the bot // iterate through every guild member in the thread and delete their history, except the bot
try { try {
log(`Number of User Guild Members in Thread being deleted: ${thread.memberCount!! - 1}`) log(`Number of User Guild Members in Thread being deleted: ${thread.memberCount!! - 1}`)
const dirPath = 'data/' const dirPath = 'data/'
// read all files in data/ // read all files in data/
fs.readdir(dirPath, (error, files) => { fs.readdir(dirPath, (error, files) => {
if (error) { if (error) {
log(`Error reading directory ${dirPath}`, error) log(`Error reading directory ${dirPath}`, error)
return return
} }
// filter files by thread id being deleted // filter files by thread id being deleted
const filesToDiscard = files.filter( const filesToDiscard = files.filter(
file => file.startsWith(`${thread.id}-`) && file => file.startsWith(`${thread.id}-`) &&
file.endsWith('.json')) file.endsWith('.json'))
// remove files by unlinking // remove files by unlinking
filesToDiscard.forEach(file => { filesToDiscard.forEach(file => {
const filePath = dirPath + file const filePath = dirPath + file
fs.unlink(filePath, error => { fs.unlink(filePath, error => {
if (error) if (error)
log(`Error deleting file ${filePath}`, error) log(`Error deleting file ${filePath}`, error)
else else
log(`Successfully deleted ${filePath} thread information`) log(`Successfully deleted ${filePath} thread information`)
})
}) })
}) })
}) } catch (error) {
} catch (error) { log(`Issue deleting user history files from ${thread.id}`)
log(`Issue deleting user history files from ${thread.id}`) }
} }
}) )

View File

@@ -21,14 +21,13 @@ export function getEnvVar(name: string, fallback?: string): string {
throw new Error(`Environment variable ${name} is not set.`) throw new Error(`Environment variable ${name} is not set.`)
// validate User-Generated Discord Application Tokens // validate User-Generated Discord Application Tokens
if (name === "CLIENT_TOKEN") if (name === "CLIENT_TOKEN" && value.length > 72)
if (value.length < 72) throw new Error(`The "CLIENT_TOKEN" provided is not of at least length 72. throw new Error(`The "CLIENT_TOKEN" provided is not of at least length 72.
This is probably an invalid token unless Discord updated their token policy. Please provide a valid token.`) This is probably an invalid token unless Discord updated their token policy. Please provide a valid token.`)
// validate IPv4 address found in environment variables // validate IPv4 address found in environment variables
if (name.endsWith("_IP") || name.endsWith("_ADDRESS")) if ((name.endsWith("_IP") || name.endsWith("_ADDRESS")) && !ipValidate.test(value))
if (!ipValidate.test(value)) throw new Error(`Environment variable ${name} does not follow IPv4 formatting.`)
throw new Error(`Environment variable ${name} does not follow IPv4 formatting.`)
// return env variable // return env variable
return value return value

View File

@@ -24,6 +24,7 @@ export type ChatParams = {
* Format for the messages to be stored when communicating when the bot * Format for the messages to be stored when communicating when the bot
* @param role either assistant, user, or system * @param role either assistant, user, or system
* @param content string of the message the user or assistant provided * @param content string of the message the user or assistant provided
* @param images array of images that the user or assistant provided
*/ */
export type UserMessage = { export type UserMessage = {
role: string, role: string,
@@ -33,12 +34,18 @@ export type UserMessage = {
// Event properties // Event properties
export interface EventProps { export interface EventProps {
client: Client client: Client,
log: LogMethod log: LogMethod,
msgHist: Queue<UserMessage> msgHist: Queue<UserMessage>,
ollama: Ollama, ollama: Ollama,
defaultModel: String defaultModel: String
} }
/**
* Format for the callback function tied to an event
* @param props the properties of the event
* @param args the arguments of the event
*/
export type EventCallback<T extends EventKeys> = ( export type EventCallback<T extends EventKeys> = (
props: EventProps, props: EventProps,
...args: ClientEvents[T] ...args: ClientEvents[T]
@@ -50,6 +57,12 @@ export interface Event<T extends EventKeys = EventKeys> {
callback: EventCallback<T> callback: EventCallback<T>
} }
/**
* Method to create an event object
* @param key type of event
* @param callback function to run when event is triggered
* @returns event object
*/
export function event<T extends EventKeys>(key: T, callback: EventCallback<T>): Event<T> { export function event<T extends EventKeys>(key: T, callback: EventCallback<T>): Event<T> {
return { key, callback } return { key, callback }
} }

View File

@@ -80,7 +80,14 @@ export async function openChannelInfo(filename: string, channel: TextChannel | T
} }
}) })
} else { // file doesn't exist, create it } else { // file doesn't exist, create it
const object: Configuration = JSON.parse(`{ \"id\": \"${channel?.id}\", \"name\": \"${channel?.name}\", \"user\": \"${user}\", \"messages\": []}`) const object: Configuration = JSON.parse(
`{
\"id\": \"${channel?.id}\",
\"name\": \"${channel?.name}\",
\"user\": \"${user}\",
\"messages\": []
}`
)
const directory = path.dirname(fullFileName) const directory = path.dirname(fullFileName)
if (!fs.existsSync(directory)) if (!fs.existsSync(directory))

View File

@@ -5,7 +5,7 @@ import { AbortableAsyncIterator } from "ollama/src/utils.js"
/** /**
* Method to query the Ollama client for async generation * Method to query the Ollama client for async generation
* @param params * @param params
* @returns Asyn * @returns AsyncIterator<ChatResponse> generated by the Ollama client
*/ */
export async function streamResponse(params: ChatParams): Promise<AbortableAsyncIterator<ChatResponse>> { export async function streamResponse(params: ChatParams): Promise<AbortableAsyncIterator<ChatResponse>> {
return await params.ollama.chat({ return await params.ollama.chat({

View File

@@ -40,7 +40,8 @@ export async function normalMessage(
result = portion.message.content result = portion.message.content
// new message block, wait for it to send and assign new block to respond. // new message block, wait for it to send and assign new block to respond.
await channel.send("Creating new stream block...").then(sentMessage => { messageBlock = sentMessage }) await channel.send("Creating new stream block...")
.then(sentMessage => { messageBlock = sentMessage })
} else { } else {
result += portion.message.content result += portion.message.content
@@ -71,7 +72,7 @@ export async function normalMessage(
} else // edit the 'generic' response to new message since <2000 } else // edit the 'generic' response to new message since <2000
sentMessage.edit(result) sentMessage.edit(result)
} }
} catch(error: any) { } catch (error: any) {
console.log(`[Util: messageNormal] Error creating message: ${error.message}`) console.log(`[Util: messageNormal] Error creating message: ${error.message}`)
if (error.message.includes('try pulling it first')) if (error.message.includes('try pulling it first'))
sentMessage.edit(`**Response generation failed.**\n\nReason: You do not have the ${model} downloaded. Ask an admin to pull it using the \`pull-model\` command.`) sentMessage.edit(`**Response generation failed.**\n\nReason: You do not have the ${model} downloaded. Ask an admin to pull it using the \`pull-model\` command.`)

View File

@@ -34,7 +34,8 @@ describe('Commands Existence', () => {
// test specific commands in the object // test specific commands in the object
it('references specific commands', () => { it('references specific commands', () => {
const commandsString = commands.map(e => e.name).join(', ') const commandsString = commands.map(e => e.name).join(', ')
expect(commandsString).toBe('thread, private-thread, message-stream, toggle-chat, shutoff, modify-capacity, clear-user-channel-history, pull-model, switch-model, delete-model') const expectedCommands = ['thread', 'private-thread', 'message-stream', 'toggle-chat', 'shutoff', 'modify-capacity', 'clear-user-channel-history', 'pull-model', 'switch-model', 'delete-model']
expect(commandsString).toBe(expectedCommands.join(', '))
}) })
}) })

View File

@@ -8,7 +8,7 @@ import { Queue } from '../src/queues/queue.js'
* @param fn function holding tests to run * @param fn function holding tests to run
*/ */
describe('Queue Structure', () => { describe('Queue Structure', () => {
let queue= new Queue<string>() let queue = new Queue<string>()
// test for queue creation // test for queue creation
it('creates a new queue', () => { it('creates a new queue', () => {