mirror of
https://github.com/kevinthedang/discord-ollama.git
synced 2026-11-08 10:51:18 -05:00
stateful logging
This commit is contained in:
@@ -42,8 +42,5 @@
|
|||||||
"engines": {
|
"engines": {
|
||||||
"npm": ">=10.9.0",
|
"npm": ">=10.9.0",
|
||||||
"node": ">=24.0.0"
|
"node": ">=24.0.0"
|
||||||
},
|
|
||||||
"allowScripts": {
|
|
||||||
"esbuild@0.25.12": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js'
|
import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js'
|
||||||
import { openConfig, SlashCommand, UserCommand } from '../utils/index.js'
|
import { openConfig, SlashCommand, UserCommand } from '../utils/index.js'
|
||||||
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
export const Capacity: SlashCommand = {
|
export const Capacity: SlashCommand = {
|
||||||
name: 'modify-capacity',
|
name: 'modify-capacity',
|
||||||
@@ -16,13 +17,13 @@ export const Capacity: SlashCommand = {
|
|||||||
],
|
],
|
||||||
|
|
||||||
// Query for message information and set the style
|
// Query for message information and set the style
|
||||||
run: async (client: Client, interaction: ChatInputCommandInteraction) => {
|
run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => {
|
||||||
// fetch channel and message
|
// fetch channel and message
|
||||||
const channel = await client.channels.fetch(interaction.channelId)
|
const channel = await client.channels.fetch(interaction.channelId)
|
||||||
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,
|
openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName,
|
||||||
interaction.options.getNumber('context-capacity')
|
interaction.options.getNumber('context-capacity')
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { Channel, Client, CommandInteraction, MessageFlags, TextChannel } from 'discord.js'
|
import { Channel, Client, CommandInteraction, MessageFlags, TextChannel } from 'discord.js'
|
||||||
import { clearChannelInfo, SlashCommand, UserCommand } from '../utils/index.js'
|
import { clearChannelInfo, SlashCommand, UserCommand } from '../utils/index.js'
|
||||||
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
export const ClearUserChannelHistory: SlashCommand = {
|
export const ClearUserChannelHistory: SlashCommand = {
|
||||||
name: 'clear-user-channel-history',
|
name: 'clear-user-channel-history',
|
||||||
description: 'clears history for user in the current channel',
|
description: 'clears history for user in the current channel',
|
||||||
|
|
||||||
// Clear channel history for intended user
|
// Clear channel history for intended user
|
||||||
run: async (client: Client, interaction: CommandInteraction) => {
|
run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => {
|
||||||
// fetch current channel
|
// fetch current channel
|
||||||
const channel: Channel | null = await client.channels.fetch(interaction.channelId)
|
const channel: Channel | null = await client.channels.fetch(interaction.channelId)
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ export const ClearUserChannelHistory: SlashCommand = {
|
|||||||
|
|
||||||
// clear channel info for user
|
// clear channel info for user
|
||||||
const successfulWipe = await clearChannelInfo(
|
const successfulWipe = await clearChannelInfo(
|
||||||
|
logger,
|
||||||
interaction.channelId,
|
interaction.channelId,
|
||||||
interaction.channel as TextChannel,
|
interaction.channel as TextChannel,
|
||||||
interaction.user.username
|
interaction.user.username
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js'
|
import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js'
|
||||||
import { AdminCommand, openConfig, SlashCommand } from '../utils/index.js'
|
import { AdminCommand, openConfig, SlashCommand } from '../utils/index.js'
|
||||||
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
export const Disable: SlashCommand = {
|
export const Disable: SlashCommand = {
|
||||||
name: 'toggle-chat',
|
name: 'toggle-chat',
|
||||||
@@ -16,7 +17,7 @@ export const Disable: SlashCommand = {
|
|||||||
],
|
],
|
||||||
|
|
||||||
// Query for message information and set the style
|
// Query for message information and set the style
|
||||||
run: async (client: Client, interaction: ChatInputCommandInteraction) => {
|
run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => {
|
||||||
// fetch channel and message
|
// fetch channel and message
|
||||||
const channel = await client.channels.fetch(interaction.channelId)
|
const channel = await client.channels.fetch(interaction.channelId)
|
||||||
if (!channel || !AdminCommand.includes(channel.type)) return
|
if (!channel || !AdminCommand.includes(channel.type)) return
|
||||||
@@ -31,7 +32,7 @@ export const Disable: SlashCommand = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// set state of bot chat features
|
// set state of bot chat features
|
||||||
openConfig(`${interaction.guildId}-config.json`, interaction.commandName,
|
openConfig(logger, `${interaction.guildId}-config.json`, interaction.commandName,
|
||||||
interaction.options.getBoolean('enabled')
|
interaction.options.getBoolean('enabled')
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { ApplicationCommandOptionType, Client, ChatInputCommandInteraction, MessageFlags } from 'discord.js'
|
import { ApplicationCommandOptionType, Client, ChatInputCommandInteraction, MessageFlags } from 'discord.js'
|
||||||
import { openConfig, SlashCommand, UserCommand } from '../utils/index.js'
|
import { openConfig, SlashCommand, UserCommand } from '../utils/index.js'
|
||||||
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
export const MessageStream: SlashCommand = {
|
export const MessageStream: SlashCommand = {
|
||||||
name: 'message-stream',
|
name: 'message-stream',
|
||||||
@@ -16,13 +17,13 @@ export const MessageStream: SlashCommand = {
|
|||||||
],
|
],
|
||||||
|
|
||||||
// change preferences based on command
|
// change preferences based on command
|
||||||
run: async (client: Client, interaction: ChatInputCommandInteraction) => {
|
run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => {
|
||||||
// verify channel
|
// verify channel
|
||||||
const channel = await client.channels.fetch(interaction.channelId)
|
const channel = await client.channels.fetch(interaction.channelId)
|
||||||
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,
|
openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName,
|
||||||
interaction.options.getBoolean('stream')
|
interaction.options.getBoolean('stream')
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export const SwitchModel: SlashCommand = {
|
|||||||
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(logger, `${interaction.user.username}-config.json`, interaction.commandName, modelInput)
|
||||||
|
|
||||||
// successful switch
|
// successful switch
|
||||||
interaction.editReply({
|
interaction.editReply({
|
||||||
@@ -52,7 +52,7 @@ export const SwitchModel: SlashCommand = {
|
|||||||
// 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
|
||||||
openConfig(`${interaction.user.username}-config.json`, interaction.commandName, modelInput)
|
openConfig(logger, `${interaction.user.username}-config.json`, interaction.commandName, modelInput)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js'
|
import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js'
|
||||||
import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js'
|
import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js'
|
||||||
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
export const ThreadCreate: SlashCommand = {
|
export const ThreadCreate: SlashCommand = {
|
||||||
name: 'thread',
|
name: 'thread',
|
||||||
description: 'creates a thread and mentions user',
|
description: 'creates a thread and mentions user',
|
||||||
|
|
||||||
// Query for server information
|
// Query for server information
|
||||||
run: async (client: Client, interaction: CommandInteraction) => {
|
run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => {
|
||||||
// fetch the channel
|
// fetch the channel
|
||||||
const channel = await client.channels.fetch(interaction.channelId)
|
const channel = await client.channels.fetch(interaction.channelId)
|
||||||
if (!channel || !AdminCommand.includes(channel.type)) return
|
if (!channel || !AdminCommand.includes(channel.type)) return
|
||||||
@@ -21,7 +22,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, thread as ThreadChannel, interaction.user.tag)
|
openChannelInfo(logger, thread.id, thread as ThreadChannel, interaction.user.tag)
|
||||||
|
|
||||||
// user only reply
|
// user only reply
|
||||||
return interaction.reply({
|
return interaction.reply({
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js'
|
import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js'
|
||||||
import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js'
|
import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js'
|
||||||
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
export const PrivateThreadCreate: SlashCommand = {
|
export const PrivateThreadCreate: SlashCommand = {
|
||||||
name: 'private-thread',
|
name: 'private-thread',
|
||||||
description: 'creates a private thread and mentions user',
|
description: 'creates a private thread and mentions user',
|
||||||
|
|
||||||
// Query for server information
|
// Query for server information
|
||||||
run: async (client: Client, interaction: CommandInteraction) => {
|
run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => {
|
||||||
// fetch the channel
|
// fetch the channel
|
||||||
const channel = await client.channels.fetch(interaction.channelId)
|
const channel = await client.channels.fetch(interaction.channelId)
|
||||||
if (!channel || !AdminCommand.includes(channel.type)) return
|
if (!channel || !AdminCommand.includes(channel.type)) return
|
||||||
@@ -22,7 +23,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, thread as ThreadChannel, interaction.user.tag)
|
openChannelInfo(logger, thread.id, thread as ThreadChannel, interaction.user.tag)
|
||||||
|
|
||||||
// user only reply
|
// user only reply
|
||||||
return interaction.reply({
|
return interaction.reply({
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { event, Events } from '../utils/index.js'
|
import { event, Events } from '../utils/index.js'
|
||||||
import commands from '../commands/index.js'
|
import commands from '../commands/index.js'
|
||||||
|
import { createLogger } from '../components/index.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interaction creation listener for the client
|
* Interaction creation listener for the client
|
||||||
@@ -15,5 +16,11 @@ export default event(Events.InteractionCreate, async ({ logger, client }, intera
|
|||||||
if (!command) return
|
if (!command) return
|
||||||
|
|
||||||
// the command exists, execute it
|
// the command exists, execute it
|
||||||
command.run(client, interaction, logger)
|
const commandLogger = createLogger({
|
||||||
|
component: 'command',
|
||||||
|
command: command.name
|
||||||
|
}, logger)
|
||||||
|
|
||||||
|
void Promise.resolve(command.run(client, interaction, commandLogger))
|
||||||
|
.catch(error => commandLogger.error({ err: error }, 'Command execution failed'))
|
||||||
})
|
})
|
||||||
@@ -33,7 +33,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
|||||||
|
|
||||||
if (channelContextHistory.length === 0) {
|
if (channelContextHistory.length === 0) {
|
||||||
channelContextHistory = await new Promise((resolve) => {
|
channelContextHistory = await new Promise((resolve) => {
|
||||||
addToChannelContext(message.channelId,
|
addToChannelContext(logger, message.channelId,
|
||||||
message.channel as TextChannel
|
message.channel as TextChannel
|
||||||
)
|
)
|
||||||
getChannelInfo(`${message.channelId}-context.json`, (channelInfo) => {
|
getChannelInfo(`${message.channelId}-context.json`, (channelInfo) => {
|
||||||
@@ -68,7 +68,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
|||||||
})
|
})
|
||||||
|
|
||||||
// Store in Channel Context
|
// Store in Channel Context
|
||||||
addToChannelContext(message.channelId,
|
addToChannelContext(logger, message.channelId,
|
||||||
message.channel as TextChannel,
|
message.channel as TextChannel,
|
||||||
channelHistory.getItems()
|
channelHistory.getItems()
|
||||||
)
|
)
|
||||||
@@ -93,7 +93,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
|||||||
// 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(logger, `${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...'))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,7 +125,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
|||||||
userConfig = await new Promise((resolve, reject) => {
|
userConfig = await new Promise((resolve, reject) => {
|
||||||
getUserConfig(`${message.author.username}-config.json`, (config) => {
|
getUserConfig(`${message.author.username}-config.json`, (config) => {
|
||||||
if (config === undefined) {
|
if (config === undefined) {
|
||||||
openConfig(`${message.author.username}-config.json`, 'switch-model', defaultModel)
|
openConfig(logger, `${message.author.username}-config.json`, 'switch-model', defaultModel)
|
||||||
reject(new Error(`No User Preferences is set up.\n\nCreating new preferences file for ${message.author.username}\nPlease try chatting again.`))
|
reject(new Error(`No User Preferences is set up.\n\nCreating new preferences file for ${message.author.username}\nPlease try chatting again.`))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -175,7 +175,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
|||||||
|
|
||||||
if (chatMessages.length === 0) {
|
if (chatMessages.length === 0) {
|
||||||
chatMessages = await new Promise((resolve, reject) => {
|
chatMessages = await new Promise((resolve, reject) => {
|
||||||
openChannelInfo(message.channelId,
|
openChannelInfo(logger, message.channelId,
|
||||||
message.channel as TextChannel,
|
message.channel as TextChannel,
|
||||||
message.author.tag
|
message.author.tag
|
||||||
)
|
)
|
||||||
@@ -225,7 +225,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
|||||||
})
|
})
|
||||||
|
|
||||||
// only update the json on success
|
// only update the json on success
|
||||||
openChannelInfo(message.channelId,
|
openChannelInfo(logger, message.channelId,
|
||||||
message.channel as TextChannel,
|
message.channel as TextChannel,
|
||||||
message.author.tag,
|
message.author.tag,
|
||||||
msgHist.getItems()
|
msgHist.getItems()
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ 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, ({ logger }, client) => {
|
export default event(Events.ClientReady, ({ logger }, 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, logger)
|
||||||
|
|
||||||
// set status of the bot
|
// set status of the bot
|
||||||
client.user.setActivity({
|
client.user.setActivity({
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import { ChatInputCommandInteraction, ChatInputApplicationCommandData, Client } from 'discord.js'
|
import { ChatInputCommandInteraction, ChatInputApplicationCommandData, Client, type Awaitable } from 'discord.js'
|
||||||
import { createLogger } from '../components/index.js'
|
|
||||||
import type { Logger as PinoLogger } from 'pino'
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
const logger = createLogger({ component: 'commands' })
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* interface for how slash commands should be run
|
* interface for how slash commands should be run
|
||||||
*/
|
*/
|
||||||
@@ -12,7 +9,7 @@ export interface SlashCommand extends ChatInputApplicationCommandData {
|
|||||||
client: Client,
|
client: Client,
|
||||||
interaction: ChatInputCommandInteraction,
|
interaction: ChatInputCommandInteraction,
|
||||||
logger: PinoLogger
|
logger: PinoLogger
|
||||||
) => void
|
) => Awaitable<unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,7 +17,7 @@ export interface SlashCommand extends ChatInputApplicationCommandData {
|
|||||||
* @param client the bot reference
|
* @param client the bot reference
|
||||||
* @param commands commands to register to the bot
|
* @param commands commands to register to the bot
|
||||||
*/
|
*/
|
||||||
export function registerCommands(client: Client, commands: SlashCommand[]): void {
|
export function registerCommands(client: Client, commands: SlashCommand[], logger: PinoLogger): void {
|
||||||
// ensure the bot is online before registering
|
// ensure the bot is online before registering
|
||||||
if (!client.application) return
|
if (!client.application) return
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,7 @@ import { TextChannel, ThreadChannel } from 'discord.js'
|
|||||||
import { Configuration, Channel, UserMessage } from '../index.js'
|
import { Configuration, Channel, UserMessage } from '../index.js'
|
||||||
import fs from 'fs'
|
import fs from 'fs'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
import { createLogger } from '../../components/index.js'
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
const logger = createLogger({ component: 'chat-history' })
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method to check if a thread history file exists
|
* Method to check if a thread history file exists
|
||||||
@@ -32,7 +30,7 @@ async function checkChannelInfoExists(channel: TextChannel, user: string) {
|
|||||||
* @param user username of user
|
* @param user username of user
|
||||||
* @returns nothing
|
* @returns nothing
|
||||||
*/
|
*/
|
||||||
export async function clearChannelInfo(filename: string, channel: TextChannel, user: string): Promise<boolean> {
|
export async function clearChannelInfo(logger: PinoLogger, filename: string, channel: TextChannel, user: string): Promise<boolean> {
|
||||||
const channelInfoExists: boolean = await checkChannelInfoExists(channel, user)
|
const channelInfoExists: boolean = await checkChannelInfoExists(channel, user)
|
||||||
|
|
||||||
// If thread does not exist, file can't be found
|
// If thread does not exist, file can't be found
|
||||||
@@ -59,7 +57,7 @@ export async function clearChannelInfo(filename: string, channel: TextChannel, u
|
|||||||
return cleanedHistory
|
return cleanedHistory
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function addToChannelContext(filename: string, channel: TextChannel | ThreadChannel, messages: UserMessage[] = []): Promise<void> {
|
export async function addToChannelContext(logger: PinoLogger, filename: string, channel: TextChannel | ThreadChannel, messages: UserMessage[] = []): Promise<void> {
|
||||||
const fullFileName = `data/${filename}-context.json`
|
const fullFileName = `data/${filename}-context.json`
|
||||||
if (fs.existsSync(fullFileName)) {
|
if (fs.existsSync(fullFileName)) {
|
||||||
fs.readFile(fullFileName, 'utf8', (error, data) => {
|
fs.readFile(fullFileName, 'utf8', (error, data) => {
|
||||||
@@ -115,7 +113,7 @@ export async function accessChannelContext(filename: string, callback: (config:
|
|||||||
* @param user the user's name
|
* @param user the user's name
|
||||||
* @param messages their messages
|
* @param messages their messages
|
||||||
*/
|
*/
|
||||||
export async function openChannelInfo(filename: string, channel: TextChannel | ThreadChannel, user: string, messages: UserMessage[] = []): Promise<void> {
|
export async function openChannelInfo(logger: PinoLogger, filename: string, channel: TextChannel | ThreadChannel, user: string, messages: UserMessage[] = []): Promise<void> {
|
||||||
const fullFileName = `data/${filename}-${user}.json`
|
const fullFileName = `data/${filename}-${user}.json`
|
||||||
if (fs.existsSync(fullFileName)) {
|
if (fs.existsSync(fullFileName)) {
|
||||||
fs.readFile(fullFileName, 'utf8', (error, data) => {
|
fs.readFile(fullFileName, 'utf8', (error, data) => {
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import { Configuration, ServerConfig, UserConfig, isServerConfigurationKey } from '../index.js'
|
import { Configuration, ServerConfig, UserConfig, isServerConfigurationKey } from '../index.js'
|
||||||
import fs from 'fs'
|
import fs from 'fs'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
import { createLogger } from '../../components/index.js'
|
import type { Logger as PinoLogger } from 'pino'
|
||||||
|
|
||||||
const logger = createLogger({ component: 'config' })
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method to open a file in the working directory and modify/create it
|
* Method to open a file in the working directory and modify/create it
|
||||||
@@ -13,7 +11,7 @@ const logger = createLogger({ component: 'config' })
|
|||||||
* @param value new value to assign
|
* @param value new value to assign
|
||||||
*/
|
*/
|
||||||
// add type of change (server, user)
|
// add type of change (server, user)
|
||||||
export function openConfig(filename: string, key: string, value: any) {
|
export function openConfig(logger: PinoLogger, filename: string, key: string, value: any) {
|
||||||
const fullFileName = `data/${filename}`
|
const fullFileName = `data/${filename}`
|
||||||
|
|
||||||
// check if the file exists, if not then make the config file
|
// check if the file exists, if not then make the config file
|
||||||
|
|||||||
@@ -42,4 +42,23 @@ describe('Pino logger', () => {
|
|||||||
expect(entry.answer).toBe(42)
|
expect(entry.answer).toBe(42)
|
||||||
expect(entry.msg).toBe('warning')
|
expect(entry.msg).toBe('warning')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('preserves parent context when adding command bindings', () => {
|
||||||
|
output = ''
|
||||||
|
const eventLogger = createLogger({
|
||||||
|
component: 'event',
|
||||||
|
event: 'InteractionCreate'
|
||||||
|
}, parentLogger)
|
||||||
|
const commandLogger = createLogger({
|
||||||
|
component: 'command',
|
||||||
|
command: 'summary'
|
||||||
|
}, eventLogger)
|
||||||
|
|
||||||
|
commandLogger.info('command started')
|
||||||
|
|
||||||
|
const entry = JSON.parse(output)
|
||||||
|
expect(entry.component).toBe('command')
|
||||||
|
expect(entry.event).toBe('InteractionCreate')
|
||||||
|
expect(entry.command).toBe('summary')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import { mkdtempSync, rmSync } from 'node:fs'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { join } from 'node:path'
|
||||||
|
import { Writable } from 'node:stream'
|
||||||
|
import { ChannelType, type ChatInputCommandInteraction, type Client, type TextChannel } from 'discord.js'
|
||||||
|
import pino from 'pino'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { createLogger } from '../src/components/logger.js'
|
||||||
|
import { Capacity } from '../src/commands/capacity.js'
|
||||||
|
import { openChannelInfo } from '../src/utils/handlers/chatHistoryHandler.js'
|
||||||
|
import { registerCommands, type SlashCommand } from '../src/utils/commands.js'
|
||||||
|
|
||||||
|
describe('logger context integration', () => {
|
||||||
|
let output = ''
|
||||||
|
const destination = new Writable({
|
||||||
|
write(chunk, _encoding, callback) {
|
||||||
|
output += chunk.toString()
|
||||||
|
callback()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const parentLogger = pino({ level: 'trace' }, destination)
|
||||||
|
let workingDirectory: string
|
||||||
|
let tempDirectory: string | undefined
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
output = ''
|
||||||
|
workingDirectory = process.cwd()
|
||||||
|
vi.stubEnv('NODE_ENV', 'test')
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.chdir(workingDirectory)
|
||||||
|
if (tempDirectory)
|
||||||
|
rmSync(tempDirectory, { recursive: true, force: true })
|
||||||
|
vi.unstubAllEnvs()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retains event and command context in registration and handler logs', async () => {
|
||||||
|
const readyLogger = createLogger({
|
||||||
|
component: 'event',
|
||||||
|
event: 'ClientReady'
|
||||||
|
}, parentLogger)
|
||||||
|
const commandsApi = {
|
||||||
|
fetch: vi.fn().mockResolvedValue(new Map()),
|
||||||
|
cache: { clear: vi.fn() },
|
||||||
|
create: vi.fn(async (command: SlashCommand) => ({
|
||||||
|
name: command.name,
|
||||||
|
options: []
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
const client = {
|
||||||
|
application: { commands: commandsApi }
|
||||||
|
} as unknown as Client
|
||||||
|
const mockCommand = {
|
||||||
|
name: 'test-command',
|
||||||
|
description: 'test command',
|
||||||
|
run: vi.fn()
|
||||||
|
} as unknown as SlashCommand
|
||||||
|
|
||||||
|
registerCommands(client, [mockCommand], readyLogger)
|
||||||
|
|
||||||
|
const commandLogger = createLogger({
|
||||||
|
component: 'command',
|
||||||
|
command: 'modify-capacity'
|
||||||
|
}, createLogger({
|
||||||
|
component: 'event',
|
||||||
|
event: 'InteractionCreate'
|
||||||
|
}, parentLogger))
|
||||||
|
const interaction = {
|
||||||
|
channelId: 'test-channel',
|
||||||
|
commandName: 'modify-capacity',
|
||||||
|
user: { username: 'test-user' },
|
||||||
|
options: {
|
||||||
|
getNumber: () => 8,
|
||||||
|
get: () => ({ value: 8 })
|
||||||
|
},
|
||||||
|
reply: vi.fn()
|
||||||
|
} as unknown as ChatInputCommandInteraction
|
||||||
|
const commandClient = {
|
||||||
|
channels: {
|
||||||
|
fetch: vi.fn().mockResolvedValue({ type: ChannelType.GuildText })
|
||||||
|
}
|
||||||
|
} as unknown as Client
|
||||||
|
|
||||||
|
tempDirectory = mkdtempSync(join(tmpdir(), 'discord-ollama-logger-'))
|
||||||
|
process.chdir(tempDirectory)
|
||||||
|
|
||||||
|
await Capacity.run(commandClient, interaction, commandLogger)
|
||||||
|
await openChannelInfo(commandLogger, 'test-channel', {
|
||||||
|
id: 'test-channel',
|
||||||
|
name: 'test'
|
||||||
|
} as TextChannel, 'test-user')
|
||||||
|
|
||||||
|
await new Promise(resolve => setImmediate(resolve))
|
||||||
|
const entries = output.trim().split('\n').map(line => JSON.parse(line))
|
||||||
|
|
||||||
|
const registration = entries.find(entry => entry.msg === 'Registered command on Discord')
|
||||||
|
expect(registration).toMatchObject({
|
||||||
|
event: 'ClientReady',
|
||||||
|
command: 'test-command',
|
||||||
|
msg: 'Registered command on Discord'
|
||||||
|
})
|
||||||
|
|
||||||
|
const configuration = entries.find(entry => entry.msg === 'Created configuration file')
|
||||||
|
expect(configuration).toMatchObject({
|
||||||
|
event: 'InteractionCreate',
|
||||||
|
component: 'command',
|
||||||
|
command: 'modify-capacity',
|
||||||
|
msg: 'Created configuration file'
|
||||||
|
})
|
||||||
|
expect(configuration.caller).toMatch(/configHandler\.ts:\d+:\d+/)
|
||||||
|
|
||||||
|
const history = entries.find(entry => entry.msg === 'Created channel history')
|
||||||
|
expect(history).toMatchObject({
|
||||||
|
event: 'InteractionCreate',
|
||||||
|
component: 'command',
|
||||||
|
command: 'modify-capacity',
|
||||||
|
msg: 'Created channel history'
|
||||||
|
})
|
||||||
|
expect(history.caller).toMatch(/chatHistoryHandler\.ts:\d+:\d+/)
|
||||||
|
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user