This commit is contained in:
丹尼尔
2026-03-12 18:42:23 +08:00
parent 66362780a0
commit 8b62c445fc
10 changed files with 4801 additions and 73 deletions

View File

@@ -4,6 +4,10 @@ PORT=3000
# BACKEND_HOST=127.0.0.1
WECHAT_UPSTREAM_BASE_URL=http://113.44.162.180:7006
CHECK_STATUS_BASE_URL=http://113.44.162.180:7006
# 群发图片:默认用 7006 /message/SendImageMessageMsgItem.MsgType=0可覆盖
# SEND_IMAGE_UPSTREAM_BASE_URL=http://113.44.162.180:7006
# SEND_IMAGE_PATH=/message/SendImageMessage
# IMAGE_MSG_TYPE=0
# 第三方滑块(7765)iframe 加载自带预填表单页,提交到下方地址
SLIDER_VERIFY_BASE_URL=http://113.44.162.180:7765
SLIDER_VERIFY_KEY=408449830

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -41,10 +41,11 @@ SLIDER_VERIFY_BASE_URL = os.getenv("SLIDER_VERIFY_BASE_URL", "http://113.44.162.
SLIDER_VERIFY_KEY = os.getenv("SLIDER_VERIFY_KEY", "408449830")
# 发送文本消息swagger 中为 POST /message/SendTextMessagebody 为 SendMessageModelMsgItem 数组)
SEND_MSG_PATH = (os.getenv("SEND_MSG_PATH") or "/message/SendTextMessage").strip()
# 发送图片消息:部分上游为独立接口,或与文本同 path 仅 MsgType 不同(如 3=图片)
SEND_IMAGE_PATH = (os.getenv("SEND_IMAGE_PATH") or "").strip() or SEND_MSG_PATH
# 图片消息 MsgType部分上游为 0常见为 3
IMAGE_MSG_TYPE = int(os.getenv("IMAGE_MSG_TYPE", "3"))
# 发送图片消息:7006 为 /message/SendImageMessagebody MsgItem 含 ImageContent、MsgType=0
SEND_IMAGE_UPSTREAM_BASE_URL = (os.getenv("SEND_IMAGE_UPSTREAM_BASE_URL") or "").strip() or CHECK_STATUS_BASE_URL
SEND_IMAGE_PATH = (os.getenv("SEND_IMAGE_PATH") or "").strip() or "/message/SendImageMessage"
# 图片消息 MsgType7006 SendImageMessage 为 0
IMAGE_MSG_TYPE = int(os.getenv("IMAGE_MSG_TYPE", "0"))
# 按 key 缓存取码结果与 Data62供后续步骤使用
qrcode_store: dict = {}
@@ -91,6 +92,17 @@ def _allowed_ai_reply(key: str, from_user: str) -> bool:
return allowed
def _is_super_admin(key: str, from_user: str) -> bool:
"""仅超级管理员可调用代发消息等 function call白名单仅可得到普通回复。"""
if not from_user or not from_user.strip():
return False
cfg = store.get_ai_reply_config(key)
if not cfg:
return False
super_admins = set(cfg.get("super_admin_wxids") or [])
return from_user.strip() in super_admins
async def _ai_takeover_reply(key: str, from_user: str, content: str) -> None:
"""收到他人消息时由 AI 接管:根据指令生成回复或调用内置动作(如代发消息)。"""
if not from_user or not content or not content.strip():
@@ -151,6 +163,13 @@ async def _ai_takeover_reply(key: str, from_user: str, content: str) -> None:
action_type = str(action.get("type") or "").strip()
if action_type == "send_message":
if not _is_super_admin(key, from_user):
await _send_message_upstream(
key, from_user,
"代发消息等操作仅限超级管理员使用,您可正常聊天获得回复。"
)
logger.info("AI send_message rejected: from_user not super_admin (key=***%s)", key[-4:] if len(key) >= 4 else "****")
return
target = str(action.get("target_wxid") or "").strip()
msg = str(action.get("content") or "").strip()
if target and msg:
@@ -1246,7 +1265,20 @@ async def api_create_push_task(body: PushTaskCreate):
@app.get("/api/messages")
async def api_list_messages(key: str = Query(..., description="账号 key"), limit: int = Query(100, le=500)):
return {"items": store.list_sync_messages(key, limit=limit)}
"""拉取同步消息列表并依联系人GetContactDetailsList的昵称将 wxid 换算为展示名FromDisplayName/ToDisplayName不使用客户档案备注。"""
items = store.list_sync_messages(key, limit=limit)
try:
contact_index = await _build_contact_index(key)
except Exception:
contact_index = {}
for m in items:
from_wxid = (m.get("FromUserName") or m.get("from") or "").strip()
to_wxid = (m.get("ToUserName") or m.get("to") or "").strip()
from_info = contact_index.get(from_wxid) if isinstance(contact_index.get(from_wxid), dict) else None
to_info = contact_index.get(to_wxid) if isinstance(contact_index.get(to_wxid), dict) else None
m["FromDisplayName"] = (from_info.get("nick_name") or from_wxid).strip() if from_info else from_wxid
m["ToDisplayName"] = (to_info.get("nick_name") or to_wxid).strip() if to_info else to_wxid
return {"items": items}
@app.get("/api/callback-status")
@@ -1359,14 +1391,14 @@ async def _send_batch_upstream(key: str, items: List[dict]) -> dict:
async def _send_image_upstream(key: str, to_user_name: str, image_content: str,
text_content: Optional[str] = "",
at_wxid_list: Optional[List[str]] = None) -> dict:
"""发送图片消息MsgItem 含 ImageContent、MsgType=3或 0依上游可选 TextContent、AtWxIDList。"""
url = f"{WECHAT_UPSTREAM_BASE_URL.rstrip('/')}{SEND_IMAGE_PATH}"
"""发送图片消息:走 7006 /message/SendImageMessageMsgItem 含 ImageContent、MsgType=0、TextContent、AtWxIDList。"""
url = f"{SEND_IMAGE_UPSTREAM_BASE_URL.rstrip('/')}{SEND_IMAGE_PATH}"
item = {
"ToUserName": to_user_name,
"MsgType": IMAGE_MSG_TYPE,
"AtWxIDList": list(at_wxid_list) if at_wxid_list else [],
"ImageContent": image_content or "",
"MsgType": IMAGE_MSG_TYPE,
"TextContent": text_content or "",
"AtWxIDList": at_wxid_list or [],
"ToUserName": to_user_name,
}
payload = {"MsgItem": [item]}
async with httpx.AsyncClient(trust_env=False, timeout=15.0) as client:

1
image/test.md Normal file

File diff suppressed because one or more lines are too long

View File

@@ -127,6 +127,11 @@
</div>
<script>
const $ = (id) => document.getElementById(id);
const escapeHtml = (s) => {
if (s == null) return '';
const t = String(s);
return t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};
// 相对路径,由 Node 代理到后端,适配 -p/-b 任意端口
const API_BASE = '';
const KEY_STORAGE = 'wechat_key';
@@ -171,13 +176,16 @@
const isUrl = (s) => typeof s === 'string' && /^https?:\/\//i.test(s.trim());
const isBase64Like = (s) => typeof s === 'string' && /^[A-Za-z0-9+/=\s]+$/.test(s) && s.replace(/\s+/g, '').length > 60;
// 图片:上游通常提供 ImageContentbase64或 Content 为图片链接
// 图片:上游通常提供 ImageContentbase64或 Content 为图片链接;无法解读时保留原样
if (imageContent || (msgType === 3) || (msgType === 0 && imageContent)) {
const src = isUrl(imageContent) ? imageContent :
(imageContent ? ('data:image/png;base64,' + imageContent.replace(/\s+/g, '')) :
(isUrl(rawContent) ? rawContent : ''));
if (src) {
return `<div class="content"><div>${rawContent ? String(rawContent) : ''}</div><img src="${src}" alt="图片消息" /></div>`;
const fallback = escapeHtml(rawContent ? String(rawContent).slice(0, 200) : '[图片无法显示]');
return '<div class="content">' + (rawContent ? '<div>' + escapeHtml(rawContent) + '</div>' : '') +
'<img src="' + src.replace(/"/g, '&quot;') + '" alt="图片消息" onerror="this.style.display=\'none\';var s=this.nextElementSibling;if(s)s.style.display=\'\';" />' +
'<span class="img-fallback small-label" style="display:none">' + fallback + '</span></div>';
}
}
@@ -197,15 +205,16 @@
return `<div class="content"><a href="${safe}" target="_blank" rel="noopener noreferrer">${safe}</a></div>`;
}
// 若内容看起来是图片 base64则按图片渲染
if (isBase64Like(rawContent) && (msgType === 3 || msgType === 0)) {
// 若内容看起来是图片 base64则按图片渲染;无法解读时维持原样
if (isBase64Like(rawContent) && (msgType === 3 || msgType === 0 || !msgType)) {
const src = 'data:image/png;base64,' + String(rawContent).replace(/\s+/g, '');
return `<div class="content"><img src="${src}" alt="图片消息" /></div>`;
const fallback = escapeHtml(String(rawContent).slice(0, 80) + (rawContent.length > 80 ? '…' : ''));
return '<div class="content"><img src="' + src.replace(/"/g, '&quot;') + '" alt="图片消息" onerror="this.style.display=\'none\';var s=this.nextElementSibling;if(s)s.style.display=\'\';" /><span class="img-fallback small-label" style="display:none">' + fallback + '</span></div>';
}
// 兜底为纯文本(含 MsgType 提示)
const text = rawContent ? String(rawContent) : (msgType != null ? `MsgType=${msgType}` : '');
return `<div class="content">${text}</div>`;
const text = rawContent ? String(rawContent) : (msgType != null ? 'MsgType=' + msgType : '');
return '<div class="content">' + escapeHtml(text) + '</div>';
}
async function loadMessages() {
@@ -235,11 +244,13 @@
});
$('message-list').innerHTML = list.length ? list.map(m => {
const isOut = m.direction === 'out';
const fromLabel = isOut ? ('我 → ' + (m.ToUserName || '')) : (m.FromUserName || m.from || m.MsgId || '-').toString().slice(0, 32);
const toDisplay = m.ToDisplayName || m.ToUserName || '';
const fromDisplay = m.FromDisplayName || m.FromUserName || m.from || m.MsgId || '-';
const fromLabel = isOut ? ('我 → ' + toDisplay) : String(fromDisplay).slice(0, 48);
const time = m.CreateTime ? (typeof m.CreateTime === 'number'
? new Date(m.CreateTime * 1000).toLocaleTimeString('zh-CN', { hour12: false })
: m.CreateTime) : '';
const meta = '<div class="meta"><span class="from">' + fromLabel + '</span>' + (time ? '<span class="time">' + time + '</span>' : '') + '</div>';
const meta = '<div class="meta"><span class="from">' + escapeHtml(fromLabel) + '</span>' + (time ? '<span class="time">' + time + '</span>' : '') + '</div>';
const body = renderMessageContent(m);
return '<div class="msg-item' + (isOut ? ' out' : '') + '">' + meta + body + '</div>';
}).join('') : '<p class="small-label">暂无对话。请确保已登录且后端 WS 已连接 GetSyncMsg发送的消息含图片、音视频等也会在此展示。</p>';

View File

@@ -93,6 +93,11 @@
.tags-chips .chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 999px; background: var(--accent-soft); border: 1px solid var(--accent); font-size: 12px; color: var(--accent); }
.tags-chips .chip button { background: none; border: none; color: var(--muted); cursor: pointer; padding: 0; font-size: 14px; line-height: 1; }
.tags-chips .chip button:hover { color: var(--text); }
.img-send-progress .img-send-bar { height: 10px; background: var(--border); border-radius: 6px; overflow: hidden; }
.img-send-progress .img-send-fill { height: 100%; background: var(--accent); border-radius: 6px; width: 0%; transition: width 0.25s ease; }
.img-send-progress .img-send-text { font-size: 12px; color: var(--muted); margin-top: 6px; }
.img-send-progress.is-error .img-send-text { color: #f87171; }
.img-send-progress.is-done .img-send-text { color: var(--accent); }
</style>
</head>
<body>
@@ -165,7 +170,7 @@
<label>选择接收人(从好友/客户列表)</label>
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
<button type="button" class="secondary" id="btn-load-friends" style="padding:4px 10px;font-size:12px">加载联系人</button>
<button type="button" class="secondary" id="btn-load-customers-mass" style="padding:4px 10px;font-size:12px" title="从客户档案加载,与联系人合并去重">加载客户</button>
<button type="button" class="secondary" id="btn-load-customers-mass" style="padding:4px 10px;font-size:12px" title="从客户档案加载,替换为仅客户列表">加载客户</button>
<span id="mass-selected-count" class="small-label">已选 0 人</span>
</div>
<div id="mass-friend-list" style="max-height:200px;overflow-y:auto;border:1px solid var(--border);border-radius:8px;padding:8px;margin-top:6px;background:rgba(15,23,42,0.6)"></div>
@@ -174,8 +179,9 @@
<button type="button" class="primary" id="btn-mass-send">一键群发</button>
</div>
<div class="small-label" style="margin-top:16px;margin-bottom:8px">发送图片消息(快捷方式)</div>
<p class="small-label" style="margin-bottom:8px">接收人:可从上方「选择接收人」勾选联系人/客户,或在下框填写 wxid多人用逗号或换行分隔</p>
<div class="mgmt-form-grid">
<div class="field"><label>接收人 wxid</label><input id="img-to-user" placeholder="zhang499142409" /></div>
<div class="field full"><label>接收人 wxid(可选,与上方勾选合并)</label><input id="img-to-user" placeholder="zhang499142409 或 多人逗号/换行分隔" /></div>
<div class="field full">
<label>图片内容base64 / URL / 本地图片)</label>
<input id="img-content" placeholder="粘贴 base64、图片 URL或从下方选择本地图片" />
@@ -186,6 +192,10 @@
</div>
<div class="field full"><label>附带文字(可选)</label><input id="img-text" placeholder="可选" /></div>
<button type="button" class="primary" id="btn-send-image">发送图片</button>
<div id="img-send-progress" class="img-send-progress" style="display:none;margin-top:12px;">
<div class="img-send-bar"><div class="img-send-fill" id="img-send-fill"></div></div>
<div class="img-send-text small-label" id="img-send-text"></div>
</div>
</div>
<hr style="border:0;border-top:1px solid var(--border);margin:20px 0" />
<div class="small-label">商品标签</div>
@@ -206,7 +216,7 @@
<div id="push-task-list"></div>
</div>
<div id="panel-ai-reply" class="mgmt-panel">
<p class="small-label" style="margin-bottom:12px">分级处理:仅<strong>超级管理员</strong><strong>白名单</strong>中的联系人会收到 AI 自动回复,其他消息一律不回复。</p>
<p class="small-label" style="margin-bottom:12px">分级处理:仅<strong>超级管理员</strong><strong>白名单</strong>中的联系人会收到 AI 自动回复,其他消息一律不回复。<br />白名单<strong>不能</strong>调用 function call如代发消息<strong>仅超级管理员</strong>可使用代发消息等操作。</p>
<div class="field full" style="margin-bottom:12px">
<span class="small-label">AI 接管状态:</span>
<span id="ai-reply-status-text"></span>
@@ -216,10 +226,12 @@
<div class="field full">
<label>超级管理员 wxid每行一个或逗号分隔</label>
<textarea id="ai-super-admin" rows="3" placeholder="zhang499142409&#10;wxid_xxx"></textarea>
<span class="small-label" style="display:block;margin-top:4px">可收到 AI 回复且可调用代发消息等 function call</span>
</div>
<div class="field full">
<label>白名单 wxid可收到 AI 回复的联系人,每行一个或逗号分隔)</label>
<textarea id="ai-whitelist" rows="4" placeholder="wxid_abc&#10;wxid_def"></textarea>
<span class="small-label" style="display:block;margin-top:4px">仅可正常聊天获得回复,不能调用代发消息等 function call</span>
</div>
<button type="button" class="primary" id="btn-ai-reply-save">保存配置</button>
</div>
@@ -667,6 +679,7 @@
const name = (f.remark_name || f.RemarkName || f.nick_name || f.NickName || wxid).toString();
return { wxid, name, source: 'friend' };
}).filter(f => f.wxid);
massSelectedWxids = [];
if (!massContactList.length) {
el.innerHTML = '<span class="small-label">暂无联系人。可点击「加载客户」从客户档案选择。</span>';
return;
@@ -681,31 +694,22 @@
const key = $('key').value.trim();
if (!key) { alert('请先登录'); return; }
const el = $('mass-friend-list');
const wasEmpty = !massContactList.length;
if (wasEmpty) el.innerHTML = '<span class="small-label">加载中…</span>';
el.innerHTML = '<span class="small-label">加载中…</span>';
try {
const data = await callApi('/api/customers?key=' + encodeURIComponent(key));
const list = data.items || [];
const existingWxids = new Set(massContactList.map(f => f.wxid));
list.forEach(c => {
massContactList = list.map(c => {
const wxid = (c.wxid || '').toString();
if (!wxid) return;
if (existingWxids.has(wxid)) return;
existingWxids.add(wxid);
massContactList.push({
wxid,
name: (c.remark_name || c.wxid || wxid).toString(),
source: 'customer'
});
});
return { wxid, name: (c.remark_name || c.wxid || wxid).toString(), source: 'customer' };
}).filter(f => f.wxid);
if (!massContactList.length) {
el.innerHTML = '<span class="small-label">暂无客户。请先在「客户档案」添加客户,或点击「加载联系人」获取好友列表。</span>';
return;
}
massSelectedWxids = [];
renderMassContactList();
} catch (e) {
if (wasEmpty) el.innerHTML = '<span class="small-label">加载失败: ' + escapeHtml(e.message) + '</span>';
else alert('加载客户失败: ' + e.message);
el.innerHTML = '<span class="small-label">加载失败: ' + escapeHtml(e.message) + '</span>';
}
}
@@ -769,35 +773,74 @@
if (isImageUrl(textInput)) return await urlToBase64(textInput);
return stripDataUrlPrefix(textInput);
}
function parseWxidsFromInput(raw) {
return (raw || '').trim().split(/[\n,\s]+/).map(s => s.trim()).filter(Boolean);
}
function showImgSendProgress(visible, current, total, text, isError, isDone) {
const wrap = $('img-send-progress');
const fill = $('img-send-fill');
const txt = $('img-send-text');
if (!wrap || !fill || !txt) return;
wrap.style.display = visible ? 'block' : 'none';
wrap.classList.remove('is-error', 'is-done');
if (isError) wrap.classList.add('is-error');
if (isDone) wrap.classList.add('is-done');
const pct = total ? Math.round((current / total) * 100) : 0;
fill.style.width = pct + '%';
txt.textContent = text || (total ? '已发送 ' + current + ' / ' + total : '');
}
async function doSendImage() {
const key = getKey();
if (!key) return;
const toUser = $('img-to-user').value.trim();
if (!toUser) { alert('请填写接收人 wxid'); return; }
let imageContent;
try {
imageContent = await resolveImageContentToBase64();
} catch (e) {
alert('解析图片失败: ' + (e.message || e));
if (!key) {
showImgSendProgress(true, 0, 0, '请先登录', true, false);
return;
}
if (!imageContent) { alert('请填写或选择图片内容base64、URL 或本地图片)'); return; }
const manualWxids = parseWxidsFromInput($('img-to-user') && $('img-to-user').value);
const wxids = [...new Set([...massSelectedWxids, ...manualWxids])].filter(Boolean);
if (!wxids.length) {
showImgSendProgress(true, 0, 0, '请在上方勾选接收人,或填写接收人 wxid多人逗号/换行分隔)', true, false);
return;
}
let imageContent;
try {
showImgSendProgress(true, 0, wxids.length, '正在解析图片…', false, false);
imageContent = await resolveImageContentToBase64();
} catch (e) {
showImgSendProgress(true, 0, wxids.length, '解析图片失败: ' + (e.message || e), true, false);
return;
}
if (!imageContent) {
showImgSendProgress(true, 0, 0, '请填写或选择图片内容base64、URL 或本地图片)', true, false);
return;
}
const textContent = ($('img-text').value || '').trim();
const total = wxids.length;
let sent = 0;
try {
for (let i = 0; i < wxids.length; i++) {
showImgSendProgress(true, i, total, '发送中 ' + (i + 1) + ' / ' + total + '…', false, false);
if (i > 0) await new Promise(r => setTimeout(r, 1000));
await callApi('/api/send-image', {
method: 'POST',
body: JSON.stringify({
key,
to_user_name: toUser,
to_user_name: wxids[i],
image_content: imageContent,
text_content: ($('img-text').value || '').trim()
text_content: textContent
})
});
alert('图片已发送');
sent = i + 1;
showImgSendProgress(true, sent, total, '已发送 ' + sent + ' / ' + total, false, false);
}
showImgSendProgress(true, total, total, '已发送至 ' + total + ' 人', false, true);
$('img-content').value = '';
if ($('img-file')) $('img-file').value = '';
if ($('img-file-name')) $('img-file-name').textContent = '';
$('img-text').value = '';
} catch (e) { alert('发送图片失败: ' + (e.message || e)); }
setTimeout(function() { showImgSendProgress(false); }, 3000);
} catch (e) {
showImgSendProgress(true, sent, total, '发送失败(已发送 ' + sent + ' / ' + total + ': ' + (e.message || e), true, false);
}
}
async function doPushSend() {

View File

@@ -106,12 +106,21 @@ fi
echo "ngrok 公网地址: $PUBLIC_URL"
# 更新 .env存在 CALLBACK_BASE_URL 则替换,否则追加
# 更新 .env已有非空 CALLBACK_BASE_URL 时默认不覆盖,避免每次重启都要重新设定;传 --update 则强制更新
FORCE_UPDATE=0
for a in "$@"; do
[ "$a" = "--update" ] && FORCE_UPDATE=1
done
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
CURRENT_CB=""
[ -f "$ENV_FILE" ] && CURRENT_CB=$(grep -E '^CALLBACK_BASE_URL=' "$ENV_FILE" 2>/dev/null | sed 's/^CALLBACK_BASE_URL=//' | tr -d '\r' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') || true
if [ "$FORCE_UPDATE" = "1" ] || [ -z "$CURRENT_CB" ]; then
if [ ! -f "$ENV_FILE" ]; then
echo "CALLBACK_BASE_URL=$PUBLIC_URL" >> "$ENV_FILE"
echo "已写入 $ENV_FILE: CALLBACK_BASE_URL=$PUBLIC_URL"
else
else
if grep -q '^CALLBACK_BASE_URL=' "$ENV_FILE" 2>/dev/null; then
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' "s|^CALLBACK_BASE_URL=.*|CALLBACK_BASE_URL=$PUBLIC_URL|" "$ENV_FILE"
@@ -125,6 +134,9 @@ else
echo "CALLBACK_BASE_URL=$PUBLIC_URL" >> "$ENV_FILE"
echo "已追加 $ENV_FILE: CALLBACK_BASE_URL=$PUBLIC_URL"
fi
fi
else
echo "已保留现有 CALLBACK_BASE_URL=$CURRENT_CB(不覆盖)。若 ngrok 已换新地址,请执行: ./run-ngrok.sh --update"
fi
echo ""

1
run.sh
View File

@@ -8,6 +8,7 @@ usage() {
echo "用法: ./run.sh [--proxy-bridge]"
echo " --proxy-bridge 先启动本地代理桥接(8899→127.0.0.1:7890),便于 7006 通过 ngrok 使用本机代理"
echo "无参数时仅: ngrok 暴露 8000 并写入 CALLBACK_BASE_URL → 启动 run-dev.sh"
echo " .env 中已有 CALLBACK_BASE_URL 时不会覆盖,重启无需重设;换 ngrok 地址后执行: ./run-ngrok.sh --update"
echo ""
echo "注意: ngrok 免费版仅 1 个隧道,已用于 8000回调代理需另开隧道或 cloudflared 暴露 8899 后填 .env。"
}