Update public-api.js via upload script - 2026-11-12 11:55:03
This commit is contained in:
parent
ee8c4d3946
commit
0bbc5b5f44
|
|
@ -171,6 +171,7 @@ function conf(name) {
|
||||||
const WEB_TRANSLATE_LANGS = {
|
const WEB_TRANSLATE_LANGS = {
|
||||||
es: 'Latin American Spanish (neutral, for Venezuela/Colombia buyers; say "UPS", never "SAI")',
|
es: 'Latin American Spanish (neutral, for Venezuela/Colombia buyers; say "UPS", never "SAI")',
|
||||||
ru: 'Russian',
|
ru: 'Russian',
|
||||||
|
ar: 'Modern Standard Arabic (for Middle East / Gulf buyers; keep model names, units and numbers in Latin characters and Western digits)',
|
||||||
};
|
};
|
||||||
// 译文缓存:英文没改就不重复调用 DeepSeek(省钱、构建也快)。单独一个文件,不碰 data.json。
|
// 译文缓存:英文没改就不重复调用 DeepSeek(省钱、构建也快)。单独一个文件,不碰 data.json。
|
||||||
const TRANSLATION_CACHE_FILE = path.join(__dirname, 'web-translations.json');
|
const TRANSLATION_CACHE_FILE = path.join(__dirname, 'web-translations.json');
|
||||||
|
|
@ -802,7 +803,7 @@ async function downloadWxImage(url, dir, name) {
|
||||||
// —— 新闻文章(kind:'article')的发布输出 ——
|
// —— 新闻文章(kind:'article')的发布输出 ——
|
||||||
// 文字按"原文"存(导入时是中文 zh);手动填了 en/es/ru 的优先,没填的自动翻译。中文 → 英/西/俄;英文原文 → 西/俄。
|
// 文字按"原文"存(导入时是中文 zh);手动填了 en/es/ru 的优先,没填的自动翻译。中文 → 英/西/俄;英文原文 → 西/俄。
|
||||||
async function translateAny(ai, strings) {
|
async function translateAny(ai, strings) {
|
||||||
const out = { en: {}, es: {}, ru: {} };
|
const out = { en: {}, es: {}, ru: {}, ar: {} };
|
||||||
const uniq = [...new Set(strings.map((x) => String(x || '').trim()).filter(Boolean))];
|
const uniq = [...new Set(strings.map((x) => String(x || '').trim()).filter(Boolean))];
|
||||||
const zh = uniq.filter(hasZh), en = uniq.filter((t) => !hasZh(t));
|
const zh = uniq.filter(hasZh), en = uniq.filter((t) => !hasZh(t));
|
||||||
const cache = loadCache();
|
const cache = loadCache();
|
||||||
|
|
@ -1392,8 +1393,9 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
||||||
en: "Hi, welcome to SKE Power 👋\nLooking for a UPS, solar inverter, energy storage or lithium batteries? Tell me what you need to power and I'll help you find the right model.",
|
en: "Hi, welcome to SKE Power 👋\nLooking for a UPS, solar inverter, energy storage or lithium batteries? Tell me what you need to power and I'll help you find the right model.",
|
||||||
es: '¡Hola, bienvenido a SKE Power! 👋\n¿Busca un UPS, un inversor solar, almacenamiento de energía o baterías de litio? Cuénteme qué necesita alimentar y le ayudo a encontrar el modelo adecuado.',
|
es: '¡Hola, bienvenido a SKE Power! 👋\n¿Busca un UPS, un inversor solar, almacenamiento de energía o baterías de litio? Cuénteme qué necesita alimentar y le ayudo a encontrar el modelo adecuado.',
|
||||||
ru: 'Здравствуйте, добро пожаловать в SKE Power 👋\nИщете ИБП, солнечный инвертор, накопитель энергии или литиевые батареи? Расскажите, что нужно питать, и я помогу подобрать модель.',
|
ru: 'Здравствуйте, добро пожаловать в SKE Power 👋\nИщете ИБП, солнечный инвертор, накопитель энергии или литиевые батареи? Расскажите, что нужно питать, и я помогу подобрать модель.',
|
||||||
|
ar: 'مرحبًا بك في SKE Power 👋\nهل تبحث عن UPS أو عاكس شمسي أو نظام تخزين طاقة أو بطاريات ليثيوم؟ أخبرني بما تحتاج إلى تشغيله وسأساعدك في اختيار الطراز المناسب.',
|
||||||
};
|
};
|
||||||
const JOINED = { en: (n, t) => `${n} (${t}) joined the chat`, es: (n, t) => `${n} (${t}) se unió al chat`, ru: (n, t) => `${n} (${t}) присоединился к чату` };
|
const JOINED = { en: (n, t) => `${n} (${t}) joined the chat`, es: (n, t) => `${n} (${t}) se unió al chat`, ru: (n, t) => `${n} (${t}) присоединился к чату`, ar: (n, t) => `انضم ${n} (${t}) إلى المحادثة` };
|
||||||
function pubMsg(conv, m) {
|
function pubMsg(conv, m) {
|
||||||
const st = S();
|
const st = S();
|
||||||
return { id: m.id, at: m.at, from: m.from === 'user' ? 'user' : m.from === 'sys' ? 'sys' : 'agent', name: m.from === 'human' ? st.managerName : m.from === 'ai' ? st.agentName : undefined, text: m.text, wa: m.wa || undefined };
|
return { id: m.id, at: m.at, from: m.from === 'user' ? 'user' : m.from === 'sys' ? 'sys' : 'agent', name: m.from === 'human' ? st.managerName : m.from === 'ai' ? st.agentName : undefined, text: m.text, wa: m.wa || undefined };
|
||||||
|
|
@ -1424,7 +1426,7 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
||||||
const ip = ipOf(req);
|
const ip = ipOf(req);
|
||||||
if (limited('start:' + ip, 8, 3600e3)) return res.status(429).json({ error: 'too many' });
|
if (limited('start:' + ip, 8, 3600e3)) return res.status(429).json({ error: 'too many' });
|
||||||
const b = req.body || {};
|
const b = req.body || {};
|
||||||
const lang = ['en', 'es', 'ru'].includes(b.lang) ? b.lang : 'en';
|
const lang = ['en', 'es', 'ru', 'ar'].includes(b.lang) ? b.lang : 'en';
|
||||||
const sid = uid('c'), token = crypto.randomBytes(16).toString('hex');
|
const sid = uid('c'), token = crypto.randomBytes(16).toString('hex');
|
||||||
const conv = store.convs[sid] = {
|
const conv = store.convs[sid] = {
|
||||||
sid, token, created: Date.now(), updated: Date.now(), lang, custLang: lang,
|
sid, token, created: Date.now(), updated: Date.now(), lang, custLang: lang,
|
||||||
|
|
@ -1488,16 +1490,17 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
||||||
});
|
});
|
||||||
|
|
||||||
/* ---------------- 第二层:重要客户转到 WhatsApp ---------------- */
|
/* ---------------- 第二层:重要客户转到 WhatsApp ---------------- */
|
||||||
const WA_LABEL = { en: (n) => `Chat with ${n} on WhatsApp`, es: (n) => `Hablar con ${n} por WhatsApp`, ru: (n) => `Написать ${n} в WhatsApp` };
|
const WA_LABEL = { en: (n) => `Chat with ${n} on WhatsApp`, es: (n) => `Hablar con ${n} por WhatsApp`, ru: (n) => `Написать ${n} в WhatsApp` , ar: (n) => `تحدّث مع ${n} عبر واتساب` };
|
||||||
const WA_TEXT = {
|
const WA_TEXT = {
|
||||||
en: (n, who, code) => `Hi ${n}, ${who ? `this is ${who}` : 'I was chatting on your website'} (SKE chat #${code}).`,
|
en: (n, who, code) => `Hi ${n}, ${who ? `this is ${who}` : 'I was chatting on your website'} (SKE chat #${code}).`,
|
||||||
es: (n, who, code) => `Hola ${n}, ${who ? `soy ${who}` : 'estuve conversando en su sitio web'} (chat SKE #${code}).`,
|
es: (n, who, code) => `Hola ${n}, ${who ? `soy ${who}` : 'estuve conversando en su sitio web'} (chat SKE #${code}).`,
|
||||||
ru: (n, who, code) => `Здравствуйте, ${n}! ${who ? `Это ${who}` : 'Я писал(а) вам на сайте'} (чат SKE #${code}).`,
|
ru: (n, who, code) => `Здравствуйте, ${n}! ${who ? `Это ${who}` : 'Я писал(а) вам на сайте'} (чат SKE #${code}).`,
|
||||||
|
ar: (n, who, code) => `مرحبًا ${n}، ${who ? `معك ${who}` : 'كنت أتحدث معكم على موقعكم'} (محادثة SKE رقم ${code}).`,
|
||||||
};
|
};
|
||||||
function waButton(conv) {
|
function waButton(conv) {
|
||||||
const st = S(); if (!st.waNumber) return null;
|
const st = S(); if (!st.waNumber) return null;
|
||||||
const l = conv.lead || {}, lang = WA_TEXT[conv.custLang] ? conv.custLang : (WA_TEXT[conv.lang] ? conv.lang : 'en');
|
const l = conv.lead || {}, lang = WA_TEXT[conv.custLang] ? conv.custLang : (WA_TEXT[conv.lang] ? conv.lang : 'en');
|
||||||
const who = [l.name, l.company && `${lang === 'es' ? 'de' : lang === 'ru' ? 'из' : 'from'} ${l.company}`].filter(Boolean).join(' ');
|
const who = [l.name, l.company && `${lang === 'es' ? 'de' : lang === 'ru' ? 'из' : lang === 'ar' ? 'من' : 'from'} ${l.company}`].filter(Boolean).join(' ');
|
||||||
return { url: `https://wa.me/${st.waNumber}?text=${encodeURIComponent(WA_TEXT[lang](st.managerName, who, conv.code))}`, label: WA_LABEL[lang](st.managerName) };
|
return { url: `https://wa.me/${st.waNumber}?text=${encodeURIComponent(WA_TEXT[lang](st.managerName, who, conv.code))}`, label: WA_LABEL[lang](st.managerName) };
|
||||||
}
|
}
|
||||||
const important = (conv) => (conv.lead && (conv.lead.score || 0) >= S().notifyScore);
|
const important = (conv) => (conv.lead && (conv.lead.score || 0) >= S().notifyScore);
|
||||||
|
|
@ -1561,7 +1564,7 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
||||||
text = String(await ai.callDeepSeekWithRetry(cfg.apiKey, msgs, { maxTokens: 700, temperature: 0.5, timeoutMs: 70000, firstTokenMs: 25000 }) || '').trim();
|
text = String(await ai.callDeepSeekWithRetry(cfg.apiKey, msgs, { maxTokens: 700, temperature: 0.5, timeoutMs: 70000, firstTokenMs: 25000 }) || '').trim();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('[chat] AI 出错:', e.message);
|
console.warn('[chat] AI 出错:', e.message);
|
||||||
text = { en: `Sorry, give me a moment — ${S().managerName}, our sales manager, will reply to you shortly. You can also reach us on WhatsApp: +86 152 0127 3157.`, es: `Disculpe, un momento: ${S().managerName}, nuestro gerente de ventas, le responderá en breve. También puede escribirnos por WhatsApp: +86 152 0127 3157.`, ru: `Извините, одну минуту — ${S().managerName}, наш менеджер по продажам, скоро ответит. Также можно написать в WhatsApp: +86 152 0127 3157.` }[conv.lang] || '';
|
text = { en: `Sorry, give me a moment — ${S().managerName}, our sales manager, will reply to you shortly. You can also reach us on WhatsApp: +86 152 0127 3157.`, es: `Disculpe, un momento: ${S().managerName}, nuestro gerente de ventas, le responderá en breve. También puede escribirnos por WhatsApp: +86 152 0127 3157.`, ru: `Извините, одну минуту — ${S().managerName}, наш менеджер по продажам, скоро ответит. Также можно написать в WhatsApp: +86 152 0127 3157.`, ar: `عذرًا، لحظة من فضلك — سيرد عليك ${S().managerName}، مدير المبيعات لدينا، قريبًا. يمكنك أيضًا التواصل معنا عبر واتساب: +86 152 0127 3157.` }[conv.lang] || '';
|
||||||
conv.lead.needsHuman = true; conv.lead.reason = 'AI 出错:' + e.message.slice(0, 80);
|
conv.lead.needsHuman = true; conv.lead.reason = 'AI 出错:' + e.message.slice(0, 80);
|
||||||
notifyLead(conv, 'AI 无法回复,需要人工');
|
notifyLead(conv, 'AI 无法回复,需要人工');
|
||||||
}
|
}
|
||||||
|
|
@ -1742,7 +1745,7 @@ ${dialog}`;
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
// 手动给客户发"转到 WhatsApp"按钮(以 Mike 的名义)
|
// 手动给客户发"转到 WhatsApp"按钮(以 Mike 的名义)
|
||||||
const WA_MSG = { en: (n) => `You can also reach me directly on WhatsApp — just tap the button below.`, es: (n) => `También puede escribirme directamente por WhatsApp; toque el botón de abajo.`, ru: (n) => `Можно написать мне напрямую в WhatsApp — нажмите кнопку ниже.` };
|
const WA_MSG = { en: (n) => `You can also reach me directly on WhatsApp — just tap the button below.`, es: (n) => `También puede escribirme directamente por WhatsApp; toque el botón de abajo.`, ru: (n) => `Можно написать мне напрямую в WhatsApp — нажмите кнопку ниже.` , ar: (n) => `يمكنك أيضًا التواصل معي مباشرة عبر واتساب — فقط اضغط على الزر أدناه.` };
|
||||||
app.post(`${A}/:sid/wa-offer`, authConv, (req, res) => {
|
app.post(`${A}/:sid/wa-offer`, authConv, (req, res) => {
|
||||||
const c = convOr404(req, res); if (!c) return;
|
const c = convOr404(req, res); if (!c) return;
|
||||||
const wa = waButton(c); if (!wa) return res.status(400).json({ error: '设置里没填 WhatsApp 号码' });
|
const wa = waButton(c); if (!wa) return res.status(400).json({ error: '设置里没填 WhatsApp 号码' });
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue