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.
Files changed (96) hide show
  1. package/package.json +1 -1
  2. package/public/dashboard/assets/index-4AuqfnH5.js +431 -0
  3. package/public/dashboard/assets/index-LvfJ8ybs.css +2 -0
  4. package/public/dashboard/index.html +2 -2
  5. package/scheduler.cjs +25 -1
  6. package/src/commands/autoschedule.cjs +40 -10
  7. package/src/commands/blacklist.cjs +35 -10
  8. package/src/commands/block.cjs +18 -5
  9. package/src/commands/calc.cjs +90 -24
  10. package/src/commands/debt.cjs +59 -33
  11. package/src/commands/deleteschedule.cjs +21 -5
  12. package/src/commands/digit.cjs +34 -8
  13. package/src/commands/gemini.cjs +235 -108
  14. package/src/commands/group/add.cjs +46 -13
  15. package/src/commands/group/all.cjs +15 -5
  16. package/src/commands/group/antiSpam.cjs +11 -4
  17. package/src/commands/group/antilink.cjs +39 -19
  18. package/src/commands/group/approveall.cjs +22 -7
  19. package/src/commands/group/clearwarns.cjs +18 -5
  20. package/src/commands/group/deletenote.cjs +18 -5
  21. package/src/commands/group/demote.cjs +25 -7
  22. package/src/commands/group/kick.cjs +28 -12
  23. package/src/commands/group/media.cjs +34 -13
  24. package/src/commands/group/members.cjs +21 -6
  25. package/src/commands/group/note.cjs +14 -4
  26. package/src/commands/group/promote.cjs +22 -6
  27. package/src/commands/group/removeall.cjs +13 -3
  28. package/src/commands/group/rules.cjs +20 -5
  29. package/src/commands/group/save.cjs +20 -5
  30. package/src/commands/group/setname.cjs +19 -6
  31. package/src/commands/group/setpp.cjs +21 -6
  32. package/src/commands/group/setrules.cjs +17 -5
  33. package/src/commands/group/setwarn.cjs +23 -7
  34. package/src/commands/group/tagadmins.cjs +16 -6
  35. package/src/commands/group/warn.cjs +35 -15
  36. package/src/commands/group/warns.cjs +33 -13
  37. package/src/commands/group/welcome.cjs +34 -16
  38. package/src/commands/group.cjs +96 -70
  39. package/src/commands/help.cjs +270 -129
  40. package/src/commands/lang.cjs +46 -13
  41. package/src/commands/listschedules.cjs +28 -11
  42. package/src/commands/loop.cjs +43 -9
  43. package/src/commands/memory.cjs +90 -30
  44. package/src/commands/mod.cjs +72 -28
  45. package/src/commands/notes.cjs +15 -5
  46. package/src/commands/perm.cjs +52 -20
  47. package/src/commands/ping.cjs +15 -3
  48. package/src/commands/poll.cjs +71 -24
  49. package/src/commands/prayer.cjs +28 -12
  50. package/src/commands/qr.cjs +20 -5
  51. package/src/commands/rand.cjs +54 -12
  52. package/src/commands/restart.cjs +13 -3
  53. package/src/commands/schedule.cjs +32 -9
  54. package/src/commands/score.cjs +26 -10
  55. package/src/commands/setprefix.cjs +27 -5
  56. package/src/commands/shortlink.cjs +36 -10
  57. package/src/commands/shutdown.cjs +13 -3
  58. package/src/commands/status.cjs +32 -11
  59. package/src/commands/sticker.cjs +34 -7
  60. package/src/commands/stt.cjs +159 -107
  61. package/src/commands/todo.cjs +31 -9
  62. package/src/commands/tts.cjs +61 -36
  63. package/src/commands/unblock.cjs +17 -4
  64. package/src/commands/weather.cjs +55 -17
  65. package/src/config/baileys.config.js +5 -1
  66. package/src/config/settings.cjs +11 -3
  67. package/src/core/connection.js +21 -2
  68. package/src/core/socket.js +31 -7
  69. package/src/db/store.cjs +24 -0
  70. package/src/handlers/command.handler.js +55 -13
  71. package/src/handlers/group.handler.js +5 -1
  72. package/src/handlers/message.handler.js +9 -0
  73. package/src/middleware/antispam.middleware.js +13 -3
  74. package/src/middleware/blacklist.middleware.js +4 -1
  75. package/src/middleware/permissions.middleware.js +38 -51
  76. package/src/routes/dashboard.api.esm.js +91 -10
  77. package/src/services/aiAgent.cjs +51 -41
  78. package/src/services/aiProviders.cjs +46 -19
  79. package/src/services/aiRouter.cjs +11 -3
  80. package/src/services/aiToolAuth.cjs +114 -0
  81. package/src/services/aiTools.cjs +492 -56
  82. package/src/services/modelRegistry.cjs +20 -5
  83. package/src/utils/commandDocs.cjs +58 -0
  84. package/src/utils/geminiMedia.cjs +99 -0
  85. package/src/utils/groupMetadataCache.cjs +83 -0
  86. package/src/utils/i18n.cjs +113 -0
  87. package/src/utils/markdownParser.cjs +4 -2
  88. package/src/utils/memory.cjs +37 -21
  89. package/src/utils/permissionLevel.cjs +83 -0
  90. package/src/utils/providerUrl.cjs +29 -2
  91. package/src/utils/sendBotMessage.cjs +7 -3
  92. package/src/utils/sendBotMessage.esm.js +27 -3
  93. package/src/utils/statusMessage.cjs +11 -4
  94. package/src/utils/storage-hub.cjs +21 -0
  95. package/public/dashboard/assets/index-BnJbz8iW.css +0 -2
  96. package/public/dashboard/assets/index-Dn8ZyzsW.js +0 -426
