levix-bot 4.1.0 → 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.
Files changed (82) hide show
  1. package/package.json +1 -1
  2. package/public/dashboard/assets/{index-DngAcp-o.js → index-4AuqfnH5.js} +80 -80
  3. package/public/dashboard/index.html +1 -1
  4. package/scheduler.cjs +6 -1
  5. package/src/commands/autoschedule.cjs +40 -10
  6. package/src/commands/blacklist.cjs +35 -10
  7. package/src/commands/block.cjs +18 -5
  8. package/src/commands/calc.cjs +90 -24
  9. package/src/commands/debt.cjs +59 -33
  10. package/src/commands/deleteschedule.cjs +21 -5
  11. package/src/commands/digit.cjs +34 -8
  12. package/src/commands/gemini.cjs +217 -87
  13. package/src/commands/group/add.cjs +46 -13
  14. package/src/commands/group/all.cjs +15 -5
  15. package/src/commands/group/antiSpam.cjs +11 -4
  16. package/src/commands/group/antilink.cjs +36 -18
  17. package/src/commands/group/approveall.cjs +22 -7
  18. package/src/commands/group/clearwarns.cjs +18 -5
  19. package/src/commands/group/deletenote.cjs +18 -5
  20. package/src/commands/group/demote.cjs +25 -7
  21. package/src/commands/group/kick.cjs +28 -12
  22. package/src/commands/group/media.cjs +31 -12
  23. package/src/commands/group/members.cjs +21 -6
  24. package/src/commands/group/note.cjs +14 -4
  25. package/src/commands/group/promote.cjs +22 -6
  26. package/src/commands/group/removeall.cjs +13 -3
  27. package/src/commands/group/rules.cjs +20 -5
  28. package/src/commands/group/save.cjs +20 -5
  29. package/src/commands/group/setname.cjs +19 -6
  30. package/src/commands/group/setpp.cjs +21 -6
  31. package/src/commands/group/setrules.cjs +17 -5
  32. package/src/commands/group/setwarn.cjs +23 -7
  33. package/src/commands/group/tagadmins.cjs +16 -6
  34. package/src/commands/group/warn.cjs +35 -15
  35. package/src/commands/group/warns.cjs +33 -13
  36. package/src/commands/group/welcome.cjs +34 -16
  37. package/src/commands/group.cjs +96 -70
  38. package/src/commands/help.cjs +270 -135
  39. package/src/commands/lang.cjs +46 -13
  40. package/src/commands/listschedules.cjs +28 -11
  41. package/src/commands/loop.cjs +43 -9
  42. package/src/commands/memory.cjs +90 -30
  43. package/src/commands/mod.cjs +69 -27
  44. package/src/commands/notes.cjs +15 -5
  45. package/src/commands/perm.cjs +52 -20
  46. package/src/commands/ping.cjs +15 -3
  47. package/src/commands/poll.cjs +40 -9
  48. package/src/commands/prayer.cjs +28 -12
  49. package/src/commands/qr.cjs +20 -5
  50. package/src/commands/rand.cjs +54 -12
  51. package/src/commands/restart.cjs +13 -3
  52. package/src/commands/schedule.cjs +32 -9
  53. package/src/commands/score.cjs +26 -10
  54. package/src/commands/setprefix.cjs +27 -5
  55. package/src/commands/shortlink.cjs +36 -10
  56. package/src/commands/shutdown.cjs +13 -3
  57. package/src/commands/status.cjs +32 -11
  58. package/src/commands/sticker.cjs +34 -7
  59. package/src/commands/stt.cjs +159 -108
  60. package/src/commands/todo.cjs +31 -9
  61. package/src/commands/tts.cjs +25 -7
  62. package/src/commands/unblock.cjs +17 -4
  63. package/src/commands/weather.cjs +55 -17
  64. package/src/config/settings.cjs +1 -1
  65. package/src/handlers/command.handler.js +50 -10
  66. package/src/handlers/group.handler.js +5 -1
  67. package/src/handlers/message.handler.js +9 -0
  68. package/src/middleware/antispam.middleware.js +9 -2
  69. package/src/services/aiAgent.cjs +44 -39
  70. package/src/services/aiProviders.cjs +46 -19
  71. package/src/services/aiRouter.cjs +2 -1
  72. package/src/services/aiTools.cjs +2 -1
  73. package/src/utils/commandDocs.cjs +58 -0
  74. package/src/utils/geminiMedia.cjs +99 -0
  75. package/src/utils/i18n.cjs +113 -0
  76. package/src/utils/markdownParser.cjs +4 -2
  77. package/src/utils/memory.cjs +2 -1
  78. package/src/utils/permissionLevel.cjs +34 -6
  79. package/src/utils/providerUrl.cjs +29 -2
  80. package/src/utils/sendBotMessage.cjs +7 -3
  81. package/src/utils/sendBotMessage.esm.js +13 -3
  82. package/src/utils/statusMessage.cjs +11 -4
