koishi-plugin-guofenbot 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/admin/commands.d.ts +5 -0
- package/lib/admin/commands.js +106 -0
- package/lib/admin/commands.js.map +1 -0
- package/lib/admin/routes.d.ts +5 -0
- package/lib/admin/routes.js +86 -0
- package/lib/admin/routes.js.map +1 -0
- package/lib/ai/openai.d.ts +12 -0
- package/lib/ai/openai.js +150 -0
- package/lib/ai/openai.js.map +1 -0
- package/lib/ai/provider.d.ts +15 -0
- package/lib/ai/provider.js +13 -0
- package/lib/ai/provider.js.map +1 -0
- package/lib/database.d.ts +10 -0
- package/lib/database.js +48 -0
- package/lib/database.js.map +1 -0
- package/lib/index.d.ts +10 -0
- package/lib/index.js +104 -0
- package/lib/index.js.map +1 -0
- package/lib/services/monitor.d.ts +28 -0
- package/lib/services/monitor.js +179 -0
- package/lib/services/monitor.js.map +1 -0
- package/lib/services/profile-manager.d.ts +18 -0
- package/lib/services/profile-manager.js +172 -0
- package/lib/services/profile-manager.js.map +1 -0
- package/lib/services/rule-manager.d.ts +10 -0
- package/lib/services/rule-manager.js +42 -0
- package/lib/services/rule-manager.js.map +1 -0
- package/lib/types.d.ts +69 -0
- package/lib/types.js +3 -0
- package/lib/types.js.map +1 -0
- package/package.json +40 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { RuleManager } from '../services/rule-manager';
|
|
3
|
+
import { ProfileManager } from '../services/profile-manager';
|
|
4
|
+
import { MonitorConfig } from '../services/monitor';
|
|
5
|
+
export declare function registerAdminCommands(ctx: Context, ruleManager: RuleManager, profileManager: ProfileManager, config: MonitorConfig): void;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerAdminCommands = registerAdminCommands;
|
|
4
|
+
function registerAdminCommands(ctx, ruleManager, profileManager, config) {
|
|
5
|
+
ctx.command('guofen.rule', '管理群规则')
|
|
6
|
+
.alias('群规则');
|
|
7
|
+
ctx.command('guofen.rule.set <content:text>', '设置当前群的规则')
|
|
8
|
+
.action(async ({ session }, content) => {
|
|
9
|
+
if (!session?.guildId)
|
|
10
|
+
return '请在群聊中使用此命令';
|
|
11
|
+
await ruleManager.setRule(session.guildId, content);
|
|
12
|
+
return '群规则已更新';
|
|
13
|
+
});
|
|
14
|
+
ctx.command('guofen.rule.show', '查看当前群的规则')
|
|
15
|
+
.action(async ({ session }) => {
|
|
16
|
+
if (!session?.guildId)
|
|
17
|
+
return '请在群聊中使用此命令';
|
|
18
|
+
const rule = await ruleManager.getRule(session.guildId);
|
|
19
|
+
if (!rule)
|
|
20
|
+
return '当前群尚未设置规则,请使用 guofen.rule.set 命令设置';
|
|
21
|
+
return `当前群规则:\n${rule.content}\n更新时间: ${rule.updatedAt.toLocaleString()}`;
|
|
22
|
+
});
|
|
23
|
+
ctx.command('guofen.rule.delete', '删除当前群的规则')
|
|
24
|
+
.action(async ({ session }) => {
|
|
25
|
+
if (!session?.guildId)
|
|
26
|
+
return '请在群聊中使用此命令';
|
|
27
|
+
await ruleManager.deleteRule(session.guildId);
|
|
28
|
+
return '群规则已删除';
|
|
29
|
+
});
|
|
30
|
+
ctx.command('guofen.profile [userId:string]', '查看成员行为画像')
|
|
31
|
+
.action(async ({ session }, userId) => {
|
|
32
|
+
if (!session?.guildId)
|
|
33
|
+
return '请在群聊中使用此命令';
|
|
34
|
+
const targetId = userId || session.userId || '';
|
|
35
|
+
const profile = await profileManager.getProfile(session.guildId, targetId);
|
|
36
|
+
if (!profile)
|
|
37
|
+
return '未找到该成员的画像数据';
|
|
38
|
+
const activeHours = JSON.parse(profile.activeHours || '[]');
|
|
39
|
+
return [
|
|
40
|
+
`成员: ${profile.username}(${profile.userId})`,
|
|
41
|
+
`发言次数: ${profile.messageCount}`,
|
|
42
|
+
`平均消息长度: ${profile.avgMessageLength.toFixed(1)}`,
|
|
43
|
+
`活跃时段: ${activeHours.sort((a, b) => a - b).join('时, ')}时`,
|
|
44
|
+
`最后发言: ${profile.lastMessageTime.toLocaleString()}`,
|
|
45
|
+
].join('\n');
|
|
46
|
+
});
|
|
47
|
+
ctx.command('guofen.alerts [page:number]', '查看当前群的告警记录')
|
|
48
|
+
.option('all', '-a 查看所有(包括已处理)')
|
|
49
|
+
.action(async ({ session, options }, page = 1) => {
|
|
50
|
+
if (!session?.guildId)
|
|
51
|
+
return '请在群聊中使用此命令';
|
|
52
|
+
const query = { guildId: session.guildId };
|
|
53
|
+
if (!options?.all)
|
|
54
|
+
query.handled = false;
|
|
55
|
+
const alerts = await ctx.database.get('guofenbot_alert', {
|
|
56
|
+
...query,
|
|
57
|
+
});
|
|
58
|
+
const perPage = 5;
|
|
59
|
+
const start = (page - 1) * perPage;
|
|
60
|
+
const pageAlerts = alerts.slice(start, start + perPage);
|
|
61
|
+
if (pageAlerts.length === 0)
|
|
62
|
+
return page === 1 ? '暂无告警记录' : '没有更多记录了';
|
|
63
|
+
const lines = pageAlerts.map((a, i) => `#${start + i + 1} [${a.alertType}] ${a.username}: ${a.messageContent.slice(0, 50)}\n 原因: ${a.reason} | 置信度: ${(a.confidence * 100).toFixed(0)}% | ${a.handled ? `已处理(${a.action})` : '未处理'}`);
|
|
64
|
+
const totalPages = Math.ceil(alerts.length / perPage);
|
|
65
|
+
lines.push(`--- 第 ${page}/${totalPages} 页, 共 ${alerts.length} 条 ---`);
|
|
66
|
+
return lines.join('\n\n');
|
|
67
|
+
});
|
|
68
|
+
ctx.command('guofen.alert.handle <alertId:number>', '处理告警(标记为已处理)')
|
|
69
|
+
.action(async ({ session }, alertId) => {
|
|
70
|
+
await ctx.database.set('guofenbot_alert', { id: alertId }, { handled: true });
|
|
71
|
+
return `告警 #${alertId} 已标记为已处理`;
|
|
72
|
+
});
|
|
73
|
+
ctx.command('guofen.enable', '在当前群启用监测')
|
|
74
|
+
.action(async ({ session }) => {
|
|
75
|
+
if (!session?.guildId)
|
|
76
|
+
return '请在群聊中使用此命令';
|
|
77
|
+
if (!config.enabledGuilds.includes(session.guildId)) {
|
|
78
|
+
config.enabledGuilds.push(session.guildId);
|
|
79
|
+
}
|
|
80
|
+
return '已在当前群启用 AI 安全监测';
|
|
81
|
+
});
|
|
82
|
+
ctx.command('guofen.disable', '在当前群停用监测')
|
|
83
|
+
.action(async ({ session }) => {
|
|
84
|
+
if (!session?.guildId)
|
|
85
|
+
return '请在群聊中使用此命令';
|
|
86
|
+
const index = config.enabledGuilds.indexOf(session.guildId);
|
|
87
|
+
if (index !== -1)
|
|
88
|
+
config.enabledGuilds.splice(index, 1);
|
|
89
|
+
return '已在当前群停用 AI 安全监测';
|
|
90
|
+
});
|
|
91
|
+
ctx.command('guofen.status', '查看插件运行状态')
|
|
92
|
+
.action(async ({ session }) => {
|
|
93
|
+
const rules = await ruleManager.getAllRules();
|
|
94
|
+
const alerts = await ctx.database.get('guofenbot_alert', {});
|
|
95
|
+
return [
|
|
96
|
+
'guofenbot 运行状态',
|
|
97
|
+
`监测群数: ${config.enabledGuilds.length}`,
|
|
98
|
+
`已设定规则: ${rules.length} 个群`,
|
|
99
|
+
`总告警记录: ${alerts.length} 条`,
|
|
100
|
+
`未处理告警: ${alerts.filter((a) => !a.handled).length} 条`,
|
|
101
|
+
`AI 自动处理: ${config.autoModerate ? '开启' : '关闭'}`,
|
|
102
|
+
`灵敏度: ${config.sensitivity}`,
|
|
103
|
+
].join('\n');
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=commands.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/admin/commands.ts"],"names":[],"mappings":";;AAKA,sDA4GC;AA5GD,SAAgB,qBAAqB,CACnC,GAAY,EACZ,WAAwB,EACxB,cAA8B,EAC9B,MAAqB;IAErB,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,O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AAM,WAAW,CAAC,WAAW,EAAE,CAAA;QAC7C,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAA;QAC5D,OAAO;YACL,gBAAgB;YAChB,SAAS,MAAM,CAAC,aAAa,CAAC,MAAM,EAAE;YACtC,UAAU,KAAK,CAAC,MAAM,KAAK;YAC3B,UAAU,MAAM,CAAC,MAAM,IAAI;YAC3B,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,IAAI;YACrD,YAAY,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE;YAC/C,QAAQ,MAAM,CAAC,WAAW,EAAE;SAC7B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACd,CAAC,CAAC,CAAA;AACN,CAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { RuleManager } from '../services/rule-manager';
|
|
3
|
+
import { ProfileManager } from '../services/profile-manager';
|
|
4
|
+
import { MonitorConfig } from '../services/monitor';
|
|
5
|
+
export declare function registerHttpRoutes(ctx: Context, ruleManager: RuleManager, profileManager: ProfileManager, config: MonitorConfig): void;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerHttpRoutes = registerHttpRoutes;
|
|
4
|
+
function registerHttpRoutes(ctx, ruleManager, profileManager, config) {
|
|
5
|
+
const server = ctx.server;
|
|
6
|
+
server.get('/api/guofenbot/status', async (koaCtx) => {
|
|
7
|
+
const rules = await ruleManager.getAllRules();
|
|
8
|
+
const alerts = await ctx.database.get('guofenbot_alert', {});
|
|
9
|
+
koaCtx.body = {
|
|
10
|
+
enabledGuilds: config.enabledGuilds.length,
|
|
11
|
+
rulesCount: rules.length,
|
|
12
|
+
totalAlerts: alerts.length,
|
|
13
|
+
pendingAlerts: alerts.filter((a) => !a.handled).length,
|
|
14
|
+
autoModerate: config.autoModerate,
|
|
15
|
+
sensitivity: config.sensitivity,
|
|
16
|
+
};
|
|
17
|
+
});
|
|
18
|
+
server.get('/api/guofenbot/rules', async (koaCtx) => {
|
|
19
|
+
const guildId = koaCtx.query.guildId;
|
|
20
|
+
if (guildId) {
|
|
21
|
+
const rule = await ruleManager.getRule(guildId);
|
|
22
|
+
koaCtx.body = rule ? [rule] : [];
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
const rules = await ruleManager.getAllRules();
|
|
26
|
+
koaCtx.body = rules;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
server.post('/api/guofenbot/rules', async (koaCtx) => {
|
|
30
|
+
const { guildId, content } = koaCtx.request.body || {};
|
|
31
|
+
if (!guildId || !content) {
|
|
32
|
+
koaCtx.status = 400;
|
|
33
|
+
koaCtx.body = { error: '缺少 guildId 或 content 参数' };
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const rule = await ruleManager.setRule(guildId, content);
|
|
37
|
+
koaCtx.body = rule;
|
|
38
|
+
});
|
|
39
|
+
server.delete('/api/guofenbot/rules/:guildId', async (koaCtx) => {
|
|
40
|
+
const { guildId } = koaCtx.params;
|
|
41
|
+
await ruleManager.deleteRule(guildId);
|
|
42
|
+
koaCtx.body = { success: true };
|
|
43
|
+
});
|
|
44
|
+
server.get('/api/guofenbot/profiles/:guildId', async (koaCtx) => {
|
|
45
|
+
const { guildId } = koaCtx.params;
|
|
46
|
+
const userId = koaCtx.query.userId;
|
|
47
|
+
if (userId) {
|
|
48
|
+
const profile = await profileManager.getProfile(guildId, userId);
|
|
49
|
+
koaCtx.body = profile;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
const profiles = await profileManager.getGuildProfiles(guildId);
|
|
53
|
+
koaCtx.body = profiles.map((p) => ({
|
|
54
|
+
...p,
|
|
55
|
+
commonWords: JSON.parse(p.commonWords || '{}'),
|
|
56
|
+
activeHours: JSON.parse(p.activeHours || '[]'),
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
server.get('/api/guofenbot/alerts', async (koaCtx) => {
|
|
61
|
+
const guildId = koaCtx.query.guildId;
|
|
62
|
+
const handled = koaCtx.query.handled;
|
|
63
|
+
const query = {};
|
|
64
|
+
if (guildId)
|
|
65
|
+
query.guildId = guildId;
|
|
66
|
+
if (handled !== undefined)
|
|
67
|
+
query.handled = handled === 'true';
|
|
68
|
+
const alerts = await ctx.database.get('guofenbot_alert', query);
|
|
69
|
+
koaCtx.body = alerts;
|
|
70
|
+
});
|
|
71
|
+
server.post('/api/guofenbot/alerts/:id/handle', async (koaCtx) => {
|
|
72
|
+
const id = parseInt(koaCtx.params.id, 10);
|
|
73
|
+
await ctx.database.set('guofenbot_alert', { id }, { handled: true });
|
|
74
|
+
koaCtx.body = { success: true };
|
|
75
|
+
});
|
|
76
|
+
server.post('/api/guofenbot/alerts/handle-all', async (koaCtx) => {
|
|
77
|
+
const { guildId } = koaCtx.request.body || {};
|
|
78
|
+
const query = { handled: false };
|
|
79
|
+
if (guildId)
|
|
80
|
+
query.guildId = guildId;
|
|
81
|
+
await ctx.database.set('guofenbot_alert', query, { handled: true });
|
|
82
|
+
koaCtx.body = { success: true };
|
|
83
|
+
});
|
|
84
|
+
ctx.logger.info('HTTP API 路由已注册: /api/guofenbot/*');
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../../src/admin/routes.ts"],"names":[],"mappings":";;AAKA,gDA0FC;AA1FD,SAAgB,kBAAkB,CAChC,GAAY,EACZ,WAAwB,EACxB,cAA8B,EAC9B,MAAqB;IAErB,MAAM,MAAM,GAAI,GAAW,CAAC,MAAM,CAAA;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QACpE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAA;QAC7C,MAAM,KAAK,GAA4B,EAAE,OAAO,EAAE,KAAK,EAAE,CAAA;QACzD,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,GAAG,OAAO,CAAA;QACpC,MAAM,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,iBAAiB,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAA;QACnE,MAAM,CAAC,IAAI,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;IACjC,CAAC,CAAC,CAAA;IAEF,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAA;AACrD,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { AIProvider, AIProviderConfig } from './provider';
|
|
3
|
+
import { AnalysisResult, MessageContext, MemberProfileSnapshot } from '../types';
|
|
4
|
+
export declare class OpenAIProvider extends AIProvider {
|
|
5
|
+
constructor(ctx: Context, config: AIProviderConfig);
|
|
6
|
+
analyzeMessage(rules: string, profiles: MemberProfileSnapshot[], message: MessageContext): Promise<AnalysisResult>;
|
|
7
|
+
validateConnection(): Promise<boolean>;
|
|
8
|
+
private buildSystemPrompt;
|
|
9
|
+
private buildUserPrompt;
|
|
10
|
+
private parseResponse;
|
|
11
|
+
private fallbackAnalysis;
|
|
12
|
+
}
|
package/lib/ai/openai.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OpenAIProvider = void 0;
|
|
4
|
+
const provider_1 = require("./provider");
|
|
5
|
+
class OpenAIProvider extends provider_1.AIProvider {
|
|
6
|
+
constructor(ctx, config) {
|
|
7
|
+
super(ctx, config);
|
|
8
|
+
}
|
|
9
|
+
async analyzeMessage(rules, profiles, message) {
|
|
10
|
+
const systemPrompt = this.buildSystemPrompt(rules, profiles);
|
|
11
|
+
const userPrompt = this.buildUserPrompt(message);
|
|
12
|
+
try {
|
|
13
|
+
const response = await this.ctx.http.post(`${this.config.endpoint}/chat/completions`, {
|
|
14
|
+
model: this.config.model,
|
|
15
|
+
messages: [
|
|
16
|
+
{ role: 'system', content: systemPrompt },
|
|
17
|
+
{ role: 'user', content: userPrompt },
|
|
18
|
+
],
|
|
19
|
+
temperature: 0.3,
|
|
20
|
+
max_tokens: 300,
|
|
21
|
+
response_format: { type: 'json_object' },
|
|
22
|
+
}, {
|
|
23
|
+
headers: {
|
|
24
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
25
|
+
'Content-Type': 'application/json',
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
const content = response.choices?.[0]?.message?.content ?? '{}';
|
|
29
|
+
return this.parseResponse(content, message);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
this.ctx.logger.warn('AI 分析请求失败,回退到本地规则检测', error);
|
|
33
|
+
return this.fallbackAnalysis(message);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async validateConnection() {
|
|
37
|
+
try {
|
|
38
|
+
await this.ctx.http.get(`${this.config.endpoint}/models`, {
|
|
39
|
+
headers: {
|
|
40
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
buildSystemPrompt(rules, profiles) {
|
|
50
|
+
const profileText = profiles
|
|
51
|
+
.map((p) => {
|
|
52
|
+
const topWords = Object.entries(p.commonWords)
|
|
53
|
+
.sort((a, b) => b[1] - a[1])
|
|
54
|
+
.slice(0, 10)
|
|
55
|
+
.map(([w]) => w)
|
|
56
|
+
.join('、');
|
|
57
|
+
return `- ${p.username}(ID:${p.userId}): 历史发言${p.messageCount}条, 平均消息长度${p.avgMessageLength.toFixed(1)}字, 常用词: ${topWords || '无'}`;
|
|
58
|
+
})
|
|
59
|
+
.join('\n');
|
|
60
|
+
return `你是一个群聊安全监测助手。你的任务是分析群聊消息,判断是否存在危险、可疑或异常言论。
|
|
61
|
+
|
|
62
|
+
## 群规则
|
|
63
|
+
${rules || '暂无设定群规则'}
|
|
64
|
+
|
|
65
|
+
## 群成员行为画像
|
|
66
|
+
${profileText || '暂无成员数据'}
|
|
67
|
+
|
|
68
|
+
## 判定标准
|
|
69
|
+
1. **dangerous(危险)**: 包含明显的违法违规内容,如诈骗、暴力威胁、人身攻击、色情内容、极端政治言论等
|
|
70
|
+
2. **suspicious(可疑)**: 存在潜在的广告推广、诱导私聊、虚假信息传播、恶意链接等
|
|
71
|
+
3. **abnormal(异常)**: 与该成员历史发言习惯明显不符,如突然改变话题风格、使用不常用词汇、异常的发言时间段等
|
|
72
|
+
|
|
73
|
+
## 输出格式
|
|
74
|
+
你必须以JSON格式返回分析结果,不要包含任何其他内容:
|
|
75
|
+
{
|
|
76
|
+
"isAbnormal": true或false,
|
|
77
|
+
"alertType": "normal"或"dangerous"或"suspicious"或"abnormal",
|
|
78
|
+
"reason": "判定理由的简短说明",
|
|
79
|
+
"confidence": 0到1之间的置信度,
|
|
80
|
+
"suggestedAction": "none"或"warn"或"mute"或"kick"
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
如果消息完全正常,设置 isAbnormal 为 false,alertType 为 "normal",confidence 为 1。`;
|
|
84
|
+
}
|
|
85
|
+
buildUserPrompt(message) {
|
|
86
|
+
return `请分析以下群聊消息:
|
|
87
|
+
发送者: ${message.username}(ID:${message.userId})
|
|
88
|
+
消息内容: ${message.content}
|
|
89
|
+
发送时间戳: ${message.timestamp}`;
|
|
90
|
+
}
|
|
91
|
+
parseResponse(content, message) {
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(content);
|
|
94
|
+
if (parsed.alertType === 'normal' || !parsed.isAbnormal) {
|
|
95
|
+
return {
|
|
96
|
+
isAbnormal: false,
|
|
97
|
+
alertType: 'suspicious',
|
|
98
|
+
reason: '',
|
|
99
|
+
confidence: 1,
|
|
100
|
+
suggestedAction: 'none',
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
isAbnormal: true,
|
|
105
|
+
alertType: parsed.alertType ?? 'suspicious',
|
|
106
|
+
reason: parsed.reason ?? 'AI 检测到异常',
|
|
107
|
+
confidence: Math.min(1, Math.max(0, parsed.confidence ?? 0.5)),
|
|
108
|
+
suggestedAction: parsed.suggestedAction ?? 'warn',
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return {
|
|
113
|
+
isAbnormal: false,
|
|
114
|
+
alertType: 'suspicious',
|
|
115
|
+
reason: '',
|
|
116
|
+
confidence: 1,
|
|
117
|
+
suggestedAction: 'none',
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
fallbackAnalysis(message) {
|
|
122
|
+
const keywords = [
|
|
123
|
+
{ pattern: /诈骗|骗钱|转账|银行卡|密码|验证码/, type: 'dangerous', action: 'kick' },
|
|
124
|
+
{ pattern: /加我|私聊|加微信|加QQ|扫码/, type: 'suspicious', action: 'warn' },
|
|
125
|
+
{ pattern: /傻逼|畜生|去死|nmsl|cnm/, type: 'dangerous', action: 'mute' },
|
|
126
|
+
{ pattern: /广告|推广|优惠|免费领取|点击链接/, type: 'suspicious', action: 'warn' },
|
|
127
|
+
{ pattern: /色情|裸聊|约炮|嫖/, type: 'dangerous', action: 'kick' },
|
|
128
|
+
];
|
|
129
|
+
for (const kw of keywords) {
|
|
130
|
+
if (kw.pattern.test(message.content)) {
|
|
131
|
+
return {
|
|
132
|
+
isAbnormal: true,
|
|
133
|
+
alertType: kw.type,
|
|
134
|
+
reason: `本地规则匹配: 触发关键词模式`,
|
|
135
|
+
confidence: 0.7,
|
|
136
|
+
suggestedAction: kw.action,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
isAbnormal: false,
|
|
142
|
+
alertType: 'suspicious',
|
|
143
|
+
reason: '',
|
|
144
|
+
confidence: 1,
|
|
145
|
+
suggestedAction: 'none',
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
exports.OpenAIProvider = OpenAIProvider;
|
|
150
|
+
//# sourceMappingURL=openai.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai.js","sourceRoot":"","sources":["../../src/ai/openai.ts"],"names":[],"mappings":";;;AACA,yCAAyD;AAGzD,MAAa,cAAe,SAAQ,qBAAU;IAC5C,YAAY,GAAY,EAAE,MAAwB;QAChD,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;IACpB,CAAC;IAED,KAAK,CAAC,cAAc,CAClB,KAAa,EACb,QAAiC,EACjC,OAAuB;QAEvB,MAAM,YAAY,GAAG,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QAC5D,MAAM,UAAU,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAA;QAEhD,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CACvC,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,mBAAmB,EAC1C;gBACE,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK;gBACxB,QAAQ,EAAE;oBACR,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE;oBACzC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE;iBACtC;gBACD,WAAW,EAAE,GAAG;gBAChB,UAAU,EAAE,GAAG;gBACf,eAAe,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE;aACzC,EACD;gBACE,OAAO,EAA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AC;CACF;AA/JD,wCA+JC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { AnalysisResult, MessageContext, MemberProfileSnapshot } from '../types';
|
|
3
|
+
export declare abstract class AIProvider {
|
|
4
|
+
protected ctx: Context;
|
|
5
|
+
protected config: AIProviderConfig;
|
|
6
|
+
constructor(ctx: Context, config: AIProviderConfig);
|
|
7
|
+
abstract analyzeMessage(rules: string, profiles: MemberProfileSnapshot[], message: MessageContext): Promise<AnalysisResult>;
|
|
8
|
+
abstract validateConnection(): Promise<boolean>;
|
|
9
|
+
}
|
|
10
|
+
export interface AIProviderConfig {
|
|
11
|
+
type: 'openai' | 'custom';
|
|
12
|
+
endpoint: string;
|
|
13
|
+
apiKey: string;
|
|
14
|
+
model: string;
|
|
15
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AIProvider = void 0;
|
|
4
|
+
class AIProvider {
|
|
5
|
+
ctx;
|
|
6
|
+
config;
|
|
7
|
+
constructor(ctx, config) {
|
|
8
|
+
this.ctx = ctx;
|
|
9
|
+
this.config = config;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.AIProvider = AIProvider;
|
|
13
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/ai/provider.ts"],"names":[],"mappings":";;;AAGA,MAAsB,UAAU;IACpB,GAAG,CAAS;IACZ,MAAM,CAAkB;IAElC,YAAY,GAAY,EAAE,MAAwB;QAChD,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;CASF;AAhBD,gCAgBC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { GuofenbotRule, GuofenbotProfile, GuofenbotAlert } from './types';
|
|
3
|
+
declare module 'koishi' {
|
|
4
|
+
interface Tables {
|
|
5
|
+
guofenbot_rule: GuofenbotRule;
|
|
6
|
+
guofenbot_profile: GuofenbotProfile;
|
|
7
|
+
guofenbot_alert: GuofenbotAlert;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export declare function registerDatabase(ctx: Context): void;
|
package/lib/database.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerDatabase = registerDatabase;
|
|
4
|
+
function registerDatabase(ctx) {
|
|
5
|
+
ctx.model.extend('guofenbot_rule', {
|
|
6
|
+
id: 'unsigned',
|
|
7
|
+
guildId: 'string(255)',
|
|
8
|
+
content: 'text',
|
|
9
|
+
createdAt: 'timestamp',
|
|
10
|
+
updatedAt: 'timestamp',
|
|
11
|
+
}, {
|
|
12
|
+
primary: 'id',
|
|
13
|
+
autoInc: true,
|
|
14
|
+
});
|
|
15
|
+
ctx.model.extend('guofenbot_profile', {
|
|
16
|
+
id: 'unsigned',
|
|
17
|
+
guildId: 'string(255)',
|
|
18
|
+
userId: 'string(255)',
|
|
19
|
+
username: 'string(255)',
|
|
20
|
+
messageCount: 'unsigned',
|
|
21
|
+
lastMessageTime: 'timestamp',
|
|
22
|
+
avgMessageLength: 'float',
|
|
23
|
+
commonWords: 'text',
|
|
24
|
+
sentimentBaseline: 'float',
|
|
25
|
+
activeHours: 'text',
|
|
26
|
+
updatedAt: 'timestamp',
|
|
27
|
+
}, {
|
|
28
|
+
primary: 'id',
|
|
29
|
+
autoInc: true,
|
|
30
|
+
});
|
|
31
|
+
ctx.model.extend('guofenbot_alert', {
|
|
32
|
+
id: 'unsigned',
|
|
33
|
+
guildId: 'string(255)',
|
|
34
|
+
userId: 'string(255)',
|
|
35
|
+
username: 'string(255)',
|
|
36
|
+
messageContent: 'text',
|
|
37
|
+
alertType: 'string(50)',
|
|
38
|
+
reason: 'text',
|
|
39
|
+
confidence: 'float',
|
|
40
|
+
handled: { type: 'boolean', initial: false },
|
|
41
|
+
action: 'string(20)',
|
|
42
|
+
createdAt: 'timestamp',
|
|
43
|
+
}, {
|
|
44
|
+
primary: 'id',
|
|
45
|
+
autoInc: true,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=database.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":";;AAWA,4CA6CC;AA7CD,SAAgB,gBAAgB,CAAC,GAAY;IAC3C,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,gBAAgB,EAAE;QACjC,EAAE,EAAE,UAAU;QACd,OAAO,EAAE,aAAa;QACtB,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,WAAW;QACtB,SAAS,EAAE,WAAW;KACvB,EAAE;QACD,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,IAAI;KACd,CAAC,CAAA;IAEF,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,mBAAmB,EAAE;QACpC,EAAE,EAAE,UAAU;QACd,OAAO,EAAE,aAAa;QACtB,MAAM,EAAE,aAAa;QACrB,QAAQ,EAAE,aAAa;QACvB,YAAY,EAAE,UAAU;QACxB,eAAe,EAAE,WAAW;QAC5B,gBAAgB,EAAE,OAAO;QACzB,WAAW,EAAE,MAAM;QACnB,iBAAiB,EAAE,OAAO;QAC1B,WAAW,EAAE,MAAM;QACnB,SAAS,EAAE,WAAW;KACvB,EAAE;QACD,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,IAAI;KACd,CAAC,CAAA;IAEF,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,iBAAiB,EAAE;QAClC,EAAE,EAAE,UAAU;QACd,OAAO,EAAE,aAAa;QACtB,MAAM,EAAE,aAAa;QACrB,QAAQ,EAAE,aAAa;QACvB,cAAc,EAAE,MAAM;QACtB,SAAS,EAAE,YAAY;QACvB,MAAM,EAAE,MAAM;QACd,UAAU,EAAE,OAAO;QACnB,OAAO,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE;QAC5C,MAAM,EAAE,YAAY;QACpB,SAAS,EAAE,WAAW;KACvB,EAAE;QACD,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,IAAI;KACd,CAAC,CAAA;AACJ,CAAC"}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Context, Schema } from 'koishi';
|
|
2
|
+
import { AIProviderConfig } from './ai/provider';
|
|
3
|
+
import { MonitorConfig } from './services/monitor';
|
|
4
|
+
export declare const name = "guofenbot";
|
|
5
|
+
export interface Config {
|
|
6
|
+
aiProvider: AIProviderConfig;
|
|
7
|
+
monitor: MonitorConfig;
|
|
8
|
+
}
|
|
9
|
+
export declare const Config: Schema<Config>;
|
|
10
|
+
export declare function apply(ctx: Context, config: Config): void;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Config = exports.name = void 0;
|
|
4
|
+
exports.apply = apply;
|
|
5
|
+
const koishi_1 = require("koishi");
|
|
6
|
+
const database_1 = require("./database");
|
|
7
|
+
const rule_manager_1 = require("./services/rule-manager");
|
|
8
|
+
const profile_manager_1 = require("./services/profile-manager");
|
|
9
|
+
const monitor_1 = require("./services/monitor");
|
|
10
|
+
const commands_1 = require("./admin/commands");
|
|
11
|
+
const routes_1 = require("./admin/routes");
|
|
12
|
+
exports.name = 'guofenbot';
|
|
13
|
+
exports.Config = koishi_1.Schema.object({
|
|
14
|
+
aiProvider: koishi_1.Schema.object({
|
|
15
|
+
type: koishi_1.Schema.union(['openai', 'custom']).default('openai').description('AI 提供商类型'),
|
|
16
|
+
endpoint: koishi_1.Schema.string()
|
|
17
|
+
.default('https://api.openai.com/v1')
|
|
18
|
+
.description('AI API 端点地址'),
|
|
19
|
+
apiKey: koishi_1.Schema.string()
|
|
20
|
+
.role('secret')
|
|
21
|
+
.description('AI API 密钥'),
|
|
22
|
+
model: koishi_1.Schema.string()
|
|
23
|
+
.default('gpt-4o-mini')
|
|
24
|
+
.description('使用的 AI 模型名称'),
|
|
25
|
+
}).description('AI 提供商配置'),
|
|
26
|
+
monitor: koishi_1.Schema.object({
|
|
27
|
+
enabledGuilds: koishi_1.Schema.array(koishi_1.Schema.string())
|
|
28
|
+
.default([])
|
|
29
|
+
.description('启用监测的群组 ID 列表'),
|
|
30
|
+
sensitivity: koishi_1.Schema.union(['low', 'medium', 'high'])
|
|
31
|
+
.default('medium')
|
|
32
|
+
.description('检测灵敏度 (low=低/medium=中/high=高)'),
|
|
33
|
+
alertTarget: koishi_1.Schema.union(['group', 'private', 'both'])
|
|
34
|
+
.default('both')
|
|
35
|
+
.description('告警发送目标 (group=群聊/private=私聊管理员/both=两者)'),
|
|
36
|
+
alertAdminIds: koishi_1.Schema.array(koishi_1.Schema.string())
|
|
37
|
+
.default([])
|
|
38
|
+
.description('接收私聊告警的管理员用户 ID 列表'),
|
|
39
|
+
autoModerate: koishi_1.Schema.boolean()
|
|
40
|
+
.default(false)
|
|
41
|
+
.description('是否允许 AI 自动处理 (禁言/踢出)'),
|
|
42
|
+
maxViolations: koishi_1.Schema.number()
|
|
43
|
+
.default(3)
|
|
44
|
+
.description('触发自动处理前允许的最大违规次数'),
|
|
45
|
+
muteDuration: koishi_1.Schema.number()
|
|
46
|
+
.default(10)
|
|
47
|
+
.description('自动禁言时长 (分钟)'),
|
|
48
|
+
}).description('监测配置'),
|
|
49
|
+
});
|
|
50
|
+
function apply(ctx, config) {
|
|
51
|
+
ctx.logger.info('guofenbot 插件正在初始化...');
|
|
52
|
+
(0, database_1.registerDatabase)(ctx);
|
|
53
|
+
const providerConfig = {
|
|
54
|
+
type: config.aiProvider.type,
|
|
55
|
+
endpoint: config.aiProvider.endpoint,
|
|
56
|
+
apiKey: config.aiProvider.apiKey,
|
|
57
|
+
model: config.aiProvider.model,
|
|
58
|
+
};
|
|
59
|
+
let aiProvider;
|
|
60
|
+
const { OpenAIProvider } = require('./ai/openai');
|
|
61
|
+
aiProvider = new OpenAIProvider(ctx, providerConfig);
|
|
62
|
+
const ruleManager = new rule_manager_1.RuleManager(ctx);
|
|
63
|
+
const profileManager = new profile_manager_1.ProfileManager(ctx);
|
|
64
|
+
const monitorConfig = {
|
|
65
|
+
enabledGuilds: config.monitor.enabledGuilds,
|
|
66
|
+
sensitivity: config.monitor.sensitivity,
|
|
67
|
+
alertTarget: config.monitor.alertTarget,
|
|
68
|
+
alertAdminIds: config.monitor.alertAdminIds,
|
|
69
|
+
autoModerate: config.monitor.autoModerate,
|
|
70
|
+
maxViolations: config.monitor.maxViolations,
|
|
71
|
+
muteDuration: config.monitor.muteDuration,
|
|
72
|
+
};
|
|
73
|
+
const monitor = new monitor_1.MonitorService(ctx, aiProvider, ruleManager, profileManager, monitorConfig);
|
|
74
|
+
(0, commands_1.registerAdminCommands)(ctx, ruleManager, profileManager, monitorConfig);
|
|
75
|
+
(0, routes_1.registerHttpRoutes)(ctx, ruleManager, profileManager, monitorConfig);
|
|
76
|
+
ctx.logger.info('后台管理 API 已启用: /api/guofenbot/*');
|
|
77
|
+
ctx.middleware(async (session, next) => {
|
|
78
|
+
if (!session?.guildId || !session?.userId || !session?.content)
|
|
79
|
+
return next();
|
|
80
|
+
if (!session.content.trim() || session.content.startsWith('/') || session.content.startsWith('guofen')) {
|
|
81
|
+
return next();
|
|
82
|
+
}
|
|
83
|
+
await monitor.processMessage({
|
|
84
|
+
userId: session.userId,
|
|
85
|
+
username: session.username ?? session.userId,
|
|
86
|
+
content: session.content,
|
|
87
|
+
guildId: session.guildId,
|
|
88
|
+
channelId: session.channelId ?? '',
|
|
89
|
+
platform: session.platform ?? '',
|
|
90
|
+
timestamp: session.timestamp ?? Date.now(),
|
|
91
|
+
});
|
|
92
|
+
return next();
|
|
93
|
+
});
|
|
94
|
+
aiProvider.validateConnection().then((valid) => {
|
|
95
|
+
if (valid) {
|
|
96
|
+
ctx.logger.info('AI 服务连接验证成功');
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
ctx.logger.warn('AI 服务连接验证失败,将使用本地规则检测作为后备');
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
ctx.logger.info('guofenbot 插件初始化完成');
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAuDA,sBAiEC;AAxHD,mCAAwC;AACxC,yCAA6C;AAE7C,0DAAqD;AACrD,gEAA2D;AAC3D,gDAAkE;AAClE,+CAAwD;AACxD,2CAAmD;AAEtC,QAAA,IAAI,GAAG,WAAW,CAAA;AAOlB,QAAA,MAAM,GAAmB,eAAM,CAAC,MAAM,CAAC;IAClD,UAAU,EAAE,eAAM,CAAC,MAAM,CAAC;QACxB,IAAI,EAAE,eAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC;QAClF,QAAQ,EAAE,eAAM,CAAC,MAAM,EAAE;aACtB,OAAO,CAAC,2BAA2B,CAAC;aACpC,WAAW,CAAC,aAAa,CAAC;QAC7B,MAAM,EAAE,eAAM,CAAC,MAAM,EAAE;aACpB,IAAI,CAAC,QAAQ,CAAC;aACd,WAAW,CAAC,WAAW,CAAC;QAC3B,KAAK,EAAE,eAAM,CAAC,MAAM,EAAE;aACnB,OAAO,CAAC,aAAa,CAAC;aACtB,WAAW,CAAC,aAAa,CAAC;KAC9B,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC;IAE1B,OAAO,EAAE,eAAM,CAAC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
4
|
+
import { ProfileManager } from './profile-manager';
|
|
5
|
+
import { MessageContext, Sensitivity, AlertTarget } from '../types';
|
|
6
|
+
export interface MonitorConfig {
|
|
7
|
+
enabledGuilds: string[];
|
|
8
|
+
sensitivity: Sensitivity;
|
|
9
|
+
alertTarget: AlertTarget;
|
|
10
|
+
alertAdminIds: string[];
|
|
11
|
+
autoModerate: boolean;
|
|
12
|
+
maxViolations: number;
|
|
13
|
+
muteDuration: number;
|
|
14
|
+
}
|
|
15
|
+
export declare class MonitorService {
|
|
16
|
+
private ctx;
|
|
17
|
+
private aiProvider;
|
|
18
|
+
private ruleManager;
|
|
19
|
+
private profileManager;
|
|
20
|
+
private config;
|
|
21
|
+
private cooldownMap;
|
|
22
|
+
constructor(ctx: Context, aiProvider: AIProvider, ruleManager: RuleManager, profileManager: ProfileManager, config: MonitorConfig);
|
|
23
|
+
processMessage(message: MessageContext): Promise<void>;
|
|
24
|
+
private getConfidenceThreshold;
|
|
25
|
+
private createAlert;
|
|
26
|
+
private dispatchAlert;
|
|
27
|
+
private autoHandle;
|
|
28
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MonitorService = void 0;
|
|
4
|
+
class MonitorService {
|
|
5
|
+
ctx;
|
|
6
|
+
aiProvider;
|
|
7
|
+
ruleManager;
|
|
8
|
+
profileManager;
|
|
9
|
+
config;
|
|
10
|
+
cooldownMap = new Map();
|
|
11
|
+
constructor(ctx, aiProvider, ruleManager, profileManager, config) {
|
|
12
|
+
this.ctx = ctx;
|
|
13
|
+
this.aiProvider = aiProvider;
|
|
14
|
+
this.ruleManager = ruleManager;
|
|
15
|
+
this.profileManager = profileManager;
|
|
16
|
+
this.config = config;
|
|
17
|
+
}
|
|
18
|
+
async processMessage(message) {
|
|
19
|
+
const guildId = message.guildId;
|
|
20
|
+
if (!this.config.enabledGuilds.includes(guildId))
|
|
21
|
+
return;
|
|
22
|
+
const cooldownKey = `${guildId}:${message.userId}`;
|
|
23
|
+
const lastCheck = this.cooldownMap.get(cooldownKey) ?? 0;
|
|
24
|
+
if (Date.now() - lastCheck < 3000)
|
|
25
|
+
return;
|
|
26
|
+
this.cooldownMap.set(cooldownKey, Date.now());
|
|
27
|
+
try {
|
|
28
|
+
await this.profileManager.updateProfile(guildId, message.userId, message.username, message.content);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
this.ctx.logger.warn('更新用户画像失败', error);
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
let analysis;
|
|
35
|
+
const rule = await this.ruleManager.getRule(guildId);
|
|
36
|
+
if (rule?.content) {
|
|
37
|
+
const profiles = await this.profileManager.getProfileSnapshots(guildId);
|
|
38
|
+
analysis = await this.aiProvider.analyzeMessage(rule.content, profiles, message);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const profile = await this.profileManager.getProfile(guildId, message.userId);
|
|
42
|
+
if (profile && profile.messageCount > 5) {
|
|
43
|
+
const anomaly = this.profileManager.detectAnomaly(profile, message.content, this.config.sensitivity);
|
|
44
|
+
if (anomaly.isAnomalous) {
|
|
45
|
+
analysis = {
|
|
46
|
+
isAbnormal: true,
|
|
47
|
+
alertType: 'abnormal',
|
|
48
|
+
reason: `行为异常: ${anomaly.reasons.join('; ')}`,
|
|
49
|
+
confidence: anomaly.score,
|
|
50
|
+
suggestedAction: anomaly.score > 0.8 ? 'mute' : 'warn',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (!analysis.isAbnormal)
|
|
62
|
+
return;
|
|
63
|
+
if (analysis.confidence < this.getConfidenceThreshold())
|
|
64
|
+
return;
|
|
65
|
+
await this.createAlert(message, analysis);
|
|
66
|
+
await this.dispatchAlert(message, analysis);
|
|
67
|
+
if (this.config.autoModerate) {
|
|
68
|
+
await this.autoHandle(message, analysis);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
this.ctx.logger.error('消息监测处理失败', error);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
getConfidenceThreshold() {
|
|
76
|
+
switch (this.config.sensitivity) {
|
|
77
|
+
case 'low': return 0.9;
|
|
78
|
+
case 'medium': return 0.7;
|
|
79
|
+
case 'high': return 0.5;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async createAlert(message, analysis) {
|
|
83
|
+
const alert = {
|
|
84
|
+
id: 0,
|
|
85
|
+
guildId: message.guildId,
|
|
86
|
+
userId: message.userId,
|
|
87
|
+
username: message.username,
|
|
88
|
+
messageContent: message.content,
|
|
89
|
+
alertType: analysis.alertType,
|
|
90
|
+
reason: analysis.reason,
|
|
91
|
+
confidence: analysis.confidence,
|
|
92
|
+
handled: false,
|
|
93
|
+
action: analysis.suggestedAction,
|
|
94
|
+
createdAt: new Date(),
|
|
95
|
+
};
|
|
96
|
+
await this.ctx.database.create('guofenbot_alert', alert);
|
|
97
|
+
}
|
|
98
|
+
async dispatchAlert(message, analysis) {
|
|
99
|
+
const alertTypeLabel = {
|
|
100
|
+
suspicious: '⚠️ 可疑言论',
|
|
101
|
+
dangerous: '🚨 危险言论',
|
|
102
|
+
abnormal: '🔍 异常行为',
|
|
103
|
+
};
|
|
104
|
+
const actionLabel = {
|
|
105
|
+
none: '不处理',
|
|
106
|
+
warn: '警告',
|
|
107
|
+
mute: '禁言',
|
|
108
|
+
kick: '踢出',
|
|
109
|
+
};
|
|
110
|
+
const alertMsg = [
|
|
111
|
+
`${alertTypeLabel[analysis.alertType]}`,
|
|
112
|
+
`群聊: ${message.guildId}`,
|
|
113
|
+
`用户: ${message.username}(${message.userId})`,
|
|
114
|
+
`内容: ${message.content.slice(0, 200)}`,
|
|
115
|
+
`原因: ${analysis.reason}`,
|
|
116
|
+
`置信度: ${(analysis.confidence * 100).toFixed(0)}%`,
|
|
117
|
+
`建议动作: ${actionLabel[analysis.suggestedAction]}`,
|
|
118
|
+
].join('\n');
|
|
119
|
+
const bot = this.ctx.bots[message.platform] ?? this.ctx.bots[0];
|
|
120
|
+
if (!bot)
|
|
121
|
+
return;
|
|
122
|
+
if ((this.config.alertTarget === 'both' || this.config.alertTarget === 'group') &&
|
|
123
|
+
message.channelId) {
|
|
124
|
+
try {
|
|
125
|
+
await bot.sendMessage(message.channelId, alertMsg);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
this.ctx.logger.warn('告警消息发送到群聊失败');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if ((this.config.alertTarget === 'both' || this.config.alertTarget === 'private') &&
|
|
132
|
+
this.config.alertAdminIds.length > 0) {
|
|
133
|
+
for (const adminId of this.config.alertAdminIds) {
|
|
134
|
+
try {
|
|
135
|
+
await bot.sendPrivateMessage(adminId, alertMsg);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
this.ctx.logger.warn(`告警消息发送到管理员 ${adminId} 失败`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
async autoHandle(message, analysis) {
|
|
144
|
+
if (analysis.suggestedAction === 'none')
|
|
145
|
+
return;
|
|
146
|
+
const bot = this.ctx.bots[message.platform] ?? this.ctx.bots[0];
|
|
147
|
+
if (!bot)
|
|
148
|
+
return;
|
|
149
|
+
const recentAlerts = await this.ctx.database.get('guofenbot_alert', {
|
|
150
|
+
userId: message.userId,
|
|
151
|
+
guildId: message.guildId,
|
|
152
|
+
});
|
|
153
|
+
const violationCount = recentAlerts.filter((a) => !a.handled).length;
|
|
154
|
+
if (violationCount < this.config.maxViolations && analysis.suggestedAction === 'warn') {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
if (analysis.suggestedAction === 'mute') {
|
|
159
|
+
const duration = this.config.muteDuration * 60 * 1000;
|
|
160
|
+
await bot.muteGuildMember(message.guildId, message.userId, duration);
|
|
161
|
+
this.ctx.logger.info(`自动禁言: ${message.username}(${message.userId}) 在群 ${message.guildId}, 时长 ${this.config.muteDuration}分钟`);
|
|
162
|
+
await this.ctx.database.set('guofenbot_alert', { userId: message.userId, guildId: message.guildId }, { handled: true, action: 'mute' });
|
|
163
|
+
}
|
|
164
|
+
else if (analysis.suggestedAction === 'kick') {
|
|
165
|
+
await bot.kickGuildMember(message.guildId, message.userId);
|
|
166
|
+
this.ctx.logger.info(`自动踢出: ${message.username}(${message.userId}) 从群 ${message.guildId}`);
|
|
167
|
+
await this.ctx.database.set('guofenbot_alert', { userId: message.userId, guildId: message.guildId }, { handled: true, action: 'kick' });
|
|
168
|
+
}
|
|
169
|
+
else if (analysis.suggestedAction === 'warn') {
|
|
170
|
+
await this.ctx.database.set('guofenbot_alert', { userId: message.userId, guildId: message.guildId }, { handled: true, action: 'warn' });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
this.ctx.logger.error('自动处理失败', error);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
exports.MonitorService = MonitorService;
|
|
179
|
+
//# sourceMappingURL=monitor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"monitor.js","sourceRoot":"","sources":["../../src/services/monitor.ts"],"names":[],"mappings":";;;AAwBA,MAAa,cAAc;IACjB,GAAG,CAAS;IACZ,UAAU,CAAY;IACtB,WAAW,CAAa;IACxB,cAAc,CAAgB;IAC9B,MAAM,CAAe;IACrB,WAAW,GAAwB,IAAI,GAAG,EAAE,CAAA;IAEpD,YACE,GAAY,EACZ,UAAsB,EACtB,WAAwB,EACxB,cAA8B,EAC9B,MAAqB;QAErB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,UAAU,GAAG,UAAU,CAA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,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,EACpD,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAClC,CAAA;YACH,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;CACF;AAvOD,wCAuOC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { GuofenbotProfile, MemberProfileSnapshot } from '../types';
|
|
3
|
+
export declare class ProfileManager {
|
|
4
|
+
private ctx;
|
|
5
|
+
constructor(ctx: Context);
|
|
6
|
+
getProfile(guildId: string, userId: string): Promise<GuofenbotProfile | null>;
|
|
7
|
+
getGuildProfiles(guildId: string): Promise<GuofenbotProfile[]>;
|
|
8
|
+
getProfileSnapshots(guildId: string): Promise<MemberProfileSnapshot[]>;
|
|
9
|
+
updateProfile(guildId: string, userId: string, username: string, messageContent: string): Promise<void>;
|
|
10
|
+
detectAnomaly(profile: GuofenbotProfile, messageContent: string, sensitivity: 'low' | 'medium' | 'high'): {
|
|
11
|
+
isAnomalous: boolean;
|
|
12
|
+
score: number;
|
|
13
|
+
reasons: string[];
|
|
14
|
+
};
|
|
15
|
+
private extractWords;
|
|
16
|
+
private pruneCommonWords;
|
|
17
|
+
private estimateSentiment;
|
|
18
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ProfileManager = void 0;
|
|
4
|
+
class ProfileManager {
|
|
5
|
+
ctx;
|
|
6
|
+
constructor(ctx) {
|
|
7
|
+
this.ctx = ctx;
|
|
8
|
+
}
|
|
9
|
+
async getProfile(guildId, userId) {
|
|
10
|
+
const profiles = await this.ctx.database.get('guofenbot_profile', { guildId, userId });
|
|
11
|
+
return profiles.length > 0 ? profiles[0] : null;
|
|
12
|
+
}
|
|
13
|
+
async getGuildProfiles(guildId) {
|
|
14
|
+
return this.ctx.database.get('guofenbot_profile', { guildId });
|
|
15
|
+
}
|
|
16
|
+
async getProfileSnapshots(guildId) {
|
|
17
|
+
const profiles = await this.getGuildProfiles(guildId);
|
|
18
|
+
return profiles.map((p) => ({
|
|
19
|
+
userId: p.userId,
|
|
20
|
+
username: p.username,
|
|
21
|
+
messageCount: p.messageCount,
|
|
22
|
+
avgMessageLength: p.avgMessageLength,
|
|
23
|
+
commonWords: JSON.parse(p.commonWords || '{}'),
|
|
24
|
+
sentimentBaseline: p.sentimentBaseline,
|
|
25
|
+
activeHours: JSON.parse(p.activeHours || '[]'),
|
|
26
|
+
lastMessageTime: new Date(p.lastMessageTime).getTime(),
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
29
|
+
async updateProfile(guildId, userId, username, messageContent) {
|
|
30
|
+
const existing = await this.getProfile(guildId, userId);
|
|
31
|
+
const now = new Date();
|
|
32
|
+
const msgLen = messageContent.length;
|
|
33
|
+
if (existing) {
|
|
34
|
+
const newCount = existing.messageCount + 1;
|
|
35
|
+
const newAvgLen = (existing.avgMessageLength * existing.messageCount + msgLen) / newCount;
|
|
36
|
+
const words = this.extractWords(messageContent);
|
|
37
|
+
const commonWords = JSON.parse(existing.commonWords || '{}');
|
|
38
|
+
for (const word of words) {
|
|
39
|
+
commonWords[word] = (commonWords[word] || 0) + 1;
|
|
40
|
+
}
|
|
41
|
+
const pruned = this.pruneCommonWords(commonWords);
|
|
42
|
+
const activeHours = JSON.parse(existing.activeHours || '[]');
|
|
43
|
+
const currentHour = now.getHours();
|
|
44
|
+
if (!activeHours.includes(currentHour)) {
|
|
45
|
+
activeHours.push(currentHour);
|
|
46
|
+
}
|
|
47
|
+
const sentiment = this.estimateSentiment(messageContent);
|
|
48
|
+
const newSentiment = (existing.sentimentBaseline * existing.messageCount + sentiment) / newCount;
|
|
49
|
+
await this.ctx.database.set('guofenbot_profile', { guildId, userId }, {
|
|
50
|
+
username,
|
|
51
|
+
messageCount: newCount,
|
|
52
|
+
lastMessageTime: now,
|
|
53
|
+
avgMessageLength: newAvgLen,
|
|
54
|
+
commonWords: JSON.stringify(pruned),
|
|
55
|
+
sentimentBaseline: newSentiment,
|
|
56
|
+
activeHours: JSON.stringify(activeHours),
|
|
57
|
+
updatedAt: now,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
const words = this.extractWords(messageContent);
|
|
62
|
+
const commonWords = {};
|
|
63
|
+
for (const word of words) {
|
|
64
|
+
commonWords[word] = 1;
|
|
65
|
+
}
|
|
66
|
+
const profile = {
|
|
67
|
+
id: 0,
|
|
68
|
+
guildId,
|
|
69
|
+
userId,
|
|
70
|
+
username,
|
|
71
|
+
messageCount: 1,
|
|
72
|
+
lastMessageTime: now,
|
|
73
|
+
avgMessageLength: msgLen,
|
|
74
|
+
commonWords: JSON.stringify(commonWords),
|
|
75
|
+
sentimentBaseline: this.estimateSentiment(messageContent),
|
|
76
|
+
activeHours: JSON.stringify([now.getHours()]),
|
|
77
|
+
updatedAt: now,
|
|
78
|
+
};
|
|
79
|
+
await this.ctx.database.create('guofenbot_profile', profile);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
detectAnomaly(profile, messageContent, sensitivity) {
|
|
83
|
+
const reasons = [];
|
|
84
|
+
let totalScore = 0;
|
|
85
|
+
let checks = 0;
|
|
86
|
+
const thresholds = { low: 0.8, medium: 0.6, high: 0.4 };
|
|
87
|
+
const msgLen = messageContent.length;
|
|
88
|
+
if (profile.messageCount > 10 && profile.avgMessageLength > 0) {
|
|
89
|
+
const lenDeviation = Math.abs(msgLen - profile.avgMessageLength) / profile.avgMessageLength;
|
|
90
|
+
if (lenDeviation > 2) {
|
|
91
|
+
reasons.push(`消息长度异常偏离 (偏差 ${(lenDeviation * 100).toFixed(0)}%)`);
|
|
92
|
+
totalScore += Math.min(1, lenDeviation / 5);
|
|
93
|
+
}
|
|
94
|
+
checks++;
|
|
95
|
+
}
|
|
96
|
+
const currentHour = new Date().getHours();
|
|
97
|
+
const activeHours = JSON.parse(profile.activeHours || '[]');
|
|
98
|
+
if (profile.messageCount > 5 && activeHours.length > 0) {
|
|
99
|
+
if (!activeHours.includes(currentHour)) {
|
|
100
|
+
reasons.push(`在非活跃时段发言 (当前 ${currentHour}时)`);
|
|
101
|
+
totalScore += 0.5;
|
|
102
|
+
}
|
|
103
|
+
checks++;
|
|
104
|
+
}
|
|
105
|
+
const currentSentiment = this.estimateSentiment(messageContent);
|
|
106
|
+
if (profile.messageCount > 10) {
|
|
107
|
+
const sentimentDiff = Math.abs(currentSentiment - profile.sentimentBaseline);
|
|
108
|
+
if (sentimentDiff > 0.6) {
|
|
109
|
+
reasons.push(`情绪基调显著偏离基线 (差异 ${sentimentDiff.toFixed(2)})`);
|
|
110
|
+
totalScore += Math.min(1, sentimentDiff);
|
|
111
|
+
}
|
|
112
|
+
checks++;
|
|
113
|
+
}
|
|
114
|
+
if (profile.messageCount > 5) {
|
|
115
|
+
const words = this.extractWords(messageContent);
|
|
116
|
+
const commonWords = JSON.parse(profile.commonWords || '{}');
|
|
117
|
+
let newWords = 0;
|
|
118
|
+
for (const word of words) {
|
|
119
|
+
if (!commonWords[word])
|
|
120
|
+
newWords++;
|
|
121
|
+
}
|
|
122
|
+
const newWordRatio = words.length > 0 ? newWords / words.length : 0;
|
|
123
|
+
if (newWordRatio > 0.7 && words.length > 3) {
|
|
124
|
+
reasons.push(`使用了大量陌生词汇 (新词比例 ${(newWordRatio * 100).toFixed(0)}%)`);
|
|
125
|
+
totalScore += Math.min(1, newWordRatio);
|
|
126
|
+
}
|
|
127
|
+
checks++;
|
|
128
|
+
}
|
|
129
|
+
const avgScore = checks > 0 ? totalScore / checks : 0;
|
|
130
|
+
const threshold = thresholds[sensitivity];
|
|
131
|
+
return {
|
|
132
|
+
isAnomalous: avgScore > threshold,
|
|
133
|
+
score: avgScore,
|
|
134
|
+
reasons,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
extractWords(content) {
|
|
138
|
+
const cleaned = content
|
|
139
|
+
.replace(/[,。!?、;:""''()【】《》\s,.!?;:'"()\[\]{}<>]+/g, ' ')
|
|
140
|
+
.trim();
|
|
141
|
+
if (/[\u4e00-\u9fa5]/.test(cleaned)) {
|
|
142
|
+
const words = [];
|
|
143
|
+
for (let i = 0; i < cleaned.length - 1; i++) {
|
|
144
|
+
if (/[\u4e00-\u9fa5]/.test(cleaned[i]) && /[\u4e00-\u9fa5]/.test(cleaned[i + 1])) {
|
|
145
|
+
words.push(cleaned[i] + cleaned[i + 1]);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return words.slice(0, 50);
|
|
149
|
+
}
|
|
150
|
+
return cleaned.split(/\s+/).filter((w) => w.length > 1).slice(0, 50);
|
|
151
|
+
}
|
|
152
|
+
pruneCommonWords(words) {
|
|
153
|
+
const entries = Object.entries(words).sort((a, b) => b[1] - a[1]);
|
|
154
|
+
return Object.fromEntries(entries.slice(0, 200));
|
|
155
|
+
}
|
|
156
|
+
estimateSentiment(content) {
|
|
157
|
+
const positive = ['好', '棒', '赞', '开心', '喜欢', '哈哈', '谢谢', '厉害', '优秀', 'nice', 'good', '爱', '快乐', '幸福'];
|
|
158
|
+
const negative = ['烦', '气', '恨', '讨厌', '垃圾', '差', '烂', '恶心', 'fuck', '操', '滚', '死', '傻', '蠢'];
|
|
159
|
+
let score = 0;
|
|
160
|
+
for (const word of positive) {
|
|
161
|
+
if (content.includes(word))
|
|
162
|
+
score += 0.1;
|
|
163
|
+
}
|
|
164
|
+
for (const word of negative) {
|
|
165
|
+
if (content.includes(word))
|
|
166
|
+
score -= 0.1;
|
|
167
|
+
}
|
|
168
|
+
return Math.max(-1, Math.min(1, score));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
exports.ProfileManager = ProfileManager;
|
|
172
|
+
//# sourceMappingURL=profile-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"profile-manager.js","sourceRoot":"","sources":["../../src/services/profile-manager.ts"],"names":[],"mappings":";;;AAGA,MAAa,cAAc;IACjB,GAAG,CAAS;IAEpB,YAAY,GAAY;QACtB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;IAChB,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,OAAe,EAAE,MAAc;QAC9C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,mBAAmB,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAA;QACtF,OAAO,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACjD,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,OAAe;QACpC,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,mBAAmB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAA;IAChE,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,OAAe;QACvC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAA;QACrD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC1B,MAAM,EAAE,CAAC,CAAC,MAAM;YAChB,QAAQ,EAAE,CAAC,CAAC,QAAQ;YACpB,YAAY,EAAE,CAAC,CAAC,YAAY;YAC5B,gBAAgB,EAAE,CAAC,CAAC,gBAAgB;YACpC,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,IAAI,IAAI,CAAC;YAC9C,iBAAiB,EAAE,CAAC,CAAC,iBAAiB;YACtC,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,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AAC;gBAAE,KAAK,IAAI,GAAG,CAAA;QAC1C,CAAC;QAED,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAA;IACzC,CAAC;CACF;AA/LD,wCA+LC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { GuofenbotRule } from '../types';
|
|
3
|
+
export declare class RuleManager {
|
|
4
|
+
private ctx;
|
|
5
|
+
constructor(ctx: Context);
|
|
6
|
+
getRule(guildId: string): Promise<GuofenbotRule | null>;
|
|
7
|
+
setRule(guildId: string, content: string): Promise<GuofenbotRule>;
|
|
8
|
+
deleteRule(guildId: string): Promise<void>;
|
|
9
|
+
getAllRules(): Promise<GuofenbotRule[]>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RuleManager = void 0;
|
|
4
|
+
class RuleManager {
|
|
5
|
+
ctx;
|
|
6
|
+
constructor(ctx) {
|
|
7
|
+
this.ctx = ctx;
|
|
8
|
+
}
|
|
9
|
+
async getRule(guildId) {
|
|
10
|
+
const rules = await this.ctx.database.get('guofenbot_rule', { guildId });
|
|
11
|
+
return rules.length > 0 ? rules[0] : null;
|
|
12
|
+
}
|
|
13
|
+
async setRule(guildId, content) {
|
|
14
|
+
const existing = await this.getRule(guildId);
|
|
15
|
+
if (existing) {
|
|
16
|
+
await this.ctx.database.set('guofenbot_rule', { guildId }, {
|
|
17
|
+
content,
|
|
18
|
+
updatedAt: new Date(),
|
|
19
|
+
});
|
|
20
|
+
return { ...existing, content, updatedAt: new Date() };
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
const rule = {
|
|
24
|
+
id: 0,
|
|
25
|
+
guildId,
|
|
26
|
+
content,
|
|
27
|
+
createdAt: new Date(),
|
|
28
|
+
updatedAt: new Date(),
|
|
29
|
+
};
|
|
30
|
+
await this.ctx.database.create('guofenbot_rule', rule);
|
|
31
|
+
return rule;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async deleteRule(guildId) {
|
|
35
|
+
await this.ctx.database.remove('guofenbot_rule', { guildId });
|
|
36
|
+
}
|
|
37
|
+
async getAllRules() {
|
|
38
|
+
return this.ctx.database.get('guofenbot_rule', {});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
exports.RuleManager = RuleManager;
|
|
42
|
+
//# sourceMappingURL=rule-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rule-manager.js","sourceRoot":"","sources":["../../src/services/rule-manager.ts"],"names":[],"mappings":";;;AAGA,MAAa,WAAW;IACd,GAAG,CAAS;IAEpB,YAAY,GAAY;QACtB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;IAChB,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,OAAe;QAC3B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAA;QACxE,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IAC3C,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,OAAe,EAAE,OAAe;QAC5C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QAC5C,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,EAAE,OAAO,EAAE,EAAE;gBACzD,OAAO;gBACP,SAAS,EAAE,IAAI,IAAI,EAAE;aACtB,CAAC,CAAA;YACF,OAAO,EAAE,GAAG,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,IAAI,EAAE,EAAE,CAAA;QACxD,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,GAAkB;gBAC1B,EAAE,EAAE,CAAC;gBACL,OAAO;gBACP,OAAO;gBACP,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,SAAS,EAAE,IAAI,IAAI,EAAE;aACtB,CAAA;YACD,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAA;YACtD,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,OAAe;QAC9B,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,gBAAgB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAA;IAC/D,CAAC;IAED,KAAK,CAAC,WAAW;QACf,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAA;IACpD,CAAC;CACF;AAxCD,kCAwCC"}
|
package/lib/types.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export interface GuofenbotRule {
|
|
2
|
+
id: number;
|
|
3
|
+
guildId: string;
|
|
4
|
+
content: string;
|
|
5
|
+
createdAt: Date;
|
|
6
|
+
updatedAt: Date;
|
|
7
|
+
}
|
|
8
|
+
export interface GuofenbotProfile {
|
|
9
|
+
id: number;
|
|
10
|
+
guildId: string;
|
|
11
|
+
userId: string;
|
|
12
|
+
username: string;
|
|
13
|
+
messageCount: number;
|
|
14
|
+
lastMessageTime: Date;
|
|
15
|
+
avgMessageLength: number;
|
|
16
|
+
commonWords: string;
|
|
17
|
+
sentimentBaseline: number;
|
|
18
|
+
activeHours: string;
|
|
19
|
+
updatedAt: Date;
|
|
20
|
+
}
|
|
21
|
+
export interface GuofenbotAlert {
|
|
22
|
+
id: number;
|
|
23
|
+
guildId: string;
|
|
24
|
+
userId: string;
|
|
25
|
+
username: string;
|
|
26
|
+
messageContent: string;
|
|
27
|
+
alertType: AlertType;
|
|
28
|
+
reason: string;
|
|
29
|
+
confidence: number;
|
|
30
|
+
handled: boolean;
|
|
31
|
+
action: AlertAction;
|
|
32
|
+
createdAt: Date;
|
|
33
|
+
}
|
|
34
|
+
export type AlertType = 'suspicious' | 'dangerous' | 'abnormal';
|
|
35
|
+
export type AlertAction = 'none' | 'warn' | 'mute' | 'kick';
|
|
36
|
+
export type Sensitivity = 'low' | 'medium' | 'high';
|
|
37
|
+
export type AlertTarget = 'group' | 'private' | 'both';
|
|
38
|
+
export interface AIProviderConfig {
|
|
39
|
+
type: 'openai' | 'custom';
|
|
40
|
+
endpoint: string;
|
|
41
|
+
apiKey: string;
|
|
42
|
+
model: string;
|
|
43
|
+
}
|
|
44
|
+
export interface MessageContext {
|
|
45
|
+
userId: string;
|
|
46
|
+
username: string;
|
|
47
|
+
content: string;
|
|
48
|
+
guildId: string;
|
|
49
|
+
channelId: string;
|
|
50
|
+
platform: string;
|
|
51
|
+
timestamp: number;
|
|
52
|
+
}
|
|
53
|
+
export interface MemberProfileSnapshot {
|
|
54
|
+
userId: string;
|
|
55
|
+
username: string;
|
|
56
|
+
messageCount: number;
|
|
57
|
+
avgMessageLength: number;
|
|
58
|
+
commonWords: Record<string, number>;
|
|
59
|
+
sentimentBaseline: number;
|
|
60
|
+
activeHours: number[];
|
|
61
|
+
lastMessageTime: number;
|
|
62
|
+
}
|
|
63
|
+
export interface AnalysisResult {
|
|
64
|
+
isAbnormal: boolean;
|
|
65
|
+
alertType: AlertType;
|
|
66
|
+
reason: string;
|
|
67
|
+
confidence: number;
|
|
68
|
+
suggestedAction: AlertAction;
|
|
69
|
+
}
|
package/lib/types.js
ADDED
package/lib/types.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "koishi-plugin-guofenbot",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "AI 群聊安全监测插件 - 支持多 AI 接入、群规则理解、成员行为分析、异常言论检测与自动处理",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"types": "lib/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"lib"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc",
|
|
12
|
+
"clean": "rm -rf lib",
|
|
13
|
+
"dev": "tsc --watch"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"koishi",
|
|
17
|
+
"plugin",
|
|
18
|
+
"ai",
|
|
19
|
+
"moderation",
|
|
20
|
+
"group-chat"
|
|
21
|
+
],
|
|
22
|
+
"author": "",
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"koishi": "^4.0.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"koishi": "^4.18.0",
|
|
29
|
+
"typescript": "^5.5.0",
|
|
30
|
+
"@types/node": "^22.0.0"
|
|
31
|
+
},
|
|
32
|
+
"koishi": {
|
|
33
|
+
"description": {
|
|
34
|
+
"zh": "AI 群聊安全监测插件 - 支持多 AI 接入、群规则理解、成员行为分析、异常言论检测与自动处理"
|
|
35
|
+
},
|
|
36
|
+
"service": {
|
|
37
|
+
"required": ["database", "server"]
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|