@@ -5,17 +5,30 @@ const logger = require("../utils/logger.cjs");
5
5
  const { createStatus } = require("../utils/statusMessage.cjs");
6
6
 
7
7
  const settings = require("../config/settings.cjs");
8
+ const { tr } = require("../utils/i18n.cjs");
8
9
 
9
10
  module.exports = {
10
11
  name: "weather",
11
- description: "Gets the current weather for a specific city.",
12
- usage: "weather <المدينة بالإنجليزية>",
12
+ description: {
13
+ en: "Shows the current weather for a city.",
14
+ ar: "يعرض حالة الطقس الحالية لمدينة معيّنة.",
15
+ },
16
+ usage: {
17
+ en: "weather <city in English>",
18
+ ar: "weather <اسم المدينة بالإنجليزية>",
19
+ },
13
20
  chat: "all",
21
+ // The city is asked for in English whatever language you speak, so it says
22
+ // nothing about which language to answer in (see utils/i18n.cjs).
23
+ neutralArgs: true,
14
24
 
15
25
  async execute(sock, msg, args) {
16
26
  if (!args || args.length === 0) {
17
27
  return await sock.sendMessage(msg.key.remoteJid, {
18
- text: "يرجى تقديم اسم المدينة باللغة الانجليزية.\n\n*مثال:* `!weather cairo`",
28
+ text: tr(
29
+ "Give the city's name in English.\n\n*Example:* `!weather cairo`",
30
+ "يرجى تقديم اسم المدينة باللغة الانجليزية.\n\n*مثال:* `!weather cairo`",
31
+ ),
19
32
  });
20
33
  }
21
34
 
@@ -23,14 +36,19 @@ module.exports = {
23
36
 
24
37
  // URL الخاص بـ OpenWeatherMap للحصول على الطقس الحالي
25
38
  // - units=metric للحصول على درجة الحرارة بالسيليزيوس
26
- // - lang=ar للحصول على الوصف باللغة العربية
39
+ // - lang: الوصف بلغة الرد
27
40
  const apiKey = settings.get("openweathermap_api_key");
28
- const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=ar`;
41
+ const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=${tr("en", "ar")}`;
29
42
 
30
43
  // One message: it starts as "looking it up" and turns into the forecast.
31
- const status = await createStatus(sock, msg.key.remoteJid, `🔍 بدور على طقس ${city}...`, {
32
- replyTo: msg,
33
- });
44
+ const status = await createStatus(
45
+ sock,
46
+ msg.key.remoteJid,
47
+ tr(`🔍 Looking up the weather in ${city}...`, `🔍 بدور على طقس ${city}...`),
48
+ {
49
+ replyTo: msg,
50
+ },
51
+ );
34
52
 
35
53
  try {
36
54
  const response = await axios.get(API_URL);
@@ -44,28 +62,48 @@ module.exports = {
44
62
  const windSpeed = weatherData.wind.speed;
45
63
 
46
64
  // تنسيق رسالة الرد مع الأيقونات
47
- const reply =
65
+ const reply = tr(
66
+ `*Weather in ${city}:*\n\n` +
67
+ `🌤️ Conditions: ${weatherDescription}\n` +
68
+ `🌡️ Temperature: ${currentTemp}°C\n` +
69
+ `🤔 Feels like: ${feelsLike}°C\n` +
70
+ `💧 Humidity: ${humidity}%\n` +
71
+ `🌬️ Wind: ${windSpeed} m/s`,
48
72
  `*حالة الطقس في مدينة ${city}:*\n\n` +
49
- `🌤️ الوصف: ${weatherDescription}\n` +
50
- `🌡️ درجة الحرارة: ${currentTemp}°C\n` +
51
- `🤔 الإحساس الفعلي: ${feelsLike}°C\n` +
52
- `💧 الرطوبة: ${humidity}%\n` +
53
- `🌬️ سرعة الرياح: ${windSpeed} متر/ثانية`;
73
+ `🌤️ الوصف: ${weatherDescription}\n` +
74
+ `🌡️ درجة الحرارة: ${currentTemp}°C\n` +
75
+ `🤔 الإحساس الفعلي: ${feelsLike}°C\n` +
76
+ `💧 الرطوبة: ${humidity}%\n` +
77
+ `🌬️ سرعة الرياح: ${windSpeed} متر/ثانية`,
78
+ );
54
79
 
55
80
  await status.finish(reply);
56
81
  } catch (error) {
57
82
  // التعامل مع الأخطاء
58
83
  if (error.response && error.response.status === 404) {
59
84
  // خطأ 404 يعني أن المدينة غير موجودة
60
- await status.finish(`لم أتمكن من العثور على مدينة باسم "${city}". يرجى التحقق من الاسم.`);
85
+ await status.finish(
86
+ tr(
87
+ `I couldn't find a city called "${city}". Check the name.`,
88
+ `لم أتمكن من العثور على مدينة باسم "${city}". يرجى التحقق من الاسم.`,
89
+ ),
90
+ );
61
91
  } else if (error.response && error.response.status === 401) {
62
92
  // خطأ 401 يعني أن مفتاح الـ API غير صالح
63
93
  logger.error("[Error] Invalid API Key for OpenWeatherMap.");
64
- await status.finish(`حدث خطأ في المصادقة مع خدمة الطقس. يرجى مراجعة مفتاح الـ API.`);
94
+ await status.finish(
95
+ tr(
96
+ "The weather service rejected the API key. Check it in the settings.",
97
+ `حدث خطأ في المصادقة مع خدمة الطقس. يرجى مراجعة مفتاح الـ API.`,
98
+ ),
99
+ );
65
100
  } else {
66
101
  // أي أخطاء أخرى
67
102
  logger.error(error.message, "[Error] in Weather API:");
68
- await status.fail(error, "عذرًا، حدث خطأ أثناء جلب بيانات الطقس");
103
+ await status.fail(
104
+ error,
105
+ tr("Sorry, fetching the weather failed", "عذرًا، حدث خطأ أثناء جلب بيانات الطقس"),
106
+ );
69
107
  }
70
108
  }
71
109
  },
@@ -42,7 +42,11 @@ export const getBaileysConfig = (cachedGroupMetadata, { pairingCode = false } =
42
42
  placeholderResendCache,
43
43
  enableAutoSessionRecreation: true,
44
44
  enableRecentMessageCache: true,
45
- generateHighQualityLinkPreview: true,
45
+ // High-quality link previews upload the fetched page image to WhatsApp's
46
+ // media servers. Even when the operator opts into previews
47
+ // (link_previews_enabled), the plain jpegThumbnail path is enough — this
48
+ // flag stays off to keep that optional feature as cheap as possible.
49
+ generateHighQualityLinkPreview: false,
46
50
 
47
51
  // V7: Add getMessage for message history
48
52
  getMessage: async (key) => {
@@ -40,7 +40,15 @@ 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
+ },
45
+ {
46
+ key: "link_previews_enabled",
47
+ type: "bool",
48
+ default: false,
49
+ group: "general",
50
+ label: "Link previews in messages",
51
+ hint: "Off (default) means the bot never fetches pages or images to preview a URL it sends — a real saving on mobile data, since AI answers with sources, short links and scheduled messages all contain URLs. On lets WhatsApp-style previews generate (one page fetch per URL sent).",
44
52
  },
45
53
  {
46
54
  key: "bot_min_delay_ms",
@@ -306,10 +314,10 @@ const SETTINGS = [
306
314
  {
307
315
  key: "thumbnail_remote",
308
316
  type: "bool",
309
- default: true,
317
+ default: false,
310
318
  group: "media",
311
319
  label: "Previews for remote media",
312
- hint: "Download media sent by URL to build a thumbnail before forwarding it.",
320
+ hint: "Off (default) keeps the bot from downloading media over the network just to build a thumbnail — send paths pass local files or buffers, so this rarely matters. On allows fetching a remote URL (up to the size limit below) when a send is given media by URL.",
313
321
  },
314
322
  {
315
323
  key: "thumbnail_remote_max_mb",
@@ -182,8 +182,24 @@ async function saveBotOwnerMetadata(sock) {
182
182
  }
183
183
  }
184
184
 
185
- // Cache all group metadata
186
- async function cacheAllGroups(sock) {
185
+ // Cache all group metadata — but not on every reconnect.
186
+ //
187
+ // Low-data design: `groupFetchAllParticipating()` pulls every group WITH its
188
+ // participants and description, and it used to run on every connection open —
189
+ // up to six times during one retry ladder. The full roster is only fetched
190
+ // when the last one is older than the TTL below (or on the first open after a
191
+ // process start, or explicitly forced); in between, pushed `groups.upsert` /
192
+ // `groups.update` events keep the cache current, and per-message reads fall
193
+ // back to single-group queries through resolveGroupMetadata() on a miss.
194
+ export const GROUP_SYNC_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
195
+ let lastFullGroupSyncAt = 0;
196
+
197
+ export async function cacheAllGroups(sock, { force = false, now = Date.now() } = {}) {
198
+ if (!force && lastFullGroupSyncAt && now - lastFullGroupSyncAt < GROUP_SYNC_TTL_MS) {
199
+ logger.info("[Cache] Recent full group sync is still fresh — skipping groupFetchAllParticipating");
200
+ return;
201
+ }
202
+
187
203
  logger.info("[Cache] Fetching and caching metadata for all groups...");
188
204
 
189
205
  try {
@@ -199,6 +215,9 @@ async function cacheAllGroups(sock) {
199
215
  cachedCount++;
200
216
  }
201
217
 
218
+ // Only a successful fetch counts as fresh — a failed one retries on the
219
+ // next connection open.
220
+ lastFullGroupSyncAt = now;
202
221
  logger.info(`[Cache] Successfully cached ${cachedCount} groups.`);
203
222
  } catch (err) {
204
223
  logger.error("[Error] Failed to fetch and cache groups:", err);
@@ -1,22 +1,45 @@
1
1
  import { makeWASocket } from "@whiskeysockets/baileys";
2
2
  import { createRequire } from "module";
3
- import NodeCache from "node-cache";
4
3
  import { useDatabaseAuthState } from "../auth/use-database-auth-state.js";
5
4
  import { getBaileysConfig, setRecentMessageGetter } from "../config/baileys.config.js";
6
- import { CACHE_CONFIG } from "../config/constants.js";
7
5
  import { getMessageFromRecent } from "../utils/recentMessageCache.esm.js";
8
6
 
9
7
  const require = createRequire(import.meta.url);
10
8
  const logger = require("../utils/logger.cjs");
11
9
  const { withMediaThumbnail } = require("../utils/thumbnail.cjs");
10
+ const settings = require("../config/settings.cjs");
12
11
 
13
- // Group metadata cache
14
- export const groupMetadataCache = new NodeCache(CACHE_CONFIG);
12
+ // The group-metadata cache lives in one shared CJS module so the CJS command
13
+ // files and these ESM core files see the SAME instance (see
14
+ // src/utils/groupMetadataCache.cjs). Re-exported under the historical name,
15
+ // so every existing import site keeps working.
16
+ const groupMetadataCacheModule = require("../utils/groupMetadataCache.cjs");
17
+ export const groupMetadataCache = groupMetadataCacheModule.cache;
15
18
 
16
19
  // Wire the recent-message cache into Baileys' getMessage hook so retries can
17
20
  // recover (rc10 enableAutoSessionRecreation needs this).
18
21
  setRecentMessageGetter(getMessageFromRecent);
19
22
 
23
+ /**
24
+ * Link previews are opt-in. Baileys fetches the page behind any URL in an
25
+ * outgoing text whenever `linkPreview` is merely undefined — with high-quality
26
+ * previews on it even uploads the page image. That made every AI answer with a
27
+ * Sources block, every short link and every scheduled message with a URL cost
28
+ * a silent page fetch. `linkPreview: null` skips it entirely; the operator
29
+ * opts back in with the `link_previews_enabled` setting (default off).
30
+ *
31
+ * This is the ONE choke point every outbound message passes through
32
+ * (sendBotMessage, the scheduler, status edits, legacy sock.sendMessage), so
33
+ * the guard lives here next to the thumbnail patch it shares a wrapper with.
34
+ */
35
+ function withoutUnwantedLinkPreview(content) {
36
+ if (!content || typeof content !== "object") return content;
37
+ if (typeof content.text !== "string") return content;
38
+ if ("linkPreview" in content) return content; // caller decided already
39
+ if (settings.get("link_previews_enabled")) return content; // operator opted in
40
+ return { ...content, linkPreview: null };
41
+ }
42
+
20
43
  /**
21
44
  * Baileys can't generate media previews in this install (no sharp/jimp, and its
22
45
  * video path shells out to a bare `ffmpeg` that isn't on the PATH), so every
@@ -25,10 +48,10 @@ setRecentMessageGetter(getMessageFromRecent);
25
48
  * sendBotMessage and the handful of legacy commands still calling
26
49
  * sock.sendMessage directly.
27
50
  */
28
- function withThumbnailSupport(sock) {
51
+ function withOutboundSavers(sock) {
29
52
  const original = sock.sendMessage.bind(sock);
30
53
 
31
- sock.sendMessage = async function sendMessageWithThumbnail(jid, content, options) {
54
+ sock.sendMessage = async function sendMessageWithOutboundSavers(jid, content, options) {
32
55
  let payload = content;
33
56
  try {
34
57
  payload = await withMediaThumbnail(content);
@@ -36,6 +59,7 @@ function withThumbnailSupport(sock) {
36
59
  logger.debug({ err: err?.message }, "[Socket] thumbnail step skipped");
37
60
  payload = content;
38
61
  }
62
+ payload = withoutUnwantedLinkPreview(payload);
39
63
  return original(jid, payload, options);
40
64
  };
41
65
 
@@ -83,7 +107,7 @@ export async function createWhatsAppSocket({ proxy = null, pairingCode = false }
83
107
  config.options = { ...(config.options || {}), dispatcher: proxy.dispatcher };
84
108
  }
85
109
 
86
- const sock = withThumbnailSupport(
110
+ const sock = withOutboundSavers(
87
111
  makeWASocket({
88
112
  auth: state,
89
113
  ...config,
package/src/db/store.cjs CHANGED
@@ -792,6 +792,28 @@ function deleteAllChatHistories() {
792
792
  q("DELETE FROM ai_history").run();
793
793
  }
794
794
 
795
+ // Read-only views for the dashboard's conversation inspector: which chats
796
+ // have stored history (no message content), and one chat's history with its
797
+ // last-updated stamp. `json_array_length` counts the stored turns without
798
+ // parsing the blob in JavaScript.
799
+ function listChatHistories() {
800
+ return q(
801
+ `SELECT chat_id AS chatId,
802
+ updated_at AS updatedAt,
803
+ json_array_length(history) AS turns
804
+ FROM ai_history
805
+ ORDER BY updated_at DESC`,
806
+ ).all();
807
+ }
808
+
809
+ function getChatHistoryWithMeta(chatId) {
810
+ const row = q("SELECT history, updated_at AS updatedAt FROM ai_history WHERE chat_id = ?").get(
811
+ chatId,
812
+ );
813
+ if (!row) return null;
814
+ return { history: parseJson(row.history, []), updatedAt: row.updatedAt };
815
+ }
816
+
795
817
  // ===================================================================
796
818
  // --- Baileys auth ---
797
819
  // ===================================================================
@@ -975,6 +997,8 @@ module.exports = {
975
997
  countSchedules,
976
998
  // AI history
977
999
  getChatHistory,
1000
+ getChatHistoryWithMeta,
1001
+ listChatHistories,
978
1002
  saveChatHistory,
979
1003
  deleteChatHistory,
980
1004
  deleteAllChatHistories,
@@ -4,12 +4,15 @@ import { dirname, join } from "path";
4
4
  import { fileURLToPath } from "url";
5
5
  import { checkBotAdmin, checkCommandPermission } from "../middleware/permissions.middleware.js";
6
6
  import { sendBotMessage } from "../utils/sendBotMessage.esm.js";
7
+ import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
7
8
 
8
9
  const __filename = fileURLToPath(import.meta.url);
9
10
  const __dirname = dirname(__filename);
10
11
  const require = createRequire(import.meta.url);
11
12
  const logger = require("../utils/logger.cjs");
12
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");
13
16
 
14
17
  // Commands collection (keyed by both names and aliases)
15
18
  const commands = new Map();
@@ -157,8 +160,12 @@ export function getCommandCatalog() {
157
160
  name: command.name,
158
161
  key,
159
162
  category: command.__category || "general",
160
- description: command.description || "",
161
- 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,
162
169
  chat: command.chat || "all",
163
170
  declaredAliases: command.__declaredAliases || [],
164
171
  aliases: runtimeConfig.getAliases(command.name, command.__declaredAliases || []),
@@ -276,22 +283,32 @@ export async function handleCommand(sock, msg, body) {
276
283
  const command = commands.get(invokedName);
277
284
  if (!command) return false;
278
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 }) {
279
295
  // Turned off from the dashboard. Answered rather than ignored so the user
280
296
  // knows the command exists and isn't broken.
281
297
  if (runtimeConfig.isDisabled(command.name)) {
282
298
  await sendBotMessage(
283
299
  sock,
284
300
  msg.key.remoteJid,
285
- { text: "⛔ الأمر ده متوقف حاليًا." },
301
+ { text: tr("⛔ This command is turned off right now.", "⛔ الأمر ده متوقف حاليًا.") },
286
302
  { replyTo: msg },
287
303
  );
288
304
  return true;
289
305
  }
290
306
 
291
307
  try {
292
- const groupMetadata = isGroup
293
- ? await sock.groupMetadata(msg.key.remoteJid).catch(() => null)
294
- : null;
308
+ // Cache-first: a live query only when no cached metadata exists yet (see
309
+ // utils/groupMetadataCache.cjs — this used to be one network round-trip
310
+ // per command attempt in every group).
311
+ const groupMetadata = isGroup ? await resolveGroupMetadata(sock, msg.key.remoteJid) : null;
295
312
 
296
313
  if (command.name !== "group") {
297
314
  // Enforce the `chat` constraint declared by the command. Until now this
@@ -301,7 +318,12 @@ export async function handleCommand(sock, msg, body) {
301
318
  await sendBotMessage(
302
319
  sock,
303
320
  msg.key.remoteJid,
304
- { text: "⚠️ هذا الأمر يعمل في المجموعات فقط." },
321
+ {
322
+ text: tr(
323
+ "⚠️ This command only works in groups.",
324
+ "⚠️ هذا الأمر يعمل في المجموعات فقط.",
325
+ ),
326
+ },
305
327
  { replyTo: msg },
306
328
  );
307
329
  return true;
@@ -310,7 +332,12 @@ export async function handleCommand(sock, msg, body) {
310
332
  await sendBotMessage(
311
333
  sock,
312
334
  msg.key.remoteJid,
313
- { text: "⚠️ هذا الأمر يعمل في المحادثات الخاصة فقط." },
335
+ {
336
+ text: tr(
337
+ "⚠️ This command only works in private chats.",
338
+ "⚠️ هذا الأمر يعمل في المحادثات الخاصة فقط.",
339
+ ),
340
+ },
314
341
  { replyTo: msg },
315
342
  );
316
343
  return true;
@@ -337,7 +364,12 @@ export async function handleCommand(sock, msg, body) {
337
364
  await sendBotMessage(
338
365
  sock,
339
366
  msg.key.remoteJid,
340
- { text: "⚠️ هذا الأمر يتطلب أن تكون مشرفًا." },
367
+ {
368
+ text: tr(
369
+ "⚠️ You need to be a group admin to use this command.",
370
+ "⚠️ هذا الأمر يتطلب أن تكون مشرفًا.",
371
+ ),
372
+ },
341
373
  { replyTo: msg },
342
374
  );
343
375
  return true;
@@ -347,7 +379,12 @@ export async function handleCommand(sock, msg, body) {
347
379
  await sendBotMessage(
348
380
  sock,
349
381
  msg.key.remoteJid,
350
- { text: "⚠️ يجب أن أكون مشرفًا لتنفيذ هذا الأمر." },
382
+ {
383
+ text: tr(
384
+ "⚠️ I need to be a group admin to do that.",
385
+ "⚠️ يجب أن أكون مشرفًا لتنفيذ هذا الأمر.",
386
+ ),
387
+ },
351
388
  { replyTo: msg },
352
389
  );
353
390
  return true;
@@ -381,9 +418,14 @@ export async function handleCommand(sock, msg, body) {
381
418
  sock,
382
419
  msg.key.remoteJid,
383
420
  {
384
- text: `❌ *فشل تنفيذ الأمر*\n\n*النوع:* \`${error.name || "Error"}\`\n*التفاصيل:* ${
385
- error.message || "غير معروف"
386
- }`,
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
+ ),
387
429
  },
388
430
  { replyTo: msg },
389
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)
@@ -7,9 +7,11 @@ import {
7
7
  sameUser,
8
8
  } from "../utils/permissions.esm.js";
9
9
  import { getGroupSettings, getPnForLid } from "../utils/storage.esm.js";
10
+ import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
10
11
 
11
12
  const require = createRequire(import.meta.url);
12
13
  const logger = require("../utils/logger.cjs");
14
+ const { tr } = require("../utils/i18n.cjs");
13
15
 
14
16
  const userMessageTimestamps = new Map();
15
17
 
@@ -41,7 +43,9 @@ export async function handleAntiSpam(sock, msg) {
41
43
  // Owners and admins are immune. The legacy owner mirror it used to import was
42
44
  // only ever populated with the bot's own JID, so real operators were
43
45
  // counted as spammers — the centralized check fixes that.
44
- const groupMetadata = await sock.groupMetadata(groupId);
46
+ // Cache-first: antispam runs on EVERY group message, so this read must not
47
+ // be a live query (see utils/groupMetadataCache.cjs).
48
+ const groupMetadata = await resolveGroupMetadata(sock, groupId);
45
49
  const protectedSender = senderCandidates.some(
46
50
  (candidate) =>
47
51
  isOwnerJid(candidate) ||
@@ -75,13 +79,19 @@ export async function handleAntiSpam(sock, msg) {
75
79
  // Take action based on config
76
80
  if (spamConfig.action === "KICK") {
77
81
  await sock.sendMessage(groupId, {
78
- text: `🚫 تم حذف @${senderId.split("@")[0]} بسبب الإزعاج (Spam).`,
82
+ text: tr(
83
+ `🚫 @${senderId.split("@")[0]} was removed for spamming.`,
84
+ `🚫 تم حذف @${senderId.split("@")[0]} بسبب الإزعاج (Spam).`,
85
+ ),
79
86
  mentions: [senderId],
80
87
  });
81
88
  await sock.groupParticipantsUpdate(groupId, [senderId], "remove");
82
89
  } else {
83
90
  await sock.sendMessage(groupId, {
84
- text: `⚠️ تحذير لـ @${senderId.split("@")[0]}! الرجاء عدم إرسال رسائل مزعجة.`,
91
+ text: tr(
92
+ `⚠️ Warning, @${senderId.split("@")[0]}! Please don't spam.`,
93
+ `⚠️ تحذير لـ @${senderId.split("@")[0]}! الرجاء عدم إرسال رسائل مزعجة.`,
94
+ ),
85
95
  mentions: [senderId],
86
96
  });
87
97
  }
@@ -1,6 +1,7 @@
1
1
  import { createRequire } from "module";
2
2
  import { getSenderCandidates, isAdminInGroup, sameUser } from "../utils/permissions.esm.js";
3
3
  import { getGroupSettings } from "../utils/storage.esm.js";
4
+ import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
4
5
 
5
6
  const require = createRequire(import.meta.url);
6
7
  const logger = require("../utils/logger.cjs");
@@ -19,7 +20,9 @@ export async function checkBlacklist(sock, msg) {
19
20
  );
20
21
 
21
22
  if (listed) {
22
- const groupMetadata = await sock.groupMetadata(groupId);
23
+ // Cache-first: admin detection for a blacklisted sender, only when the
24
+ // blacklist actually matched (see utils/groupMetadataCache.cjs).
25
+ const groupMetadata = await resolveGroupMetadata(sock, groupId);
23
26
  const isSenderAdmin = senderCandidates.some((candidate) =>
24
27
  isAdminInGroup(groupMetadata, candidate),
25
28
  );