@@ -40,7 +40,7 @@ const SETTINGS = [
40
40
  },
41
41
  group: "general",
42
42
  label: "Bot response language",
43
- hint: "Preferred language for AI replies and status updates. Can also be switched with !lang.",
43
+ hint: "Preferred language for AI replies, status updates and !help. Auto follows the language each message is written in. Can also be switched with !lang.",
44
44
  },
45
45
  {
46
46
  key: "link_previews_enabled",
@@ -11,6 +11,8 @@ const __dirname = dirname(__filename);
11
11
  const require = createRequire(import.meta.url);
12
12
  const logger = require("../utils/logger.cjs");
13
13
  const runtimeConfig = require("../config/runtime-config.cjs");
14
+ const { localize, bothLanguages } = require("../utils/commandDocs.cjs");
15
+ const { langForCommand, withLang, tr } = require("../utils/i18n.cjs");
14
16
 
15
17
  // Commands collection (keyed by both names and aliases)
16
18
  const commands = new Map();
@@ -158,8 +160,12 @@ export function getCommandCatalog() {
158
160
  name: command.name,
159
161
  key,
160
162
  category: command.__category || "general",
161
- description: command.description || "",
162
- usage: command.usage || null,
163
+ // Strings, as the dashboard has always had them (English first), plus
164
+ // both languages so it can follow its own UI language.
165
+ description: localize(command.description, "en"),
166
+ descriptions: bothLanguages(command.description),
167
+ usage: command.usage ? localize(command.usage, "en") : null,
168
+ usages: command.usage ? bothLanguages(command.usage) : null,
163
169
  chat: command.chat || "all",
164
170
  declaredAliases: command.__declaredAliases || [],
165
171
  aliases: runtimeConfig.getAliases(command.name, command.__declaredAliases || []),
@@ -277,13 +283,22 @@ export async function handleCommand(sock, msg, body) {
277
283
  const command = commands.get(invokedName);
278
284
  if (!command) return false;
279
285
 
286
+ // Everything this command sends goes out in one language: the bot's, or in
287
+ // "auto" the one this message is written in — judged on the arguments, not
288
+ // on the command's own keywords (see utils/i18n.cjs).
289
+ const aliases = runtimeConfig.getAliases(command.name, command.__declaredAliases || []);
290
+ const lang = langForCommand(command, args, aliases);
291
+ return withLang(lang, () => runCommand(sock, msg, body, { command, args, invokedName, isGroup }));
292
+ }
293
+
294
+ async function runCommand(sock, msg, body, { command, args, invokedName, isGroup }) {
280
295
  // Turned off from the dashboard. Answered rather than ignored so the user
281
296
  // knows the command exists and isn't broken.
282
297
  if (runtimeConfig.isDisabled(command.name)) {
283
298
  await sendBotMessage(
284
299
  sock,
285
300
  msg.key.remoteJid,
286
- { text: "⛔ الأمر ده متوقف حاليًا." },
301
+ { text: tr("⛔ This command is turned off right now.", "⛔ الأمر ده متوقف حاليًا.") },
287
302
  { replyTo: msg },
288
303
  );
289
304
  return true;
@@ -303,7 +318,12 @@ export async function handleCommand(sock, msg, body) {
303
318
  await sendBotMessage(
304
319
  sock,
305
320
  msg.key.remoteJid,
306
- { text: "⚠️ هذا الأمر يعمل في المجموعات فقط." },
321
+ {
322
+ text: tr(
323
+ "⚠️ This command only works in groups.",
324
+ "⚠️ هذا الأمر يعمل في المجموعات فقط.",
325
+ ),
326
+ },
307
327
  { replyTo: msg },
308
328
  );
309
329
  return true;
@@ -312,7 +332,12 @@ export async function handleCommand(sock, msg, body) {
312
332
  await sendBotMessage(
313
333
  sock,
314
334
  msg.key.remoteJid,
315
- { text: "⚠️ هذا الأمر يعمل في المحادثات الخاصة فقط." },
335
+ {
336
+ text: tr(
337
+ "⚠️ This command only works in private chats.",
338
+ "⚠️ هذا الأمر يعمل في المحادثات الخاصة فقط.",
339
+ ),
340
+ },
316
341
  { replyTo: msg },
317
342
  );
318
343
  return true;
@@ -339,7 +364,12 @@ export async function handleCommand(sock, msg, body) {
339
364
  await sendBotMessage(
340
365
  sock,
341
366
  msg.key.remoteJid,
342
- { text: "⚠️ هذا الأمر يتطلب أن تكون مشرفًا." },
367
+ {
368
+ text: tr(
369
+ "⚠️ You need to be a group admin to use this command.",
370
+ "⚠️ هذا الأمر يتطلب أن تكون مشرفًا.",
371
+ ),
372
+ },
343
373
  { replyTo: msg },
344
374
  );
345
375
  return true;
@@ -349,7 +379,12 @@ export async function handleCommand(sock, msg, body) {
349
379
  await sendBotMessage(
350
380
  sock,
351
381
  msg.key.remoteJid,
352
- { text: "⚠️ يجب أن أكون مشرفًا لتنفيذ هذا الأمر." },
382
+ {
383
+ text: tr(
384
+ "⚠️ I need to be a group admin to do that.",
385
+ "⚠️ يجب أن أكون مشرفًا لتنفيذ هذا الأمر.",
386
+ ),
387
+ },
353
388
  { replyTo: msg },
354
389
  );
355
390
  return true;
@@ -383,9 +418,14 @@ export async function handleCommand(sock, msg, body) {
383
418
  sock,
384
419
  msg.key.remoteJid,
385
420
  {
386
- text: `❌ *فشل تنفيذ الأمر*\n\n*النوع:* \`${error.name || "Error"}\`\n*التفاصيل:* ${
387
- error.message || "غير معروف"
388
- }`,
421
+ text: tr(
422
+ `❌ *The command failed*\n\n*Type:* \`${error.name || "Error"}\`\n*Details:* ${
423
+ error.message || "unknown"
424
+ }`,
425
+ `❌ *فشل تنفيذ الأمر*\n\n*النوع:* \`${error.name || "Error"}\`\n*التفاصيل:* ${
426
+ error.message || "غير معروف"
427
+ }`,
428
+ ),
389
429
  },
390
430
  { replyTo: msg },
391
431
  );
@@ -4,6 +4,7 @@ import { getGroupSettings } from "../utils/storage.esm.js";
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  const logger = require("../utils/logger.cjs");
7
+ const { tr } = require("../utils/i18n.cjs");
7
8
 
8
9
  // Handle group participant updates (join/leave)
9
10
  export async function handleGroupParticipantsUpdate(sock, update) {
@@ -62,7 +63,10 @@ export async function handleGroupJoinRequests(sock, events) {
62
63
 
63
64
  await delay(500);
64
65
  await sock.sendMessage(groupId, {
65
- text: `✅ تم قبول طلب انضمام @${participantId.split("@")[0]} تلقائيًا.`,
66
+ text: tr(
67
+ `✅ @${participantId.split("@")[0]}'s join request was approved automatically.`,
68
+ `✅ تم قبول طلب انضمام @${participantId.split("@")[0]} تلقائيًا.`,
69
+ ),
66
70
  mentions: [participantId],
67
71
  });
68
72
  }
@@ -10,6 +10,7 @@ import { handleCommand } from "./command.handler.js";
10
10
  const require = createRequire(import.meta.url);
11
11
  const logger = require("../utils/logger.cjs");
12
12
  const { visibleText } = require("../utils/messageContent.cjs");
13
+ const { detectLang, withLang } = require("../utils/i18n.cjs");
13
14
 
14
15
  // Envelopes that carry no user-visible content: message revokes and edits
15
16
  // (protocolMessage), reactions, poll votes, the undecrypted edit envelope, and
@@ -76,6 +77,14 @@ export async function handleIncomingMessage(sock, m) {
76
77
  // otherwise sending an image with caption "!gemini حلل ده" is invisible
77
78
  // to the command handler and the user sees nothing happen.
78
79
  const body = visibleText(msg.message);
80
+
81
+ // Everything the bot says about this message — a moderation warning, a
82
+ // command's reply — goes out in one language (see utils/i18n.cjs). A
83
+ // command narrows this down to its own arguments.
84
+ return withLang(detectLang(body), () => processMessage(sock, msg, body));
85
+ }
86
+
87
+ async function processMessage(sock, msg, body) {
79
88
  const isGroup = msg.key.remoteJid.endsWith("@g.us");
80
89
 
81
90
  // Update user metadata (last seen)
@@ -11,6 +11,7 @@ import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
11
11
 
12
12
  const require = createRequire(import.meta.url);
13
13
  const logger = require("../utils/logger.cjs");
14
+ const { tr } = require("../utils/i18n.cjs");
14
15
 
15
16
  const userMessageTimestamps = new Map();
16
17
 
@@ -78,13 +79,19 @@ export async function handleAntiSpam(sock, msg) {
78
79
  // Take action based on config
79
80
  if (spamConfig.action === "KICK") {
80
81
  await sock.sendMessage(groupId, {
81
- text: `🚫 تم حذف @${senderId.split("@")[0]} بسبب الإزعاج (Spam).`,
82
+ text: tr(
83
+ `🚫 @${senderId.split("@")[0]} was removed for spamming.`,
84
+ `🚫 تم حذف @${senderId.split("@")[0]} بسبب الإزعاج (Spam).`,
85
+ ),
82
86
  mentions: [senderId],
83
87
  });
84
88
  await sock.groupParticipantsUpdate(groupId, [senderId], "remove");
85
89
  } else {
86
90
  await sock.sendMessage(groupId, {
87
- text: `⚠️ تحذير لـ @${senderId.split("@")[0]}! الرجاء عدم إرسال رسائل مزعجة.`,
91
+ text: tr(
92
+ `⚠️ Warning, @${senderId.split("@")[0]}! Please don't spam.`,
93
+ `⚠️ تحذير لـ @${senderId.split("@")[0]}! الرجاء عدم إرسال رسائل مزعجة.`,
94
+ ),
88
95
  mentions: [senderId],
89
96
  });
90
97
  }
@@ -14,10 +14,16 @@
14
14
  // runtime block and whatever is in the long-term memory files.
15
15
 
16
16
  const fs = require("fs");
17
- const path = require("path");
18
17
  const { GoogleGenAI, FunctionCallingConfigMode } = require("@google/genai");
19
18
 
20
19
  const logger = require("../utils/logger.cjs");
20
+ const {
21
+ mediaKind,
22
+ baseMimeType,
23
+ downloadMedia,
24
+ uploadToGemini,
25
+ } = require("../utils/geminiMedia.cjs");
26
+ const { tr } = require("../utils/i18n.cjs");
21
27
  const aiIdentity = require("../config/ai-identity.cjs");
22
28
  const settings = require("../config/settings.cjs");
23
29
  const memory = require("../utils/memory.cjs");
@@ -238,7 +244,15 @@ function withTimeout(promise, ms, label) {
238
244
  promise,
239
245
  new Promise((_, reject) => {
240
246
  timer = setTimeout(
241
- () => reject(new Error(`${label} تأخرت أكتر من ${Math.round(ms / 1000)} ثانية`)),
247
+ () =>
248
+ reject(
249
+ new Error(
250
+ tr(
251
+ `${label} took longer than ${Math.round(ms / 1000)} seconds`,
252
+ `${label} تأخرت أكتر من ${Math.round(ms / 1000)} ثانية`,
253
+ ),
254
+ ),
255
+ ),
242
256
  ms,
243
257
  );
244
258
  }),
@@ -385,7 +399,7 @@ function formatSources(sources) {
385
399
  lines.push(`• ${label} — ${source.uri}`);
386
400
  if (lines.length >= MAX_SOURCES) break;
387
401
  }
388
- return lines.length ? `\n\n*Sources:*\n${lines.join("\n")}` : "";
402
+ return lines.length ? `\n\n${tr("*Sources:*", "*المصادر:*")}\n${lines.join("\n")}` : "";
389
403
  }
390
404
 
391
405
  /**
@@ -422,54 +436,42 @@ class GeminiProvider extends BaseAIProvider {
422
436
  parts,
423
437
  mediaMessage,
424
438
  mimeOverride,
425
- { downloadContentFromMessage, genAI, tempDir } = {},
439
+ { downloadContentFromMessage, genAI, downloadType } = {},
426
440
  ) {
427
441
  if (!genAI) throw new Error("Gemini client unavailable");
428
- const mime = mimeOverride || mediaMessage?.mimetype || "";
442
+ const rawMime = mimeOverride || mediaMessage?.mimetype || "";
443
+ const kind = mediaKind(rawMime);
429
444
  const caps = detectModelCapabilities("gemini");
430
- if (mime.startsWith("image/") && (!settings.get("ai_vision_enabled") || !caps.supportsVision)) {
445
+ if (kind === "image" && (!settings.get("ai_vision_enabled") || !caps.supportsVision)) {
431
446
  parts.push({
432
447
  text: "[تم إرفاق صورة — الرؤية غير مفعّلة للنموذج المحدد / Vision is disabled for the selected model]",
433
448
  });
434
449
  return null;
435
450
  }
436
- if (mime.startsWith("audio/") && (!settings.get("ai_stt_enabled") || !caps.supportsAudioStt)) {
451
+ if (kind === "audio" && (!settings.get("ai_stt_enabled") || !caps.supportsAudioStt)) {
437
452
  parts.push({
438
453
  text: "[تم إرفاق صوت — تحويل الكلام غير مفعّل للنموذج المحدد / Speech-to-text is disabled for the selected model]",
439
454
  });
440
455
  return null;
441
456
  }
442
- const tempFilePath = path.join(tempDir || __dirname, `temp_media_${Date.now()}`);
443
- const stream = await downloadContentFromMessage(
457
+
458
+ // The MIME type goes in `config` (see utils/geminiMedia.cjs) — passing it
459
+ // anywhere else is what made every upload fail with "Can not determine
460
+ // mimeType".
461
+ const mimeType = baseMimeType(rawMime, kind);
462
+ const buffer = await downloadMedia(
463
+ downloadContentFromMessage,
444
464
  mediaMessage,
445
- mediaMessage.mimetype?.startsWith("image/")
446
- ? "image"
447
- : mediaMessage.mimetype?.startsWith("video/")
448
- ? "video"
449
- : mediaMessage.mimetype?.startsWith("audio/")
450
- ? "audio"
451
- : "document",
465
+ downloadType || kind,
452
466
  );
453
- let buffer = Buffer.from([]);
454
- for await (const chunk of stream) buffer = Buffer.concat([buffer, chunk]);
455
- if (!buffer.length) throw new Error("Empty media buffer");
456
- await fs.promises.writeFile(tempFilePath, buffer);
457
-
458
- try {
459
- const uploadResult = await genAI.files.upload({
460
- file: tempFilePath,
461
- mimeType: mediaMessage.mimetype,
462
- });
463
- parts.push({
464
- fileData: {
465
- fileUri: uploadResult.uri,
466
- mimeType: uploadResult.mimeType,
467
- },
468
- });
469
- return uploadResult.uri;
470
- } finally {
471
- await fs.promises.unlink(tempFilePath).catch(() => {});
472
- }
467
+ const file = await uploadToGemini(genAI, buffer, mimeType);
468
+ parts.push({
469
+ fileData: {
470
+ fileUri: file.uri,
471
+ mimeType: file.mimeType || mimeType,
472
+ },
473
+ });
474
+ return file.uri;
473
475
  }
474
476
 
475
477
  async runTurn(options) {
@@ -504,7 +506,7 @@ async function runGeminiTurn({
504
506
  search = null,
505
507
  } = {}) {
506
508
  const genAI = geminiClient();
507
- if (!genAI) throw new Error("GEMINI_API_KEY غير معرف");
509
+ if (!genAI) throw new Error(tr("No Gemini API key is set", "GEMINI_API_KEY غير معرف"));
508
510
  await assertProviderRequestUrl(settings.get("gemini_base_url"), { allowLoopback: true });
509
511
 
510
512
  const stepBudget = maxSteps ?? settings.get("ai_max_tool_steps");
@@ -604,7 +606,7 @@ async function runGeminiTurn({
604
606
  });
605
607
  }
606
608
 
607
- if (status) await status.update("🤖 بجهّز الرد...");
609
+ if (status) await status.update(tr("🤖 Writing the answer...", "🤖 بجهّز الرد..."));
608
610
  // One message carrying every functionResponse part, which is what the API
609
611
  // expects when the model asked for several calls in one turn.
610
612
  response = await chat.sendMessage({ message: responses });
@@ -622,7 +624,10 @@ async function runGeminiTurn({
622
624
  }
623
625
 
624
626
  if (!text && steps >= stepBudget) {
625
- text = "شغّلت الأدوات المتاحة بس مقدرتش أوصل لإجابة نهائية. جرّب تسأل بصيغة أوضح.";
627
+ text = tr(
628
+ "I ran the tools I have but couldn't reach a final answer. Try asking more clearly.",
629
+ "شغّلت الأدوات المتاحة بس مقدرتش أوصل لإجابة نهائية. جرّب تسأل بصيغة أوضح.",
630
+ );
626
631
  }
627
632
 
628
633
  let newHistory = [];
@@ -32,6 +32,7 @@ const logger = require("../utils/logger.cjs");
32
32
  const settings = require("../config/settings.cjs");
33
33
  const { toolDeclarations, describeCall, runTool } = require("./aiTools.cjs");
34
34
  const { assertProviderBaseUrl, safeProviderFetch } = require("../utils/providerUrl.cjs");
35
+ const { baseMimeType, downloadMedia } = require("../utils/geminiMedia.cjs");
35
36
 
36
37
  // Shown in place of a media part, on the wire and in the canonical history.
37
38
  const MEDIA_NOTE = "[تم إرفاق ملف/وسائط في الرسالة]";
@@ -102,6 +103,7 @@ const {
102
103
  getProvider,
103
104
  detectModelCapabilities,
104
105
  } = require("./aiRouter.cjs");
106
+ const { tr } = require("../utils/i18n.cjs");
105
107
 
106
108
  function visionAllowed(providerId) {
107
109
  const id = providerId || settings.get("ai_provider");
@@ -114,23 +116,24 @@ async function prepareInlineImageMedia(
114
116
  mediaMessage,
115
117
  mimeOverride,
116
118
  downloadContentFromMessage,
119
+ downloadType,
117
120
  ) {
118
121
  const isVisionOn = visionAllowed(providerId);
119
122
  const mime = mimeOverride || mediaMessage?.mimetype || "ملف";
120
123
  if (isVisionOn && mime.startsWith("image/") && typeof downloadContentFromMessage === "function") {
121
124
  try {
122
- const stream = await downloadContentFromMessage(mediaMessage, "image");
123
- let buffer = Buffer.from([]);
124
- for await (const chunk of stream) buffer = Buffer.concat([buffer, chunk]);
125
- if (buffer.length) {
126
- parts.push({
127
- inlineData: {
128
- mimeType: mime,
129
- data: buffer.toString("base64"),
130
- },
131
- });
132
- return "inline:image";
133
- }
125
+ const buffer = await downloadMedia(
126
+ downloadContentFromMessage,
127
+ mediaMessage,
128
+ downloadType || "image",
129
+ );
130
+ parts.push({
131
+ inlineData: {
132
+ mimeType: baseMimeType(mime, "image"),
133
+ data: buffer.toString("base64"),
134
+ },
135
+ });
136
+ return "inline:image";
134
137
  } catch (err) {
135
138
  logger.warn({ err }, `[${providerId}] failed to extract inline image for vision`);
136
139
  }
@@ -154,13 +157,19 @@ class OpenAIProvider extends BaseAIProvider {
154
157
  });
155
158
  }
156
159
 
157
- async prepareMedia(parts, mediaMessage, mimeOverride, { downloadContentFromMessage } = {}) {
160
+ async prepareMedia(
161
+ parts,
162
+ mediaMessage,
163
+ mimeOverride,
164
+ { downloadContentFromMessage, downloadType } = {},
165
+ ) {
158
166
  return prepareInlineImageMedia(
159
167
  "openai",
160
168
  parts,
161
169
  mediaMessage,
162
170
  mimeOverride,
163
171
  downloadContentFromMessage,
172
+ downloadType,
164
173
  );
165
174
  }
166
175
 
@@ -182,13 +191,19 @@ class AnthropicProvider extends BaseAIProvider {
182
191
  });
183
192
  }
184
193
 
185
- async prepareMedia(parts, mediaMessage, mimeOverride, { downloadContentFromMessage } = {}) {
194
+ async prepareMedia(
195
+ parts,
196
+ mediaMessage,
197
+ mimeOverride,
198
+ { downloadContentFromMessage, downloadType } = {},
199
+ ) {
186
200
  return prepareInlineImageMedia(
187
201
  "anthropic",
188
202
  parts,
189
203
  mediaMessage,
190
204
  mimeOverride,
191
205
  downloadContentFromMessage,
206
+ downloadType,
192
207
  );
193
208
  }
194
209
 
@@ -202,7 +217,7 @@ registerProvider("anthropic", new AnthropicProvider());
202
217
 
203
218
  function adapterFor(provider) {
204
219
  const adapter = ADAPTERS[provider];
205
- if (!adapter) throw new Error(`مزود غير معروف: ${provider}`);
220
+ if (!adapter) throw new Error(tr(`Unknown provider: ${provider}`, `مزود غير معروف: ${provider}`));
206
221
  return adapter;
207
222
  }
208
223
 
@@ -223,7 +238,7 @@ const PROVIDER_KEY_SETTINGS = Object.freeze({
223
238
 
224
239
  function activeProviderKeySetting(provider = settings.get("ai_provider")) {
225
240
  const keySetting = PROVIDER_KEY_SETTINGS[provider];
226
- if (!keySetting) throw new Error(`مزود غير معروف: ${provider}`);
241
+ if (!keySetting) throw new Error(tr(`Unknown provider: ${provider}`, `مزود غير معروف: ${provider}`));
227
242
  return keySetting;
228
243
  }
229
244
 
@@ -623,7 +638,15 @@ function withTimeout(promise, ms, label) {
623
638
  promise,
624
639
  new Promise((_, reject) => {
625
640
  timer = setTimeout(
626
- () => reject(new Error(`${label} استغرقت العملية أكثر من ${Math.round(ms / 1000)} ثانية`)),
641
+ () =>
642
+ reject(
643
+ new Error(
644
+ tr(
645
+ `${label} took longer than ${Math.round(ms / 1000)} seconds`,
646
+ `${label} استغرقت العملية أكثر من ${Math.round(ms / 1000)} ثانية`,
647
+ ),
648
+ ),
649
+ ),
627
650
  ms,
628
651
  );
629
652
  }),
@@ -731,7 +754,11 @@ async function runProviderAgent(
731
754
  // Same contract as the Gemini loop: the budget answer, not a lie.
732
755
  return finish({
733
756
  text:
734
- parsed.text || "شغّلت الأدوات المتاحة بس مقدرتش أوصل لإجابة نهائية. جرّب تسأل بصيغة أوضح.",
757
+ parsed.text ||
758
+ tr(
759
+ "I ran the tools I have but couldn't reach a final answer. Try asking more clearly.",
760
+ "شغّلت الأدوات المتاحة بس مقدرتش أوصل لإجابة نهائية. جرّب تسأل بصيغة أوضح.",
761
+ ),
735
762
  canonical,
736
763
  toolCalls,
737
764
  steps,
@@ -778,7 +805,7 @@ async function runProviderAgent(
778
805
  })),
779
806
  });
780
807
 
781
- if (status) await status.update("🤖 بجهّز الرد...");
808
+ if (status) await status.update(tr("🤖 Writing the answer...", "🤖 بجهّز الرد..."));
782
809
  response = await send();
783
810
  }
784
811
  }
@@ -7,6 +7,7 @@
7
7
 
8
8
  const settings = require("../config/settings.cjs");
9
9
  const { resolveCapabilities } = require("./modelRegistry.cjs");
10
+ const { tr } = require("../utils/i18n.cjs");
10
11
 
11
12
  class BaseAIProvider {
12
13
  constructor({
@@ -82,7 +83,7 @@ function getProvider(id = settings.get("ai_provider")) {
82
83
  const key = String(id || "gemini").toLowerCase();
83
84
  const provider = REGISTRY.get(key);
84
85
  if (!provider) {
85
- throw new Error(`مزود غير معروف: ${id}`);
86
+ throw new Error(tr(`Unknown provider: ${id}`, `مزود غير معروف: ${id}`));
86
87
  }
87
88
  return provider;
88
89
  }
@@ -56,6 +56,7 @@ const UA =
56
56
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
57
57
 
58
58
  const settings = require("../config/settings.cjs");
59
+ const { currentLang } = require("../utils/i18n.cjs");
59
60
 
60
61
  const MAX_PAGE_CHARS = 6000;
61
62
  const MAX_FETCH_BYTES = 3 * 1024 * 1024;
@@ -1167,7 +1168,7 @@ async function summarizeWithProvider(transcript) {
1167
1168
  }
1168
1169
 
1169
1170
  /** The status line for a tool call (falls back to the raw name). */
1170
- function describeCall(name, args, lang = settings.get("bot_language")) {
1171
+ function describeCall(name, args, lang = currentLang()) {
1171
1172
  const tool = TOOLS[name];
1172
1173
  const isEn = lang === "en";
1173
1174
  const fallback = isEn ? `⚙️ Running: ${name}` : `⚙️ جاري تشغيل: ${name}`;
@@ -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 };