mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 退群监控接入自动化能力统一管理, 支持发送个人/文件传输助手/指定群聊
This commit is contained in:
1 parent
3bd3935042
commit
59872daf52
43 files changed
+5661
-1132
No files matched your search
@@ -32,6 +32,7 @@ export interface AutomationMatchInput {
|
||||
}
|
||||
|
||||
export type AutomationMatchFailure =
|
||||
| 'rule_type'
|
||||
| 'disabled'
|
||||
| 'self'
|
||||
| 'scope'
|
||||
@@ -52,6 +53,15 @@ export function matchAutomationRule(
|
||||
/** 自己的 username 候选集(`getMyUsernameCandidates()`)。 */
|
||||
selfUsernames: readonly string[]
|
||||
): AutomationMatchResult {
|
||||
// **规则类型闸门放在最前面。**
|
||||
//
|
||||
// 「退群通知」的空关键词 + 不要求 @我,会让它命中**每一条群消息** ——
|
||||
// 那是最坏的一类 bug:用户什么都没配,规则却开始乱跑。
|
||||
// 类型分派必须在这里一处解决,预览与真实执行才会一致。
|
||||
if (rule.ruleType === 'leave_notification') {
|
||||
return { matched: false, reason: 'rule_type' }
|
||||
}
|
||||
|
||||
if (!rule.enabled) return { matched: false, reason: 'disabled' }
|
||||
|
||||
// 防死循环第一道闸:自己发的消息默认不触发。
|
||||
|
||||
+278
-18
@@ -5,6 +5,8 @@
|
||||
* 第一版不做:regex、IF/ELSE 嵌套、可视化编排、Webhook、通用 AI 机器人。
|
||||
*/
|
||||
|
||||
import { normalizeGroupExitNotificationTemplate } from './group-exit-monitor'
|
||||
|
||||
/** 触发事件类型。第一版只支持「收到消息」。 */
|
||||
export type AutomationTriggerType = 'message'
|
||||
|
||||
@@ -19,6 +21,49 @@ export type KeywordMatchMode = 'contains' | 'exact' | 'prefix'
|
||||
/** 消息来源过滤。 */
|
||||
export type AutomationMessageScope = 'group' | 'direct' | 'all'
|
||||
|
||||
/**
|
||||
* 规则类型。
|
||||
*
|
||||
* 决定**这条规则由什么驱动、有哪些字段有意义**:
|
||||
* - `daily_report`:消息驱动,条件 + 动作链(@我生成日报);
|
||||
* - `leave_notification`:退群事件驱动,通知目标 + 模板(退群通知)。
|
||||
*
|
||||
* ⚠️ 这是一条**硬分派**:`matchAutomationRule` 会直接拒绝非 `daily_report` 的规则,
|
||||
* 否则一条 keyword 为空的退群通知会命中**每一条群消息**。
|
||||
*/
|
||||
export type AutomationRuleType = 'daily_report' | 'leave_notification'
|
||||
|
||||
/** 规则类型的界面标签(Tab 与首页卡片共用一处文案)。 */
|
||||
export const AUTOMATION_RULE_TYPE_LABELS: Record<AutomationRuleType, string> = {
|
||||
daily_report: '@我生成日报',
|
||||
leave_notification: '退群通知'
|
||||
}
|
||||
|
||||
/** 退群通知发到哪里。刻意只有这四种。 */
|
||||
export type LeaveNotificationTargetType = 'source_chat' | 'self' | 'file_transfer' | 'contact'
|
||||
|
||||
export interface LeaveNotificationTarget {
|
||||
type: LeaveNotificationTargetType
|
||||
/**
|
||||
* `contact` 时必填。
|
||||
*
|
||||
* **稳定 id(wxid)**,不是显示昵称 —— 昵称会改,改完就发错人。
|
||||
*/
|
||||
contactId?: string
|
||||
}
|
||||
|
||||
export interface LeaveNotificationConfig {
|
||||
target: LeaveNotificationTarget
|
||||
template: string
|
||||
/**
|
||||
* 迁移时旧配置**无法无损映射**的标记(旧「通知群聊」是 per-group 多值,
|
||||
* 新目标是单值)。为 true 时:规则不执行发送,UI 提示用户重选目标。
|
||||
*
|
||||
* 只有迁移会把它置为 true,用户手动保存一次即清除。
|
||||
*/
|
||||
targetNeedsReview?: boolean
|
||||
}
|
||||
|
||||
export interface AutomationConditions {
|
||||
/** 必须**真正** @我(走 source → atuserlist,不是正文里的 @昵称)。 */
|
||||
requireMentionMe: boolean
|
||||
@@ -44,6 +89,8 @@ export interface AutomationRule {
|
||||
id: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
/** 规则类型。缺省视为 `daily_report`(历史 rules.json 没有这个字段)。 */
|
||||
ruleType: AutomationRuleType
|
||||
trigger: AutomationTriggerType
|
||||
scope: AutomationMessageScope
|
||||
conditions: AutomationConditions
|
||||
@@ -61,6 +108,8 @@ export interface AutomationRule {
|
||||
* `normalizeReplyDelaySeconds()` 处理 ⇒ 缺省即默认 2 秒,不是「不等待」。
|
||||
*/
|
||||
replyDelaySeconds: number
|
||||
/** `ruleType === 'leave_notification'` 时必填。 */
|
||||
leaveNotification?: LeaveNotificationConfig
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
@@ -68,8 +117,26 @@ export interface AutomationRule {
|
||||
/** 执行步骤状态。`skipped` 用于「上一步失败所以这一步不做」。 */
|
||||
export type AutomationStepStatus = 'pending' | 'running' | 'success' | 'failed' | 'skipped'
|
||||
|
||||
/** 执行步骤键。只有**真正进入执行**的规则才会有步骤。 */
|
||||
export type AutomationStepKey = 'received' | 'matched' | 'reply' | 'report' | 'send'
|
||||
/**
|
||||
* 执行步骤键。
|
||||
*
|
||||
* 分两族,**不共用**:
|
||||
* - 消息型(`daily_report`):received / matched / reply / report / send
|
||||
* - 退群型(`leave_notification`):exit_received / exit_matched / exit_target / exit_send
|
||||
*
|
||||
* 不共用的理由:给退群通知渲染一个「回复确认 已跳过」的步骤是纯噪声,
|
||||
* 用户会以为规则配错了。
|
||||
*/
|
||||
export type AutomationStepKey =
|
||||
| 'received'
|
||||
| 'matched'
|
||||
| 'reply'
|
||||
| 'report'
|
||||
| 'send'
|
||||
| 'exit_received'
|
||||
| 'exit_matched'
|
||||
| 'exit_target'
|
||||
| 'exit_send'
|
||||
|
||||
export interface AutomationStep {
|
||||
key: AutomationStepKey
|
||||
@@ -79,6 +146,13 @@ export interface AutomationStep {
|
||||
startedAt?: number
|
||||
finishedAt?: number
|
||||
durationMs?: number
|
||||
/**
|
||||
* 用户可读的**细节**(例如已解析的通知目标显示名「文件传输助手」)。
|
||||
*
|
||||
* ⚠️ 展示层契约:只允许放用户能理解的名称。
|
||||
* **禁止** wxid / chatroom id / localId / serverId / 文件路径 / 原始 payload。
|
||||
*/
|
||||
detail?: string
|
||||
/** 用户可读的错误信息。**禁止**含 wxid / 文件路径 / 原始 payload。 */
|
||||
error?: string
|
||||
/**
|
||||
@@ -143,7 +217,15 @@ export const AUTOMATION_SEND_PURPOSE = {
|
||||
/** 触发确认文字回复。 */
|
||||
reply: 'automation_reply',
|
||||
/** 日报图片。 */
|
||||
report: 'automation_report'
|
||||
report: 'automation_report',
|
||||
/**
|
||||
* 退群通知文字。
|
||||
*
|
||||
* 刻意**不复用**历史 purpose `member_left_notification`:那一个被 WechatActionGateway
|
||||
* 的作用域锁绑死在「只能发回事件所在群」,而现在的目标可以是自己 / 文件传输助手 /
|
||||
* 指定好友。用新 purpose 才能真正解除那个锁,同时让旧 purpose 变成无生产者的历史值。
|
||||
*/
|
||||
leaveNotification: 'automation_leave_notification'
|
||||
} as const
|
||||
|
||||
/** 审计日志里的来源标识(`WechatActionOrigin`)。 */
|
||||
@@ -194,6 +276,7 @@ export function automationIdempotencyKey(
|
||||
export interface AutomationRuleDraft {
|
||||
name: string
|
||||
enabled: boolean
|
||||
ruleType: AutomationRuleType
|
||||
trigger: AutomationTriggerType
|
||||
scope: AutomationMessageScope
|
||||
conditions: AutomationConditions
|
||||
@@ -201,6 +284,8 @@ export interface AutomationRuleDraft {
|
||||
cooldownSeconds: number
|
||||
/** 命中后等多久再回复确认(秒)。0 = 立刻回复。 */
|
||||
replyDelaySeconds: number
|
||||
/** `ruleType === 'leave_notification'` 时的通知配置。 */
|
||||
leaveNotification?: LeaveNotificationConfig
|
||||
}
|
||||
|
||||
/** 顶部状态条数据(全部来自 main 侧真实能力,UI 不做平台判断)。 */
|
||||
@@ -244,33 +329,41 @@ export const AUTOMATION_RULE_TEMPLATES: AutomationRuleTemplate[] = [
|
||||
name: '定时发送日报',
|
||||
description: '按固定时间自动生成并发送群日报',
|
||||
available: false,
|
||||
unavailableReason: '沿用现有「定时日报」能力,本轮不迁移'
|
||||
},
|
||||
{
|
||||
id: 'member-exit-notice',
|
||||
name: '退群通知',
|
||||
description: '群成员退出时自动发送通知',
|
||||
available: false,
|
||||
unavailableReason: '现有「退群监控」已具备该能力,本轮不迁移'
|
||||
unavailableReason: ''
|
||||
},
|
||||
{
|
||||
id: 'keyword-reply',
|
||||
name: '关键词自动回复',
|
||||
description: '消息命中关键词时自动回复指定内容',
|
||||
available: false,
|
||||
unavailableReason: '本轮验收对象为「@我生成日报」,关键词模板下一轮开放'
|
||||
unavailableReason: ''
|
||||
}
|
||||
]
|
||||
|
||||
/** 内置规则 id。固定值,便于升级时不重复创建。 */
|
||||
export const BUILTIN_DAILY_REPORT_RULE_ID = 'builtin-mention-me-daily-report'
|
||||
|
||||
/**
|
||||
* 内置「退群通知」规则 id。
|
||||
*
|
||||
* 这是一个 **singleton / system rule**:保存永远按这个 id upsert,
|
||||
* 不允许"每打开一次编辑页多一条规则"。
|
||||
*/
|
||||
export const BUILTIN_LEAVE_NOTIFICATION_RULE_ID = 'builtin-leave-notification'
|
||||
|
||||
/** 退群通知的默认展示名。 */
|
||||
export const LEAVE_NOTIFICATION_RULE_NAME = '退群通知'
|
||||
|
||||
export const AUTOMATION_STEP_LABELS: Record<AutomationStepKey, string> = {
|
||||
received: '收到消息',
|
||||
matched: '规则匹配',
|
||||
reply: '回复确认',
|
||||
report: '生成日报',
|
||||
send: '发送日报图片'
|
||||
send: '发送日报图片',
|
||||
exit_received: '检测到成员退出',
|
||||
exit_matched: '规则匹配',
|
||||
exit_target: '确定通知目标',
|
||||
exit_send: '发送退群通知'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -316,8 +409,80 @@ export function matchKeyword(
|
||||
return haystack.includes(needle)
|
||||
}
|
||||
|
||||
/**
|
||||
* 退群通知的四种发送目标(展示层单一来源)。
|
||||
*
|
||||
* UI 单选项与首页卡片摘要都从这里取文案,避免同一句话在两个文件里各写一份、慢慢漂移。
|
||||
* **顺序即界面顺序**:`当前群聊` 排第一,因为它也是默认值。
|
||||
*/
|
||||
export const LEAVE_NOTIFICATION_TARGET_OPTIONS: ReadonlyArray<{
|
||||
type: LeaveNotificationTargetType
|
||||
label: string
|
||||
description: string
|
||||
}> = [
|
||||
{
|
||||
type: 'source_chat',
|
||||
label: '当前群聊',
|
||||
description: '将通知发送到发生成员退出的群聊。'
|
||||
},
|
||||
{
|
||||
type: 'file_transfer',
|
||||
label: '文件传输助手',
|
||||
description: '将通知发送到文件传输助手。'
|
||||
},
|
||||
{
|
||||
type: 'self',
|
||||
label: '发给自己',
|
||||
description: '将通知发送到当前登录微信账号自己的会话。'
|
||||
},
|
||||
{
|
||||
type: 'contact',
|
||||
label: '指定好友',
|
||||
description: '将通知发送给一个指定联系人。'
|
||||
}
|
||||
]
|
||||
|
||||
/**
|
||||
* 新安装 / 无历史配置时的默认目标。
|
||||
*
|
||||
* 「当前群聊」= 旧「退群监控」通知的原始行为(通知发回事件所在群),
|
||||
* 所以它既是默认值、也排在选项第一位。
|
||||
*/
|
||||
export const LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE: LeaveNotificationTargetType = 'source_chat'
|
||||
|
||||
/** 目标类型 → 界面短标签。 */
|
||||
export function leaveNotificationTargetLabel(type: LeaveNotificationTargetType): string {
|
||||
return LEAVE_NOTIFICATION_TARGET_OPTIONS.find((option) => option.type === type)?.label ?? ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 「范围」摘要:退群通知覆盖多少个已监控群聊。
|
||||
*
|
||||
* 数字**必须**来自退群监控(`GroupExitMonitorState`),自动化不维护副本。
|
||||
*/
|
||||
export function describeMonitoredScope(monitoredCount: number): string {
|
||||
return `${Math.max(0, Math.floor(Number(monitoredCount) || 0))} 个已监控群聊`
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标的一句话描述(首页卡片摘要用)。
|
||||
*
|
||||
* `contact` 需要外部把联系人显示名传进来 —— shared 不读通讯录。
|
||||
* 名字拿不到时如实说「未选择好友」,不伪造一个收件人。
|
||||
*/
|
||||
export function describeLeaveNotificationTarget(
|
||||
config: LeaveNotificationConfig | undefined,
|
||||
contactDisplayName?: string
|
||||
): string {
|
||||
const target = config?.target
|
||||
if (!target) return '未配置'
|
||||
if (target.type === 'contact') return contactDisplayName?.trim() || '未选择好友'
|
||||
return leaveNotificationTargetLabel(target.type)
|
||||
}
|
||||
|
||||
/** 触发条件的一句话摘要(UI 展示用,不含任何内部 id)。 */
|
||||
export function describeRuleTrigger(rule: AutomationRule): string {
|
||||
if (rule.ruleType === 'leave_notification') return '检测到群成员退出'
|
||||
const parts: string[] = []
|
||||
if (rule.conditions.requireMentionMe) parts.push('@我')
|
||||
if (rule.conditions.keyword.trim()) {
|
||||
@@ -328,6 +493,7 @@ export function describeRuleTrigger(rule: AutomationRule): string {
|
||||
|
||||
/** 动作链的一句话摘要。 */
|
||||
export function describeRuleActions(rule: AutomationRule): string {
|
||||
if (rule.ruleType === 'leave_notification') return '发送退群通知'
|
||||
const labels: Record<AutomationActionType, string> = {
|
||||
replyText: '回复确认',
|
||||
generateReport: '生成日报',
|
||||
@@ -354,6 +520,7 @@ export function createDefaultDailyReportRule(now: number): AutomationRule {
|
||||
id: BUILTIN_DAILY_REPORT_RULE_ID,
|
||||
name: '@我生成日报',
|
||||
enabled: true,
|
||||
ruleType: 'daily_report',
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: {
|
||||
@@ -375,10 +542,66 @@ export function createDefaultDailyReportRule(now: number): AutomationRule {
|
||||
}
|
||||
}
|
||||
|
||||
/** 构造内置规则「退群通知」(singleton,固定 id)。 */
|
||||
export function createDefaultLeaveNotificationRule(
|
||||
now: number,
|
||||
options: {
|
||||
template?: string
|
||||
target?: LeaveNotificationTarget
|
||||
enabled?: boolean
|
||||
targetNeedsReview?: boolean
|
||||
} = {}
|
||||
): AutomationRule {
|
||||
return {
|
||||
id: BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
name: LEAVE_NOTIFICATION_RULE_NAME,
|
||||
// 规则级启停是**唯一**开关;退群通知没有第二个"发送"开关。
|
||||
enabled: options.enabled !== false,
|
||||
ruleType: 'leave_notification',
|
||||
// 由退群事件驱动,不参与消息匹配。这两个字段保留只是为了 schema 完整。
|
||||
trigger: 'message',
|
||||
scope: 'group',
|
||||
conditions: {
|
||||
requireMentionMe: false,
|
||||
keyword: '',
|
||||
keywordMatchMode: 'contains',
|
||||
conversationIds: [],
|
||||
ignoreSelf: true
|
||||
},
|
||||
// 退群通知没有动作链,动作由 leaveNotification 表达。
|
||||
actions: [],
|
||||
// 不套用消息型规则的 cooldown:两次退群不能被 60 秒窗口合并。
|
||||
cooldownSeconds: 0,
|
||||
replyDelaySeconds: AUTOMATION_REPLY_DELAY_DEFAULT_SECONDS,
|
||||
leaveNotification: {
|
||||
target: options.target ?? { type: LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE },
|
||||
template: normalizeLeaveNotificationTemplate(options.template),
|
||||
...(options.targetNeedsReview ? { targetNeedsReview: true } : {})
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板归一化。
|
||||
*
|
||||
* 复用退群监控那份校验/归一化(含 legacy 模板升级),保证
|
||||
* 「模板规则只有一处实现」——迁移不产生第二套占位符解析。
|
||||
*/
|
||||
export function normalizeLeaveNotificationTemplate(value: unknown): string {
|
||||
return normalizeGroupExitNotificationTemplate(value)
|
||||
}
|
||||
|
||||
/** 归一化用户提交的草稿:把未知值收敛成合法值,避免脏数据落盘。 */
|
||||
export function normalizeRuleDraft(input: unknown, fallbackName = '未命名自动化'): AutomationRuleDraft {
|
||||
export function normalizeRuleDraft(
|
||||
input: unknown,
|
||||
fallbackName = '未命名自动化'
|
||||
): AutomationRuleDraft {
|
||||
const raw = (input ?? {}) as Partial<AutomationRuleDraft>
|
||||
const conditions = (raw.conditions ?? {}) as Partial<AutomationConditions>
|
||||
const ruleType: AutomationRuleType =
|
||||
raw.ruleType === 'leave_notification' ? 'leave_notification' : 'daily_report'
|
||||
const keywordMatchMode: KeywordMatchMode =
|
||||
conditions.keywordMatchMode === 'exact' || conditions.keywordMatchMode === 'prefix'
|
||||
? conditions.keywordMatchMode
|
||||
@@ -393,14 +616,18 @@ export function normalizeRuleDraft(input: unknown, fallbackName = '未命名自
|
||||
enabled: action.enabled !== false,
|
||||
...(typeof action.text === 'string' ? { text: action.text } : {})
|
||||
}))
|
||||
.filter((action) =>
|
||||
action.type === 'replyText' || action.type === 'generateReport' || action.type === 'sendReportImage'
|
||||
.filter(
|
||||
(action) =>
|
||||
action.type === 'replyText' ||
|
||||
action.type === 'generateReport' ||
|
||||
action.type === 'sendReportImage'
|
||||
)
|
||||
const cooldown = Number(raw.cooldownSeconds)
|
||||
return {
|
||||
const base = {
|
||||
name: String(raw.name ?? '').trim() || fallbackName,
|
||||
enabled: raw.enabled !== false,
|
||||
trigger: 'message',
|
||||
ruleType,
|
||||
trigger: 'message' as AutomationTriggerType,
|
||||
scope,
|
||||
conditions: {
|
||||
requireMentionMe: conditions.requireMentionMe !== false,
|
||||
@@ -415,4 +642,37 @@ export function normalizeRuleDraft(input: unknown, fallbackName = '未命名自
|
||||
cooldownSeconds: Number.isFinite(cooldown) ? Math.max(0, Math.floor(cooldown)) : 60,
|
||||
replyDelaySeconds: normalizeReplyDelaySeconds(raw.replyDelaySeconds)
|
||||
}
|
||||
if (ruleType !== 'leave_notification') return base
|
||||
return { ...base, leaveNotification: normalizeLeaveNotificationConfig(raw.leaveNotification) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 收敛退群通知配置。
|
||||
*
|
||||
* 目标是**必填**的:缺失一律回落到默认目标(文件传输助手),
|
||||
* 而不是留一个"没有目标"的规则 —— 那种规则在运行时只能失败。
|
||||
* `contact` 缺 contactId 时同样回落,避免存下一条永远发不出去的规则。
|
||||
*/
|
||||
export function normalizeLeaveNotificationConfig(input: unknown): LeaveNotificationConfig {
|
||||
const raw = (input ?? {}) as Partial<LeaveNotificationConfig>
|
||||
const targetRaw = (raw.target ?? {}) as Partial<LeaveNotificationTarget>
|
||||
const allowed: LeaveNotificationTargetType[] = ['source_chat', 'self', 'file_transfer', 'contact']
|
||||
const type: LeaveNotificationTargetType = allowed.includes(
|
||||
targetRaw.type as LeaveNotificationTargetType
|
||||
)
|
||||
? (targetRaw.type as LeaveNotificationTargetType)
|
||||
: LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE
|
||||
const contactId = String(targetRaw.contactId ?? '').trim()
|
||||
// `contact` 但没有 id → 回落默认目标;宁可发到文件助手,也不能存一条必然失败的规则。
|
||||
const effectiveType: LeaveNotificationTargetType =
|
||||
type === 'contact' && !contactId ? LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE : type
|
||||
return {
|
||||
target: {
|
||||
type: effectiveType,
|
||||
...(effectiveType === 'contact' ? { contactId } : {})
|
||||
},
|
||||
template: normalizeLeaveNotificationTemplate(raw.template),
|
||||
// 用户手动保存一次即视为已确认目标,清除迁移提示。
|
||||
...(raw.targetNeedsReview === true ? { targetNeedsReview: true } : {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import {
|
||||
buildGroupExitNotificationValues,
|
||||
renderGroupExitNotificationTemplate,
|
||||
type GroupExitMonitorEvent
|
||||
} from './group-exit-monitor'
|
||||
|
||||
/**
|
||||
* GroupMemberExitedEvent —— 退群监控交给自动化消费的**稳定事件契约**。
|
||||
*
|
||||
* 为什么不让 Automation 直接吃 `GroupExitMonitorEvent`:
|
||||
* 后者是退群监控的**存储形态**(含 delta / message 展示串 / 历史通知状态),
|
||||
* 会随监控自身的演进而变。Automation 只需要「谁、在哪个群、什么时候、人数怎么变」,
|
||||
* 所以这里显式定义一份最小契约 + 一个纯映射函数。
|
||||
*
|
||||
* `eventId` 是**唯一键**,直接复用退群记录自己的 id(`GroupExitMonitorEvent.id`)——
|
||||
* 不允许用昵称 / 群名 / 显示文本做唯一键。
|
||||
*/
|
||||
|
||||
export interface GroupMemberExitedEvent {
|
||||
/** 稳定事件 id(= 退群记录的 id)。Automation 侧幂等以它为准。 */
|
||||
eventId: string
|
||||
/** 发生退群的群(`xxx@chatroom`)。`source_chat` 目标就是它。 */
|
||||
conversationId: string
|
||||
/** 群显示名(用户可读,用于日志/展示,**不是**唯一键)。 */
|
||||
groupName?: string
|
||||
/** 成员在本群的备注。 */
|
||||
groupRemark?: string
|
||||
/** 退群成员的稳定 id(wxid)。唯一键之一,但**不进用户可见日志**。 */
|
||||
memberId: string
|
||||
/** 成员显示名(用户可读)。 */
|
||||
memberName?: string
|
||||
/** 联系人表里的微信昵称。 */
|
||||
wechatNickname?: string
|
||||
/** 通讯录备注。 */
|
||||
contactRemark?: string
|
||||
previousCount: number
|
||||
currentCount: number
|
||||
/** 事件发生时间(epoch ms)。 */
|
||||
occurredAt: number
|
||||
}
|
||||
|
||||
/** 纯映射:退群记录 → 自动化事件。 */
|
||||
export function toGroupMemberExitedEvent(event: GroupExitMonitorEvent): GroupMemberExitedEvent {
|
||||
const groupName = String(event.groupName || '').trim()
|
||||
const groupRemark = String(event.groupRemark || '').trim()
|
||||
const memberName = String(event.memberName || '').trim()
|
||||
const wechatNickname = String(event.wechatName || '').trim()
|
||||
const contactRemark = String(event.contactRemark || '').trim()
|
||||
return {
|
||||
eventId: String(event.id || '').trim(),
|
||||
conversationId: String(event.roomId || '').trim(),
|
||||
...(groupName ? { groupName } : {}),
|
||||
...(groupRemark ? { groupRemark } : {}),
|
||||
memberId: String(event.memberWxid || '').trim(),
|
||||
...(memberName ? { memberName } : {}),
|
||||
...(wechatNickname ? { wechatNickname } : {}),
|
||||
...(contactRemark ? { contactRemark } : {}),
|
||||
previousCount: Number(event.previousCount) || 0,
|
||||
currentCount: Number(event.currentCount) || 0,
|
||||
occurredAt: Number(event.detectedAt) || 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染退群通知文本。
|
||||
*
|
||||
* **复用**退群监控那份唯一的插值实现(`renderGroupExitNotificationTemplate`)——
|
||||
* 迁移不允许产生第二套模板 regex,否则预览与实发迟早不一致。
|
||||
*/
|
||||
export function renderLeaveNotificationText(
|
||||
event: GroupMemberExitedEvent,
|
||||
template: string
|
||||
): string {
|
||||
return renderGroupExitNotificationTemplate(
|
||||
template,
|
||||
buildGroupExitNotificationValues({
|
||||
groupName: event.groupName,
|
||||
wechatNickname: event.wechatNickname,
|
||||
memberName: event.memberName,
|
||||
memberId: event.memberId,
|
||||
groupRemark: event.groupRemark,
|
||||
previousCount: event.previousCount,
|
||||
currentCount: event.currentCount,
|
||||
occurredAt: event.occurredAt
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* **只服务效果预览**的样本事件。
|
||||
*
|
||||
* 它永远不会进入发送路径:渲染层拿它把模板渲染出来给用户看。
|
||||
* 时间取"此刻",所以预览里显示的是当前时间,而不是一个伪造的历史日期。
|
||||
* 集中定义在这里,避免散落的假数据被误当成真实事件。
|
||||
*
|
||||
* ⚠️ **样本必须与真实数据同形**,否则预览会骗人:
|
||||
* `groupRemark` 是「退群成员**在本群的昵称**」(真实来源 `member.groupNickname`),
|
||||
* 不是群名;群名是 `groupName`。两者取不同的值,区别才看得出来。
|
||||
*/
|
||||
export function createGroupExitPreviewSample(now: number): GroupMemberExitedEvent {
|
||||
return {
|
||||
eventId: 'preview-sample',
|
||||
conversationId: 'preview@chatroom',
|
||||
groupName: 'TraceMemo 交流群',
|
||||
// 成员在本群的昵称:刻意与 groupName 取不同的值,一眼能看出两者不是一回事。
|
||||
groupRemark: '小张',
|
||||
// 明确是占位符,**不要**长得像真实账号 —— 预览里的 {wxid} 不是任何人的 wxid。
|
||||
memberId: 'wxid_xxxxx',
|
||||
memberName: '张三',
|
||||
wechatNickname: '张三',
|
||||
previousCount: 243,
|
||||
currentCount: 242,
|
||||
occurredAt: now
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { WechatActionResult } from './wechat-action'
|
||||
|
||||
export interface GroupExitMonitorMember {
|
||||
wxid: string
|
||||
nickname?: string
|
||||
@@ -9,23 +7,6 @@ export interface GroupExitMonitorMember {
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
export type GroupExitNotificationStatus =
|
||||
| 'not_requested'
|
||||
| 'pending'
|
||||
| 'sent'
|
||||
| 'blocked'
|
||||
| 'failed'
|
||||
|
||||
export interface GroupExitNotificationState {
|
||||
status: GroupExitNotificationStatus
|
||||
actionId?: string
|
||||
decision?: WechatActionResult['decision']
|
||||
errorCode?: string
|
||||
reason?: string
|
||||
startedAt?: string
|
||||
finishedAt?: string
|
||||
}
|
||||
|
||||
export interface GroupExitMonitorEvent {
|
||||
id: string
|
||||
contactId: string
|
||||
@@ -44,9 +25,6 @@ export interface GroupExitMonitorEvent {
|
||||
delta: number
|
||||
message: string
|
||||
detectedAt: number
|
||||
/** 可选通知的结果;退群检测与通知发送彼此独立。 */
|
||||
notificationStatus?: GroupExitNotificationStatus
|
||||
notification?: GroupExitNotificationState
|
||||
}
|
||||
|
||||
const LEGACY_GROUP_EXIT_NOTIFICATION_TEMPLATE = [
|
||||
@@ -65,6 +43,8 @@ const LEGACY_GROUP_EXIT_NOTIFICATION_TEMPLATE = [
|
||||
export const GROUP_EXIT_NOTIFICATION_TEMPLATE = [
|
||||
'[退群监测]',
|
||||
'',
|
||||
'群聊: {groupName}',
|
||||
'',
|
||||
'用户: {user}',
|
||||
'',
|
||||
'群备注: {groupRemark}',
|
||||
@@ -78,6 +58,9 @@ export const GROUP_EXIT_NOTIFICATION_TEMPLATE = [
|
||||
|
||||
export const GROUP_EXIT_NOTIFICATION_TEMPLATE_MAX_LENGTH = 2_000
|
||||
export const GROUP_EXIT_NOTIFICATION_TEMPLATE_PLACEHOLDERS = [
|
||||
// 群名排在最前:通知一旦发给「文件传输助手 / 自己 / 指定好友」,
|
||||
// 收件人第一件要知道的事就是**哪个群**退的人。
|
||||
'groupName',
|
||||
'user',
|
||||
'groupRemark',
|
||||
'wxid',
|
||||
@@ -86,6 +69,26 @@ export const GROUP_EXIT_NOTIFICATION_TEMPLATE_PLACEHOLDERS = [
|
||||
'time'
|
||||
] as const
|
||||
|
||||
/**
|
||||
* 每个变量的**中文含义**(编辑器悬停提示用)。
|
||||
*
|
||||
* 为什么必须有:变量清单原先只有 `{groupRemark}` 这种符号,用户看不出含义 ——
|
||||
* 实测有人把 `{groupRemark}` 当成"群名"(它其实是**成员在本群的昵称**),
|
||||
* 于是以为通知里已经有群名了。这类误会只能靠把含义写出来消除。
|
||||
*/
|
||||
export const GROUP_EXIT_NOTIFICATION_PLACEHOLDER_LABELS: Record<
|
||||
(typeof GROUP_EXIT_NOTIFICATION_TEMPLATE_PLACEHOLDERS)[number],
|
||||
string
|
||||
> = {
|
||||
groupName: '群聊名(发生退群的群)',
|
||||
user: '退群成员的显示名',
|
||||
groupRemark: '退群成员在本群的昵称(不是群名)',
|
||||
wxid: '成员的微信号',
|
||||
previousCount: '退群前人数',
|
||||
currentCount: '退群后人数',
|
||||
time: '退群时间'
|
||||
}
|
||||
|
||||
export interface GroupExitNotificationTemplateValidation {
|
||||
valid: boolean
|
||||
template?: string
|
||||
@@ -134,26 +137,20 @@ export function formatGroupExitMonitorTime(timestamp: number): string {
|
||||
)}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
/** 根据模板生成通知文本。 */
|
||||
export function renderGroupExitMonitorNotification(
|
||||
event: GroupExitMonitorEvent,
|
||||
template = GROUP_EXIT_NOTIFICATION_TEMPLATE
|
||||
/**
|
||||
* 模板插值的**唯一实现**。
|
||||
*
|
||||
* 退群监控的「复制退群信息」与自动化的「退群通知」都走这里 ——
|
||||
* 迁移不允许产生第二套 regex,否则预览与实际发送迟早不一致。
|
||||
*/
|
||||
export function renderGroupExitNotificationTemplate(
|
||||
template: string,
|
||||
values: GroupExitNotificationValues
|
||||
): string {
|
||||
const user =
|
||||
event.wechatName?.trim() || event.memberName?.trim() || event.memberWxid || '未读取到'
|
||||
const groupRemark = event.groupRemark?.trim() || '未设置'
|
||||
const wxid = event.memberWxid?.trim() || '未读取到'
|
||||
const values = {
|
||||
user,
|
||||
groupRemark,
|
||||
wxid,
|
||||
previousCount: String(event.previousCount),
|
||||
currentCount: String(event.currentCount),
|
||||
time: formatGroupExitMonitorTime(event.detectedAt)
|
||||
}
|
||||
return normalizeGroupExitNotificationTemplate(template).replace(
|
||||
/\{(user|groupRemark|wxid|previousCount|currentCount|time)\}/g,
|
||||
/\{(groupName|user|groupRemark|wxid|previousCount|currentCount|time)\}/g,
|
||||
(placeholder) => {
|
||||
if (placeholder === '{groupName}') return values.groupName
|
||||
if (placeholder === '{user}') return values.user
|
||||
if (placeholder === '{groupRemark}') return values.groupRemark
|
||||
if (placeholder === '{wxid}') return values.wxid
|
||||
@@ -164,12 +161,64 @@ export function renderGroupExitMonitorNotification(
|
||||
)
|
||||
}
|
||||
|
||||
/** 主进程中的辅助函数,供生成通知和预览时共用。 */
|
||||
export function buildMemberLeftNotification(
|
||||
export interface GroupExitNotificationValues {
|
||||
/** 发生退群的**群显示名**(含群备注)。 */
|
||||
groupName: string
|
||||
/** 退群成员的显示名(微信名 → 群昵称 → 微信号 依次回退)。 */
|
||||
user: string
|
||||
/** 退群成员**在本群的昵称**。⚠️ 不是群名 —— 群名是 `groupName`。 */
|
||||
groupRemark: string
|
||||
wxid: string
|
||||
previousCount: string
|
||||
currentCount: string
|
||||
time: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 变量取值的**唯一实现**,含全部 fallback 规则。
|
||||
*
|
||||
* ⚠️ 这些 fallback 是历史产品行为(`未读取到` / `未设置`),迁移**不得**改变输出:
|
||||
* 退群监控与自动化都从这里取值,所以不存在"两处 fallback 漂移"的可能。
|
||||
*/
|
||||
export function buildGroupExitNotificationValues(input: {
|
||||
groupName?: string
|
||||
wechatNickname?: string
|
||||
memberName?: string
|
||||
memberId?: string
|
||||
groupRemark?: string
|
||||
previousCount: number
|
||||
currentCount: number
|
||||
occurredAt: number
|
||||
}): GroupExitNotificationValues {
|
||||
return {
|
||||
groupName: input.groupName?.trim() || '未读取到',
|
||||
user: input.wechatNickname?.trim() || input.memberName?.trim() || input.memberId || '未读取到',
|
||||
groupRemark: input.groupRemark?.trim() || '未设置',
|
||||
wxid: input.memberId?.trim() || '未读取到',
|
||||
previousCount: String(input.previousCount),
|
||||
currentCount: String(input.currentCount),
|
||||
time: formatGroupExitMonitorTime(input.occurredAt)
|
||||
}
|
||||
}
|
||||
|
||||
/** 根据模板生成通知文本(退群监控侧入口,保持既有签名与输出)。 */
|
||||
export function renderGroupExitMonitorNotification(
|
||||
event: GroupExitMonitorEvent,
|
||||
template = GROUP_EXIT_NOTIFICATION_TEMPLATE
|
||||
): string {
|
||||
return renderGroupExitMonitorNotification(event, template)
|
||||
return renderGroupExitNotificationTemplate(
|
||||
template,
|
||||
buildGroupExitNotificationValues({
|
||||
groupName: event.groupName,
|
||||
wechatNickname: event.wechatName,
|
||||
memberName: event.memberName,
|
||||
memberId: event.memberWxid,
|
||||
groupRemark: event.groupRemark,
|
||||
previousCount: event.previousCount,
|
||||
currentCount: event.currentCount,
|
||||
occurredAt: event.detectedAt
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
export interface GroupExitMonitorState {
|
||||
@@ -185,10 +234,6 @@ export interface GroupExitMonitorState {
|
||||
monitorSelectionConfigured?: boolean
|
||||
/** 管理页选中的群。 */
|
||||
monitoredRoomIds?: string[]
|
||||
/** 需要发送通知的群。 */
|
||||
notificationRoomIds?: string[]
|
||||
/** 自动通知模板。 */
|
||||
notificationTemplate?: string
|
||||
lastCheckedAt?: number
|
||||
lastReadAt: number
|
||||
unreadCount: number
|
||||
@@ -219,3 +264,31 @@ export function findRemovedGroupMembers(
|
||||
seen.add(member.wxid)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `群聊: {groupName}` 补进一份**已有**模板。
|
||||
*
|
||||
* 放在 shared 而不是 main:主进程的模板升级迁移要用它,
|
||||
* 编辑器的「一键补上群聊名」也要用它 —— 只允许有一份实现。
|
||||
*
|
||||
* 三条约束:
|
||||
* 1. **幂等**:已经含 `{groupName}` 就原样返回;
|
||||
* 2. **不破坏用户内容**:只在标题行后插入一行,其余文本与顺序一字不动;
|
||||
* 3. 调用方负责"只补一次"—— 否则用户删掉这一行后重启它又回来,
|
||||
* 那种"删不掉"的行为比缺失信息更糟。
|
||||
*/
|
||||
export function insertGroupNamePlaceholder(template: string): string {
|
||||
const normalized = String(template ?? '').replace(/\r\n?/g, '\n')
|
||||
if (!normalized.trim()) return template
|
||||
if (normalized.includes('{groupName}')) return template
|
||||
|
||||
const lines = normalized.split('\n')
|
||||
const titleIndex = lines.findIndex((line) => line.trim())
|
||||
// 首行是标题(`[退群监测]` 这类)就插在它后面,否则插到最前面。
|
||||
const insertAt = titleIndex >= 0 && lines[titleIndex].trim().startsWith('[') ? titleIndex + 1 : 0
|
||||
// 前后各留一个空行(与标题、与下文都分开);紧随其后的多余空行由下面的压缩处理掉。
|
||||
return [...lines.slice(0, insertAt), '', '群聊: {groupName}', '', ...lines.slice(insertAt)]
|
||||
.join('\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim()
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
export type WechatActionOrigin =
|
||||
/**
|
||||
* 退群监控历史发送用的来源。
|
||||
*
|
||||
* 迁移后**没有任何生产者**了(退群监控不再自己发送)。保留它只为两件事:
|
||||
* 让磁盘上的历史 audit 记录仍能正常显示,以及让类型仍是穷举的。
|
||||
*/
|
||||
| 'member_monitor'
|
||||
| 'scheduled_report'
|
||||
| 'user_tts'
|
||||
@@ -10,12 +16,19 @@ export type WechatActionOrigin =
|
||||
* 也不进 Send Log —— 排查「消息到底发没发出去」时会缺一份证据。
|
||||
*/
|
||||
| 'user_manual'
|
||||
/** Automation v1(@我生成日报)。与 `shared/automation.ts` 的 AUTOMATION_SEND_ORIGIN 一致。 */
|
||||
/** Automation(@我生成日报 / 退群通知)。与 `shared/automation.ts` 的 AUTOMATION_SEND_ORIGIN 一致。 */
|
||||
| 'automation'
|
||||
| 'unknown'
|
||||
| (string & {})
|
||||
|
||||
export type WechatActionPurpose =
|
||||
/**
|
||||
* 历史用途:退群监控自己发通知。
|
||||
*
|
||||
* 迁移后**没有任何生产者**,也已从 `AUTOMATION_PURPOSE_ALLOWLIST` 摘除 ——
|
||||
* 即"旧链路在代码上已经不可能再发出去"。保留类型成员只为让历史 audit 记录可读
|
||||
* (界面仍把它显示成「退群通知」)。
|
||||
*/
|
||||
| 'member_left_notification'
|
||||
| 'scheduled_report'
|
||||
| 'tts_voice'
|
||||
@@ -28,14 +41,16 @@ export type WechatActionPurpose =
|
||||
/** 日报图片成功后的后置词;只有图片 sent 后才会创建。 */
|
||||
| 'manual_report_postfix'
|
||||
/**
|
||||
* Automation v1 的两个用途。
|
||||
* Automation 的三个用途。
|
||||
*
|
||||
* ⚠️ 这两个值必须同步登记进 `wechat-action-gateway.ts` 的
|
||||
* ⚠️ 这三个值必须同步登记进 `wechat-action-gateway.ts` 的
|
||||
* `AUTOMATION_PURPOSE_ALLOWLIST`,否则会被策略层以 `ACTION_NOT_ALLOWED` 拦下。
|
||||
* 与 `shared/automation.ts` 的 `AUTOMATION_SEND_PURPOSE` 保持一致。
|
||||
*/
|
||||
| 'automation_reply'
|
||||
| 'automation_report'
|
||||
/** 退群通知(由 Automation 发出)。目标可以是群 / 自己 / 文件传输助手 / 指定好友。 */
|
||||
| 'automation_leave_notification'
|
||||
| (string & {})
|
||||
|
||||
export type WechatActionTriggerType = 'automation' | 'user'
|
||||
@@ -99,11 +114,6 @@ export interface PolicyDecision {
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export interface WechatActionMemberEventReference {
|
||||
id: string
|
||||
roomId: string
|
||||
}
|
||||
|
||||
export interface WechatActionAuditRecord {
|
||||
actionId: string
|
||||
idempotencyKey?: string
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* 微信协议层的**固定身份**。
|
||||
*
|
||||
* 为什么要有这个文件:这些值不是「昵称」,是协议里写死的 username。
|
||||
* 用昵称去搜索(`nickname === '文件传输助手'`)在改过备注、多语言、
|
||||
* 或同名联系人存在时会直接选错发送对象 —— 而发错人是不可撤销的。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 文件传输助手。
|
||||
*
|
||||
* 微信客户端的固定 username,不随账号语言、昵称、备注变化。
|
||||
* **真机核对项**:需在真机实测一次。
|
||||
*/
|
||||
export const WECHAT_FILE_HELPER_USERNAME = 'filehelper'
|
||||
|
||||
export function isFileHelperUsername(value: string | undefined | null): boolean {
|
||||
return String(value || '').trim().toLowerCase() === WECHAT_FILE_HELPER_USERNAME
|
||||
}
|
||||
Reference in new issue
Block a user