openclaw-zalo-mod 2.30.0 → 2.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
6
  [![OpenClaw Plugin](https://img.shields.io/badge/OpenClaw-Plugin-blue.svg)](https://openclaw.ai)
7
- [![Version](https://img.shields.io/badge/version-2.30.0-green.svg)](./CHANGELOG.md)
7
+ [![Version](https://img.shields.io/badge/version-2.31.1-green.svg)](./CHANGELOG.md)
8
8
 
9
9
  **[🇺🇸 English](./README.md)**
10
10
 
package/README.vi.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
6
  [![OpenClaw Plugin](https://img.shields.io/badge/OpenClaw-Plugin-blue.svg)](https://openclaw.ai)
7
- [![Version](https://img.shields.io/badge/version-2.30.0-green.svg)](./CHANGELOG.md)
7
+ [![Version](https://img.shields.io/badge/version-2.31.1-green.svg)](./CHANGELOG.md)
8
8
 
9
9
  **[🇺🇸 English](./README.md)**
10
10
 
package/dashboard.js CHANGED
@@ -10,7 +10,7 @@ const modalBody = document.getElementById('modalBody');
10
10
  const modalCancel = document.getElementById('modalCancel');
11
11
  const modalConfirm = document.getElementById('modalConfirm');
12
12
  const token = window.ZALO_DASHBOARD_TOKEN || '';
13
- const pluginVersion = '2.30.0';
13
+ const pluginVersion = '2.31.1';
14
14
  let state = null;
15
15
  let activeGroupId = '';
16
16
  let lang = localStorage.getItem('zaloDashboardLang') || 'vi';
@@ -169,6 +169,24 @@ function setSection(id) {
169
169
  if (id === 'contacts') renderCrmContacts();
170
170
  if (id === 'leads') renderCrmLeads();
171
171
  if (id === 'tasks') renderCrmTasks();
172
+ // Trang đọc từ `state` cache trong trình duyệt — nhưng dữ liệu phía server có thể đã đổi mà
173
+ // KHÔNG đi qua tab này: owner nhắn "đồng bộ nhóm" là agent chạy sync-groups qua zalo_mod_action
174
+ // (cùng handler với nút UI). Đo thật 30/08/2026 trên bot "Em Mơ": server/API trả 15 nhóm mà tab
175
+ // mở sẵn vẫn vẽ 9 nhóm cũ — nhìn y như "đồng bộ không ăn". Refetch NỀN khi mở các trang
176
+ // state-driven; loadState() tự kết thúc bằng renderState() nên gọi là đủ. Chỉ các trang này —
177
+ // trang on-demand (chat, journal…) không refetch kẻo re-render nuốt nội dung đang gõ.
178
+ if (id === 'groups' || id === 'overview' || id === 'members') refreshStateQuiet();
179
+ }
180
+
181
+ // Refetch state ở nền khi chuyển trang. Cờ in-flight để bấm qua lại nhanh không dồn request;
182
+ // lỗi mạng nuốt im — chuyển trang không được nổ toast vì một lần refetch nền hỏng.
183
+ let _stateRefreshQuietInFlight = false;
184
+ function refreshStateQuiet() {
185
+ if (_stateRefreshQuietInFlight) return;
186
+ _stateRefreshQuietInFlight = true;
187
+ loadState()
188
+ .catch(() => {})
189
+ .finally(() => { _stateRefreshQuietInFlight = false; });
172
190
  }
173
191
  // Re-render whichever on-demand section is currently active (these render on
174
192
  // tab-open via setSection, not inside renderState). Called when the selected bot
@@ -7047,7 +7065,9 @@ function chatMsgHtml(m, { isGroup, lastDay, isNew = false }) {
7047
7065
  const html = `${sep}<div class="chat-msg${m.fromSelf ? ' me' : ''}${isNew ? ' chat-msg-new' : ''}" data-msg-id="${crmEsc(m.id)}">
7048
7066
  ${/* Tên người gửi chỉ có nghĩa trong nhóm — DM thì hai bên đã rõ, in thêm chỉ tổ rối. */''}
7049
7067
  ${isGroup && !m.fromSelf ? `<div class="chat-msg-who">${crmEsc(m.senderName || m.senderId)}</div>` : ''}
7050
- <div class="chat-bubble">${media}${crmEsc(m.text || '')}</div>
7068
+ ${/* Co anh roi thi khong in kem chu "[Media attachment]" — day la chu do host sinh ra khi
7069
+ tin khong co phan chu, giu lai chi lam bong bong roi. */''}
7070
+ <div class="chat-bubble">${media}${crmEsc(media && /^\[(media|file|image|sticker)[^\]]*\]$/i.test((m.text || '').trim()) ? '' : (m.text || ''))}</div>
7051
7071
  <div class="chat-msg-time">${chatTime(m.sentAt)}</div>
7052
7072
  </div>`;
7053
7073
  return { html, day };
package/index.html CHANGED
@@ -127,7 +127,7 @@
127
127
  log.</span>
128
128
  </div>
129
129
  <div class="plugin-meta">
130
- <strong>zalo-mod <span id="pluginVersion">v2.30.0</span></strong>
130
+ <strong>zalo-mod <span id="pluginVersion">v2.31.1</span></strong>
131
131
  <span>Được làm ❤️ bởi tuanminhole</span>
132
132
  <div class="socials" aria-label="Author links">
133
133
  <a href="https://www.facebook.com/holeminhtuan.it/" target="_blank" rel="noreferrer"
package/index.js CHANGED
@@ -25,6 +25,7 @@ import http from 'node:http';
25
25
  import path from 'node:path';
26
26
  import { fileURLToPath } from 'node:url';
27
27
  import { definePluginEntry } from 'openclaw/plugin-sdk/plugin-entry';
28
+ import { ghepLaiMedia } from './src/storage/media-backfill.js';
28
29
  import { createZaloModEngine } from './src/integration/zalo-mod-engine.js';
29
30
  import { handleCrmAction } from './src/crm/crm-api.js';
30
31
  import { buildZaloPeople } from './src/crm/zalo-people.js';
@@ -205,6 +206,15 @@ function foldText(value) {
205
206
  .trim();
206
207
  }
207
208
 
209
+ function isAddressedByBareName(foldedContent, foldedName) {
210
+ // Khop TEN TRAN (khong co '@') co RANH GIOI TU, tren chuoi da bo dau + thuong hoa.
211
+ // Cung ngu nghia voi textMentionsAnyName cua zalo-connect, de hai tang khong lech nhau.
212
+ // Ten < 2 ky tu bi bo: qua ngan thi khop nham nhieu hon la trung.
213
+ if (!foldedName || foldedName.length < 2) return false;
214
+ const escaped = foldedName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
215
+ return new RegExp(`(^|[^\\p{L}\\p{N}])${escaped}([^\\p{L}\\p{N}]|$)`, 'u').test(foldedContent);
216
+ }
217
+
208
218
  async function safeReadJson(filePath) {
209
219
  try {
210
220
  const raw = await fs.readFile(filePath, 'utf8');
@@ -475,6 +485,17 @@ async function getTemplateContent(filePath, defaultContent) {
475
485
  return defaultContent;
476
486
  }
477
487
 
488
+ // Tên bot HIỂN THỊ phải theo tên Zalo THẬT đang đăng nhập (bridge trả displayName khi replay/set
489
+ // name-trigger, được ghi vào globalThis.__zaloModLiveBotNames). pluginCfg.botName là cấu hình tĩnh:
490
+ // tài khoản đổi tên Zalo thì template ({botName}, @{botName} trong welcome) vẫn in tên cũ và dạy
491
+ // thành viên tag một cái tên không còn tag được. Đo 31/08/2026: welcome in "@Em Mơ" trong khi tên
492
+ // thật đã là "Em Mơ Trợ Lí".
493
+ function liveBotName(profile, fallback) {
494
+ const map = globalThis.__zaloModLiveBotNames || {};
495
+ const key = String(profile || 'default').split(',')[0].trim() || 'default';
496
+ return String(map[key] || '').trim() || fallback;
497
+ }
498
+
478
499
  function renderTemplate(templateStr, vars) {
479
500
  let result = String(templateStr || '');
480
501
  for (const [key, value] of Object.entries(vars)) {
@@ -571,14 +592,40 @@ function isMessageMentioningBot(event, botNames, profileName) {
571
592
  searchNames = [liveName, ...liveZaloNames].filter(Boolean);
572
593
  }
573
594
  }
595
+
596
+ // ── Ten goi do DASHBOARD luu nam o STORE KHAC ────────────────────────────────────
597
+ // Hop thoai "Che do Im lang — ten goi bot" luu qua persistNameTriggers(), ma ham do ghi
598
+ // vao settings.json (`global.nameTriggersByAccount`) — KHONG phai config.json ma doan tren
599
+ // vua doc. Thieu doan nay thi moi ten them tu hop thoai deu VO HINH voi tang nay:
600
+ // zalo-connect nhan duoc (bridge replay doc settings.json) nen cho qua cong cua no, roi
601
+ // den day bi chan — nhin tu ngoai la "da luu ma bot van khong tra loi".
602
+ // Do that 30/08/2026: settings.json co ["Mơ ơi","Em Mơ","trợ lý mơ","trợ lí mơ"] trong khi
603
+ // config.json van la danh sach cu ⇒ goi "trợ lý mơ" bot im.
604
+ for (const dp of dataPaths) {
605
+ const settingsPath = path.join(path.dirname(dp), 'settings.json');
606
+ if (!existsSync(settingsPath)) continue;
607
+ const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
608
+ const byAccount = settings?.global?.nameTriggersByAccount || {};
609
+ const saved = byAccount[profileName || 'default'] || byAccount.default || [];
610
+ if (Array.isArray(saved) && saved.length) {
611
+ searchNames = [...searchNames, ...saved.map(String)].filter(Boolean);
612
+ }
613
+ break;
614
+ }
574
615
  } catch (e) { }
575
616
 
576
617
  // Check all known bot names/aliases
618
+ const foldedContent = foldText(content);
577
619
  for (const raw of searchNames) {
578
620
  const name = String(raw || '').toLowerCase().trim();
579
621
  if (!name) continue;
580
622
  const folded = foldText(name);
581
623
  if (content.includes(`@${name}`) || content.includes(`@${folded}`)) return true;
624
+ // Goi TEN TRAN (khong co '@') — dung tinh nang "Im lang: bot tra loi khi goi dung ten bot"
625
+ // ma dashboard hua. zalo-connect DA cho qua cong cua no (do that 30/08/2026:
626
+ // wasNamed=true, skip=false) nhung o day van doi '@' nen tin rot lai va KHONG de lai
627
+ // log nao — nhin tu ngoai chi thay bot tha tim roi im.
628
+ if (isAddressedByBareName(foldedContent, folded)) return true;
582
629
  }
583
630
  // OpenClaw native mention flag
584
631
  if (event.wasMentioned === true) return true;
@@ -2545,7 +2592,7 @@ Quy tắc:
2545
2592
  try {
2546
2593
  const botCfg = getBotConfig(groupId);
2547
2594
  const welcomeTpl = await loadTemplateContent(dataDir, 'welcome');
2548
- const welcomeText = renderTemplate(welcomeTpl, { memberName, groupName: getGroupName(groupId), botName: botCfg.botName, cmdPrefix: botCfg.cmdPrefix });
2595
+ const welcomeText = renderTemplate(welcomeTpl, { memberName, groupName: getGroupName(groupId), botName: liveBotName(botCfg.profile, botCfg.botName), cmdPrefix: botCfg.cmdPrefix });
2549
2596
  await sendGroupMsg({ accountId: botCfg.profile }, groupId, welcomeText);
2550
2597
  await appendToMemoryFile(groupId, 'chat-highlights.md', `| ${nowShort()} | SYSTEM | Welcome: ${memberName} joined (detected by watcher) |`);
2551
2598
  logger.info(`[openclaw-zalo-mod] [WATCHER] welcome sent for ${memberName} in group ${groupId}`);
@@ -4246,7 +4293,13 @@ Quy tắc:
4246
4293
  const map = readTriggerMap();
4247
4294
  let applied = 0;
4248
4295
  for (const [accountId, list] of Object.entries(map)) {
4249
- try { await bridge.setNameTriggers(accountId, Array.isArray(list) ? list : []); applied++; }
4296
+ try {
4297
+ const runtime = await bridge.setNameTriggers(accountId, Array.isArray(list) ? list : []);
4298
+ applied++;
4299
+ // Bridge trả kèm tên Zalo THẬT — nguồn duy nhất luôn đúng sau khi đổi tên.
4300
+ const dn = String(runtime?.displayName || '').trim();
4301
+ if (dn) (globalThis.__zaloModLiveBotNames ||= {})[accountId] = dn;
4302
+ }
4250
4303
  catch (e) { logger.warn(`[openclaw-zalo-mod] name-trigger replay ${accountId}: ${e.message}`); }
4251
4304
  }
4252
4305
  return { applied, total: Object.keys(map).length };
@@ -5568,7 +5621,11 @@ Quy tắc:
5568
5621
  const bridge = globalThis.__zaloModEngine?.bridge;
5569
5622
  let runtime = null;
5570
5623
  if (bridge?.setNameTriggers) {
5571
- try { runtime = await bridge.setNameTriggers(accountId, input); }
5624
+ try {
5625
+ runtime = await bridge.setNameTriggers(accountId, input);
5626
+ const dn = String(runtime?.displayName || '').trim();
5627
+ if (dn) (globalThis.__zaloModLiveBotNames ||= {})[accountId] = dn;
5628
+ }
5572
5629
  catch (e) { logger.warn(`[openclaw-zalo-mod] set-name-triggers ${accountId}: ${e.message}`); }
5573
5630
  }
5574
5631
  // Persist the runtime-cleaned list when available so store and runtime match.
@@ -5828,6 +5885,23 @@ Quy tắc:
5828
5885
  // sử kéo về), nên mở khung chat không tốn một lượt gọi mạng nào và không đụng hạn mức
5829
5886
  // của Zalo. Đổi lại: chỉ thấy được những gì đã đồng bộ — nên phần mô tả trang nói thẳng
5830
5887
  // là lịch sử về khi bấm Sync account.
5888
+ // Ghep lai anh cu voi tin da mat link (P17). Chay duoc nhieu lan: `setMessageMedia`
5889
+ // chi ghi khi media_json con NULL nen khong bao gio de len du lieu dung.
5890
+ // `dryRun: true` de xem truoc se ghep bao nhieu ma khong sua gi.
5891
+ if (action === 'chat-backfill-media') {
5892
+ const store = zEngine?.storage;
5893
+ if (!store?.messagesWithoutMedia) throw new Error('Ghep lai anh can SQLite (Node >= 22.5).');
5894
+ const kq = ghepLaiMedia(store, _openclawHome, {
5895
+ toleranceMs: Math.min(Number(payload.toleranceMs) || 5000, 60000),
5896
+ limit: Math.min(Number(payload.limit) || 5000, 20000),
5897
+ dryRun: payload.dryRun === true,
5898
+ });
5899
+ logger.info(`[openclaw-zalo-mod] ghep lai anh: quet ${kq.quet} tin, ghep ${kq.ghep}`
5900
+ + `, bo qua nhap nhang ${kq.boQuaNhapNhang}, khong co tep ${kq.khongCo}`
5901
+ + (payload.dryRun === true ? ' (xem truoc, chua ghi)' : ''));
5902
+ return kq;
5903
+ }
5904
+
5831
5905
  if (action === 'chat-conversations' || action === 'chat-messages' || action === 'chat-version') {
5832
5906
  const store = zEngine?.storage;
5833
5907
  if (!store?.listConversations) throw new Error('Khung chat cần SQLite (Node >= 22.5).');
@@ -6312,6 +6386,49 @@ Quy tắc:
6312
6386
  return;
6313
6387
  }
6314
6388
 
6389
+ // ── Anh/tep dinh kem da tai ve (P17) ──
6390
+ //
6391
+ // OpenClaw tai san media ve `<home>/.openclaw/media/{inbound,outbound}`. Khung chat
6392
+ // can mot URL de dat vao <img src>, ma duong dan tren dia thi trinh duyet khong mo
6393
+ // duoc — nen phuc vu qua chinh dashboard. Khong doi token, GIONG logo/QR: dashboard
6394
+ // chi bind 127.0.0.1 va vao qua duong ham SSH; hon nua <img src> KHONG gui duoc
6395
+ // header Authorization nen bat token o day la tu khoa cua mo anh.
6396
+ //
6397
+ // Chan duong vong: chi nhan DUNG mot ten tep (khong thu muc con), loai bo moi thu
6398
+ // co '/', '\\' hay '..', roi doi soat lai bang path.resolve — vao duoc ngoai thu muc
6399
+ // media la tu choi. Chi phuc vu duoi tep da biet.
6400
+ if (req.method === 'GET' && url.pathname.startsWith('/media/')) {
6401
+ const parts = url.pathname.split('/').filter(Boolean); // ['media', kind, name]
6402
+ const kind = parts[1];
6403
+ const name = decodeURIComponent(parts[2] || '');
6404
+ const MIME = {
6405
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
6406
+ '.gif': 'image/gif', '.webp': 'image/webp', '.mp4': 'video/mp4',
6407
+ '.pdf': 'application/pdf',
6408
+ };
6409
+ const ext = path.extname(name).toLowerCase();
6410
+ const hopLe = parts.length === 3
6411
+ && (kind === 'inbound' || kind === 'outbound')
6412
+ && name && !name.includes('/') && !name.includes('\\') && !name.includes('..')
6413
+ && Object.prototype.hasOwnProperty.call(MIME, ext);
6414
+ if (!hopLe) {
6415
+ sendDashboardJson(res, 400, { ok: false, error: 'Media path khong hop le' });
6416
+ return;
6417
+ }
6418
+ const goc = path.resolve(_openclawHome, '.openclaw', 'media', kind);
6419
+ const tep = path.resolve(goc, name);
6420
+ if (!tep.startsWith(goc + path.sep) || !existsSync(tep)) {
6421
+ sendDashboardJson(res, 404, { ok: false, error: 'Media not found' });
6422
+ return;
6423
+ }
6424
+ res.writeHead(200, {
6425
+ 'content-type': MIME[ext],
6426
+ 'cache-control': 'private, max-age=86400',
6427
+ });
6428
+ res.end(readFileSync(tep));
6429
+ return;
6430
+ }
6431
+
6315
6432
  if (req.method === 'GET' && (url.pathname === '/assets/logo.png' || url.pathname === '/logo.png' || url.pathname === '/favicon.ico')) {
6316
6433
  if (!existsSync(logoFile)) {
6317
6434
  sendDashboardJson(res, 404, { ok: false, error: 'Logo not found' });
@@ -6657,7 +6774,22 @@ Quy tắc:
6657
6774
  } catch (_) { /* not JSON, normal text — continue */ }
6658
6775
 
6659
6776
  const rawConvId = String(ctx.conversationId || event.conversationId || '');
6660
- const isGroupMsg = rawConvId.startsWith('group:');
6777
+ // ── Nhan biet NHOM vs DM — do that, khong suy tu hop dong ──────────────────────
6778
+ // Tren hook `before_dispatch`, tin NHOM den duoi dang:
6779
+ // conversationId = "'zalo-connect':<GROUP_ID>" (KHONG co tien to `group:`)
6780
+ // event.isGroup = false (openclaw bao SAI)
6781
+ // Do that tren bot "Em Mo" 30/08/2026, cung dang voi DM (`'zalo-connect':<USER_ID>`),
6782
+ // nen KHONG co cach nao phan biet bang hinh dang chuoi. Hau qua neu doan sai: moi tin
6783
+ // nhom roi vao nhanh DM ben duoi ⇒ `permissions.dm.mode="owner"` khoa luon ca nhom,
6784
+ // ngoai owner ra khong ai noi duoc voi bot o BAT KY dau, du nhom da tick trong Quyen
6785
+ // Group. Tin bi `handled:true` nuot mat, khong de lai dau vet trong log zalo-connect.
6786
+ // Nguon tin cay duy nhat: SO NHOM cua chinh plugin (`groupNames`, tra qua
6787
+ // plainGroupId). Duoi id lay sau dau ':' cuoi vi tien to la ten kenh co nhay don.
6788
+ const convTailId = rawConvId.replace(/^.*:/, '').trim();
6789
+ const knownGroupId = plainGroupId(rawConvId, convTailId);
6790
+ const isGroupMsg = event?.isGroup === true
6791
+ || rawConvId.startsWith('group:')
6792
+ || !!knownGroupId;
6661
6793
  const senderId = String(ctx.senderId || event.senderId || '');
6662
6794
  // Group event thường KHÔNG kèm tên hiển thị → thử các field rẻ trước, resolve qua API sau (bên dưới).
6663
6795
  let senderName = String(event.senderName || event.sender?.name || event.dName || event.data?.dName || '').trim() || senderId;
@@ -6666,7 +6798,10 @@ Quy tắc:
6666
6798
  // profile ghi nhận của group. Nhờ vậy mỗi bot trong group nhiều bot sẽ
6667
6799
  // dùng đúng tên/prefix/owner của chính nó (check @mention, slash, owner...).
6668
6800
  const botCfg = getBotConfig(ctx?.accountId || (isGroupMsg ? rawConvId : 'default'));
6669
- const { profile, botName, botNames, cmdPrefix, ownerId: activeOwnerId } = botCfg;
6801
+ const { profile, botName: cfgBotName, botNames, cmdPrefix, ownerId: activeOwnerId } = botCfg;
6802
+ // Moi cho hien thi ten bot trong handler nay (template, menu owner, DM…) dung ten
6803
+ // Zalo THAT; cau hinh tinh chi con la fallback khi bridge chua tra displayName.
6804
+ const botName = liveBotName(profile, cfgBotName);
6670
6805
  const currentOwnerId = activeOwnerId || (profile === 'default' ? ownerId : '');
6671
6806
 
6672
6807
  // Tên hiển thị: nếu event không kèm tên (senderName == id) → resolve qua API bot nhận tin (có cache).
@@ -6813,10 +6948,25 @@ Quy tắc:
6813
6948
  return { handled: true };
6814
6949
  }
6815
6950
 
6816
- const groupId = rawConvId.replace(/^group:/, '');
6951
+ // rawConvId co the la "'zalo-connect':<id>" nen khong the chi cat tien to `group:`
6952
+ // — cat vay se ra chuoi rac va `isGroupAllowed()` ben duoi luon truot.
6953
+ const groupId = knownGroupId || rawConvId.replace(/^group:/, '');
6817
6954
 
6818
6955
  // ── GROUP ACCESS GATE — bot chỉ hoạt động ở group được phép (owner luôn lọt) ──
6819
- if (!isGroupAllowed(groupId) && senderId !== currentOwnerId) return { handled: true };
6956
+ if (!isGroupAllowed(groupId) && senderId !== currentOwnerId) {
6957
+ // Ngoại lệ NHỎ: lệnh TEMPLATE tĩnh vẫn trả lời được. Welcome/follow là toggle theo
6958
+ // nhóm, ĐỘC LẬP với allowList Quyền Group — nên chính bot vẫn gửi welcome dạy
6959
+ // "/bot-noi-quy", "/bot-menu" vào nhóm chưa tick, thành viên bấm theo mà bot im thì
6960
+ // như bot hỏng (đo 31/08/2026, nhóm "Kinh Doanh Một Người Với AI"). Chỉ mở template:
6961
+ // text tĩnh, zero-token, không LLM, không đổi cấu hình; mọi thứ khác chặn như cũ.
6962
+ const _m = String(content || '').match(/(?:^|\s)(\/[a-z][a-z0-9-]*)/i);
6963
+ const _raw = _m ? _m[1].toLowerCase() : '';
6964
+ const _pfx = String(cmdPrefix || '').toLowerCase();
6965
+ const _cmd = _raw && _pfx && _raw.startsWith(_pfx) ? '/' + _raw.slice(_pfx.length) : '';
6966
+ const _isStaticTpl = ['/noi-quy', '/menu', '/huong-dan'].includes(_cmd)
6967
+ || (!!_cmd && !!resolveTemplateKeyByCommand(_cmd, pluginCfg));
6968
+ if (!_isStaticTpl) return { handled: true };
6969
+ }
6820
6970
 
6821
6971
  // ── MUTE CHECK — first gate, before everything else ───
6822
6972
  const isMuted = store.getSetting(groupId, 'muted', false);
@@ -6836,9 +6986,21 @@ Quy tắc:
6836
6986
  // ── Z2: Passive capture (zero-token) — TRƯỚC mention gating ──
6837
6987
  // Mọi tin group được phép vào ConversationBuffer + SQLite; khi bot
6838
6988
  // được tag sẽ inject bounded context. Tuyệt đối không gọi LLM ở đây.
6839
- zEngine.captureInbound({
6989
+ // Duong bridge `onInbound` DA ghi MOI tin vao (msgId THAT + text THO). Den day
6990
+ // `before_dispatch` khong con msgId nen engine phai bia `derived:<sender>:<ts>`, va
6991
+ // `content` luc nay la ban DA BOC ("[userId: …, name: …]: …" + khoi "Recent group
6992
+ // chat") ⇒ moi tin bi ghi HAI lan, Khung chat hien hai dong, dong thu hai lo ca prompt
6993
+ // noi bo. Do that 30/08/2026: moi tin that deu co mot ban sinh doi id `derived:…`.
6994
+ // Vi vay chi ghi khi KHONG co bridge (ban cai cu), con lai de bridge lam.
6995
+ if (!globalThis.__zaloConnectBridgeService) zEngine.captureInbound({
6840
6996
  accountId: ctx?.accountId,
6841
- conversationId: rawConvId,
6997
+ // PHAI chuan hoa ve dang `group:<id>` — dung dang ma duong sync dung
6998
+ // (zalo-mod-engine.js đã ghi chú đúng lỗi này cho đường của nó). Hook
6999
+ // `before_dispatch` giao rawConvId dạng "'zalo-connect':<id>"; ghi thẳng chuỗi đó
7000
+ // là CÙNG một nhóm nằm ở hai hàng hội thoại khác nhau, Khung chat hiện thành hai
7001
+ // dòng với hai số đếm rời rạc — trên bot "Em Mơ" 30/08/2026 ra tận BA khoá:
7002
+ // `group:1388…` 53 tin, `'zalo-connect':1388…` 7 tin, `1388…` 4 tin.
7003
+ conversationId: groupId ? `group:${groupId}` : rawConvId,
6842
7004
  groupId,
6843
7005
  messageId: event?.msgId ?? event?.messageId ?? event?.cliMsgId,
6844
7006
  senderId,
@@ -3,7 +3,7 @@
3
3
  "name": "OpenClaw Zalo Mod",
4
4
  "description": "Zero-token Zalo group moderation — slash commands, anti-spam, warn system, memory integration. Blocks LLM for non-mention messages.",
5
5
  "icon": "https://cdn.simpleicons.org/zalo",
6
- "version": "2.30.0",
6
+ "version": "2.31.1",
7
7
  "enabledByDefault": false,
8
8
  "activation": {
9
9
  "onStartup": true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openclaw-zalo-mod",
3
- "version": "2.30.0",
3
+ "version": "2.31.1",
4
4
  "description": "Zero-token Zalo group moderation plugin for OpenClaw — slash commands, anti-spam, warn system, and memory integration.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -48,8 +48,11 @@ export class ConversationBuffer {
48
48
  senderId: event.quote.senderId != null ? String(event.quote.senderId) : undefined,
49
49
  text: event.quote.text,
50
50
  }) : undefined,
51
+ // `url` PHAI giu: no la thu duy nhat cho phep khung chat hien anh that thay vi
52
+ // mot dong chu "[Media attachment]". Ban dau chi giu kind/filename/mime/size nen
53
+ // link bi cat ngay tai day, truoc khi kip ghi xuong SQLite.
51
54
  attachments: Object.freeze((event.attachments || []).map(a => ({
52
- kind: a.kind, filename: a.filename, mime: a.mime, size: a.size,
55
+ kind: a.kind, filename: a.filename, mime: a.mime, size: a.size, url: a.url,
53
56
  }))),
54
57
  reactions: event.reactions ? Object.freeze([...event.reactions]) : undefined,
55
58
  });
@@ -86,6 +89,7 @@ export class ConversationBuffer {
86
89
  rawType: rec.rawType,
87
90
  sentAt: rec.timestamp,
88
91
  quoteId: rec.quote?.messageId ?? null,
92
+ mediaUrls: (rec.attachments || []).map(a => a.url).filter(Boolean),
89
93
  });
90
94
  } catch {
91
95
  // Persistence là best-effort; buffer trong RAM vẫn là nguồn cho context.
@@ -185,7 +185,7 @@ export function createZaloModEngine({ dataDir, logger, runtime, getConfig, confi
185
185
  * Ghi passive một tin group/DM được phép — gọi TRƯỚC mention gating.
186
186
  * Zero-token: chỉ RAM + SQLite. Không bao giờ throw (best-effort).
187
187
  */
188
- captureInbound({ accountId, conversationId, groupId, messageId, senderId, senderName, text, timestamp, rawType, quote }) {
188
+ captureInbound({ accountId, conversationId, groupId, messageId, senderId, senderName, text, timestamp, rawType, quote, attachments }) {
189
189
  try {
190
190
  const acc = accountId || 'default';
191
191
  const ms = toMs(timestamp);
@@ -207,6 +207,10 @@ export function createZaloModEngine({ dataDir, logger, runtime, getConfig, confi
207
207
  timestamp: ms,
208
208
  rawType: rawType || 'message',
209
209
  quote,
210
+ // Thieu dong nay la anh/tep gui truc tiep bi mat link: khung chat chi con
211
+ // chu "[Media attachment]" tron tro (tin keo ve bang Sync thi van co anh,
212
+ // nen loi trong rat kho doan). Xem test media-capture.test.js.
213
+ attachments,
210
214
  });
211
215
  } catch (e) {
212
216
  log.warn?.(`[zalo-mod] captureInbound bỏ qua: ${e.message}`);
@@ -100,6 +100,21 @@ export class SqliteStore {
100
100
  return this._selRecent.all(conversationId, limit).reverse();
101
101
  }
102
102
 
103
+ /** Tin CHUA co media (media_json NULL) — dau vao cho viec ghep lai anh da tai ve. */
104
+ messagesWithoutMedia(limit = 5000) {
105
+ return this.db.prepare(`SELECT id, sent_at, from_self FROM messages
106
+ WHERE media_json IS NULL ORDER BY sent_at DESC LIMIT ?`).all(Math.min(Number(limit) || 5000, 20000));
107
+ }
108
+
109
+ /** Ga link media cho MOT tin da co. Tra ve true neu that su co dong bi sua. */
110
+ setMessageMedia(id, urls) {
111
+ const list = (Array.isArray(urls) ? urls : []).filter(Boolean);
112
+ if (!list.length) return false;
113
+ const r = this.db.prepare('UPDATE messages SET media_json = ? WHERE id = ? AND media_json IS NULL')
114
+ .run(JSON.stringify(list), String(id));
115
+ return Number(r.changes) > 0;
116
+ }
117
+
103
118
  /** Danh sách hội thoại, mới nhất trước — cột trái của khung chat. */
104
119
  listConversations({ accountId, limit = 100 } = {}) {
105
120
  const where = accountId ? 'WHERE account_id = ?' : '';
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Ghép lại ảnh đã tải về với tin nhắn đã mất link.
3
+ *
4
+ * OpenClaw tải sẵn ảnh về `<home>/.openclaw/media/{inbound,outbound}` và đặt tên theo mốc thời gian
5
+ * (`2026-08-21T12-03-47-zalo-<hash>.jpg`). Trước bản vá P17, đường bắt tin trực tiếp đánh rơi link
6
+ * nên `media_json` là NULL — chữ "[Media attachment]" trơ ra dù ẢNH VẪN CÒN TRÊN ĐĨA.
7
+ *
8
+ * Hàm này nối hai thứ đó lại bằng thời gian.
9
+ *
10
+ * 🔴 Luật quan trọng: **chỉ nhận ghép 1-1**. Trong cửa sổ ±N giây mà có nhiều hơn một tệp thì BỎ QUA,
11
+ * không đoán. Gán nhầm ảnh của người này sang tin của người khác trong một khung chat CRM là hỏng
12
+ * nặng hơn nhiều so với việc thiếu một tấm ảnh.
13
+ */
14
+ import { readdirSync, existsSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+
17
+ const TEN_TEP = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/;
18
+ const DUOI_HOP_LE = /\.(jpg|jpeg|png|gif|webp|mp4|pdf)$/i;
19
+
20
+ /** Đọc kho media, trả về [{ url, t }] với `t` là mốc thời gian lấy từ TÊN TỆP. */
21
+ export function docKhoMedia(openclawHome, kinds = ['inbound', 'outbound']) {
22
+ const out = [];
23
+ for (const kind of kinds) {
24
+ const dir = join(openclawHome, '.openclaw', 'media', kind);
25
+ if (!existsSync(dir)) continue;
26
+ for (const f of readdirSync(dir)) {
27
+ const m = TEN_TEP.exec(f);
28
+ if (!m || !DUOI_HOP_LE.test(f)) continue;
29
+ const t = Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}Z`);
30
+ if (Number.isNaN(t)) continue;
31
+ out.push({ url: `/media/${kind}/${encodeURIComponent(f)}`, t, kind });
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /**
38
+ * @returns {{ quet: number, ghep: number, boQuaNhapNhang: number, khongCo: number }}
39
+ */
40
+ export function ghepLaiMedia(storage, openclawHome, { toleranceMs = 5000, limit = 5000, dryRun = false } = {}) {
41
+ const kho = docKhoMedia(openclawHome);
42
+ const tin = storage.messagesWithoutMedia?.(limit) || [];
43
+ let ghep = 0, boQuaNhapNhang = 0, khongCo = 0;
44
+
45
+ for (const t of tin) {
46
+ const sentAt = Number(t.sent_at) || 0;
47
+ // Tin của chính bot thì ảnh nằm ở `outbound`, tin người khác ở `inbound` — lọc theo đúng
48
+ // hướng để bớt hẳn nhập nhằng khi bot và khách gửi ảnh gần như cùng lúc.
49
+ const huong = t.from_self ? 'outbound' : 'inbound';
50
+ const ungVien = kho.filter((m) => m.kind === huong && Math.abs(m.t - sentAt) <= toleranceMs);
51
+ if (ungVien.length === 0) { khongCo++; continue; }
52
+ if (ungVien.length > 1) { boQuaNhapNhang++; continue; }
53
+ if (dryRun) { ghep++; continue; }
54
+ if (storage.setMessageMedia?.(t.id, [ungVien[0].url])) ghep++;
55
+ }
56
+ return { quet: tin.length, ghep, boQuaNhapNhang, khongCo };
57
+ }