mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 新增拓展中心功能, 提供 关键词回复 去水印模板
This commit is contained in:
1 parent
aca103cb96
commit
b9ad4e1d71
85 files changed
+14750
-106
No files matched your search
@@ -0,0 +1,116 @@
|
||||
# 关键词回复机器人
|
||||
|
||||
监听微信文本消息,按规则表匹配关键词,命中后经 TraceMemo Gateway 回复。
|
||||
|
||||
两条入口共用同一份配置与同一套判定(`lib/matcher.js`):
|
||||
|
||||
- `message.received` 事件:扩展自己判断范围与冷却,再调用 `tm.wechat.send`;
|
||||
- 自动化动作 `keyword.reply`:只返回回复文本,不发送,发送由宿主的自动化流程完成。
|
||||
|
||||
扩展本身不碰 socket、dylib 或 HTTP,所有发送都经过宿主 Gateway 的权限、授权校验、限流与审计。
|
||||
|
||||
## 目录
|
||||
|
||||
```text
|
||||
keyword-bot/
|
||||
manifest.json 权限、订阅、页面与自动化动作声明
|
||||
background/index.js 事件编排、冷却表、命中统计
|
||||
lib/matcher.js 纯函数:规范化 / 匹配 / 范围 / 模板 / 决策
|
||||
ui/ 配置页(沙箱 iframe,只调用 storage.* / capabilities.get / extension.info)
|
||||
tests/matcher.test.mjs
|
||||
```
|
||||
|
||||
## 功能
|
||||
|
||||
- 规则支持三种匹配方式:`contains`(包含)、`exact`(完全匹配)、`prefix`(以…开头),均不区分大小写;
|
||||
- 每条规则可单独启用/停用,并设置优先级与冷却;
|
||||
- 监听范围可按群限定,可开关私聊,可要求真正 @ 我;
|
||||
- 回复内容支持模板变量;
|
||||
- 配置页展示今日命中数与最近 5 条命中结果。
|
||||
|
||||
## 配置字段
|
||||
|
||||
顶层:
|
||||
|
||||
| 字段 | 类型 | 默认 | 说明 |
|
||||
| ------------------------ | -------- | ------- | ----------------------------------------- |
|
||||
| `configVersion` | number | `2` | 保存时写入;v1(无此字段)读取时自动迁移 |
|
||||
| `enabled` | boolean | `false` | 总开关。缺省关闭,避免安装后立即对外发送 |
|
||||
| `rules` | array | `[]` | 规则表,见下 |
|
||||
| `scope.groups` | string[] | `[]` | 群 id(`xxx@chatroom`);空数组表示全部群 |
|
||||
| `scope.includeDirect` | boolean | `true` | 是否处理私聊 |
|
||||
| `scope.requireMentionMe` | boolean | `false` | 是否只处理真正 @ 登录账号的消息 |
|
||||
|
||||
规则:
|
||||
|
||||
| 字段 | 类型 | 默认 | 约束 |
|
||||
| ----------------- | ------- | ------------- | ------------------------------------------- |
|
||||
| `id` | string | `rule-<序号>` | ≤ 64 字符;冷却键的一部分,尽量稳定 |
|
||||
| `keyword` | string | `''` | ≤ 120 字符;启用中为空的规则会被丢弃 |
|
||||
| `mode` | string | `contains` | `contains` / `exact` / `prefix` |
|
||||
| `reply` | string | `''` | ≤ 2000 字符;启用中为空的规则会被丢弃 |
|
||||
| `cooldownSeconds` | number | `0` | 0–3600,取整到秒 |
|
||||
| `enabled` | boolean | `true` | v1 规则迁移后为 `true`;显式 `false` 才停用 |
|
||||
| `priority` | number | `0` | 0–100 整数,越大越先匹配 |
|
||||
|
||||
配置页保存时只校验**启用中**的规则必须有 `keyword` 与 `reply`;停用的规则允许留空,方便先存草稿。
|
||||
|
||||
## 模板变量
|
||||
|
||||
| 变量 | 含义 |
|
||||
| ----------- | -------------------------------------------------------------------------- |
|
||||
| `{sender}` | 发送者昵称;为空时渲染为「你」。自动化动作路径没有发送者上下文,恒为「你」 |
|
||||
| `{keyword}` | 命中的关键词(规则里的原文) |
|
||||
| `{time}` | 当前本地时间 `HH:mm` |
|
||||
|
||||
未知变量(例如 `{group}`)原样保留,不会被静默删除。渲染结果 trim 后截断到 2000 字符。
|
||||
|
||||
## 优先级与冷却语义
|
||||
|
||||
- 只考虑 `enabled !== false` 的规则;按 `priority` 降序排列,同优先级保持规则在数组中的顺序;
|
||||
- 取**第一个**命中的规则,一条消息最多回复一次(stopOnMatch),不会叠加多条回复;
|
||||
- 冷却键是 `conversationId:ruleId`,即「同一会话 + 同一条规则」各自独立计时;
|
||||
- 冷却只在**发送成功后**写入:发送失败不占用冷却,下一条命中会立刻重试;
|
||||
- 冷却表只存在内存里,扩展进程重启后清空——宁可多回一条,也不跨重启误拦。
|
||||
|
||||
## 统计口径与隐私边界
|
||||
|
||||
存储键 `stats`,结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"dateKey": "2026-11-12",
|
||||
"todayCount": 3,
|
||||
"lastHits": [{ "at": 0, "ruleId": "rule-1", "ok": true }]
|
||||
}
|
||||
```
|
||||
|
||||
- 每条命中记一条,**成功和失败都记**;`todayCount` 统计的是命中的次数(含发送失败);
|
||||
- `lastHits` 最多保留 20 条,配置页只展示最近 5 条;`at` 是 epoch 毫秒;
|
||||
- 跨日后读取会把 `todayCount` 归零,`lastHits` 作为滚动历史保留;
|
||||
- 只记录规则 id、时间与发送结果,**不记录会话 id、消息正文、发送者昵称或群名**;
|
||||
- 统计写入失败只打 warn 日志,不影响回复;
|
||||
- 统计只覆盖事件自动回复,不包含自动化动作 `keyword.reply` 的调用。
|
||||
|
||||
## 测试
|
||||
|
||||
零依赖,Node 内置测试运行器,不安装任何包:
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
|
||||
node --check examples/extensions/keyword-bot/lib/matcher.js
|
||||
node --check examples/extensions/keyword-bot/background/index.js
|
||||
node --check examples/extensions/keyword-bot/ui/app.js
|
||||
```
|
||||
|
||||
用例覆盖:三种匹配方式、大小写、空关键词、禁用规则、优先级与稳定性、群范围与私聊开关、@ 要求、自己发的消息、冷却中/过期、模板替换与未知变量、超长截断、v1 迁移、非法规则丢弃、数值越界收敛、决策顺序。
|
||||
|
||||
`tests/matcher.test.mjs` 中的 fixture 全部为占位数据(`张三`、`李四`、`测试群`、`fixture-room@chatroom`、`wxid_fixture`)。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 不回复自己发送的消息(`isSelf` 直接跳过);
|
||||
- 消息事件是「至多一次」投递:扩展进程重启的瞬间可能丢事件,没有补投队列;
|
||||
- 不读取群名,因此没有 `{group}` 变量;需要按群定制时请拆成多条规则并配合「监听范围」;
|
||||
- 配置缓存窗口为 1 秒,保存后最多 1 秒生效;
|
||||
- 冷却表与配置缓存都在扩展后台进程内存中,进程重启即丢失。
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* 关键词回复机器人。
|
||||
*
|
||||
* 两条入口共用同一份配置与 `lib/matcher.js` 的同一套判定:
|
||||
* 1. `message.received` 事件 → 自己判断范围 / 冷却 → `tm.wechat.send`;
|
||||
* 2. 自动化动作 `keyword.reply` → 只返回回复内容,由宿主 Gateway 发送。
|
||||
*
|
||||
* 发送**永远**经过宿主:本文件里没有任何 socket、dylib 或 HTTP 调用。
|
||||
* 匹配/规范化逻辑全部在 `lib/matcher.js`,本文件只负责编排与统计。
|
||||
*/
|
||||
|
||||
const { normalizeConfig, pickRule, renderReply, shouldReply } = require('../lib/matcher.js')
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
/** 配置缓存窗口:配置页保存后最多 1 秒生效,避免每条消息都读一次 storage。 */
|
||||
const CONFIG_TTL_MS = 1000
|
||||
/** 最近命中记录上限;只保留规则 id、时间与结果,不保留任何会话内容。 */
|
||||
const STATS_HISTORY_LIMIT = 20
|
||||
/** 冷却表清理阈值:超过后剔除已过期项,避免长期运行无限增长。 */
|
||||
const COOLDOWN_PRUNE_SIZE = 500
|
||||
|
||||
let tm = null
|
||||
let cachedConfig = null
|
||||
let cachedAt = 0
|
||||
let cachedStats = null
|
||||
const cooldownUntil = new Map()
|
||||
/** 统计写入串行化:并发消息不互相覆盖 `stats` 快照。 */
|
||||
let statsChain = Promise.resolve()
|
||||
|
||||
function loadConfig() {
|
||||
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return Promise.resolve(cachedConfig)
|
||||
return Promise.resolve(tm.storage.get(CONFIG_KEY))
|
||||
.then((stored) => {
|
||||
cachedConfig = normalizeConfig(stored)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
})
|
||||
.catch((error) => {
|
||||
tm.log.warn(`读取配置失败,本次按未启用处理:${describeError(error)}`)
|
||||
// 读失败也要缓存一小段时间,避免每条消息都打一次失败日志。
|
||||
cachedConfig = normalizeConfig(null)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
})
|
||||
}
|
||||
|
||||
/** 本地时区的 `YYYY-MM-DD`,用于判定「今日」。 */
|
||||
function statsDateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
/** 本地时区的 `HH:mm`,模板变量 `{time}` 与统计展示共用。 */
|
||||
function formatClock(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${hour}:${minute}`
|
||||
}
|
||||
|
||||
function emptyStats(timestamp) {
|
||||
return { dateKey: statsDateKey(timestamp), todayCount: 0, lastHits: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化统计快照。
|
||||
*
|
||||
* 跨日后 `todayCount` 归零;`lastHits` 作为滚动历史保留(它记的是「最近命中」,
|
||||
* 不是「今日命中」)。任何字段缺失或类型不对都退化为空值,统计损坏不能影响回复。
|
||||
*/
|
||||
function normalizeStats(raw, timestamp) {
|
||||
const base = emptyStats(timestamp)
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base
|
||||
const lastHits = Array.isArray(raw.lastHits)
|
||||
? raw.lastHits
|
||||
.filter((hit) => hit && typeof hit === 'object')
|
||||
.map((hit) => ({
|
||||
at: Number(hit.at),
|
||||
ruleId: String(hit.ruleId == null ? '' : hit.ruleId).slice(0, 64),
|
||||
ok: hit.ok === true
|
||||
}))
|
||||
.filter((hit) => Number.isFinite(hit.at) && hit.at > 0 && hit.ruleId)
|
||||
.slice(-STATS_HISTORY_LIMIT)
|
||||
: []
|
||||
const sameDay = raw.dateKey === base.dateKey
|
||||
const count = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
|
||||
return { dateKey: base.dateKey, todayCount: count, lastHits }
|
||||
}
|
||||
|
||||
function loadStats() {
|
||||
if (cachedStats) return Promise.resolve(cachedStats)
|
||||
return Promise.resolve(tm.storage.get(STATS_KEY))
|
||||
.then((stored) => {
|
||||
cachedStats = normalizeStats(stored, Date.now())
|
||||
return cachedStats
|
||||
})
|
||||
.catch(() => {
|
||||
cachedStats = emptyStats(Date.now())
|
||||
return cachedStats
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加一条命中记录并落库。
|
||||
*
|
||||
* 成功与失败都记;只写 `ruleId` / `at` / `ok`,绝不写会话 id、正文或昵称。
|
||||
* 写失败只 warn:统计是旁路,不能因为 storage 异常把回复一起吞掉。
|
||||
*/
|
||||
function recordHit(ruleId, ok) {
|
||||
statsChain = statsChain
|
||||
.then(async () => {
|
||||
const stats = await loadStats()
|
||||
const now = Date.now()
|
||||
const dateKey = statsDateKey(now)
|
||||
if (stats.dateKey !== dateKey) {
|
||||
stats.dateKey = dateKey
|
||||
stats.todayCount = 0
|
||||
}
|
||||
stats.todayCount += 1
|
||||
stats.lastHits = stats.lastHits
|
||||
.concat({ at: now, ruleId: String(ruleId || '').slice(0, 64), ok: ok === true })
|
||||
.slice(-STATS_HISTORY_LIMIT)
|
||||
await tm.storage.set(STATS_KEY, stats)
|
||||
})
|
||||
.catch((error) => {
|
||||
tm.log.warn(`命中统计写入失败:${describeError(error)}`)
|
||||
})
|
||||
return statsChain
|
||||
}
|
||||
|
||||
/** 冷却只在真正发送成功后写入;发送失败不占冷却,下一条可以立刻重试。 */
|
||||
function markCooldown(conversationId, rule, timestamp) {
|
||||
const seconds = Number(rule.cooldownSeconds) || 0
|
||||
cooldownUntil.set(`${conversationId}:${rule.id}`, timestamp + seconds * 1000)
|
||||
if (cooldownUntil.size > COOLDOWN_PRUNE_SIZE) {
|
||||
for (const [key, until] of cooldownUntil) {
|
||||
if (until <= timestamp) cooldownUntil.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function describeError(error) {
|
||||
return error && error.message ? error.message : String(error)
|
||||
}
|
||||
|
||||
async function onMessage(event) {
|
||||
try {
|
||||
const config = await loadConfig()
|
||||
const now = Date.now()
|
||||
const verdict = shouldReply(event, config, cooldownUntil, now)
|
||||
if (!verdict.reply || !verdict.rule) return
|
||||
|
||||
const rule = verdict.rule
|
||||
const text = renderReply(rule.reply, {
|
||||
senderName: event.senderName,
|
||||
keyword: rule.keyword,
|
||||
time: formatClock(now)
|
||||
})
|
||||
|
||||
try {
|
||||
await tm.wechat.send({
|
||||
to: event.conversationId,
|
||||
text,
|
||||
// 同一条微信消息在补投/重启后 eventId 不变,交给 Gateway 幂等短路。
|
||||
dedupeKey: event.eventId
|
||||
})
|
||||
} catch (error) {
|
||||
await recordHit(rule.id, false)
|
||||
throw error
|
||||
}
|
||||
|
||||
markCooldown(event.conversationId, rule, Date.now())
|
||||
await recordHit(rule.id, true)
|
||||
tm.log.info(`关键词命中,已发送回复(规则 ${rule.id})`)
|
||||
} catch (error) {
|
||||
tm.log.error(`自动回复失败:${describeError(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function activate(api) {
|
||||
tm = api
|
||||
tm.events.on('message.received', onMessage)
|
||||
|
||||
tm.automation.registerAction({
|
||||
id: 'keyword.reply',
|
||||
title: '关键词回复',
|
||||
description: '按机器人配置匹配关键词并返回回复内容',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { text: { type: 'string' } },
|
||||
required: ['text']
|
||||
},
|
||||
async handler(input) {
|
||||
const config = await loadConfig()
|
||||
if (!config.enabled) {
|
||||
return { success: false, error: '机器人未启用' }
|
||||
}
|
||||
const rule = pickRule(input.text, config)
|
||||
if (!rule) {
|
||||
return { success: true, output: { matched: false } }
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
output: { matched: true, ruleId: rule.id },
|
||||
// 动作路径没有发送者上下文,`{sender}` 会渲染成「你」。
|
||||
reply: {
|
||||
type: 'text',
|
||||
text: renderReply(rule.reply, {
|
||||
keyword: rule.keyword,
|
||||
time: formatClock(Date.now())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
tm.log.info('关键词回复机器人已加载')
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 关键词回复的纯函数层:配置规范化、匹配、范围判定、模板渲染、决策。
|
||||
*
|
||||
* 契约:
|
||||
* - 全部函数无副作用、不读写 storage、不打印日志,便于单测与后台进程复用;
|
||||
* - 输入一律容忍 `undefined` / 错误类型,坏配置退化为「不回复」而不是抛错;
|
||||
* - `enabled` 在任何一层都是硬开关:配置损坏时不能自动对外发送。
|
||||
*/
|
||||
|
||||
/** 当前配置结构版本。v1 没有该字段,读取时按 v1 迁移。 */
|
||||
const CONFIG_VERSION = 2
|
||||
|
||||
/** 与 UI、宿主动作输出保持一致的长度上限(字符)。 */
|
||||
const MAX_RULE_ID_LENGTH = 64
|
||||
const MAX_KEYWORD_LENGTH = 120
|
||||
const MAX_REPLY_LENGTH = 2000
|
||||
const MAX_GROUPS = 200
|
||||
|
||||
const MODES = new Set(['contains', 'exact', 'prefix'])
|
||||
|
||||
/**
|
||||
* 把任意来源的配置规范化为 `configVersion: 2`。
|
||||
*
|
||||
* 启用中的空规则丢弃,停用的空规则保留为草稿;顶层 `enabled` 缺省 `false`,
|
||||
* 配置缺失或损坏时宁可静默,也不能自动群发。
|
||||
*
|
||||
* @param {unknown} raw storage 里读出的原始值
|
||||
*/
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const sourceRules = Array.isArray(input.rules) ? input.rules : []
|
||||
const rules = sourceRules
|
||||
.filter((rule) => rule && typeof rule === 'object' && !Array.isArray(rule))
|
||||
.map((rule, index) => ({
|
||||
id: String(rule.id || `rule-${index + 1}`).slice(0, MAX_RULE_ID_LENGTH),
|
||||
keyword: String(rule.keyword == null ? '' : rule.keyword).slice(0, MAX_KEYWORD_LENGTH),
|
||||
mode: MODES.has(rule.mode) ? rule.mode : 'contains',
|
||||
reply: String(rule.reply == null ? '' : rule.reply).slice(0, MAX_REPLY_LENGTH),
|
||||
cooldownSeconds: clampNumber(rule.cooldownSeconds, 0, 3600),
|
||||
// v1 规则没有该字段;只有显式 false 才算禁用。
|
||||
enabled: rule.enabled !== false,
|
||||
priority: clampNumber(rule.priority, 0, 100)
|
||||
}))
|
||||
.filter((rule) => rule.enabled === false || (rule.keyword.trim() && rule.reply.trim()))
|
||||
|
||||
const scope = input.scope && typeof input.scope === 'object' ? input.scope : {}
|
||||
return {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: input.enabled === true,
|
||||
rules,
|
||||
scope: {
|
||||
groups: Array.isArray(scope.groups)
|
||||
? scope.groups
|
||||
.map((id) => String(id == null ? '' : id).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, MAX_GROUPS)
|
||||
: [],
|
||||
includeDirect: scope.includeDirect !== false,
|
||||
requireMentionMe: scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条规则是否命中文本:大小写不敏感;`exact` / `prefix` 先 trim,
|
||||
* `contains` 只 trim 关键词;空关键词恒为 false。
|
||||
*
|
||||
* @param {unknown} text 消息正文
|
||||
* @param {{ keyword?: unknown, mode?: unknown }} rule
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function matchRule(text, rule) {
|
||||
const keyword = String((rule && rule.keyword) == null ? '' : rule.keyword)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (!keyword) return false
|
||||
const haystack = String(text == null ? '' : text).toLowerCase()
|
||||
const mode = rule && MODES.has(rule.mode) ? rule.mode : 'contains'
|
||||
if (mode === 'exact') return haystack.trim() === keyword
|
||||
if (mode === 'prefix') return haystack.trim().startsWith(keyword)
|
||||
return haystack.includes(keyword)
|
||||
}
|
||||
|
||||
/**
|
||||
* 选出唯一命中的规则:`priority` 降序、同优先级保持数组顺序,取第一个命中。
|
||||
*
|
||||
* 这就是 stopOnMatch 语义:一条消息最多回复一次,命中即停。
|
||||
* 禁用规则(`enabled === false`)不参与匹配。
|
||||
*
|
||||
* @param {unknown} text
|
||||
* @param {object} config normalizeConfig 的产物
|
||||
*/
|
||||
function pickRule(text, config) {
|
||||
const rules = config && Array.isArray(config.rules) ? config.rules : []
|
||||
const candidates = rules
|
||||
.map((rule, index) => ({ rule, index }))
|
||||
.filter((item) => item.rule && item.rule.enabled !== false)
|
||||
// 显式带下标排序,避免依赖引擎排序稳定性。
|
||||
.sort((a, b) => (b.rule.priority || 0) - (a.rule.priority || 0) || a.index - b.index)
|
||||
for (const item of candidates) {
|
||||
if (matchRule(text, item.rule)) return item.rule
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话是否在生效范围内。
|
||||
*
|
||||
* - 群聊:`groups` 为空表示全部群;非空时必须包含 `event.conversationId`;
|
||||
* - 私聊:只看 `includeDirect`。
|
||||
*
|
||||
* 范围在规则匹配之前判定:范围外的会话连匹配都不做,避免误触统计。
|
||||
*/
|
||||
function inScope(event, config) {
|
||||
const scope = (config && config.scope) || {}
|
||||
if (event && event.isGroup) {
|
||||
const groups = Array.isArray(scope.groups) ? scope.groups : []
|
||||
return groups.length === 0 || groups.includes(event.conversationId)
|
||||
}
|
||||
return scope.includeDirect !== false
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染回复模板。
|
||||
*
|
||||
* 支持 `{sender}`(发送者昵称,空则「你」)、`{keyword}`(命中关键词)、
|
||||
* `{time}`(调用方给的本地时间字符串,缺省空串)。未知 `{xxx}` 原样保留,
|
||||
* 方便用户在模板里写其它占位而不是被静默吃掉。结果 trim 后截断到 2000 字符。
|
||||
*/
|
||||
function renderReply(template, ctx) {
|
||||
const source = String(template == null ? '' : template)
|
||||
const context = ctx && typeof ctx === 'object' ? ctx : {}
|
||||
const sender = String(context.senderName == null ? '' : context.senderName).trim() || '你'
|
||||
const keyword = String(context.keyword == null ? '' : context.keyword)
|
||||
const time = String(context.time == null ? '' : context.time)
|
||||
const rendered = source.replace(/\{(sender|keyword|time)\}/g, (match, token) => {
|
||||
if (token === 'sender') return sender
|
||||
if (token === 'keyword') return keyword
|
||||
if (token === 'time') return time
|
||||
return match
|
||||
})
|
||||
return rendered.trim().slice(0, MAX_REPLY_LENGTH)
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合决策:是否回复、用哪条规则、为什么。
|
||||
*
|
||||
* `reason` 取值固定,可直接用于日志/统计口径:
|
||||
* `disabled` | `self` | `type` | `scope` | `mention` | `no_match` | `cooldown` | `ok`。
|
||||
*
|
||||
* 判断顺序固定为:总开关 → 自己发的 → 消息类型 → 会话范围 → @ 要求 → 规则匹配 → 冷却。
|
||||
* 冷却键为 `conversationId:ruleId`,值为到期时间戳(epoch 毫秒),`now < until` 即冷却中。
|
||||
* 冷却表允许是 `Map` 或普通对象,后台进程重启后自然清空(宁可多回一条,也不跨重启误拦)。
|
||||
*
|
||||
* @param {object} event 宿主的 message.received 事件
|
||||
* @param {object} config normalizeConfig 的产物
|
||||
* @param {Map<string, number>|Record<string, number>} [cooldownUntil]
|
||||
* @param {number} [now] epoch 毫秒,缺省取当前时间
|
||||
*/
|
||||
function shouldReply(event, config, cooldownUntil, now) {
|
||||
if (!config || config.enabled !== true) {
|
||||
return { reply: false, rule: null, reason: 'disabled' }
|
||||
}
|
||||
if (!event || event.isSelf === true) {
|
||||
return { reply: false, rule: null, reason: 'self' }
|
||||
}
|
||||
if (event.type !== 'text') {
|
||||
return { reply: false, rule: null, reason: 'type' }
|
||||
}
|
||||
if (!inScope(event, config)) {
|
||||
return { reply: false, rule: null, reason: 'scope' }
|
||||
}
|
||||
if (config.scope && config.scope.requireMentionMe === true && event.mentionsMe !== true) {
|
||||
return { reply: false, rule: null, reason: 'mention' }
|
||||
}
|
||||
const rule = pickRule(event.text, config)
|
||||
if (!rule) {
|
||||
return { reply: false, rule: null, reason: 'no_match' }
|
||||
}
|
||||
const currentTime = Number.isFinite(now) ? now : Date.now()
|
||||
const key = `${event.conversationId}:${rule.id}`
|
||||
if (currentTime < readCooldown(cooldownUntil, key)) {
|
||||
return { reply: false, rule: null, reason: 'cooldown' }
|
||||
}
|
||||
return { reply: true, rule, reason: 'ok' }
|
||||
}
|
||||
|
||||
/** 冷却表读取:兼容 Map 与普通对象,缺失值按 0(永不冷却)。 */
|
||||
function readCooldown(table, key) {
|
||||
if (!table) return 0
|
||||
const value = table instanceof Map ? table.get(key) : table[key]
|
||||
const until = Number(value)
|
||||
return Number.isFinite(until) ? until : 0
|
||||
}
|
||||
|
||||
/** 收敛到 [min, max] 的整数;非数字 / NaN 一律当 0。 */
|
||||
function clampNumber(value, min, max) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return 0
|
||||
return Math.min(Math.max(Math.round(numeric), min), max)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CONFIG_VERSION,
|
||||
normalizeConfig,
|
||||
matchRule,
|
||||
pickRule,
|
||||
inScope,
|
||||
renderReply,
|
||||
shouldReply
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.keyword-bot",
|
||||
"name": "关键词回复机器人",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.subscribe",
|
||||
"contacts.list",
|
||||
"wechat.send.text",
|
||||
"storage",
|
||||
"automation.action"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": ["text"],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": false,
|
||||
"includeSelf": false
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "settings",
|
||||
"title": "机器人配置"
|
||||
}
|
||||
],
|
||||
"automationActions": [
|
||||
{
|
||||
"id": "keyword.reply",
|
||||
"title": "关键词回复",
|
||||
"description": "按机器人配置匹配关键词并返回回复内容"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import matcher from '../lib/matcher.js'
|
||||
|
||||
const { normalizeConfig, matchRule, pickRule, inScope, renderReply, shouldReply } = matcher
|
||||
|
||||
const GROUP_ID = 'fixture-room@chatroom'
|
||||
const NOW = 1_700_000_000_000
|
||||
|
||||
/** 构造一份启用状态下的最小配置,参数按需覆盖。 */
|
||||
function buildConfig(overrides = {}) {
|
||||
return normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [{ id: 'rule-1', keyword: '关键词', mode: 'contains', reply: '默认回复' }],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false },
|
||||
...overrides
|
||||
})
|
||||
}
|
||||
|
||||
/** 构造一条群聊文本消息事件。 */
|
||||
function buildEvent(overrides = {}) {
|
||||
return {
|
||||
eventId: 'event-fixture-1',
|
||||
accountId: 'account-fixture',
|
||||
conversationId: GROUP_ID,
|
||||
messageId: 'message-fixture-1',
|
||||
senderId: 'wxid_fixture',
|
||||
senderName: '张三',
|
||||
isGroup: true,
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text: '你好,关键词',
|
||||
mentionsMe: false,
|
||||
timestamp: NOW,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
test('exact 模式比较 trim 后的完整文本', () => {
|
||||
const rule = { keyword: '关键词', mode: 'exact' }
|
||||
assert.equal(matchRule(' 关键词 ', rule), true)
|
||||
assert.equal(matchRule('你好,关键词', rule), false)
|
||||
})
|
||||
|
||||
test('exact 模式不匹配大小写不同的关键词之外的差异', () => {
|
||||
const rule = { keyword: 'Hello', mode: 'exact' }
|
||||
assert.equal(matchRule('hello', rule), true)
|
||||
assert.equal(matchRule('hello world', rule), false)
|
||||
})
|
||||
|
||||
test('contains 模式匹配任意位置的子串', () => {
|
||||
const rule = { keyword: '关键词', mode: 'contains' }
|
||||
assert.equal(matchRule('前面的关键词后面', rule), true)
|
||||
assert.equal(matchRule('完全无关', rule), false)
|
||||
})
|
||||
|
||||
test('prefix 模式只匹配开头', () => {
|
||||
const rule = { keyword: '你好', mode: 'prefix' }
|
||||
assert.equal(matchRule(' 你好世界', rule), true)
|
||||
assert.equal(matchRule('世界你好', rule), false)
|
||||
})
|
||||
|
||||
test('匹配对大小写不敏感', () => {
|
||||
assert.equal(matchRule('Say HELLO now', { keyword: 'hello', mode: 'contains' }), true)
|
||||
assert.equal(matchRule('HELLO WORLD', { keyword: 'hello', mode: 'prefix' }), true)
|
||||
})
|
||||
|
||||
test('空关键词在任何模式下都不命中', () => {
|
||||
for (const mode of ['contains', 'exact', 'prefix']) {
|
||||
assert.equal(matchRule('任意文本', { keyword: ' ', mode }), false)
|
||||
assert.equal(matchRule('', { keyword: '', mode }), false)
|
||||
}
|
||||
})
|
||||
|
||||
test('pickRule 跳过禁用规则', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'disabled', keyword: '关键词', reply: '不会发送', enabled: false },
|
||||
{ id: 'active', keyword: '关键词', reply: '会发送' }
|
||||
]
|
||||
})
|
||||
const rule = pickRule('关键词', config)
|
||||
assert.equal(rule.id, 'active')
|
||||
})
|
||||
|
||||
test('pickRule 按 priority 降序选择', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'low', keyword: '关键词', reply: '低', priority: 10 },
|
||||
{ id: 'high', keyword: '关键词', reply: '高', priority: 90 }
|
||||
]
|
||||
})
|
||||
assert.equal(pickRule('关键词', config).id, 'high')
|
||||
})
|
||||
|
||||
test('同优先级保持数组顺序(先定义先命中)', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'first', keyword: '关键词', reply: '一', priority: 50 },
|
||||
{ id: 'second', keyword: '关键词', reply: '二', priority: 50 }
|
||||
]
|
||||
})
|
||||
assert.equal(pickRule('关键词', config).id, 'first')
|
||||
})
|
||||
|
||||
test('同一条消息只返回一个规则(stopOnMatch)', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'a', keyword: '关键词', reply: '一', priority: 1 },
|
||||
{ id: 'b', keyword: '关键词', reply: '二', priority: 2 }
|
||||
]
|
||||
})
|
||||
const rule = pickRule('关键词 关键词', config)
|
||||
assert.equal(rule.id, 'b')
|
||||
})
|
||||
|
||||
test('群范围命中指定群', () => {
|
||||
const config = buildConfig({ scope: { groups: [GROUP_ID] } })
|
||||
assert.equal(inScope(buildEvent(), config), true)
|
||||
})
|
||||
|
||||
test('群范围排除未列出的群', () => {
|
||||
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
|
||||
assert.equal(inScope(buildEvent(), config), false)
|
||||
})
|
||||
|
||||
test('groups 为空表示全部群聊', () => {
|
||||
const config = buildConfig({ scope: { groups: [] } })
|
||||
assert.equal(inScope(buildEvent(), config), true)
|
||||
})
|
||||
|
||||
test('includeDirect 为 false 时不处理私聊', () => {
|
||||
const closed = buildConfig({ scope: { groups: [], includeDirect: false } })
|
||||
const open = buildConfig({ scope: { groups: [], includeDirect: true } })
|
||||
const direct = buildEvent({ isGroup: false, conversationId: 'wxid_fixture' })
|
||||
assert.equal(inScope(direct, closed), false)
|
||||
assert.equal(inScope(direct, open), true)
|
||||
})
|
||||
|
||||
test('requireMentionMe 只放行真正 @ 我的消息', () => {
|
||||
const config = buildConfig({ scope: { groups: [], requireMentionMe: true } })
|
||||
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'mention')
|
||||
assert.equal(shouldReply(buildEvent({ mentionsMe: true }), config, new Map(), NOW).reason, 'ok')
|
||||
})
|
||||
|
||||
test('自己发的消息不回复', () => {
|
||||
const verdict = shouldReply(buildEvent({ isSelf: true }), buildConfig(), new Map(), NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'self' })
|
||||
})
|
||||
|
||||
test('非文本消息不回复', () => {
|
||||
const verdict = shouldReply(buildEvent({ type: 'image' }), buildConfig(), new Map(), NOW)
|
||||
assert.equal(verdict.reason, 'type')
|
||||
})
|
||||
|
||||
test('总开关关闭时不回复', () => {
|
||||
const config = buildConfig({ enabled: false })
|
||||
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'disabled')
|
||||
assert.equal(shouldReply(buildEvent(), null, new Map(), NOW).reason, 'disabled')
|
||||
})
|
||||
|
||||
test('没有命中规则时 reason 为 no_match', () => {
|
||||
const verdict = shouldReply(buildEvent({ text: '无关内容' }), buildConfig(), new Map(), NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'no_match' })
|
||||
})
|
||||
|
||||
test('冷却中不回复', () => {
|
||||
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW + 30_000]])
|
||||
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'cooldown' })
|
||||
})
|
||||
|
||||
test('冷却过期后恢复回复', () => {
|
||||
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW]])
|
||||
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
|
||||
assert.equal(verdict.reply, true)
|
||||
assert.equal(verdict.reason, 'ok')
|
||||
assert.equal(verdict.rule.id, 'rule-1')
|
||||
})
|
||||
|
||||
test('冷却表也支持普通对象', () => {
|
||||
const cooldown = { [`${GROUP_ID}:rule-1`]: NOW + 1 }
|
||||
assert.equal(shouldReply(buildEvent(), buildConfig(), cooldown, NOW).reason, 'cooldown')
|
||||
assert.equal(shouldReply(buildEvent(), buildConfig(), {}, NOW).reason, 'ok')
|
||||
})
|
||||
|
||||
test('模板变量按上下文替换', () => {
|
||||
const text = renderReply('{sender} 说了 {keyword},现在是 {time}', {
|
||||
senderName: '张三',
|
||||
keyword: '关键词',
|
||||
time: '09:05'
|
||||
})
|
||||
assert.equal(text, '张三 说了 关键词,现在是 09:05')
|
||||
})
|
||||
|
||||
test('发送者昵称为空时渲染为「你」', () => {
|
||||
assert.equal(renderReply('{sender}', { senderName: ' ' }), '你')
|
||||
assert.equal(renderReply('{sender}', {}), '你')
|
||||
})
|
||||
|
||||
test('未知变量原样保留', () => {
|
||||
const text = renderReply('{sender} 和 {group}', { senderName: '李四' })
|
||||
assert.equal(text, '李四 和 {group}')
|
||||
})
|
||||
|
||||
test('模板缺失的时间变量渲染为空串', () => {
|
||||
assert.equal(renderReply('[{time}]', {}), '[]')
|
||||
})
|
||||
|
||||
test('渲染结果 trim 后截断到 2000 字符', () => {
|
||||
const input = ` ${'长'.repeat(2100)} `
|
||||
const text = renderReply(input, {})
|
||||
assert.equal(text.length, 2000)
|
||||
assert.equal(text, '长'.repeat(2000))
|
||||
})
|
||||
|
||||
test('v1 配置迁移补齐 enabled / priority 与 configVersion', () => {
|
||||
const config = normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [{ id: 'old', keyword: '关键词', mode: 'contains', reply: '旧规则' }],
|
||||
scope: { groups: ['fixture-room@chatroom'] }
|
||||
})
|
||||
assert.equal(config.configVersion, 2)
|
||||
assert.equal(config.rules.length, 1)
|
||||
assert.equal(config.rules[0].enabled, true)
|
||||
assert.equal(config.rules[0].priority, 0)
|
||||
assert.equal(config.scope.includeDirect, true)
|
||||
assert.equal(config.scope.requireMentionMe, false)
|
||||
})
|
||||
|
||||
test('keyword 或 reply 为空的启用规则被丢弃,停用草稿保留', () => {
|
||||
const config = normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [
|
||||
{ id: 'no-keyword', keyword: ' ', reply: '有回复' },
|
||||
{ id: 'no-reply', keyword: '有词', reply: ' ' },
|
||||
{ id: 'draft', keyword: '', reply: '', enabled: false },
|
||||
{ id: 'ok', keyword: '有词', reply: '有回复' }
|
||||
]
|
||||
})
|
||||
assert.deepEqual(
|
||||
config.rules.map((rule) => rule.id),
|
||||
['draft', 'ok']
|
||||
)
|
||||
})
|
||||
|
||||
test('非对象与缺失字段的配置退化为未启用空配置', () => {
|
||||
for (const raw of [null, undefined, 'broken', 42, []]) {
|
||||
const config = normalizeConfig(raw)
|
||||
assert.equal(config.configVersion, 2)
|
||||
assert.equal(config.enabled, false)
|
||||
assert.deepEqual(config.rules, [])
|
||||
assert.deepEqual(config.scope, { groups: [], includeDirect: true, requireMentionMe: false })
|
||||
}
|
||||
})
|
||||
|
||||
test('越界数值收敛到边界,非法值按 0', () => {
|
||||
const config = normalizeConfig({
|
||||
rules: [
|
||||
{ id: 'clamp-high', keyword: '一', reply: '一', cooldownSeconds: 99_999, priority: 999 },
|
||||
{ id: 'clamp-low', keyword: '二', reply: '二', cooldownSeconds: -5, priority: -5 },
|
||||
{ id: 'nan', keyword: '三', reply: '三', cooldownSeconds: 'oops', priority: 'oops' }
|
||||
]
|
||||
})
|
||||
assert.equal(config.rules[0].cooldownSeconds, 3600)
|
||||
assert.equal(config.rules[0].priority, 100)
|
||||
assert.equal(config.rules[1].cooldownSeconds, 0)
|
||||
assert.equal(config.rules[1].priority, 0)
|
||||
assert.equal(config.rules[2].cooldownSeconds, 0)
|
||||
assert.equal(config.rules[2].priority, 0)
|
||||
})
|
||||
|
||||
test('群范围过滤先于规则匹配,范围外不产生命中', () => {
|
||||
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
|
||||
const verdict = shouldReply(buildEvent(), config, new Map(), NOW)
|
||||
assert.equal(verdict.reason, 'scope')
|
||||
assert.equal(verdict.rule, null)
|
||||
})
|
||||
@@ -0,0 +1,495 @@
|
||||
const EXTENSION_ID = 'com.example.keyword-bot'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
const CONFIG_VERSION = 2
|
||||
const MAX_KEYWORD_LENGTH = 120
|
||||
const MAX_REPLY_LENGTH = 2000
|
||||
const STATS_PREVIEW = 5
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: false,
|
||||
rules: [
|
||||
{
|
||||
id: 'rule-1',
|
||||
keyword: '你好',
|
||||
mode: 'contains',
|
||||
reply: '你好呀,{sender}!',
|
||||
cooldownSeconds: 30,
|
||||
enabled: true,
|
||||
priority: 0
|
||||
}
|
||||
],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false }
|
||||
}
|
||||
|
||||
const pending = new Map()
|
||||
let sequence = 0
|
||||
let config = clone(DEFAULT_CONFIG)
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = `req-${++sequence}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const entry = pending.get(data.requestId)
|
||||
if (!entry) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) entry.resolve(data.result)
|
||||
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
|
||||
})
|
||||
|
||||
const rulesContainer = document.getElementById('rules')
|
||||
const status = document.getElementById('status')
|
||||
const statsSummary = document.getElementById('stats-summary')
|
||||
const statsList = document.getElementById('stats-list')
|
||||
const groupPicker = document.getElementById('group-picker')
|
||||
const groupChips = document.getElementById('group-chips')
|
||||
const groupSearch = document.getElementById('group-search')
|
||||
const groupOptions = document.getElementById('group-options')
|
||||
|
||||
let allGroups = []
|
||||
let selectedGroupIds = new Set()
|
||||
let groupLoadError = ''
|
||||
|
||||
function groupDisplayName(group) {
|
||||
if (!group) return ''
|
||||
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
|
||||
}
|
||||
|
||||
function renderGroupChips() {
|
||||
groupChips.textContent = ''
|
||||
groupChips.hidden = selectedGroupIds.size === 0
|
||||
for (const id of selectedGroupIds) {
|
||||
const group = allGroups.find((item) => item.id === id)
|
||||
const chip = document.createElement('span')
|
||||
chip.className = 'group-chip'
|
||||
const name = document.createElement('span')
|
||||
name.textContent = group ? group.name || id : id
|
||||
name.title = id
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'group-chip-remove'
|
||||
remove.textContent = '×'
|
||||
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
|
||||
remove.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
selectedGroupIds.delete(id)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
})
|
||||
chip.append(name, remove)
|
||||
groupChips.append(chip)
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroupOptions() {
|
||||
if (groupOptions.hidden) return
|
||||
const query = groupSearch.value.trim().toLowerCase()
|
||||
groupOptions.textContent = ''
|
||||
if (groupLoadError) {
|
||||
groupOptions.append(emptyGroupOption(groupLoadError))
|
||||
return
|
||||
}
|
||||
if (!allGroups.length) {
|
||||
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
|
||||
return
|
||||
}
|
||||
const matches = allGroups.filter((group) => {
|
||||
if (!query) return true
|
||||
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
|
||||
})
|
||||
if (!matches.length) {
|
||||
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
|
||||
return
|
||||
}
|
||||
for (const group of matches.slice(0, 200)) {
|
||||
const option = document.createElement('label')
|
||||
option.className = 'group-option'
|
||||
const checkbox = document.createElement('input')
|
||||
checkbox.type = 'checkbox'
|
||||
checkbox.checked = selectedGroupIds.has(group.id)
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedGroupIds.add(group.id)
|
||||
else selectedGroupIds.delete(group.id)
|
||||
renderGroupChips()
|
||||
})
|
||||
const text = document.createElement('span')
|
||||
text.textContent = groupDisplayName(group)
|
||||
option.append(checkbox, text)
|
||||
groupOptions.append(option)
|
||||
}
|
||||
}
|
||||
|
||||
function emptyGroupOption(text) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-option-empty'
|
||||
empty.textContent = text
|
||||
return empty
|
||||
}
|
||||
|
||||
function openGroupOptions() {
|
||||
groupOptions.hidden = false
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function closeGroupOptions() {
|
||||
groupOptions.hidden = true
|
||||
groupSearch.value = ''
|
||||
}
|
||||
|
||||
groupSearch.addEventListener('focus', openGroupOptions)
|
||||
groupSearch.addEventListener('input', openGroupOptions)
|
||||
groupSearch.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
closeGroupOptions()
|
||||
groupSearch.blur()
|
||||
}
|
||||
})
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!groupPicker.contains(event.target)) closeGroupOptions()
|
||||
})
|
||||
|
||||
async function loadGroups() {
|
||||
try {
|
||||
const result = await callHost('contacts.listGroups', {})
|
||||
allGroups = result && Array.isArray(result.groups) ? result.groups : []
|
||||
groupLoadError = ''
|
||||
} catch (error) {
|
||||
allGroups = []
|
||||
groupLoadError = `群列表读取失败:${error.message}`
|
||||
}
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function setStatus(text, kind) {
|
||||
status.textContent = text
|
||||
status.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function clampInteger(value, min, max, fallback) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.min(Math.max(Math.round(numeric), min), max)
|
||||
}
|
||||
|
||||
function newRuleId() {
|
||||
return `rule-${Date.now().toString(36)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面侧的轻量规范化:只用于展示与回写,真正的判定在后台 lib/matcher.js。
|
||||
* 缺字段一律补默认值,保证 v1 配置打开后能直接编辑。
|
||||
*/
|
||||
function normalizeRule(rule, index) {
|
||||
const source = rule && typeof rule === 'object' ? rule : {}
|
||||
return {
|
||||
id: String(source.id || `rule-${index + 1}`).slice(0, 64),
|
||||
keyword: String(source.keyword == null ? '' : source.keyword).slice(0, MAX_KEYWORD_LENGTH),
|
||||
mode: ['contains', 'exact', 'prefix'].includes(source.mode) ? source.mode : 'contains',
|
||||
reply: String(source.reply == null ? '' : source.reply).slice(0, MAX_REPLY_LENGTH),
|
||||
cooldownSeconds: clampInteger(source.cooldownSeconds, 0, 3600, 0),
|
||||
enabled: source.enabled !== false,
|
||||
priority: clampInteger(source.priority, 0, 100, 0)
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStoredConfig(stored) {
|
||||
if (!stored || typeof stored !== 'object') return clone(DEFAULT_CONFIG)
|
||||
const scope = stored.scope && typeof stored.scope === 'object' ? stored.scope : {}
|
||||
return {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: stored.enabled === true,
|
||||
rules: Array.isArray(stored.rules)
|
||||
? stored.rules.map(normalizeRule)
|
||||
: clone(DEFAULT_CONFIG.rules),
|
||||
scope: {
|
||||
groups: Array.isArray(scope.groups)
|
||||
? scope.groups.map((id) => String(id).trim()).filter(Boolean)
|
||||
: [],
|
||||
includeDirect: scope.includeDirect !== false,
|
||||
requireMentionMe: scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function field(label, control) {
|
||||
const wrapper = document.createElement('label')
|
||||
wrapper.className = 'field'
|
||||
const caption = document.createElement('span')
|
||||
caption.textContent = label
|
||||
wrapper.append(caption, control)
|
||||
return wrapper
|
||||
}
|
||||
|
||||
function renderRules() {
|
||||
rulesContainer.textContent = ''
|
||||
config.rules.forEach((rule, index) => {
|
||||
const card = document.createElement('article')
|
||||
card.className = 'rule-card'
|
||||
if (!rule.enabled) card.classList.add('is-disabled')
|
||||
|
||||
const head = document.createElement('div')
|
||||
head.className = 'rule-head'
|
||||
const title = document.createElement('strong')
|
||||
title.textContent = `规则 ${index + 1}`
|
||||
const toggle = document.createElement('label')
|
||||
toggle.className = 'check'
|
||||
const enabledInput = document.createElement('input')
|
||||
enabledInput.type = 'checkbox'
|
||||
enabledInput.checked = rule.enabled
|
||||
enabledInput.addEventListener('change', () => {
|
||||
rule.enabled = enabledInput.checked
|
||||
card.classList.toggle('is-disabled', !rule.enabled)
|
||||
})
|
||||
const toggleText = document.createElement('span')
|
||||
toggleText.textContent = '启用'
|
||||
toggle.append(enabledInput, toggleText)
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'ghost danger'
|
||||
remove.textContent = '删除'
|
||||
remove.addEventListener('click', () => {
|
||||
config.rules.splice(index, 1)
|
||||
renderRules()
|
||||
})
|
||||
const headActions = document.createElement('div')
|
||||
headActions.className = 'rule-head-actions'
|
||||
headActions.append(toggle, remove)
|
||||
head.append(title, headActions)
|
||||
|
||||
const keywordInput = document.createElement('input')
|
||||
keywordInput.type = 'text'
|
||||
keywordInput.maxLength = MAX_KEYWORD_LENGTH
|
||||
keywordInput.value = rule.keyword
|
||||
keywordInput.addEventListener('input', () => {
|
||||
rule.keyword = keywordInput.value
|
||||
})
|
||||
|
||||
const modeSelect = document.createElement('select')
|
||||
;[
|
||||
['contains', '包含'],
|
||||
['exact', '完全匹配'],
|
||||
['prefix', '以…开头']
|
||||
].forEach(([value, label]) => {
|
||||
const option = document.createElement('option')
|
||||
option.value = value
|
||||
option.textContent = label
|
||||
option.selected = rule.mode === value
|
||||
modeSelect.append(option)
|
||||
})
|
||||
modeSelect.addEventListener('change', () => {
|
||||
rule.mode = modeSelect.value
|
||||
})
|
||||
|
||||
const replyInput = document.createElement('textarea')
|
||||
replyInput.rows = 2
|
||||
replyInput.maxLength = MAX_REPLY_LENGTH
|
||||
replyInput.value = rule.reply
|
||||
replyInput.addEventListener('input', () => {
|
||||
rule.reply = replyInput.value
|
||||
})
|
||||
const replyBlock = field('回复内容', replyInput)
|
||||
const replyHint = document.createElement('p')
|
||||
replyHint.className = 'hint'
|
||||
replyHint.textContent =
|
||||
'可用变量:{sender}(发送者)、{keyword}(命中词)、{time}(当前时间 HH:mm)'
|
||||
replyBlock.append(replyHint)
|
||||
|
||||
const cooldownInput = document.createElement('input')
|
||||
cooldownInput.type = 'number'
|
||||
cooldownInput.min = '0'
|
||||
cooldownInput.max = '3600'
|
||||
cooldownInput.value = String(rule.cooldownSeconds)
|
||||
cooldownInput.addEventListener('change', () => {
|
||||
rule.cooldownSeconds = clampInteger(cooldownInput.value, 0, 3600, 0)
|
||||
cooldownInput.value = String(rule.cooldownSeconds)
|
||||
})
|
||||
|
||||
const priorityInput = document.createElement('input')
|
||||
priorityInput.type = 'number'
|
||||
priorityInput.min = '0'
|
||||
priorityInput.max = '100'
|
||||
priorityInput.step = '1'
|
||||
priorityInput.value = String(rule.priority)
|
||||
priorityInput.addEventListener('change', () => {
|
||||
rule.priority = clampInteger(priorityInput.value, 0, 100, 0)
|
||||
priorityInput.value = String(rule.priority)
|
||||
})
|
||||
|
||||
const numberRow = document.createElement('div')
|
||||
numberRow.className = 'field-row'
|
||||
const cooldownField = field('冷却时间(秒)', cooldownInput)
|
||||
const priorityField = field('优先级(0–100,越大越先匹配)', priorityInput)
|
||||
numberRow.append(cooldownField, priorityField)
|
||||
|
||||
card.append(
|
||||
head,
|
||||
field('关键词', keywordInput),
|
||||
field('匹配方式', modeSelect),
|
||||
replyBlock,
|
||||
numberRow
|
||||
)
|
||||
rulesContainer.append(card)
|
||||
})
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('enabled').checked = config.enabled === true
|
||||
selectedGroupIds = new Set(config.scope.groups)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
document.getElementById('include-direct').checked = config.scope.includeDirect !== false
|
||||
document.getElementById('require-mention').checked = config.scope.requireMentionMe === true
|
||||
renderRules()
|
||||
}
|
||||
|
||||
function readForm() {
|
||||
config.enabled = document.getElementById('enabled').checked
|
||||
config.scope.groups = [...selectedGroupIds].slice(0, 200)
|
||||
config.scope.includeDirect = document.getElementById('include-direct').checked
|
||||
config.scope.requireMentionMe = document.getElementById('require-mention').checked
|
||||
}
|
||||
|
||||
function localDateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
function formatClock(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${hour}:${minute}`
|
||||
}
|
||||
|
||||
/** 统计展示:只读 storage,不参与任何写入。 */
|
||||
function renderStats(raw) {
|
||||
statsList.textContent = ''
|
||||
const now = Date.now()
|
||||
const sameDay = raw && raw.dateKey === localDateKey(now)
|
||||
const todayCount = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
|
||||
const hits = raw && Array.isArray(raw.lastHits) ? raw.lastHits.filter((hit) => hit && hit.at) : []
|
||||
|
||||
if (!hits.length && todayCount === 0) {
|
||||
statsSummary.textContent = '暂无命中记录'
|
||||
return
|
||||
}
|
||||
statsSummary.textContent = `今日命中 ${todayCount} 次`
|
||||
|
||||
hits
|
||||
.slice(-STATS_PREVIEW)
|
||||
.reverse()
|
||||
.forEach((hit) => {
|
||||
const item = document.createElement('li')
|
||||
item.className = 'stats-item'
|
||||
const time = document.createElement('span')
|
||||
time.textContent = formatClock(Number(hit.at))
|
||||
const ruleId = document.createElement('code')
|
||||
ruleId.textContent = String(hit.ruleId || '未知规则')
|
||||
const result = document.createElement('span')
|
||||
result.className = hit.ok === true ? 'stats-ok' : 'stats-fail'
|
||||
result.textContent = hit.ok === true ? '成功' : '失败'
|
||||
item.append(time, ruleId, result)
|
||||
statsList.append(item)
|
||||
})
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: STATS_KEY })
|
||||
renderStats(stored)
|
||||
} catch (error) {
|
||||
renderStats(null)
|
||||
setStatus(`统计读取失败:${error.message}`, 'error')
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('add-rule').addEventListener('click', () => {
|
||||
config.rules.push({
|
||||
id: newRuleId(),
|
||||
keyword: '',
|
||||
mode: 'contains',
|
||||
reply: '',
|
||||
cooldownSeconds: 30,
|
||||
enabled: true,
|
||||
priority: 0
|
||||
})
|
||||
renderRules()
|
||||
})
|
||||
|
||||
document.getElementById('save').addEventListener('click', async () => {
|
||||
readForm()
|
||||
// 只有启用中的规则必须有内容:停用的草稿允许留空,方便先存后写。
|
||||
const invalid = config.rules.find(
|
||||
(rule) => rule.enabled && (!rule.keyword.trim() || !rule.reply.trim())
|
||||
)
|
||||
if (invalid) {
|
||||
setStatus('启用中的规则都需要关键词和回复内容;也可以先取消启用再保存。', 'error')
|
||||
return
|
||||
}
|
||||
const payload = {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: config.enabled === true,
|
||||
rules: config.rules.map(normalizeRule),
|
||||
scope: {
|
||||
groups: config.scope.groups.slice(0, 200),
|
||||
includeDirect: config.scope.includeDirect !== false,
|
||||
requireMentionMe: config.scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: payload })
|
||||
// 回写规范化结果但保留原对象引用:卡片上的输入事件仍在改这些对象。
|
||||
payload.rules.forEach((rule, index) => Object.assign(config.rules[index], rule))
|
||||
config.configVersion = CONFIG_VERSION
|
||||
setStatus('配置已保存。后台进程会在下一次收到消息时生效。', 'ok')
|
||||
loadStats()
|
||||
} catch (error) {
|
||||
setStatus(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('reset').addEventListener('click', async () => {
|
||||
config = clone(DEFAULT_CONFIG)
|
||||
syncForm()
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setStatus('已恢复默认配置。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`重置失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('refresh-stats').addEventListener('click', () => {
|
||||
loadStats()
|
||||
})
|
||||
|
||||
async function boot() {
|
||||
const stored = await callHost('storage.get', { key: CONFIG_KEY })
|
||||
config = normalizeStoredConfig(stored)
|
||||
syncForm()
|
||||
await loadGroups()
|
||||
setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
|
||||
loadStats()
|
||||
}
|
||||
|
||||
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
|
||||
@@ -0,0 +1,71 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>关键词回复机器人</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>关键词回复机器人</h1>
|
||||
<p>收到文本消息后按规则匹配,命中即经 TraceMemo Gateway 回复。本页只写配置,不直接发送。</p>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input id="enabled" type="checkbox" />
|
||||
<span>启用机器人</span>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>关键词规则</h2>
|
||||
<button id="add-rule" type="button" class="ghost">添加规则</button>
|
||||
</div>
|
||||
<div id="rules" class="rules"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>监听范围</h2>
|
||||
<div class="field">
|
||||
<span>只监听这些群聊(可多选、可搜索;留空表示全部群聊)</span>
|
||||
<div id="group-picker" class="group-picker">
|
||||
<div id="group-chips" class="group-chips" hidden></div>
|
||||
<input
|
||||
id="group-search"
|
||||
type="text"
|
||||
placeholder="搜索群聊名称或 id…"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<div id="group-options" class="group-options" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="check"><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label>
|
||||
<label class="check"><input id="require-mention" type="checkbox" /><span>只处理真正 @ 我的消息</span></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>运行统计</h2>
|
||||
<button id="refresh-stats" type="button" class="ghost">刷新</button>
|
||||
</div>
|
||||
<p id="stats-summary" class="stats-summary">暂无命中记录</p>
|
||||
<ul id="stats-list" class="stats-list"></ul>
|
||||
<p class="hint">统计只记录规则编号、命中时间与发送结果,不含会话、昵称与消息正文。</p>
|
||||
</section>
|
||||
|
||||
<footer class="page-footer">
|
||||
<div class="row">
|
||||
<button id="save" type="button" class="primary">保存配置</button>
|
||||
<button id="reset" type="button" class="ghost">恢复默认</button>
|
||||
</div>
|
||||
<p id="status" class="status" role="status"></p>
|
||||
</footer>
|
||||
</main>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,384 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f8f7;
|
||||
--card: #ffffff;
|
||||
--text: #1c2622;
|
||||
--muted: #6b7a73;
|
||||
--border: #dfe6e2;
|
||||
--brand: #247a63;
|
||||
--danger: #b4472f;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #161c19;
|
||||
--card: #1e2622;
|
||||
--text: #eef4f1;
|
||||
--muted: #9aaba3;
|
||||
--border: #33403a;
|
||||
--brand: #4bb894;
|
||||
--danger: #e0735a;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
padding: 26px 22px 40px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
header p {
|
||||
margin: 8px 0 0;
|
||||
max-width: 52ch;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rules {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rule-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.rule-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rule-head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.rule-card.is-disabled {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.rule-card.is-disabled .field,
|
||||
.rule-card.is-disabled .field-row {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.stats-summary {
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.stats-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats-ok {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.stats-fail {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.field-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.field > span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
input[type='number'],
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.check,
|
||||
.switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.switch {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 6px 11px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: transparent;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
button.ghost:hover {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
button.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 18px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status[data-kind='ok'] {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.status[data-kind='error'] {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
|
||||
.group-picker {
|
||||
position: relative;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.group-picker:focus-within {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.group-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 2px 4px 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.group-chip > span {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-chip-remove {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.group-chip-remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.group-picker > input[type='text'] {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
padding: 4px 2px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-options {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 4px);
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.group-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 6px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-option:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.group-option input {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group-option-empty {
|
||||
padding: 8px 6px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
Reference in new issue
Block a user