Upgrade Npm Packages (#159)

* Update: upgrade packages

* Update: add in all packages

* Update: fix whitespace in events

---------

Co-authored-by: JT2M0L3Y <jtsmoley@icloud.com>
This commit is contained in:
Kevin Dang
2025-02-23 20:00:53 -08:00
committed by GitHub
parent ed0d8600df
commit 40783818b9
7 changed files with 736 additions and 667 deletions

1019
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -27,22 +27,22 @@
"author": "Kevin Dang", "author": "Kevin Dang",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"discord.js": "^14.17.3", "discord.js": "^14.18.0",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"ollama": "^0.5.11", "ollama": "^0.5.13",
"redis": "^4.7.0" "redis": "^4.7.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.10.2", "@types/node": "^22.13.5",
"@vitest/coverage-v8": "^2.1.8", "@vitest/coverage-v8": "^3.0.6",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"tsx": "^4.19.2", "tsx": "^4.19.3",
"typescript": "^5.7.2", "typescript": "^5.7.3",
"vitest": "^2.1.4" "vitest": "^3.0.4"
}, },
"type": "module", "type": "module",
"engines": { "engines": {
"npm": ">=10.9.0", "npm": ">=10.9.0",
"node": ">=22.12.0" "node": ">=22.12.0"
} }
} }

View File

@@ -6,15 +6,14 @@ 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

@@ -16,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
else if (!config.options['toggle-chat'])
reject(new Error('Admin(s) have disabled chat features.\n\n Please contact your server\'s admin(s).'))
else
resolve(config)
})
})
break // successful
} catch (error) {
++attempt
if (attempt < maxRetries) {
log(`Attempt ${attempt} failed for Server Preferences. Retrying in ${delay}ms...`)
await new Promise(ret => setTimeout(ret, delay))
} else
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>\`.`))
// check if chat is disabled
else if (!config.options['toggle-chat'])
reject(new Error('Admin(s) have disabled chat features.\n\n Please contact your server\'s admin(s).'))
else
resolve(config) resolve(config)
})
}) })
break // successful })
} catch (error) { break // successful
++attempt } catch (error) {
if (attempt < maxRetries) { ++attempt
log(`Attempt ${attempt} failed for User Preferences. Retrying in ${delay}ms...`) if (attempt < maxRetries) {
await new Promise(ret => setTimeout(ret, delay)) log(`Attempt ${attempt} failed for Server Preferences. Retrying in ${delay}ms...`)
} else await new Promise(ret => setTimeout(ret, delay))
throw new Error(`Could not retrieve User Preferences, please try chatting again...`) } else
} throw new Error(`Could not retrieve Server Preferences, please try chatting again...`)
} }
}
// need new check for "open/active" threads/channels here! // Reset attempts for User preferences
let chatMessages: UserMessage[] = await new Promise((resolve) => { attempt = 0
// set new queue to modify 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) {
chatMessages = await new Promise((resolve, reject) => {
openChannelInfo(message.channelId,
message.channel as TextChannel,
message.author.tag
)
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...`)
resolve([]) reject(new Error(`Failed to find ${message.author.username}'s history. Try chatting again.`))
} }
}) })
}) })
}
if (chatMessages.length === 0) { if (!userConfig)
chatMessages = await new Promise((resolve, reject) => { 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.`)
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,47 +148,46 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
cleanedMessage += await getTextFileAttachmentData(attachment) cleanedMessage += await getTextFileAttachmentData(attachment)
else if (attachment) else if (attachment)
messageAttachment = await getAttachmentData(attachment) messageAttachment = await getAttachmentData(attachment)
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,15 +4,14 @@ 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,36 +6,35 @@ 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) { })
log(`Issue deleting user history files from ${thread.id}`) } catch (error) {
} log(`Issue deleting user history files from ${thread.id}`)
} }
) })

View File

@@ -17,7 +17,7 @@ export class Queue<T> implements IQueue<T> {
* Set up Queue * Set up Queue
* @param capacity max length of queue * @param capacity max length of queue
*/ */
constructor(public capacity: number = 5) {} constructor(public capacity: number = 5) { }
/** /**
* Put item in front of queue * Put item in front of queue