updated src/events/messageCreate.ts
This commit is contained in:
@@ -64,10 +64,14 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
// Check if message is a bot response to avoid loops
|
// Check if message is a bot response to avoid loops
|
||||||
const isBotResponseKey = `message:${message.id}:is_bot_response`
|
const isBotResponseKey = `message:${message.id}:is_bot_response`
|
||||||
if (isBotMessage) {
|
if (isBotMessage) {
|
||||||
const isBotResponse = await redis.get(isBotResponseKey)
|
try {
|
||||||
if (isBotResponse === 'true') {
|
const isBotResponse = await redis.get(isBotResponseKey)
|
||||||
log(`Skipping bot message ${message.id} as it is a bot response.`)
|
if (isBotResponse === 'true') {
|
||||||
return
|
log(`Skipping bot message ${message.id} as it is a bot response.`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log(`Failed to check isBotResponse in Redis: ${error}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,12 +134,14 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
try {
|
try {
|
||||||
// Retrieve Server/Guild Preferences
|
// Retrieve Server/Guild Preferences
|
||||||
let attempt = 0
|
let attempt = 0
|
||||||
|
let serverConfig;
|
||||||
while (attempt < maxRetries) {
|
while (attempt < maxRetries) {
|
||||||
try {
|
try {
|
||||||
await new Promise((resolve, reject) => {
|
serverConfig = await new Promise((resolve, reject) => {
|
||||||
getServerConfig(`${message.guildId}-config.json`, (config) => {
|
getServerConfig(`${message.guildId}-config.json`, (config) => {
|
||||||
if (config === undefined) {
|
if (config === undefined) {
|
||||||
redis.set(`server:${message.guildId}:config`, JSON.stringify({ options: { 'toggle-chat': true } }))
|
redis.set(`server:${message.guildId}:config`, JSON.stringify({ options: { 'toggle-chat': true } }))
|
||||||
|
.catch(err => log(`Failed to set default server config in Redis: ${err}`));
|
||||||
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...'))
|
||||||
} else if (!config.options['toggle-chat']) {
|
} else if (!config.options['toggle-chat']) {
|
||||||
reject(new Error('Admin(s) have disabled chat features.\n\nPlease contact your server\'s admin(s).'))
|
reject(new Error('Admin(s) have disabled chat features.\n\nPlease contact your server\'s admin(s).'))
|
||||||
@@ -166,7 +172,13 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
redis.get(userConfigKey).then(configRaw => {
|
redis.get(userConfigKey).then(configRaw => {
|
||||||
let config: UserConfig | undefined
|
let config: UserConfig | undefined
|
||||||
if (configRaw) {
|
if (configRaw) {
|
||||||
config = JSON.parse(configRaw)
|
try {
|
||||||
|
config = JSON.parse(configRaw)
|
||||||
|
} catch (parseError) {
|
||||||
|
log(`Failed to parse user config JSON: ${parseError}`)
|
||||||
|
reject(parseError)
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!config) {
|
if (!config) {
|
||||||
const defaultConfig: UserConfig = {
|
const defaultConfig: UserConfig = {
|
||||||
@@ -178,6 +190,7 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
redis.set(userConfigKey, JSON.stringify(defaultConfig))
|
redis.set(userConfigKey, JSON.stringify(defaultConfig))
|
||||||
|
.catch(err => log(`Failed to set default user config in Redis: ${err}`));
|
||||||
log(`Created default config for ${message.author.username}`)
|
log(`Created default config for ${message.author.username}`)
|
||||||
reject(new Error('No User Preferences is set up.\n\nCreating preferences with defaults.\nPlease try chatting again.'))
|
reject(new Error('No User Preferences is set up.\n\nCreating preferences with defaults.\nPlease try chatting again.'))
|
||||||
return
|
return
|
||||||
@@ -198,7 +211,10 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
}
|
}
|
||||||
|
|
||||||
resolve(config)
|
resolve(config)
|
||||||
}).catch(err => reject(err))
|
}).catch(err => {
|
||||||
|
log(`Redis error fetching user config: ${err}`)
|
||||||
|
reject(err)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
break
|
break
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -218,8 +234,13 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
try {
|
try {
|
||||||
const historyRaw = await redis.get(channelHistoryKey)
|
const historyRaw = await redis.get(channelHistoryKey)
|
||||||
if (historyRaw) {
|
if (historyRaw) {
|
||||||
chatMessages = JSON.parse(historyRaw)
|
try {
|
||||||
log(`Retrieved ${chatMessages.length} messages from Redis for ${channelHistoryKey}`)
|
chatMessages = JSON.parse(historyRaw)
|
||||||
|
log(`Retrieved ${chatMessages.length} messages from Redis for ${channelHistoryKey}`)
|
||||||
|
} catch (parseError) {
|
||||||
|
log(`Failed to parse channel history JSON: ${parseError}`)
|
||||||
|
chatMessages = []
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
log(`No history found for ${channelHistoryKey}. Initializing empty history.`)
|
log(`No history found for ${channelHistoryKey}. Initializing empty history.`)
|
||||||
chatMessages = []
|
chatMessages = []
|
||||||
@@ -237,9 +258,17 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
const attachment = message.attachments.first()
|
const attachment = message.attachments.first()
|
||||||
let messageAttachment: string[] = []
|
let messageAttachment: string[] = []
|
||||||
if (attachment && attachment.name?.endsWith(".txt")) {
|
if (attachment && attachment.name?.endsWith(".txt")) {
|
||||||
cleanedMessage += await getTextFileAttachmentData(attachment)
|
try {
|
||||||
|
cleanedMessage += await getTextFileAttachmentData(attachment)
|
||||||
|
} catch (error) {
|
||||||
|
log(`Failed to process text attachment: ${error}`)
|
||||||
|
}
|
||||||
} else if (attachment) {
|
} else if (attachment) {
|
||||||
messageAttachment = await getAttachmentData(attachment)
|
try {
|
||||||
|
messageAttachment = await getAttachmentData(attachment)
|
||||||
|
} catch (error) {
|
||||||
|
log(`Failed to process attachment: ${error}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const model: string = userConfig.options['switch-model']
|
const model: string = userConfig.options['switch-model']
|
||||||
@@ -339,11 +368,19 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
})
|
})
|
||||||
|
|
||||||
// Call Ollama
|
// Call Ollama
|
||||||
const response = await ollama.chat({
|
let response;
|
||||||
model,
|
try {
|
||||||
messages: [{ role: 'user', content: prompt }],
|
response = await ollama.chat({
|
||||||
stream: shouldStream
|
model,
|
||||||
})
|
messages: [{ role: 'user', content: prompt }],
|
||||||
|
stream: shouldStream
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
log(`Ollama chat error: ${error}`)
|
||||||
|
message.reply('Sorry, I’m having trouble contacting the AI model. Try again later?')
|
||||||
|
msgHist.pop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Parse JSON response
|
// Parse JSON response
|
||||||
let jsonResponse: ModelResponse
|
let jsonResponse: ModelResponse
|
||||||
@@ -359,7 +396,7 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(`Failed to parse model response: ${error}`)
|
log(`Failed to parse model response: ${error}`)
|
||||||
//message.reply('Sorry, I’m having trouble thinking right now. Try again?')
|
message.reply('Sorry, I’m having trouble thinking right now. Try again?')
|
||||||
msgHist.pop()
|
msgHist.pop()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -402,8 +439,16 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Send reply to Discord and mark as bot response
|
// Send reply to Discord and mark as bot response
|
||||||
const reply = jsonResponse.reply || 'Huh?'
|
const reply = jsonResponse.reply || 'Sorry, I didn’t get that. Can you try again?'
|
||||||
const replyMessage = await message.reply(reply)
|
let replyMessage;
|
||||||
|
try {
|
||||||
|
replyMessage = await message.reply(reply)
|
||||||
|
} catch (error) {
|
||||||
|
log(`Failed to send reply to Discord: ${error}`)
|
||||||
|
msgHist.pop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (isBotMessage) {
|
if (isBotMessage) {
|
||||||
try {
|
try {
|
||||||
await redis.set(`message:${replyMessage.id}:is_bot_response`, 'true', { EX: 3600 }) // 1 hour TTL
|
await redis.set(`message:${replyMessage.id}:is_bot_response`, 'true', { EX: 3600 }) // 1 hour TTL
|
||||||
@@ -441,7 +486,8 @@ export default event(Events.MessageCreate, async ({ log, msgHist, ollama, client
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
msgHist.pop()
|
log(`Error in message processing: ${error.message}`)
|
||||||
message.reply(`**Error Occurred:**\n\n**Reason:** *${error.message}*`)
|
message.reply(`**Error Occurred:**\n\n**Reason:** *${error.message}*`)
|
||||||
|
msgHist.pop()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user