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": {
|
||||
"npm": ">=10.9.0",
|
||||
"node": ">=24.0.0"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js'
|
||||
import { openConfig, SlashCommand, UserCommand } from '../utils/index.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
export const Capacity: SlashCommand = {
|
||||
name: 'modify-capacity',
|
||||
@@ -16,13 +17,13 @@ export const Capacity: SlashCommand = {
|
||||
],
|
||||
|
||||
// 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
|
||||
const channel = await client.channels.fetch(interaction.channelId)
|
||||
if (!channel || !UserCommand.includes(channel.type)) return
|
||||
|
||||
// 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')
|
||||
)
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Channel, Client, CommandInteraction, MessageFlags, TextChannel } from 'discord.js'
|
||||
import { clearChannelInfo, SlashCommand, UserCommand } from '../utils/index.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
export const ClearUserChannelHistory: SlashCommand = {
|
||||
name: 'clear-user-channel-history',
|
||||
description: 'clears history for user in the current channel',
|
||||
|
||||
// Clear channel history for intended user
|
||||
run: async (client: Client, interaction: CommandInteraction) => {
|
||||
run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => {
|
||||
// fetch current channel
|
||||
const channel: Channel | null = await client.channels.fetch(interaction.channelId)
|
||||
|
||||
@@ -15,6 +16,7 @@ export const ClearUserChannelHistory: SlashCommand = {
|
||||
|
||||
// clear channel info for user
|
||||
const successfulWipe = await clearChannelInfo(
|
||||
logger,
|
||||
interaction.channelId,
|
||||
interaction.channel as TextChannel,
|
||||
interaction.user.username
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Client, ChatInputCommandInteraction, ApplicationCommandOptionType, MessageFlags } from 'discord.js'
|
||||
import { AdminCommand, openConfig, SlashCommand } from '../utils/index.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
export const Disable: SlashCommand = {
|
||||
name: 'toggle-chat',
|
||||
@@ -16,7 +17,7 @@ export const Disable: SlashCommand = {
|
||||
],
|
||||
|
||||
// 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
|
||||
const channel = await client.channels.fetch(interaction.channelId)
|
||||
if (!channel || !AdminCommand.includes(channel.type)) return
|
||||
@@ -31,7 +32,7 @@ export const Disable: SlashCommand = {
|
||||
}
|
||||
|
||||
// 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')
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApplicationCommandOptionType, Client, ChatInputCommandInteraction, MessageFlags } from 'discord.js'
|
||||
import { openConfig, SlashCommand, UserCommand } from '../utils/index.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
export const MessageStream: SlashCommand = {
|
||||
name: 'message-stream',
|
||||
@@ -16,13 +17,13 @@ export const MessageStream: SlashCommand = {
|
||||
],
|
||||
|
||||
// change preferences based on command
|
||||
run: async (client: Client, interaction: ChatInputCommandInteraction) => {
|
||||
run: async (client: Client, interaction: ChatInputCommandInteraction, logger: PinoLogger) => {
|
||||
// verify channel
|
||||
const channel = await client.channels.fetch(interaction.channelId)
|
||||
if (!channel || !UserCommand.includes(channel.type)) return
|
||||
|
||||
// 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')
|
||||
)
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ export const SwitchModel: SlashCommand = {
|
||||
for (const model in response.models) {
|
||||
const currentModel: ModelResponse = response.models[model]
|
||||
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
|
||||
interaction.editReply({
|
||||
@@ -52,7 +52,7 @@ export const SwitchModel: SlashCommand = {
|
||||
// todo: problem can be here if async messes up
|
||||
if (switchSuccess) {
|
||||
// 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
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js'
|
||||
import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
export const ThreadCreate: SlashCommand = {
|
||||
name: 'thread',
|
||||
description: 'creates a thread and mentions user',
|
||||
|
||||
// Query for server information
|
||||
run: async (client: Client, interaction: CommandInteraction) => {
|
||||
run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => {
|
||||
// fetch the channel
|
||||
const channel = await client.channels.fetch(interaction.channelId)
|
||||
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.`)
|
||||
|
||||
// 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
|
||||
return interaction.reply({
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { ChannelType, Client, CommandInteraction, MessageFlags, TextChannel, ThreadChannel } from 'discord.js'
|
||||
import { AdminCommand, openChannelInfo, SlashCommand } from '../utils/index.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
export const PrivateThreadCreate: SlashCommand = {
|
||||
name: 'private-thread',
|
||||
description: 'creates a private thread and mentions user',
|
||||
|
||||
// Query for server information
|
||||
run: async (client: Client, interaction: CommandInteraction) => {
|
||||
run: async (client: Client, interaction: CommandInteraction, logger: PinoLogger) => {
|
||||
// fetch the channel
|
||||
const channel = await client.channels.fetch(interaction.channelId)
|
||||
if (!channel || !AdminCommand.includes(channel.type)) return
|
||||
@@ -22,7 +23,7 @@ export const PrivateThreadCreate: SlashCommand = {
|
||||
|
||||
// handle storing this chat channel
|
||||
// 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
|
||||
return interaction.reply({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { event, Events } from '../utils/index.js'
|
||||
import commands from '../commands/index.js'
|
||||
import { createLogger } from '../components/index.js'
|
||||
|
||||
/**
|
||||
* Interaction creation listener for the client
|
||||
@@ -15,5 +16,11 @@ export default event(Events.InteractionCreate, async ({ logger, client }, intera
|
||||
if (!command) return
|
||||
|
||||
// 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) {
|
||||
channelContextHistory = await new Promise((resolve) => {
|
||||
addToChannelContext(message.channelId,
|
||||
addToChannelContext(logger, message.channelId,
|
||||
message.channel as TextChannel
|
||||
)
|
||||
getChannelInfo(`${message.channelId}-context.json`, (channelInfo) => {
|
||||
@@ -68,7 +68,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
||||
})
|
||||
|
||||
// Store in Channel Context
|
||||
addToChannelContext(message.channelId,
|
||||
addToChannelContext(logger, message.channelId,
|
||||
message.channel as TextChannel,
|
||||
channelHistory.getItems()
|
||||
)
|
||||
@@ -93,7 +93,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
||||
// check if config.json exists
|
||||
if (config === undefined) {
|
||||
// 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...'))
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
||||
userConfig = await new Promise((resolve, reject) => {
|
||||
getUserConfig(`${message.author.username}-config.json`, (config) => {
|
||||
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.`))
|
||||
return
|
||||
}
|
||||
@@ -175,7 +175,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
||||
|
||||
if (chatMessages.length === 0) {
|
||||
chatMessages = await new Promise((resolve, reject) => {
|
||||
openChannelInfo(message.channelId,
|
||||
openChannelInfo(logger, message.channelId,
|
||||
message.channel as TextChannel,
|
||||
message.author.tag
|
||||
)
|
||||
@@ -225,7 +225,7 @@ export default event(Events.MessageCreate, async ({ logger, msgHist, channelHist
|
||||
})
|
||||
|
||||
// only update the json on success
|
||||
openChannelInfo(message.channelId,
|
||||
openChannelInfo(logger, message.channelId,
|
||||
message.channel as TextChannel,
|
||||
message.author.tag,
|
||||
msgHist.getItems()
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import commands from '../commands/index.js'
|
||||
// Log when the bot successfully logs in and export it
|
||||
export default event(Events.ClientReady, ({ logger }, client) => {
|
||||
// Register the commands associated with the bot upon loggin in
|
||||
registerCommands(client, commands)
|
||||
registerCommands(client, commands, logger)
|
||||
|
||||
// set status of the bot
|
||||
client.user.setActivity({
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { ChatInputCommandInteraction, ChatInputApplicationCommandData, Client } from 'discord.js'
|
||||
import { createLogger } from '../components/index.js'
|
||||
import { ChatInputCommandInteraction, ChatInputApplicationCommandData, Client, type Awaitable } from 'discord.js'
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
const logger = createLogger({ component: 'commands' })
|
||||
|
||||
/**
|
||||
* interface for how slash commands should be run
|
||||
*/
|
||||
@@ -12,7 +9,7 @@ export interface SlashCommand extends ChatInputApplicationCommandData {
|
||||
client: Client,
|
||||
interaction: ChatInputCommandInteraction,
|
||||
logger: PinoLogger
|
||||
) => void
|
||||
) => Awaitable<unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -20,7 +17,7 @@ export interface SlashCommand extends ChatInputApplicationCommandData {
|
||||
* @param client the bot reference
|
||||
* @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
|
||||
if (!client.application) return
|
||||
|
||||
|
||||
@@ -2,9 +2,7 @@ import { TextChannel, ThreadChannel } from 'discord.js'
|
||||
import { Configuration, Channel, UserMessage } from '../index.js'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { createLogger } from '../../components/index.js'
|
||||
|
||||
const logger = createLogger({ component: 'chat-history' })
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @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)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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`
|
||||
if (fs.existsSync(fullFileName)) {
|
||||
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 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`
|
||||
if (fs.existsSync(fullFileName)) {
|
||||
fs.readFile(fullFileName, 'utf8', (error, data) => {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { Configuration, ServerConfig, UserConfig, isServerConfigurationKey } from '../index.js'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { createLogger } from '../../components/index.js'
|
||||
|
||||
const logger = createLogger({ component: 'config' })
|
||||
import type { Logger as PinoLogger } from 'pino'
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
// 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}`
|
||||
|
||||
// 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.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