koishi-plugin-virtual-pet
Version:
虚拟宠物插件,具有记忆功能,可以监听群聊并智能回复
176 lines • 8.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Config = exports.using = exports.name = void 0;
exports.apply = apply;
const koishi_1 = require("koishi");
const ai_1 = require("./services/ai");
const memory_1 = require("./services/memory");
exports.name = 'virtual-pet';
exports.using = ['database'];
exports.Config = koishi_1.Schema.object({
cheapAi: koishi_1.Schema.object({
enabled: koishi_1.Schema.boolean().default(true),
apiUrl: koishi_1.Schema.string().required(),
apiKey: koishi_1.Schema.string().required(),
model: koishi_1.Schema.string().default('gpt-3.5-turbo'),
}),
expensiveAi: koishi_1.Schema.object({
enabled: koishi_1.Schema.boolean().default(true),
apiUrl: koishi_1.Schema.string().required(),
apiKey: koishi_1.Schema.string().required(),
model: koishi_1.Schema.string().default('gpt-4'),
}),
memory: koishi_1.Schema.object({
maxMessages: koishi_1.Schema.number().default(100),
summaryInterval: koishi_1.Schema.number().default(100),
}),
pet: koishi_1.Schema.object({
name: koishi_1.Schema.string().default('小宠物'),
personality: koishi_1.Schema.string().default('你是一个可爱、友善的虚拟宠物,喜欢和群友们聊天互动。'),
responseRate: koishi_1.Schema.number().default(0.3),
}),
groups: koishi_1.Schema.array(koishi_1.Schema.string()).default([]),
});
function apply(ctx, config) {
// 创建服务实例
const aiService = new ai_1.AiService(config);
const memoryService = new memory_1.MemoryService(config, ctx);
// 插件启动日志
ctx.logger('virtual-pet').info(`虚拟宠物 "${config.pet.name}" 已启动`);
// 监听群聊消息
ctx.on('message', async (session) => {
// 只处理群聊消息
if (session.subtype !== 'group') {
ctx.logger('virtual-pet').debug(`忽略非群聊消息: ${session.subtype}`);
return;
}
// 检查是否在启用的群组中
if (config.groups.length > 0 && !config.groups.includes(session.guildId)) {
ctx.logger('virtual-pet').debug(`群组 ${session.guildId} 不在启用列表中`);
return;
}
// 忽略机器人自己的消息
if (session.userId === session.bot?.userId) {
ctx.logger('virtual-pet').debug(`忽略机器人自己的消息`);
return;
}
ctx.logger('virtual-pet').info(`收到群聊消息 - 用户: ${session.username}, 内容: ${session.content}`);
// 存储消息到记忆中
await memoryService.addMessage(session);
// 检查是否需要回复
ctx.logger('virtual-pet').debug(`开始分析是否需要回复...`);
const shouldRespond = await aiService.shouldRespond(session, memoryService.getRecentMessages());
ctx.logger('virtual-pet').info(`AI分析结果 - ${shouldRespond ? '需要回复' : '不需要回复'}`);
if (shouldRespond) {
try {
ctx.logger('virtual-pet').info(`开始生成回复...`);
// 生成回复
const response = await aiService.generateResponse(session, memoryService.getRecentMessages());
ctx.logger('virtual-pet').info(`生成回复: ${response}`);
// 发送回复
await session.send(response);
ctx.logger('virtual-pet').info(`回复已发送`);
// 记录自己的回复
await memoryService.addBotMessage(response, session);
}
catch (error) {
ctx.logger('virtual-pet').error('生成回复失败:', error);
}
}
// 检查是否需要总结记忆
if (memoryService.shouldSummarize()) {
try {
await memoryService.summarizeMemory(aiService);
}
catch (error) {
ctx.logger('virtual-pet').error('记忆总结失败:', error);
}
}
});
// 添加命令:查看宠物状态
ctx.command('pet.status', '查看虚拟宠物状态')
.action(async ({ session }) => {
const status = await memoryService.getPetStatus();
return `🐾 ${config.pet.name}的状态:\n${status}`;
});
// 添加命令:清除记忆
ctx.command('pet.clear', '清除虚拟宠物记忆')
.action(async ({ session }) => {
await memoryService.clearMemory();
return `🧹 ${config.pet.name}的记忆已清除`;
});
// 添加命令:手动触发记忆总结
ctx.command('pet.summarize', '手动触发记忆总结')
.action(async ({ session }) => {
try {
await memoryService.summarizeMemory(aiService);
return `📝 ${config.pet.name}的记忆总结完成`;
}
catch (error) {
return `❌ 记忆总结失败: ${error instanceof Error ? error.message : String(error)}`;
}
});
// 添加命令:测试AI连接
ctx.command('pet.test', '测试AI连接和配置')
.action(async ({ session }) => {
try {
ctx.logger('virtual-pet').info('开始测试AI连接...');
// 测试便宜AI
if (config.cheapAi.enabled) {
const testPrompt = '你好';
const shouldRespond = await aiService.shouldRespond(session, []);
ctx.logger('virtual-pet').info(`便宜AI测试结果: ${shouldRespond}`);
}
// 测试贵AI
if (config.expensiveAi.enabled) {
const testResponse = await aiService.generateResponse(session, []);
ctx.logger('virtual-pet').info(`贵AI测试结果: ${testResponse}`);
}
return `✅ AI连接测试完成,请查看日志了解详细信息`;
}
catch (error) {
ctx.logger('virtual-pet').error('AI测试失败:', error);
return `❌ AI测试失败: ${error instanceof Error ? error.message : String(error)}`;
}
});
// 添加命令:强制回复
ctx.command('pet.talk <content:text>', '让宠物说指定的话')
.action(async ({ session }, content) => {
try {
ctx.logger('virtual-pet').info(`强制回复命令: ${content}`);
if (!session) {
return `❌ 无法获取会话信息`;
}
if (config.expensiveAi.enabled) {
// 使用AI生成回复
const response = await aiService.generateResponse(session, memoryService.getRecentMessages());
await session.send(response);
await memoryService.addBotMessage(response, session);
return `✅ ${config.pet.name}说了话`;
}
else {
// 使用随机回复
const response = `${config.pet.name}:${content}`;
await session.send(response);
await memoryService.addBotMessage(response, session);
return `✅ ${config.pet.name}说了话`;
}
}
catch (error) {
ctx.logger('virtual-pet').error('强制回复失败:', error);
return `❌ 强制回复失败: ${error instanceof Error ? error.message : String(error)}`;
}
});
// 添加命令:查看配置
ctx.command('pet.config', '查看当前配置')
.action(async ({ session }) => {
return `🔧 ${config.pet.name}的配置:
- 启用便宜AI: ${config.cheapAi.enabled ? '是' : '否'}
- 启用贵AI: ${config.expensiveAi.enabled ? '是' : '否'}
- 回复概率: ${(config.pet.responseRate * 100).toFixed(1)}%
- 记忆上限: ${config.memory.maxMessages}条
- 总结间隔: ${config.memory.summaryInterval}条
- 启用群组: ${config.groups.length > 0 ? config.groups.join(', ') : '全部群组'}`;
});
}
//# sourceMappingURL=index.js.map