levix-bot 4.0.4 → 4.2.0
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/package.json +1 -1
- package/public/dashboard/assets/index-4AuqfnH5.js +431 -0
- package/public/dashboard/assets/index-LvfJ8ybs.css +2 -0
- package/public/dashboard/index.html +2 -2
- package/scheduler.cjs +25 -1
- package/src/commands/autoschedule.cjs +40 -10
- package/src/commands/blacklist.cjs +35 -10
- package/src/commands/block.cjs +18 -5
- package/src/commands/calc.cjs +90 -24
- package/src/commands/debt.cjs +59 -33
- package/src/commands/deleteschedule.cjs +21 -5
- package/src/commands/digit.cjs +34 -8
- package/src/commands/gemini.cjs +235 -108
- package/src/commands/group/add.cjs +46 -13
- package/src/commands/group/all.cjs +15 -5
- package/src/commands/group/antiSpam.cjs +11 -4
- package/src/commands/group/antilink.cjs +39 -19
- package/src/commands/group/approveall.cjs +22 -7
- package/src/commands/group/clearwarns.cjs +18 -5
- package/src/commands/group/deletenote.cjs +18 -5
- package/src/commands/group/demote.cjs +25 -7
- package/src/commands/group/kick.cjs +28 -12
- package/src/commands/group/media.cjs +34 -13
- package/src/commands/group/members.cjs +21 -6
- package/src/commands/group/note.cjs +14 -4
- package/src/commands/group/promote.cjs +22 -6
- package/src/commands/group/removeall.cjs +13 -3
- package/src/commands/group/rules.cjs +20 -5
- package/src/commands/group/save.cjs +20 -5
- package/src/commands/group/setname.cjs +19 -6
- package/src/commands/group/setpp.cjs +21 -6
- package/src/commands/group/setrules.cjs +17 -5
- package/src/commands/group/setwarn.cjs +23 -7
- package/src/commands/group/tagadmins.cjs +16 -6
- package/src/commands/group/warn.cjs +35 -15
- package/src/commands/group/warns.cjs +33 -13
- package/src/commands/group/welcome.cjs +34 -16
- package/src/commands/group.cjs +96 -70
- package/src/commands/help.cjs +270 -129
- package/src/commands/lang.cjs +46 -13
- package/src/commands/listschedules.cjs +28 -11
- package/src/commands/loop.cjs +43 -9
- package/src/commands/memory.cjs +90 -30
- package/src/commands/mod.cjs +72 -28
- package/src/commands/notes.cjs +15 -5
- package/src/commands/perm.cjs +52 -20
- package/src/commands/ping.cjs +15 -3
- package/src/commands/poll.cjs +71 -24
- package/src/commands/prayer.cjs +28 -12
- package/src/commands/qr.cjs +20 -5
- package/src/commands/rand.cjs +54 -12
- package/src/commands/restart.cjs +13 -3
- package/src/commands/schedule.cjs +32 -9
- package/src/commands/score.cjs +26 -10
- package/src/commands/setprefix.cjs +27 -5
- package/src/commands/shortlink.cjs +36 -10
- package/src/commands/shutdown.cjs +13 -3
- package/src/commands/status.cjs +32 -11
- package/src/commands/sticker.cjs +34 -7
- package/src/commands/stt.cjs +159 -107
- package/src/commands/todo.cjs +31 -9
- package/src/commands/tts.cjs +61 -36
- package/src/commands/unblock.cjs +17 -4
- package/src/commands/weather.cjs +55 -17
- package/src/config/baileys.config.js +5 -1
- package/src/config/settings.cjs +11 -3
- package/src/core/connection.js +21 -2
- package/src/core/socket.js +31 -7
- package/src/db/store.cjs +24 -0
- package/src/handlers/command.handler.js +55 -13
- package/src/handlers/group.handler.js +5 -1
- package/src/handlers/message.handler.js +9 -0
- package/src/middleware/antispam.middleware.js +13 -3
- package/src/middleware/blacklist.middleware.js +4 -1
- package/src/middleware/permissions.middleware.js +38 -51
- package/src/routes/dashboard.api.esm.js +91 -10
- package/src/services/aiAgent.cjs +51 -41
- package/src/services/aiProviders.cjs +46 -19
- package/src/services/aiRouter.cjs +11 -3
- package/src/services/aiToolAuth.cjs +114 -0
- package/src/services/aiTools.cjs +492 -56
- package/src/services/modelRegistry.cjs +20 -5
- package/src/utils/commandDocs.cjs +58 -0
- package/src/utils/geminiMedia.cjs +99 -0
- package/src/utils/groupMetadataCache.cjs +83 -0
- package/src/utils/i18n.cjs +113 -0
- package/src/utils/markdownParser.cjs +4 -2
- package/src/utils/memory.cjs +37 -21
- package/src/utils/permissionLevel.cjs +83 -0
- package/src/utils/providerUrl.cjs +29 -2
- package/src/utils/sendBotMessage.cjs +7 -3
- package/src/utils/sendBotMessage.esm.js +27 -3
- package/src/utils/statusMessage.cjs +11 -4
- package/src/utils/storage-hub.cjs +21 -0
- package/public/dashboard/assets/index-BnJbz8iW.css +0 -2
- package/public/dashboard/assets/index-Dn8ZyzsW.js +0 -426
|
@@ -330,14 +330,29 @@ function resolveCapabilities(provider, modelId, providerCaps = null) {
|
|
|
330
330
|
/**
|
|
331
331
|
* Independent vision / STT guards. Unsupported features are forced off;
|
|
332
332
|
* supported features keep the operator's existing choice.
|
|
333
|
+
*
|
|
334
|
+
* "Unknown" is not "unsupported": a model the registry has never seen (a new
|
|
335
|
+
* Gemini drop, a gateway's own id) must keep the operator's toggles exactly as
|
|
336
|
+
* they are, otherwise enabling vision/STT on a custom endpoint is impossible —
|
|
337
|
+
* the save would be silently reverted. Only seed/live metadata that says
|
|
338
|
+
* `vision: false` / `stt: false` counts as proof, and even that only when the
|
|
339
|
+
* operator left auto-detection on (`ai_auto_detect_capabilities`).
|
|
333
340
|
*/
|
|
334
|
-
function applyCapabilityGuards({
|
|
341
|
+
function applyCapabilityGuards({
|
|
342
|
+
visionEnabled,
|
|
343
|
+
sttEnabled,
|
|
344
|
+
capabilities,
|
|
345
|
+
capabilitySource = "seed",
|
|
346
|
+
autoDetect = true,
|
|
347
|
+
}) {
|
|
335
348
|
const caps = normalizeCapabilities(capabilities);
|
|
349
|
+
const known = capabilitySource === "seed" || capabilitySource === "provider";
|
|
350
|
+
const enforce = Boolean(autoDetect) && known;
|
|
336
351
|
return {
|
|
337
|
-
visionEnabled: caps.vision ? Boolean(visionEnabled)
|
|
338
|
-
sttEnabled: caps.stt ? Boolean(sttEnabled)
|
|
339
|
-
visionLocked: !caps.vision,
|
|
340
|
-
sttLocked: !caps.stt,
|
|
352
|
+
visionEnabled: enforce && !caps.vision ? false : Boolean(visionEnabled),
|
|
353
|
+
sttEnabled: enforce && !caps.stt ? false : Boolean(sttEnabled),
|
|
354
|
+
visionLocked: enforce && !caps.vision,
|
|
355
|
+
sttLocked: enforce && !caps.stt,
|
|
341
356
|
};
|
|
342
357
|
}
|
|
343
358
|
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// A command's documentation, in the language the reader wants.
|
|
2
|
+
//
|
|
3
|
+
// `description` and `usage` on a command are either a plain string — one
|
|
4
|
+
// language, shown as-is in both menus — or `{ en, ar }`. localize() picks the
|
|
5
|
+
// requested language and falls back to the other one, so a command that ships
|
|
6
|
+
// only one language still appears in both.
|
|
7
|
+
//
|
|
8
|
+
// Which language: `!help ar` / `!help en` say so explicitly. Otherwise it is
|
|
9
|
+
// the language every other reply uses — see utils/i18n.cjs.
|
|
10
|
+
|
|
11
|
+
const LANGS = ["en", "ar"];
|
|
12
|
+
|
|
13
|
+
// Words accepted after !help to pick a language.
|
|
14
|
+
const LANG_WORDS = new Map([
|
|
15
|
+
["en", "en"],
|
|
16
|
+
["english", "en"],
|
|
17
|
+
["eng", "en"],
|
|
18
|
+
["انجليزي", "en"],
|
|
19
|
+
["إنجليزي", "en"],
|
|
20
|
+
["انجليزى", "en"],
|
|
21
|
+
["الانجليزية", "en"],
|
|
22
|
+
["الإنجليزية", "en"],
|
|
23
|
+
["ar", "ar"],
|
|
24
|
+
["arabic", "ar"],
|
|
25
|
+
["عربي", "ar"],
|
|
26
|
+
["عربى", "ar"],
|
|
27
|
+
["العربية", "ar"],
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/** "ar" | "en" for a word like `ar`, `english`, `عربي`; null otherwise. */
|
|
31
|
+
function parseLang(word) {
|
|
32
|
+
return (
|
|
33
|
+
LANG_WORDS.get(
|
|
34
|
+
String(word || "")
|
|
35
|
+
.trim()
|
|
36
|
+
.toLowerCase(),
|
|
37
|
+
) || null
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Pick `lang` out of a string or an `{ en, ar }` object. */
|
|
42
|
+
function localize(value, lang = "en") {
|
|
43
|
+
if (value == null) return "";
|
|
44
|
+
if (typeof value === "string") return value;
|
|
45
|
+
if (typeof value !== "object") return String(value);
|
|
46
|
+
if (value[lang]) return value[lang];
|
|
47
|
+
for (const other of LANGS) {
|
|
48
|
+
if (value[other]) return value[other];
|
|
49
|
+
}
|
|
50
|
+
return "";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Both languages, for the dashboard (which follows its own UI language). */
|
|
54
|
+
function bothLanguages(value) {
|
|
55
|
+
return { en: localize(value, "en"), ar: localize(value, "ar") };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
module.exports = { LANGS, parseLang, localize, bothLanguages };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Getting WhatsApp media in front of Gemini.
|
|
2
|
+
//
|
|
3
|
+
// Two things used to break here, and both ended in an error card instead of an
|
|
4
|
+
// answer:
|
|
5
|
+
//
|
|
6
|
+
// * The Files API needs a MIME type, and @google/genai reads it from
|
|
7
|
+
// `config.mimeType` or infers it from a file extension — nowhere else. The
|
|
8
|
+
// agent passed it at the top level of the call and wrote the bytes to a
|
|
9
|
+
// temp file with no extension, so every photo, video, voice note and
|
|
10
|
+
// document failed with "Can not determine mimeType".
|
|
11
|
+
// * WhatsApp labels voice notes `audio/ogg; codecs=opus`. Gemini's supported
|
|
12
|
+
// type is `audio/ogg`; the codec parameter is not part of it.
|
|
13
|
+
//
|
|
14
|
+
// Nothing here touches the disk. The bytes go up as a Blob, so there is no temp
|
|
15
|
+
// file written next to the code (which a global install, a packaged binary or
|
|
16
|
+
// the Android build may not even allow) and nothing to clean up afterwards.
|
|
17
|
+
|
|
18
|
+
// Used only when WhatsApp sent no MIME type at all.
|
|
19
|
+
const FALLBACK_MIME = {
|
|
20
|
+
image: "image/jpeg",
|
|
21
|
+
video: "video/mp4",
|
|
22
|
+
audio: "audio/ogg",
|
|
23
|
+
document: "application/octet-stream",
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// A video is usable only once Google has processed it; images and audio are
|
|
27
|
+
// normally ACTIVE straight away.
|
|
28
|
+
const PROCESSING_POLL_MS = 1500;
|
|
29
|
+
const PROCESSING_TIMEOUT_MS = 90_000;
|
|
30
|
+
|
|
31
|
+
/** "image" | "video" | "audio" | "document", from a MIME type. */
|
|
32
|
+
function mediaKind(mime) {
|
|
33
|
+
const type = String(mime || "").toLowerCase();
|
|
34
|
+
if (type.startsWith("image/")) return "image";
|
|
35
|
+
if (type.startsWith("video/")) return "video";
|
|
36
|
+
if (type.startsWith("audio/")) return "audio";
|
|
37
|
+
return "document";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The bare type Gemini expects: parameters dropped, lower-cased.
|
|
42
|
+
* `audio/ogg; codecs=opus` -> `audio/ogg`.
|
|
43
|
+
*/
|
|
44
|
+
function baseMimeType(mime, kind = mediaKind(mime)) {
|
|
45
|
+
const bare = String(mime || "")
|
|
46
|
+
.split(";")[0]
|
|
47
|
+
.trim()
|
|
48
|
+
.toLowerCase();
|
|
49
|
+
return bare || FALLBACK_MIME[kind] || FALLBACK_MIME.document;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Download and decrypt a WhatsApp media message into one Buffer.
|
|
54
|
+
*
|
|
55
|
+
* `downloadType` picks the decryption keys, so it has to follow the message
|
|
56
|
+
* type (an image sent as a document is a "document"), not the MIME type.
|
|
57
|
+
*/
|
|
58
|
+
async function downloadMedia(downloadContentFromMessage, mediaMessage, downloadType) {
|
|
59
|
+
const stream = await downloadContentFromMessage(mediaMessage, downloadType);
|
|
60
|
+
const chunks = [];
|
|
61
|
+
for await (const chunk of stream) chunks.push(chunk);
|
|
62
|
+
const buffer = Buffer.concat(chunks);
|
|
63
|
+
if (!buffer.length) throw new Error("Empty media buffer");
|
|
64
|
+
return buffer;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Upload bytes to the Gemini Files API and return the File once it can be
|
|
71
|
+
* used in a request.
|
|
72
|
+
*/
|
|
73
|
+
async function uploadToGemini(
|
|
74
|
+
genAI,
|
|
75
|
+
buffer,
|
|
76
|
+
mimeType,
|
|
77
|
+
{ displayName, pollMs = PROCESSING_POLL_MS, timeoutMs = PROCESSING_TIMEOUT_MS } = {},
|
|
78
|
+
) {
|
|
79
|
+
let file = await genAI.files.upload({
|
|
80
|
+
file: new Blob([buffer], { type: mimeType }),
|
|
81
|
+
config: { mimeType, ...(displayName ? { displayName } : {}) },
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const deadline = Date.now() + timeoutMs;
|
|
85
|
+
while (file?.state === "PROCESSING" && file.name) {
|
|
86
|
+
if (Date.now() > deadline) {
|
|
87
|
+
throw new Error("Gemini is still processing the file — try again in a moment");
|
|
88
|
+
}
|
|
89
|
+
await sleep(pollMs);
|
|
90
|
+
file = await genAI.files.get({ name: file.name });
|
|
91
|
+
}
|
|
92
|
+
if (file?.state === "FAILED") {
|
|
93
|
+
throw new Error("Gemini could not process this file");
|
|
94
|
+
}
|
|
95
|
+
if (!file?.uri) throw new Error("Gemini did not return a file URI");
|
|
96
|
+
return file;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { mediaKind, baseMimeType, downloadMedia, uploadToGemini };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// The one group-metadata cache, and the cache-first resolver every
|
|
2
|
+
// per-message path should use.
|
|
3
|
+
//
|
|
4
|
+
// Why a shared module: Baileys' `sock.groupMetadata()` is ALWAYS a live server
|
|
5
|
+
// query — it never consults the `cachedGroupMetadata` config hook (that hook
|
|
6
|
+
// only serves the message-send path). Without this module, every prefixed
|
|
7
|
+
// group message and every moderation check cost its own network round-trip.
|
|
8
|
+
// Now the hot path reads the cache and only the first caller after a miss
|
|
9
|
+
// pays for one query, which is then shared by everyone.
|
|
10
|
+
//
|
|
11
|
+
// The cache is populated from three places:
|
|
12
|
+
// * `groupFetchAllParticipating()` on connection open (see
|
|
13
|
+
// src/core/connection.js — itself TTL-gated to avoid full rosters on every
|
|
14
|
+
// reconnect),
|
|
15
|
+
// * pushed `groups.upsert` / `groups.update` events (src/core/events.js),
|
|
16
|
+
// * the write-back in resolveGroupMetadata() below.
|
|
17
|
+
//
|
|
18
|
+
// CommonJS on purpose: the consumers are the CJS command files and the ESM
|
|
19
|
+
// handlers/ middleware, and this module must be loadable from both.
|
|
20
|
+
|
|
21
|
+
const NodeCache = require("node-cache");
|
|
22
|
+
|
|
23
|
+
// Same values the old src/config/constants.js CACHE_CONFIG had (1h entries,
|
|
24
|
+
// swept every 5m). constants.js is ESM and this module must be CJS, so the
|
|
25
|
+
// literals live here now.
|
|
26
|
+
const CACHE_CONFIG = {
|
|
27
|
+
stdTTL: 60 * 60, // 1 hour
|
|
28
|
+
checkperiod: 60 * 5, // 5 minutes
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const cache = new NodeCache(CACHE_CONFIG);
|
|
32
|
+
|
|
33
|
+
function isGroupJid(jid) {
|
|
34
|
+
return String(jid || "").endsWith("@g.us");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function getCached(jid) {
|
|
38
|
+
return cache.get(jid);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function setCached(jid, metadata) {
|
|
42
|
+
if (isGroupJid(jid) && metadata) cache.set(jid, metadata);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function flushAll() {
|
|
46
|
+
cache.flushAll();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function keys() {
|
|
50
|
+
return cache.keys();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Group metadata, cache-first. A cache hit costs nothing; a miss makes ONE
|
|
55
|
+
* live query and writes the answer back so concurrent and later readers share
|
|
56
|
+
* it. A failing live query resolves null without caching anything, so the
|
|
57
|
+
* next caller retries — correctness beats request avoidance.
|
|
58
|
+
*/
|
|
59
|
+
async function resolveGroupMetadata(sock, jid) {
|
|
60
|
+
if (!isGroupJid(jid)) return null;
|
|
61
|
+
|
|
62
|
+
const hit = cache.get(jid);
|
|
63
|
+
if (hit) return hit;
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
const live = await sock.groupMetadata(jid);
|
|
67
|
+
if (live) setCached(jid, live);
|
|
68
|
+
return live;
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
module.exports = {
|
|
75
|
+
cache,
|
|
76
|
+
CACHE_CONFIG,
|
|
77
|
+
isGroupJid,
|
|
78
|
+
getCached,
|
|
79
|
+
setCached,
|
|
80
|
+
flushAll,
|
|
81
|
+
keys,
|
|
82
|
+
resolveGroupMetadata,
|
|
83
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The language the bot answers in.
|
|
2
|
+
//
|
|
3
|
+
// Every reply is written in both languages where it is sent —
|
|
4
|
+
// `tr("Done.", "تم.")` — and tr() picks one for the message being answered.
|
|
5
|
+
// The choice is made once per incoming message, before any handler runs, and
|
|
6
|
+
// AsyncLocalStorage carries it through everything that message causes: the
|
|
7
|
+
// helpers deep inside a command, the status line it edits, a timer it starts.
|
|
8
|
+
// Nothing has to pass a `lang` argument around.
|
|
9
|
+
//
|
|
10
|
+
// bot_language = ar | en that language, always
|
|
11
|
+
// bot_language = auto the language the message is written in:
|
|
12
|
+
// Arabic letters -> Arabic
|
|
13
|
+
// English words, other than the command's own
|
|
14
|
+
// syntax (`add`, `on`, `list`, ...) -> English
|
|
15
|
+
// a bare command (`!ping`, `!kick @x`) -> Arabic
|
|
16
|
+
//
|
|
17
|
+
// A bare command carries no language of its own, and Arabic is what the bot
|
|
18
|
+
// has always answered in, so an operator on the default setting sees no change
|
|
19
|
+
// until someone actually writes to it in English. Outside any message (a
|
|
20
|
+
// scheduled send, a member joining a group) there is nothing to detect, and
|
|
21
|
+
// auto means Arabic there too.
|
|
22
|
+
|
|
23
|
+
const { AsyncLocalStorage } = require("node:async_hooks");
|
|
24
|
+
const settings = require("../config/settings.cjs");
|
|
25
|
+
|
|
26
|
+
const scope = new AsyncLocalStorage();
|
|
27
|
+
|
|
28
|
+
const ARABIC_LETTERS = /[\u0621-\u064A\u0671-\u06D3\u06FA-\u06FF]/;
|
|
29
|
+
const LATIN_WORD = /[a-z][a-z'’-]*/gi;
|
|
30
|
+
// A whole token made of letters. `3fa85f64-…` (an id), `2d6`, `10pm` are not
|
|
31
|
+
// words in any language.
|
|
32
|
+
const ENGLISH_WORD = /^[a-z][a-z'’-]*[a-z]$/i;
|
|
33
|
+
const TOKEN_EDGES = /^[\s.,!?:;()"'`[\]{}<>|*_~]+|[\s.,!?:;()"'`[\]{}<>|*_~]+$/g;
|
|
34
|
+
// Not language: links, mentions, e-mail addresses.
|
|
35
|
+
const NOT_WORDS = /(?:https?:\/\/|www\.)\S+|\S+@\S+|@\S+/gi;
|
|
36
|
+
|
|
37
|
+
/** The configured language, or null for "auto". */
|
|
38
|
+
function configuredLang() {
|
|
39
|
+
const setting = settings.get("bot_language");
|
|
40
|
+
return setting === "ar" || setting === "en" ? setting : null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The language to answer `text` in.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} text what the person wrote (for a command: the part after
|
|
47
|
+
* the command name)
|
|
48
|
+
* @param {object} [options]
|
|
49
|
+
* @param {Iterable<string>} [options.syntax] words that are the command's own
|
|
50
|
+
* syntax rather than language — see syntaxWords()
|
|
51
|
+
*/
|
|
52
|
+
function detectLang(text = "", { syntax = [] } = {}) {
|
|
53
|
+
const fixed = configuredLang();
|
|
54
|
+
if (fixed) return fixed;
|
|
55
|
+
|
|
56
|
+
const clean = String(text || "").replace(NOT_WORDS, " ");
|
|
57
|
+
if (ARABIC_LETTERS.test(clean)) return "ar";
|
|
58
|
+
|
|
59
|
+
const ignore = new Set([...syntax].map((word) => String(word).toLowerCase()));
|
|
60
|
+
const words = clean
|
|
61
|
+
.split(/\s+/)
|
|
62
|
+
.map((token) => token.replace(TOKEN_EDGES, "").toLowerCase())
|
|
63
|
+
.filter((token) => ENGLISH_WORD.test(token) && !ignore.has(token));
|
|
64
|
+
return words.length ? "en" : "ar";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The Latin words that are part of a command's syntax: its name, its aliases,
|
|
69
|
+
* the literal keywords in its usage (`add`, `on|off`, `global`, `--multi`)
|
|
70
|
+
* and any `keywords` it declares.
|
|
71
|
+
* The Arabic usage is where those keywords live on their own — its
|
|
72
|
+
* placeholders are Arabic — so it is the one read.
|
|
73
|
+
*/
|
|
74
|
+
function syntaxWords(command, aliases = command?.aliases || []) {
|
|
75
|
+
const words = new Set();
|
|
76
|
+
const add = (text) => {
|
|
77
|
+
for (const word of String(text || "").match(LATIN_WORD) || []) words.add(word.toLowerCase());
|
|
78
|
+
};
|
|
79
|
+
add(command?.name);
|
|
80
|
+
for (const alias of aliases || []) add(alias);
|
|
81
|
+
const usage = command?.usage;
|
|
82
|
+
add(typeof usage === "string" ? usage : usage?.ar || usage?.en);
|
|
83
|
+
// Synonyms a command accepts but doesn't list in its usage (`grant`, `me`).
|
|
84
|
+
for (const keyword of command?.keywords || []) add(keyword);
|
|
85
|
+
return words;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The language to answer a command in, judged on its arguments. A command
|
|
90
|
+
* whose arguments are never language — a city name `!prayer` wants in English,
|
|
91
|
+
* a link — sets `neutralArgs` and is answered like a bare command.
|
|
92
|
+
*/
|
|
93
|
+
function langForCommand(command, args = [], aliases = command?.aliases || []) {
|
|
94
|
+
const text = command?.neutralArgs ? "" : args.join(" ");
|
|
95
|
+
return detectLang(text, { syntax: syntaxWords(command, aliases) });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Run `fn` with replies in `lang`. Returns what `fn` returns. */
|
|
99
|
+
function withLang(lang, fn) {
|
|
100
|
+
return scope.run(lang === "en" ? "en" : "ar", fn);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The language of the message being answered right now. */
|
|
104
|
+
function currentLang() {
|
|
105
|
+
return scope.getStore() || configuredLang() || "ar";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Pick the reply for the current message. */
|
|
109
|
+
function tr(en, ar) {
|
|
110
|
+
return currentLang() === "en" ? en : ar;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { detectLang, syntaxWords, langForCommand, withLang, currentLang, tr };
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { tr } = require("./i18n.cjs");
|
|
2
|
+
|
|
1
3
|
// file: src/utils/markdownParser.cjs
|
|
2
4
|
//
|
|
3
5
|
// Converts standard Markdown output (especially from LLMs) into human-readable
|
|
@@ -48,13 +50,13 @@ function formatTableForWhatsApp({ headers, rows }) {
|
|
|
48
50
|
const cards = [];
|
|
49
51
|
|
|
50
52
|
rows.forEach((row, rowIndex) => {
|
|
51
|
-
const primaryLabel = row[0] || `عنصر ${rowIndex + 1}
|
|
53
|
+
const primaryLabel = row[0] || tr(`Item ${rowIndex + 1}`, `عنصر ${rowIndex + 1}`);
|
|
52
54
|
const fields = [];
|
|
53
55
|
|
|
54
56
|
// If there's more than 1 column, list the remaining fields with bullet points
|
|
55
57
|
if (headers.length > 1) {
|
|
56
58
|
for (let c = 0; c < headers.length; c++) {
|
|
57
|
-
const headerName = headers[c] || `عمود ${c + 1}
|
|
59
|
+
const headerName = headers[c] || tr(`Column ${c + 1}`, `عمود ${c + 1}`);
|
|
58
60
|
const cellValue = row[c] || "—";
|
|
59
61
|
fields.push(` • *${headerName}:* ${cellValue}`);
|
|
60
62
|
}
|
package/src/utils/memory.cjs
CHANGED
|
@@ -50,6 +50,7 @@ const GLOBAL_FILE = path.join(ROOT, "global.md");
|
|
|
50
50
|
const MAX_ENTRY_CHARS = 2000;
|
|
51
51
|
// Read per call so the dashboard can change it without a restart.
|
|
52
52
|
const settings = require("../config/settings.cjs");
|
|
53
|
+
const { tr } = require("./i18n.cjs");
|
|
53
54
|
const maxContextChars = () => settings.get("memory_context_chars");
|
|
54
55
|
|
|
55
56
|
// ---------------------------------------------------------------------------
|
|
@@ -211,7 +212,7 @@ function addMemory({ scope = "chat", chatId, content, by, chatName } = {}) {
|
|
|
211
212
|
const text = String(content || "")
|
|
212
213
|
.trim()
|
|
213
214
|
.slice(0, MAX_ENTRY_CHARS);
|
|
214
|
-
if (!text) throw new Error("مفيش محتوى أحفظه");
|
|
215
|
+
if (!text) throw new Error(tr("There is nothing to save", "مفيش محتوى أحفظه"));
|
|
215
216
|
|
|
216
217
|
const filePath = memoryFilePath(normalizedScope, chatId);
|
|
217
218
|
ensureDirs();
|
|
@@ -334,43 +335,58 @@ function searchMemory(query, { scope = "chat", chatId } = {}) {
|
|
|
334
335
|
return entries.filter((entry) => entry.content.toLowerCase().includes(needle));
|
|
335
336
|
}
|
|
336
337
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
338
|
+
/**
|
|
339
|
+
* The meaningful content of one memory file: the bot's entries AND any prose
|
|
340
|
+
* the operator wrote by hand (dashboard editor or a text editor). Entry
|
|
341
|
+
* metadata rides in trailing HTML comments and the file's own header/notes
|
|
342
|
+
* start with `#` or `>` — both are stripped; everything else is injected
|
|
343
|
+
* verbatim, so an edit made from the panel reaches the model the way it was
|
|
344
|
+
* written. Returns "" for a file with nothing to say.
|
|
345
|
+
*/
|
|
346
|
+
function memoryFileContext(raw) {
|
|
347
|
+
const lines = String(raw || "")
|
|
348
|
+
.split("\n")
|
|
349
|
+
.map((line) => line.replace(/<!--.*?-->/g, "").trimEnd())
|
|
350
|
+
.filter((line) => line.trim() && !line.startsWith("#") && !line.startsWith(">"));
|
|
351
|
+
return lines.join("\n").trim();
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Keep the tail of a block (newest entries are appended at the bottom), cut on a line boundary. */
|
|
355
|
+
function clipTail(text, limitChars) {
|
|
356
|
+
if (text.length <= limitChars) return text;
|
|
357
|
+
const kept = text.slice(-Math.max(1, limitChars));
|
|
358
|
+
const firstNewline = kept.indexOf("\n");
|
|
359
|
+
return firstNewline === -1 ? kept : kept.slice(firstNewline + 1);
|
|
348
360
|
}
|
|
349
361
|
|
|
350
362
|
/**
|
|
351
363
|
* The memory block injected into the model's system instruction.
|
|
352
364
|
* Returns "" when both files are empty, so a fresh install pays nothing.
|
|
365
|
+
*
|
|
366
|
+
* Both scopes are injected in full (prose included), each capped at half the
|
|
367
|
+
* character budget when both have content so one busy file can't starve the
|
|
368
|
+
* other.
|
|
353
369
|
*/
|
|
354
370
|
function buildMemoryContext(chatId, { limitChars = maxContextChars() } = {}) {
|
|
355
|
-
const
|
|
356
|
-
const
|
|
357
|
-
if (!
|
|
371
|
+
const globalText = memoryFileContext(readRaw(GLOBAL_FILE));
|
|
372
|
+
const chatText = chatId ? memoryFileContext(readRaw(memoryFilePath("chat", chatId))) : "";
|
|
373
|
+
if (!globalText && !chatText) return "";
|
|
358
374
|
|
|
359
|
-
const perScope = Math.floor(limitChars / (
|
|
375
|
+
const perScope = Math.floor(limitChars / (globalText && chatText ? 2 : 1));
|
|
360
376
|
const blocks = [];
|
|
361
377
|
|
|
362
|
-
if (
|
|
363
|
-
blocks.push(`### ذاكرة عامة (global.md)\n${
|
|
378
|
+
if (globalText) {
|
|
379
|
+
blocks.push(`### ذاكرة عامة (global.md)\n${clipTail(globalText, perScope)}`);
|
|
364
380
|
}
|
|
365
|
-
if (
|
|
381
|
+
if (chatText) {
|
|
366
382
|
blocks.push(
|
|
367
|
-
`### ذاكرة المحادثة دي (${safeFileName(chatId)}.md)\n${
|
|
383
|
+
`### ذاكرة المحادثة دي (${safeFileName(chatId)}.md)\n${clipTail(chatText, perScope)}`,
|
|
368
384
|
);
|
|
369
385
|
}
|
|
370
386
|
|
|
371
387
|
return [
|
|
372
388
|
"## 🧠 الذاكرة الدائمة",
|
|
373
|
-
"دي معلومات اتحفظت قبل
|
|
389
|
+
"دي معلومات اتحفظت قبل كده — سطور بالعلامة `-` اتسجلت بالبوت أو بصاحب البوت، وأي نص حر مكتوب هنا اتكتب بإيد صاحب البوت. اعتبر كل ده حقيقة واستخدمه من غير ما تقول إنك بتقرأ من ملف.",
|
|
374
390
|
"",
|
|
375
391
|
...blocks,
|
|
376
392
|
].join("\n");
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// What each permission level lets through — the one copy of that rule.
|
|
2
|
+
//
|
|
3
|
+
// The command dispatcher (middleware/permissions.middleware.js) and the AI
|
|
4
|
+
// agent's tools (services/aiToolAuth.cjs) both ask this function, so a command
|
|
5
|
+
// and the tool that stands in for it (`!schedule` and create_reminder, say)
|
|
6
|
+
// can never drift apart. The level itself comes from runtime-config, which
|
|
7
|
+
// means a dashboard change to a command's permission moves both doors at once.
|
|
8
|
+
//
|
|
9
|
+
// Pure on purpose: who the sender is gets resolved elsewhere (resolveSender()),
|
|
10
|
+
// and this only answers "may that sender use something gated at `level`".
|
|
11
|
+
// The refusal is worded in the language of the message being answered.
|
|
12
|
+
|
|
13
|
+
const { tr } = require("./i18n.cjs");
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {string} level - MEMBERS | ALL | OWNER_ONLY | ADMINS_ONLY | ADMINS_OWNER
|
|
17
|
+
* @param {object} subject
|
|
18
|
+
* @param {boolean} subject.isGroup - the message came from a group
|
|
19
|
+
* @param {boolean} subject.isOwner - bot owner
|
|
20
|
+
* @param {boolean} subject.isBotAdmin - bot-level admin (a role, valid in every chat)
|
|
21
|
+
* @param {boolean} subject.isSenderAdmin - bot admin, or admin of this WhatsApp group
|
|
22
|
+
* @returns {{hasPermission: boolean, reason: string, unknownLevel: boolean}}
|
|
23
|
+
*/
|
|
24
|
+
function evaluatePermissionLevel(level, { isGroup, isOwner, isBotAdmin, isSenderAdmin } = {}) {
|
|
25
|
+
switch (level) {
|
|
26
|
+
case "MEMBERS":
|
|
27
|
+
case "ALL":
|
|
28
|
+
return verdict(true, "");
|
|
29
|
+
|
|
30
|
+
case "OWNER_ONLY":
|
|
31
|
+
return verdict(
|
|
32
|
+
Boolean(isOwner),
|
|
33
|
+
tr("🚫 Only the bot owner can use this command.", "🚫 هذا الأمر متاح للمالك فقط."),
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
case "ADMINS_ONLY":
|
|
37
|
+
// Owners and bot-admins can run admin-only commands from anywhere —
|
|
38
|
+
// useful for the operator pinging the bot privately to manage a group.
|
|
39
|
+
return isGroup
|
|
40
|
+
? verdict(
|
|
41
|
+
Boolean(isSenderAdmin || isOwner),
|
|
42
|
+
tr("🚫 Only group admins can use this command.", "🚫 هذا الأمر متاح للمشرفين فقط."),
|
|
43
|
+
)
|
|
44
|
+
: verdict(
|
|
45
|
+
Boolean(isOwner || isBotAdmin),
|
|
46
|
+
tr(
|
|
47
|
+
"⚠️ This command only works in groups (or for the owner in private).",
|
|
48
|
+
"⚠️ هذا الأمر يعمل في المجموعات فقط (أو للمالك في الخاص).",
|
|
49
|
+
),
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
case "ADMINS_OWNER":
|
|
53
|
+
return isGroup
|
|
54
|
+
? verdict(
|
|
55
|
+
Boolean(isOwner || isSenderAdmin),
|
|
56
|
+
tr(
|
|
57
|
+
"🚫 Only group admins and the owner can use this command.",
|
|
58
|
+
"🚫 هذا الأمر متاح للمشرفين والمالك فقط.",
|
|
59
|
+
),
|
|
60
|
+
)
|
|
61
|
+
: verdict(
|
|
62
|
+
Boolean(isOwner || isBotAdmin),
|
|
63
|
+
tr(
|
|
64
|
+
"⚠️ This command only works in groups, or for the owner.",
|
|
65
|
+
"⚠️ هذا الأمر يعمل في المجموعات أو للمالك فقط.",
|
|
66
|
+
),
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
default:
|
|
70
|
+
// Fail closed: a level nobody knows how to evaluate lets nobody through.
|
|
71
|
+
return {
|
|
72
|
+
hasPermission: false,
|
|
73
|
+
reason: tr("🚫 Unknown permission level.", "🚫 مستوى الصلاحية غير معروف."),
|
|
74
|
+
unknownLevel: true,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function verdict(hasPermission, reason) {
|
|
80
|
+
return { hasPermission, reason, unknownLevel: false };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = { evaluatePermissionLevel };
|
|
@@ -6,7 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
const dns = require("node:dns").promises;
|
|
8
8
|
const net = require("node:net");
|
|
9
|
-
const {
|
|
9
|
+
const {
|
|
10
|
+
Agent,
|
|
11
|
+
fetch: undiciFetch,
|
|
12
|
+
FormData: UndiciFormData,
|
|
13
|
+
Response: UndiciResponse,
|
|
14
|
+
} = require("undici");
|
|
10
15
|
|
|
11
16
|
function ipv4Bytes(host) {
|
|
12
17
|
const parts = String(host).split(".");
|
|
@@ -261,11 +266,33 @@ function responseWithDispatcherCleanup(response, dispatcher) {
|
|
|
261
266
|
});
|
|
262
267
|
}
|
|
263
268
|
|
|
269
|
+
// Node's global FormData and the undici package's are different classes, and
|
|
270
|
+
// the package's fetch only recognises its own: handed a global one it sends the
|
|
271
|
+
// string "[object FormData]" as text/plain. That is what every Whisper upload
|
|
272
|
+
// from !stt was. Copy the entries across; File values keep their filename.
|
|
273
|
+
function undiciBody(body) {
|
|
274
|
+
if (
|
|
275
|
+
typeof globalThis.FormData === "function" &&
|
|
276
|
+
body instanceof globalThis.FormData &&
|
|
277
|
+
!(body instanceof UndiciFormData)
|
|
278
|
+
) {
|
|
279
|
+
const copy = new UndiciFormData();
|
|
280
|
+
for (const [name, value] of body.entries()) copy.append(name, value);
|
|
281
|
+
return copy;
|
|
282
|
+
}
|
|
283
|
+
return body;
|
|
284
|
+
}
|
|
285
|
+
|
|
264
286
|
async function safeProviderFetch(raw, init = {}, options = {}) {
|
|
265
287
|
const { url, host, addresses } = await resolveProviderRequestUrl(raw, options);
|
|
266
288
|
const dispatcher = new Agent({ connect: { lookup: pinnedLookup(host, addresses) } });
|
|
267
289
|
try {
|
|
268
|
-
const response = await undiciFetch(url, {
|
|
290
|
+
const response = await undiciFetch(url, {
|
|
291
|
+
...init,
|
|
292
|
+
...(init.body !== undefined ? { body: undiciBody(init.body) } : {}),
|
|
293
|
+
redirect: "manual",
|
|
294
|
+
dispatcher,
|
|
295
|
+
});
|
|
269
296
|
return responseWithDispatcherCleanup(response, dispatcher);
|
|
270
297
|
} catch (error) {
|
|
271
298
|
Promise.resolve(dispatcher.destroy()).catch(() => {});
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// We lazy-import the ESM module on first call and cache the resolved exports.
|
|
3
3
|
|
|
4
4
|
const logger = require("./logger.cjs");
|
|
5
|
+
const { tr } = require("./i18n.cjs");
|
|
5
6
|
|
|
6
7
|
let cached = null;
|
|
7
8
|
|
|
@@ -26,16 +27,19 @@ async function sendBotMessage(sock, jid, content, options = {}) {
|
|
|
26
27
|
}
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
async function sendBotError(sock, jid, err,
|
|
30
|
+
async function sendBotError(sock, jid, err, lead = tr("Something went wrong", "حدث خطأ"), options = {}) {
|
|
30
31
|
try {
|
|
31
32
|
const mod = await getModule();
|
|
32
|
-
return await mod.sendBotError(sock, jid, err,
|
|
33
|
+
return await mod.sendBotError(sock, jid, err, lead, options);
|
|
33
34
|
} catch (innerErr) {
|
|
34
35
|
logger.error({ err: innerErr }, "[sendBotMessage.cjs] error helper failed");
|
|
35
36
|
const name = err?.name || "Error";
|
|
36
37
|
const message = err?.message || String(err);
|
|
37
38
|
return sock.sendMessage(jid, {
|
|
38
|
-
text:
|
|
39
|
+
text: tr(
|
|
40
|
+
`❌ *${lead}*\n\n*Type:* \`${name}\`\n*Details:* ${message}`,
|
|
41
|
+
`❌ *${lead}*\n\n*النوع:* \`${name}\`\n*التفاصيل:* ${message}`,
|
|
42
|
+
),
|
|
39
43
|
});
|
|
40
44
|
}
|
|
41
45
|
}
|