levix-bot 4.1.0 → 4.2.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/package.json +1 -1
- package/public/dashboard/assets/{index-DngAcp-o.js → index-4AuqfnH5.js} +80 -80
- package/public/dashboard/index.html +1 -1
- package/scheduler.cjs +6 -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 +217 -87
- 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 +36 -18
- 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 +31 -12
- 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 -135
- 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 +69 -27
- 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 +40 -9
- 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 +163 -108
- package/src/commands/todo.cjs +31 -9
- package/src/commands/tts.cjs +25 -7
- package/src/commands/unblock.cjs +17 -4
- package/src/commands/weather.cjs +55 -17
- package/src/config/settings.cjs +1 -1
- package/src/handlers/command.handler.js +50 -10
- package/src/handlers/group.handler.js +5 -1
- package/src/handlers/message.handler.js +9 -0
- package/src/middleware/antispam.middleware.js +9 -2
- package/src/services/aiAgent.cjs +40 -39
- package/src/services/aiProviders.cjs +46 -19
- package/src/services/aiRouter.cjs +2 -1
- package/src/services/aiTools.cjs +2 -1
- package/src/utils/commandDocs.cjs +58 -0
- package/src/utils/geminiMedia.cjs +168 -0
- package/src/utils/i18n.cjs +113 -0
- package/src/utils/markdownParser.cjs +4 -2
- package/src/utils/memory.cjs +2 -1
- package/src/utils/permissionLevel.cjs +34 -6
- package/src/utils/providerUrl.cjs +29 -2
- package/src/utils/sendBotMessage.cjs +7 -3
- package/src/utils/sendBotMessage.esm.js +13 -3
- package/src/utils/statusMessage.cjs +11 -4
|
@@ -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,168 @@
|
|
|
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
|
+
// And not every Gemini endpoint has a Files API. A gateway or reverse proxy set
|
|
19
|
+
// as `gemini_base_url` often forwards generateContent and nothing else — and
|
|
20
|
+
// even one that forwards everything breaks if it lives under a path: the SDK
|
|
21
|
+
// takes the upload URL Google hands back and swaps in the base URL's host only,
|
|
22
|
+
// so `https://proxy.example/gemini` uploads to `https://proxy.example/upload/…`
|
|
23
|
+
// and gets the proxy's own 404. Text and voice notes worked (they ride inside
|
|
24
|
+
// the request); every photo failed. geminiMediaPart() tries the upload, and
|
|
25
|
+
// when the endpoint isn't there sends the bytes inline instead — and remembers,
|
|
26
|
+
// so the next photo doesn't pay for the failed upload again.
|
|
27
|
+
|
|
28
|
+
const logger = require("./logger.cjs");
|
|
29
|
+
|
|
30
|
+
// Used only when WhatsApp sent no MIME type at all.
|
|
31
|
+
const FALLBACK_MIME = {
|
|
32
|
+
image: "image/jpeg",
|
|
33
|
+
video: "video/mp4",
|
|
34
|
+
audio: "audio/ogg",
|
|
35
|
+
document: "application/octet-stream",
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// Gemini caps a whole inline request at 20 MB; media past this goes through the
|
|
39
|
+
// Files API or not at all.
|
|
40
|
+
const INLINE_MEDIA_LIMIT = 15 * 1024 * 1024;
|
|
41
|
+
|
|
42
|
+
// A video is usable only once Google has processed it; images and audio are
|
|
43
|
+
// normally ACTIVE straight away.
|
|
44
|
+
const PROCESSING_POLL_MS = 1500;
|
|
45
|
+
const PROCESSING_TIMEOUT_MS = 90_000;
|
|
46
|
+
|
|
47
|
+
/** "image" | "video" | "audio" | "document", from a MIME type. */
|
|
48
|
+
function mediaKind(mime) {
|
|
49
|
+
const type = String(mime || "").toLowerCase();
|
|
50
|
+
if (type.startsWith("image/")) return "image";
|
|
51
|
+
if (type.startsWith("video/")) return "video";
|
|
52
|
+
if (type.startsWith("audio/")) return "audio";
|
|
53
|
+
return "document";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The bare type Gemini expects: parameters dropped, lower-cased.
|
|
58
|
+
* `audio/ogg; codecs=opus` -> `audio/ogg`.
|
|
59
|
+
*/
|
|
60
|
+
function baseMimeType(mime, kind = mediaKind(mime)) {
|
|
61
|
+
const bare = String(mime || "")
|
|
62
|
+
.split(";")[0]
|
|
63
|
+
.trim()
|
|
64
|
+
.toLowerCase();
|
|
65
|
+
return bare || FALLBACK_MIME[kind] || FALLBACK_MIME.document;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Download and decrypt a WhatsApp media message into one Buffer.
|
|
70
|
+
*
|
|
71
|
+
* `downloadType` picks the decryption keys, so it has to follow the message
|
|
72
|
+
* type (an image sent as a document is a "document"), not the MIME type.
|
|
73
|
+
*/
|
|
74
|
+
async function downloadMedia(downloadContentFromMessage, mediaMessage, downloadType) {
|
|
75
|
+
const stream = await downloadContentFromMessage(mediaMessage, downloadType);
|
|
76
|
+
const chunks = [];
|
|
77
|
+
for await (const chunk of stream) chunks.push(chunk);
|
|
78
|
+
const buffer = Buffer.concat(chunks);
|
|
79
|
+
if (!buffer.length) throw new Error("Empty media buffer");
|
|
80
|
+
return buffer;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Upload bytes to the Gemini Files API and return the File once it can be
|
|
87
|
+
* used in a request.
|
|
88
|
+
*/
|
|
89
|
+
async function uploadToGemini(
|
|
90
|
+
genAI,
|
|
91
|
+
buffer,
|
|
92
|
+
mimeType,
|
|
93
|
+
{ displayName, pollMs = PROCESSING_POLL_MS, timeoutMs = PROCESSING_TIMEOUT_MS } = {},
|
|
94
|
+
) {
|
|
95
|
+
let file = await genAI.files.upload({
|
|
96
|
+
file: new Blob([buffer], { type: mimeType }),
|
|
97
|
+
config: { mimeType, ...(displayName ? { displayName } : {}) },
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const deadline = Date.now() + timeoutMs;
|
|
101
|
+
while (file?.state === "PROCESSING" && file.name) {
|
|
102
|
+
if (Date.now() > deadline) {
|
|
103
|
+
throw new Error("Gemini is still processing the file — try again in a moment");
|
|
104
|
+
}
|
|
105
|
+
await sleep(pollMs);
|
|
106
|
+
file = await genAI.files.get({ name: file.name });
|
|
107
|
+
}
|
|
108
|
+
if (file?.state === "FAILED") {
|
|
109
|
+
throw new Error("Gemini could not process this file");
|
|
110
|
+
}
|
|
111
|
+
if (!file?.uri) throw new Error("Gemini did not return a file URI");
|
|
112
|
+
return file;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* True when an upload failed because the endpoint has no Files API — not
|
|
117
|
+
* because of the key, the quota or the file. A 404/405/501, an HTML page where
|
|
118
|
+
* JSON belongs, or the SDK's own complaints about the upload handshake.
|
|
119
|
+
*/
|
|
120
|
+
function isMissingUploadEndpoint(error) {
|
|
121
|
+
const status = Number(error?.status || error?.code || error?.response?.status);
|
|
122
|
+
if ([404, 405, 501].includes(status)) return true;
|
|
123
|
+
const message = String(error?.message || "");
|
|
124
|
+
return /<html|upload url|upload status is not finalized/i.test(message);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Base URLs whose Files API turned out to be missing. In memory on purpose: a
|
|
128
|
+
// restart (or a changed base URL) tries the upload again.
|
|
129
|
+
const inlineOnly = new Set();
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The part that puts `buffer` in front of Gemini: a `fileData` reference when
|
|
133
|
+
* the Files API is there, else the bytes inline.
|
|
134
|
+
*
|
|
135
|
+
* Inline media rides along in the stored conversation, the way the
|
|
136
|
+
* OpenAI-compatible and Anthropic providers already keep their images, so a
|
|
137
|
+
* follow-up question can still see the photo.
|
|
138
|
+
*/
|
|
139
|
+
async function geminiMediaPart(genAI, buffer, mimeType, { baseUrl = "", ...uploadOptions } = {}) {
|
|
140
|
+
const key = baseUrl || "(default)";
|
|
141
|
+
const inline = () => ({ inlineData: { mimeType, data: buffer.toString("base64") } });
|
|
142
|
+
const fitsInline = buffer.length <= INLINE_MEDIA_LIMIT;
|
|
143
|
+
|
|
144
|
+
if (inlineOnly.has(key) && fitsInline) return inline();
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
const file = await uploadToGemini(genAI, buffer, mimeType, uploadOptions);
|
|
148
|
+
return { fileData: { fileUri: file.uri, mimeType: file.mimeType || mimeType } };
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (!fitsInline || !isMissingUploadEndpoint(error)) throw error;
|
|
151
|
+
inlineOnly.add(key);
|
|
152
|
+
logger.warn(
|
|
153
|
+
{ status: error?.status, baseUrl: baseUrl || null },
|
|
154
|
+
"[geminiMedia] this Gemini endpoint has no Files API — sending media inline from now on",
|
|
155
|
+
);
|
|
156
|
+
return inline();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
module.exports = {
|
|
161
|
+
INLINE_MEDIA_LIMIT,
|
|
162
|
+
mediaKind,
|
|
163
|
+
baseMimeType,
|
|
164
|
+
downloadMedia,
|
|
165
|
+
uploadToGemini,
|
|
166
|
+
geminiMediaPart,
|
|
167
|
+
isMissingUploadEndpoint,
|
|
168
|
+
};
|
|
@@ -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();
|
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
//
|
|
9
9
|
// Pure on purpose: who the sender is gets resolved elsewhere (resolveSender()),
|
|
10
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");
|
|
11
14
|
|
|
12
15
|
/**
|
|
13
16
|
* @param {string} level - MEMBERS | ALL | OWNER_ONLY | ADMINS_ONLY | ADMINS_OWNER
|
|
@@ -25,26 +28,51 @@ function evaluatePermissionLevel(level, { isGroup, isOwner, isBotAdmin, isSender
|
|
|
25
28
|
return verdict(true, "");
|
|
26
29
|
|
|
27
30
|
case "OWNER_ONLY":
|
|
28
|
-
return verdict(
|
|
31
|
+
return verdict(
|
|
32
|
+
Boolean(isOwner),
|
|
33
|
+
tr("🚫 Only the bot owner can use this command.", "🚫 هذا الأمر متاح للمالك فقط."),
|
|
34
|
+
);
|
|
29
35
|
|
|
30
36
|
case "ADMINS_ONLY":
|
|
31
37
|
// Owners and bot-admins can run admin-only commands from anywhere —
|
|
32
38
|
// useful for the operator pinging the bot privately to manage a group.
|
|
33
39
|
return isGroup
|
|
34
|
-
? verdict(
|
|
40
|
+
? verdict(
|
|
41
|
+
Boolean(isSenderAdmin || isOwner),
|
|
42
|
+
tr("🚫 Only group admins can use this command.", "🚫 هذا الأمر متاح للمشرفين فقط."),
|
|
43
|
+
)
|
|
35
44
|
: verdict(
|
|
36
45
|
Boolean(isOwner || isBotAdmin),
|
|
37
|
-
|
|
46
|
+
tr(
|
|
47
|
+
"⚠️ This command only works in groups (or for the owner in private).",
|
|
48
|
+
"⚠️ هذا الأمر يعمل في المجموعات فقط (أو للمالك في الخاص).",
|
|
49
|
+
),
|
|
38
50
|
);
|
|
39
51
|
|
|
40
52
|
case "ADMINS_OWNER":
|
|
41
53
|
return isGroup
|
|
42
|
-
? verdict(
|
|
43
|
-
|
|
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
|
+
);
|
|
44
68
|
|
|
45
69
|
default:
|
|
46
70
|
// Fail closed: a level nobody knows how to evaluate lets nobody through.
|
|
47
|
-
return {
|
|
71
|
+
return {
|
|
72
|
+
hasPermission: false,
|
|
73
|
+
reason: tr("🚫 Unknown permission level.", "🚫 مستوى الصلاحية غير معروف."),
|
|
74
|
+
unknownLevel: true,
|
|
75
|
+
};
|
|
48
76
|
}
|
|
49
77
|
}
|
|
50
78
|
|
|
@@ -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
|
}
|
|
@@ -18,6 +18,7 @@ import { createRequire } from "module";
|
|
|
18
18
|
|
|
19
19
|
const require = createRequire(import.meta.url);
|
|
20
20
|
const logger = require("./logger.cjs");
|
|
21
|
+
const { tr } = require("./i18n.cjs");
|
|
21
22
|
const settings = require("../config/settings.cjs");
|
|
22
23
|
|
|
23
24
|
const lastSendTime = new Map(); // chatJid -> timestamp ms
|
|
@@ -130,13 +131,22 @@ export async function sendBotMessage(sock, jid, content, options = {}) {
|
|
|
130
131
|
* @param {object} sock
|
|
131
132
|
* @param {string} jid
|
|
132
133
|
* @param {Error|string} err
|
|
133
|
-
* @param {string} [
|
|
134
|
+
* @param {string} [lead] - one-line summary in the reply language, via tr()
|
|
134
135
|
* @param {object} [options] - forwarded to sendBotMessage
|
|
135
136
|
*/
|
|
136
|
-
export async function sendBotError(
|
|
137
|
+
export async function sendBotError(
|
|
138
|
+
sock,
|
|
139
|
+
jid,
|
|
140
|
+
err,
|
|
141
|
+
lead = tr("Something went wrong", "حدث خطأ"),
|
|
142
|
+
options = {},
|
|
143
|
+
) {
|
|
137
144
|
const name = err?.name || (typeof err === "string" ? "Error" : "Error");
|
|
138
145
|
const message = err?.message || (typeof err === "string" ? err : JSON.stringify(err));
|
|
139
|
-
const text =
|
|
146
|
+
const text = tr(
|
|
147
|
+
`❌ *${lead}*\n\n*Type:* \`${name}\`\n*Details:* ${message}`,
|
|
148
|
+
`❌ *${lead}*\n\n*النوع:* \`${name}\`\n*التفاصيل:* ${message}`,
|
|
149
|
+
).slice(0, 1500);
|
|
140
150
|
return sendBotMessage(sock, jid, { text }, options);
|
|
141
151
|
}
|
|
142
152
|
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
const logger = require("./logger.cjs");
|
|
17
17
|
const { sendBotMessage } = require("./sendBotMessage.cjs");
|
|
18
|
+
const { tr } = require("./i18n.cjs");
|
|
18
19
|
|
|
19
20
|
// WhatsApp tolerates a few edits per message; spacing them out keeps the
|
|
20
21
|
// server happy and the animation readable.
|
|
@@ -106,12 +107,18 @@ class StatusMessage {
|
|
|
106
107
|
return ok;
|
|
107
108
|
}
|
|
108
109
|
|
|
109
|
-
/**
|
|
110
|
-
|
|
110
|
+
/**
|
|
111
|
+
* Turn the line into the standard error card. `lead` is the one-line
|
|
112
|
+
* summary, already in the reply language — pass it through tr().
|
|
113
|
+
*/
|
|
114
|
+
async fail(err, lead = tr("Something went wrong", "حصلت مشكلة")) {
|
|
111
115
|
const name = err?.name || "Error";
|
|
112
|
-
const message = err?.message || String(err || "غير معروف");
|
|
116
|
+
const message = err?.message || String(err || tr("unknown", "غير معروف"));
|
|
113
117
|
return this.finish(
|
|
114
|
-
|
|
118
|
+
tr(
|
|
119
|
+
`❌ *${lead}*\n\n*Type:* \`${name}\`\n*Details:* ${message}`,
|
|
120
|
+
`❌ *${lead}*\n\n*النوع:* \`${name}\`\n*التفاصيل:* ${message}`,
|
|
121
|
+
).slice(0, 1500),
|
|
115
122
|
);
|
|
116
123
|
}
|
|
117
124
|
|