feat(wip): 對話

This commit is contained in:
CrescentLeaf
2025-09-20 00:31:36 +08:00
parent c6bfca0482
commit d473ff81bd
11 changed files with 201 additions and 47 deletions

View File

@@ -5,22 +5,59 @@ import chalk from "chalk"
import config from "../config.ts"
import Chat from "./Chat.ts"
import MessageBean from "./MessageBean.ts"
export default class MessagesManager {
static table_name: string = "Messages"
static database: DatabaseSync = this.init()
private static init(): DatabaseSync {
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, this.table_name + '.db'))
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, 'Messages.db'))
return db
}
static getInstance(chat: Chat) {
static getInstanceForChat(chat: Chat) {
return new MessagesManager(chat)
}
declare chat: Chat
constructor(chat: Chat) {
this.chat = chat
MessagesManager.database.exec(`
CREATE TABLE IF NOT EXISTS ${this.getTableName()} (
/* 序号, MessageId */ id INTEGER PRIMARY KEY AUTOINCREMENT,
/* 消息文本 */ text TEXT NOT NULL,
/* 发送者 */ user_id TEXT NOT NULL,
);
`)
}
protected getTableName() {
return `messages_${this.chat.bean.id}`
}
addMessage({
text,
user_id
}: {
text: string,
user_id?: string
}) {
MessagesManager.database.prepare(`INSERT INTO ${this.getTableName()} (
text,
user_id
) VALUES (?, ?);`).run(
text,
user_id || null
)
}
addSystemMessage(text: string) {
this.addMessage({
text
})
}
getMessages(limit: number = 15, offset: number = 0) {
return MessagesManager.database.prepare(`SELECT * FROM ${this.getTableName()} ORDER BY id DESC LIMIT ? OFFSET ?;`).all(limit, offset) as unknown as MessageBean[]
}
getMessagesWithPage(limit: number = 15, page: number = 0) {
return this.getMessages(limit, limit * page)
}
}