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
@@ -1,10 +1,10 @@
1
1
  // Speech-to-Text Command using FREE Gemini API
2
2
  const { GoogleGenAI } = require("@google/genai");
3
3
  const { downloadContentFromMessage } = require("@whiskeysockets/baileys");
4
- const fs = require("fs").promises;
5
- const path = require("path");
6
4
  const logger = require("../utils/logger.cjs");
7
5
  const { createStatus } = require("../utils/statusMessage.cjs");
6
+ const { unwrapMessage } = require("../utils/messageContent.cjs");
7
+ const { baseMimeType, downloadMedia, uploadToGemini } = require("../utils/geminiMedia.cjs");
8
8
 
9
9
  const settings = require("../config/settings.cjs");
10
10
  const {
@@ -12,6 +12,7 @@ const {
12
12
  assertProviderRequestUrl,
13
13
  safeProviderFetch,
14
14
  } = require("../utils/providerUrl.cjs");
15
+ const { tr } = require("../utils/i18n.cjs");
15
16
 
16
17
  // Built on first use from whatever key is in force, and
17
18
  // rebuilt if that key changes — the operator can paste one without a restart.
@@ -58,9 +59,55 @@ function resolveSttProvider() {
58
59
  : "gemini";
59
60
  }
60
61
 
62
+ const TRANSCRIBE_PROMPT =
63
+ "Please transcribe this audio message accurately. Return ONLY the transcription text without any additional commentary, explanations, or formatting. Just the raw transcribed text.";
64
+
65
+ // A voice note is a few hundred KB, so it rides inline in the request: one
66
+ // round trip, instead of an upload, a finalize and then the request. Past this
67
+ // size (Gemini caps a whole inline request at 20 MB) it goes through the Files
68
+ // API instead.
69
+ const INLINE_AUDIO_LIMIT = 15 * 1024 * 1024;
70
+
71
+ async function transcribeWithGemini(audioBuffer, mimetype) {
72
+ const gemini = geminiStt();
73
+ if (!gemini)
74
+ throw new Error(
75
+ tr("No Gemini key is set in the settings", "مفتاح Gemini غير مضبوط في الإعدادات"),
76
+ );
77
+ await assertProviderRequestUrl(settings.get("gemini_base_url"), {
78
+ allowLoopback: true,
79
+ });
80
+
81
+ // WhatsApp labels voice notes `audio/ogg; codecs=opus`; Gemini's type is
82
+ // `audio/ogg`, and the codec parameter is not part of it.
83
+ const mimeType = baseMimeType(mimetype, "audio");
84
+ let audioPart;
85
+ if (audioBuffer.length <= INLINE_AUDIO_LIMIT) {
86
+ audioPart = { inlineData: { mimeType, data: audioBuffer.toString("base64") } };
87
+ } else {
88
+ const file = await uploadToGemini(gemini.genAI, audioBuffer, mimeType, {
89
+ displayName: `audio-${Date.now()}`,
90
+ });
91
+ audioPart = { fileData: { mimeType: file.mimeType || mimeType, fileUri: file.uri } };
92
+ }
93
+
94
+ const response = await gemini.genAI.models.generateContent({
95
+ model: sttModel(),
96
+ contents: [{ role: "user", parts: [audioPart, { text: TRANSCRIBE_PROMPT }] }],
97
+ });
98
+ return (response.text ?? "").trim();
99
+ }
100
+
61
101
  async function transcribeWithOpenAi(audioBuffer, mimetype) {
62
102
  const apiKey = settings.get("openai_api_key");
63
- if (!apiKey) throw new Error("مفتاح OpenAI / Groq غير مضبوط في الإعدادات");
103
+ if (!apiKey) {
104
+ throw new Error(
105
+ tr(
106
+ "No OpenAI / Groq key is set in the settings",
107
+ "مفتاح OpenAI / Groq غير مضبوط في الإعدادات",
108
+ ),
109
+ );
110
+ }
64
111
  const baseUrl = assertProviderBaseUrl(
65
112
  settings.get("openai_base_url") || "https://api.openai.com/v1",
66
113
  { allowLoopback: true },
@@ -68,10 +115,10 @@ async function transcribeWithOpenAi(audioBuffer, mimetype) {
68
115
  const model = settings.get("openai_stt_model") || "whisper-large-v3";
69
116
 
70
117
  const formData = new FormData();
71
- const mime = mimetype || "audio/ogg";
118
+ const mime = baseMimeType(mimetype, "audio");
72
119
  const ext = mime.includes("mp4")
73
120
  ? "m4a"
74
- : mime.includes("mp3")
121
+ : mime.includes("mp3") || mime.includes("mpeg")
75
122
  ? "mp3"
76
123
  : mime.includes("wav")
77
124
  ? "wav"
@@ -83,14 +130,18 @@ async function transcribeWithOpenAi(audioBuffer, mimetype) {
83
130
  const controller = new AbortController();
84
131
  const timer = setTimeout(() => controller.abort(), 60000);
85
132
  try {
86
- const res = await safeProviderFetch(`${baseUrl}/audio/transcriptions`, {
87
- method: "POST",
88
- headers: {
89
- Authorization: `Bearer ${apiKey}`,
133
+ const res = await safeProviderFetch(
134
+ `${baseUrl}/audio/transcriptions`,
135
+ {
136
+ method: "POST",
137
+ headers: {
138
+ Authorization: `Bearer ${apiKey}`,
139
+ },
140
+ body: formData,
141
+ signal: controller.signal,
90
142
  },
91
- body: formData,
92
- signal: controller.signal,
93
- }, { allowLoopback: true });
143
+ { allowLoopback: true },
144
+ );
94
145
  if (!res.ok) {
95
146
  const err = await res.text().catch(() => "");
96
147
  throw new Error(`STT API (${res.status}): ${err}`);
@@ -102,139 +153,140 @@ async function transcribeWithOpenAi(audioBuffer, mimetype) {
102
153
  }
103
154
  }
104
155
 
156
+ /** Audio bytes -> text, on whichever engine the settings pick. */
157
+ async function transcribe(audioBuffer, mimetype) {
158
+ const provider = resolveSttProvider();
159
+ const hasOpenAi = !!settings.get("openai_api_key");
160
+ if (provider === "openai" && hasOpenAi) {
161
+ logger.info("[STT] Transcribing via OpenAI/Groq Whisper API");
162
+ return transcribeWithOpenAi(audioBuffer, mimetype);
163
+ }
164
+ if (geminiStt()) {
165
+ logger.info("[STT] Transcribing via Gemini");
166
+ return transcribeWithGemini(audioBuffer, mimetype);
167
+ }
168
+ if (hasOpenAi) {
169
+ logger.info("[STT] Fallback transcribing via OpenAI/Groq Whisper API");
170
+ return transcribeWithOpenAi(audioBuffer, mimetype);
171
+ }
172
+ throw new Error(
173
+ tr(
174
+ "No AI key (Gemini or OpenAI/Groq) is set",
175
+ "مفتاح الذكاء الاصطناعي (Gemini أو OpenAI/Groq) غير مضبوط",
176
+ ),
177
+ );
178
+ }
179
+
180
+ function sttErrorHint(error) {
181
+ const message = String(error?.message || "");
182
+ if (/quota|RESOURCE_EXHAUSTED|429/i.test(message)) {
183
+ return tr(
184
+ "The free quota is used up. Try again later.",
185
+ "تم تجاوز الحد المجاني. حاول مرة أخرى لاحقاً.",
186
+ );
187
+ }
188
+ if (/API key|API_KEY|401|403/i.test(message)) {
189
+ return tr(
190
+ "Check the API key in the control panel (Settings).",
191
+ "راجع مفتاح الـ API من لوحة التحكم (Settings).",
192
+ );
193
+ }
194
+ if (/upload/i.test(message)) {
195
+ return tr("Uploading the audio failed. Try again.", "فشل رفع الملف الصوتي. حاول مرة أخرى.");
196
+ }
197
+ return "";
198
+ }
199
+
105
200
  module.exports = {
106
201
  name: "stt",
107
202
  aliases: ["totext", "transcribe"],
108
- description: "Convert speech/audio to text (supports Gemini & Groq/OpenAI Whisper)",
109
- usage: "stt (قم بالرد على رسالة صوتية أو إرسالها مع الأمر)",
203
+ description: {
204
+ en: "Converts speech/audio to text (Gemini or Groq/OpenAI Whisper).",
205
+ ar: "يحوّل الكلام/الصوت إلى نص (عبر Gemini أو Groq/OpenAI Whisper).",
206
+ },
207
+ usage: {
208
+ en: "stt (reply to a voice note, or send one with the command)",
209
+ ar: "stt (رد على رسالة صوتية أو أرسلها مع الأمر)",
210
+ },
110
211
  chat: "all",
111
212
 
112
213
  async execute(sock, msg, args, body, groupMetadata) {
113
214
  const chatId = msg.key.remoteJid;
114
215
 
115
216
  // Check if message has audio or if it's a reply to an audio message
217
+ const own = unwrapMessage(msg.message);
116
218
  const audioMessage =
117
- msg.message?.audioMessage ||
118
- msg.message?.extendedTextMessage?.contextInfo?.quotedMessage?.audioMessage;
219
+ own.audioMessage ||
220
+ unwrapMessage(own.extendedTextMessage?.contextInfo?.quotedMessage).audioMessage;
119
221
 
120
222
  if (!audioMessage) {
121
223
  return await sock.sendMessage(chatId, {
122
- text: "📢 الاستخدام:\nأرسل رسالة صوتية أو قم بالرد على رسالة صوتية بالأمر !stt\n\n✨ يدعم تفريغ الصوت عبر Gemini و Groq/OpenAI Whisper\n🌍 يدعم العربية والإنجليزية وكافة اللغات",
224
+ text: tr(
225
+ "📢 Usage:\nSend a voice note, or reply to one, with !stt\n\n✨ Transcribes with Gemini or Groq/OpenAI Whisper\n🌍 Arabic, English and every other language",
226
+ "📢 الاستخدام:\nأرسل رسالة صوتية أو قم بالرد على رسالة صوتية بالأمر !stt\n\n✨ يدعم تفريغ الصوت عبر Gemini و Groq/OpenAI Whisper\n🌍 يدعم العربية والإنجليزية وكافة اللغات",
227
+ ),
123
228
  });
124
229
  }
125
230
 
126
- const provider = resolveSttProvider();
127
231
  const hasGemini = !!geminiStt();
128
232
  const hasOpenAi = !!settings.get("openai_api_key");
129
233
 
130
234
  if (!hasGemini && !hasOpenAi) {
131
235
  return await sock.sendMessage(chatId, {
132
- text: "⚠️ مفتاح الذكاء الاصطناعي (Gemini أو OpenAI/Groq) غير مضبوط. يرجى إضافته من لوحة التحكم (Settings).",
236
+ text: tr(
237
+ "⚠️ No AI key (Gemini or OpenAI/Groq) is set. Add one in the control panel (Settings).",
238
+ "⚠️ مفتاح الذكاء الاصطناعي (Gemini أو OpenAI/Groq) غير مضبوط. يرجى إضافته من لوحة التحكم (Settings).",
239
+ ),
133
240
  });
134
241
  }
135
242
 
136
- let tempAudioPath = null;
137
-
138
243
  // One message, edited from "transcribing" into the transcript itself.
139
- const status = await createStatus(sock, chatId, "🎧 جاري تحويل الصوت إلى نص...", {
140
- replyTo: msg,
141
- });
244
+ const status = await createStatus(
245
+ sock,
246
+ chatId,
247
+ tr("🎧 Transcribing...", "🎧 جاري تحويل الصوت إلى نص..."),
248
+ {
249
+ replyTo: msg,
250
+ },
251
+ );
142
252
 
143
253
  try {
144
- // Download audio content
145
- const audioBuffer = await downloadContentFromMessage(audioMessage, "audio");
146
-
147
- let transcription = "";
148
- if (provider === "openai" && hasOpenAi) {
149
- logger.info("[STT] Transcribing via OpenAI/Groq Whisper API");
150
- transcription = await transcribeWithOpenAi(audioBuffer, audioMessage.mimetype);
151
- } else if (hasGemini) {
152
- await assertProviderRequestUrl(settings.get("gemini_base_url"), {
153
- allowLoopback: true,
154
- });
155
- // Save audio to temporary file
156
- tempAudioPath = path.join(__dirname, `stt_audio_${Date.now()}.ogg`);
157
- await fs.writeFile(tempAudioPath, audioBuffer);
158
-
159
- logger.info(`[STT] Saved audio to temporary file: ${tempAudioPath}`);
160
-
161
- // Upload audio to Gemini. ai.files.upload returns the File directly
162
- const uploaded = await gemini.genAI.files.upload({
163
- file: tempAudioPath,
164
- config: {
165
- mimeType: audioMessage.mimetype || "audio/ogg; codecs=opus",
166
- displayName: `audio-${Date.now()}`,
167
- },
168
- });
169
-
170
- logger.info(`[STT] Uploaded audio to Gemini: ${uploaded.uri}`);
171
-
172
- // Generate transcription using Gemini
173
- const response = await gemini.genAI.models.generateContent({
174
- model: sttModel(),
175
- contents: [
176
- {
177
- role: "user",
178
- parts: [
179
- {
180
- fileData: {
181
- mimeType: uploaded.mimeType,
182
- fileUri: uploaded.uri,
183
- },
184
- },
185
- {
186
- text: "Please transcribe this audio message accurately. Return ONLY the transcription text without any additional commentary, explanations, or formatting. Just the raw transcribed text.",
187
- },
188
- ],
189
- },
190
- ],
191
- });
192
-
193
- transcription = (response.text ?? "").trim();
194
- } else if (hasOpenAi) {
195
- logger.info("[STT] Fallback transcribing via OpenAI/Groq Whisper API");
196
- transcription = await transcribeWithOpenAi(audioBuffer, audioMessage.mimetype);
197
- }
254
+ // A real Buffer, not the download stream: the Whisper path wraps it in
255
+ // a Blob, and a stream in a Blob is the string "[object Object]".
256
+ const audioBuffer = await downloadMedia(downloadContentFromMessage, audioMessage, "audio");
257
+ const transcription = await transcribe(audioBuffer, audioMessage.mimetype);
198
258
 
199
- if (!transcription || transcription === "") {
259
+ if (!transcription) {
200
260
  await status.finish(
201
- "⚠️ لم أتمكن من استخراج أي نص من الرسالة الصوتية. تأكد من أن الصوت واضح.",
261
+ tr(
262
+ "⚠️ I couldn't get any text out of that voice note. Make sure the audio is clear.",
263
+ "⚠️ لم أتمكن من استخراج أي نص من الرسالة الصوتية. تأكد من أن الصوت واضح.",
264
+ ),
202
265
  );
203
266
  return;
204
267
  }
205
268
 
206
269
  // The status line becomes the transcript.
207
- await status.finish(`📝 النص المستخرج:\n\n${transcription}`);
270
+ await status.finish(
271
+ tr(`📝 Transcript:\n\n${transcription}`, `📝 النص المستخرج:\n\n${transcription}`),
272
+ );
208
273
 
209
- logger.info("[STT] Successfully transcribed audio to text (FREE - Gemini)");
274
+ logger.info("[STT] Successfully transcribed audio to text");
210
275
  } catch (error) {
211
276
  logger.error({ err: error }, "[STT] Error transcribing audio");
212
277
 
213
- let errorMessage = "❌ حدث خطأ أثناء تحويل الصوت إلى نص.";
214
-
215
- // Provide more specific error messages
216
- if (error.message?.includes("quota")) {
217
- errorMessage += "\n\nتم تجاوز الحد المجاني. حاول مرة أخرى لاحقاً.";
218
- } else if (error.message?.includes("API key")) {
219
- errorMessage += "\n\nخطأ في مفتاح API. تواصل مع المطور.";
220
- } else if (error.message?.includes("upload")) {
221
- errorMessage += "\n\nفشل رفع الملف الصوتي. حاول مرة أخرى.";
222
- }
223
-
224
- await status.finish(errorMessage);
225
- } finally {
226
- // Clean up temporary file
227
- if (tempAudioPath) {
228
- try {
229
- await fs.unlink(tempAudioPath);
230
- logger.info(`[STT] Deleted temporary file: ${tempAudioPath}`);
231
- } catch (cleanupErr) {
232
- logger.warn(
233
- { err: cleanupErr },
234
- `[STT] Failed to delete temporary file: ${tempAudioPath}`,
235
- );
236
- }
237
- }
278
+ // The real reason goes in the card — a bare "an error happened" left
279
+ // nothing to act on.
280
+ const details = String(error?.message || error || tr("unknown", "غير معروف")).slice(0, 800);
281
+ const hint = sttErrorHint(error);
282
+ await status.finish(
283
+ tr(
284
+ `❌ *Transcription failed*\n\n*Details:* ${details}${hint ? `\n\n${hint}` : ""}`,
285
+ `❌ *حدث خطأ أثناء تحويل الصوت إلى نص*\n\n*التفاصيل:* ${details}${hint ? `\n\n${hint}` : ""}`,
286
+ ),
287
+ );
238
288
  }
239
289
  },
240
290
  };
291
+
292
+ module.exports.transcribe = transcribe;
@@ -1,12 +1,19 @@
1
1
  // file: /commands/todo.cjs (Corrected Reply Logic)
2
2
  const { getUserTodos, saveUserTodos } = require("../utils/storage.cjs");
3
3
  const logger = require("../utils/logger.cjs");
4
+ const { tr } = require("../utils/i18n.cjs");
4
5
  const normalizeJid = require("../utils/normalizeJid.esm.js").default;
5
6
 
6
7
  module.exports = {
7
8
  name: "todo",
8
- description: "Manages your personal to-do list.",
9
- usage: "todo list\ntodo add <المهمة>\ntodo del <رقم المهمة>",
9
+ description: {
10
+ en: "Manages your personal to-do list.",
11
+ ar: "يدير قائمة مهامك الشخصية.",
12
+ },
13
+ usage: {
14
+ en: "todo list\ntodo add <task>\ntodo del <task number>",
15
+ ar: "todo list\ntodo add <المهمة>\ntodo del <رقم المهمة>",
16
+ },
10
17
  chat: "all",
11
18
 
12
19
  async execute(sock, msg, args) {
@@ -22,13 +29,16 @@ module.exports = {
22
29
  const taskToAdd = args.slice(1).join(" ");
23
30
  if (!taskToAdd) {
24
31
  return await sock.sendMessage(remoteJid, {
25
- text: "يرجى كتابة المهمة التي تريد إضافتها.",
32
+ text: tr("Write the task you want to add.", "يرجى كتابة المهمة التي تريد إضافتها."),
26
33
  });
27
34
  }
28
35
  userTasks.push(taskToAdd);
29
36
  saveUserTodos(senderId, userTasks);
30
37
  await sock.sendMessage(remoteJid, {
31
- text: `✅ يا @${senderId.split("@")[0]}، تمت إضافة المهمة لقائمتك.`,
38
+ text: tr(
39
+ `✅ @${senderId.split("@")[0]}, the task was added to your list.`,
40
+ `✅ يا @${senderId.split("@")[0]}، تمت إضافة المهمة لقائمتك.`,
41
+ ),
32
42
  mentions: [senderId],
33
43
  });
34
44
  break;
@@ -39,13 +49,16 @@ module.exports = {
39
49
  const taskNumber = parseInt(args[1], 10);
40
50
  if (isNaN(taskNumber) || taskNumber <= 0 || taskNumber > userTasks.length) {
41
51
  return await sock.sendMessage(remoteJid, {
42
- text: "رقم المهمة غير صالح.",
52
+ text: tr("That task number isn't valid.", "رقم المهمة غير صالح."),
43
53
  });
44
54
  }
45
55
  const removedTask = userTasks.splice(taskNumber - 1, 1);
46
56
  saveUserTodos(senderId, userTasks);
47
57
  await sock.sendMessage(remoteJid, {
48
- text: `☑️ يا @${senderId.split("@")[0]}، تم حذف المهمة: *${removedTask[0]}*`,
58
+ text: tr(
59
+ `☑️ @${senderId.split("@")[0]}, removed the task: *${removedTask[0]}*`,
60
+ `☑️ يا @${senderId.split("@")[0]}، تم حذف المهمة: *${removedTask[0]}*`,
61
+ ),
49
62
  mentions: [senderId],
50
63
  });
51
64
  break;
@@ -55,12 +68,18 @@ module.exports = {
55
68
  default: {
56
69
  if (userTasks.length === 0) {
57
70
  return await sock.sendMessage(remoteJid, {
58
- text: `قائمة مهامك فارغة يا @${senderId.split("@")[0]}.`,
71
+ text: tr(
72
+ `Your to-do list is empty, @${senderId.split("@")[0]}.`,
73
+ `قائمة مهامك فارغة يا @${senderId.split("@")[0]}.`,
74
+ ),
59
75
  mentions: [senderId],
60
76
  });
61
77
  }
62
78
 
63
- let reply = `*📋 قائمة مهامك يا @${senderId.split("@")[0]}:*\n\n`;
79
+ let reply = tr(
80
+ `*📋 Your to-do list, @${senderId.split("@")[0]}:*\n\n`,
81
+ `*📋 قائمة مهامك يا @${senderId.split("@")[0]}:*\n\n`,
82
+ );
64
83
  userTasks.forEach((task, index) => {
65
84
  reply += `${index + 1}. ${task}\n`;
66
85
  });
@@ -75,7 +94,10 @@ module.exports = {
75
94
  } catch (error) {
76
95
  logger.error({ err: error, command: "todo" }, "An error occurred in the todo command");
77
96
  await sock.sendMessage(msg.key.remoteJid, {
78
- text: "حدث خطأ أثناء معالجة قائمة المهام.",
97
+ text: tr(
98
+ "Something went wrong with the to-do list.",
99
+ "حدث خطأ أثناء معالجة قائمة المهام.",
100
+ ),
79
101
  });
80
102
  }
81
103
  },
@@ -23,6 +23,7 @@ const { sendBotMessage } = require("../utils/sendBotMessage.cjs");
23
23
  const execFileAsync = promisify(execFile);
24
24
 
25
25
  const { ffmpegPath } = require("../utils/thumbnail.cjs");
26
+ const { tr } = require("../utils/i18n.cjs");
26
27
 
27
28
  function tmpPath(ext) {
28
29
  return path.join(
@@ -31,9 +32,9 @@ function tmpPath(ext) {
31
32
  );
32
33
  }
33
34
 
34
- async function synthesizeMp3(text, mp3Path) {
35
+ async function synthesizeMp3(text, mp3Path, lang = "ar") {
35
36
  const parts = await googleTTS.getAllAudioBase64(text, {
36
- lang: "ar",
37
+ lang,
37
38
  slow: false,
38
39
  timeout: 15_000,
39
40
  splitPunct: "،,.!?؟؛;:\n",
@@ -105,11 +106,42 @@ async function transcodeToOpus(mp3Path) {
105
106
  return null;
106
107
  }
107
108
 
109
+ /**
110
+ * Text -> sendable voice payload, shared by the !tts command and the AI
111
+ * agent's `speak` tool. Resolves to { audio, mimetype, ptt }: Opus/OGG for a
112
+ * proper push-to-talk note when ffmpeg can transcode, raw MP3 otherwise.
113
+ * Temp files are cleaned up here either way.
114
+ */
115
+ async function synthesizeVoice(text, lang = "ar") {
116
+ const mp3Path = tmpPath("mp3");
117
+ try {
118
+ await synthesizeMp3(text, mp3Path, lang);
119
+
120
+ const oggPath = await transcodeToOpus(mp3Path);
121
+ if (oggPath && fs.existsSync(oggPath)) {
122
+ const audio = await fsp.readFile(oggPath);
123
+ await fsp.unlink(oggPath).catch(() => {});
124
+ return { audio, mimetype: "audio/ogg; codecs=opus", ptt: true };
125
+ }
126
+
127
+ const audio = await fsp.readFile(mp3Path);
128
+ return { audio, mimetype: "audio/mpeg", ptt: false };
129
+ } finally {
130
+ await fsp.unlink(mp3Path).catch(() => {});
131
+ }
132
+ }
133
+
108
134
  module.exports = {
109
135
  name: "tts",
110
136
  aliases: ["tovoice", "speak"],
111
- description: "Convert text to speech (FREE - no API costs)",
112
- usage: "tts <النص> (أو رد على رسالة نصية)",
137
+ description: {
138
+ en: "Converts text to speech (free — no API costs).",
139
+ ar: "يحوّل النص إلى كلام مسموع (مجاني — بدون تكلفة API).",
140
+ },
141
+ usage: {
142
+ en: "tts <text> (or reply to a text message)",
143
+ ar: "tts <النص> (أو رد على رسالة نصية)",
144
+ },
113
145
  chat: "all",
114
146
 
115
147
  async execute(sock, msg, args) {
@@ -127,40 +159,35 @@ module.exports = {
127
159
  sock,
128
160
  chatId,
129
161
  {
130
- text: "📢 الاستخدام:\n!tts <النص>\n\nأو رد على رسالة نصية بالأمر !tts\n\n✨ مجاني تماماً - بدون تكاليف!",
162
+ text: tr(
163
+ "📢 Usage:\n!tts <text>\n\nor reply to a text message with !tts\n\n✨ Completely free — no costs!",
164
+ "📢 الاستخدام:\n!tts <النص>\n\nأو رد على رسالة نصية بالأمر !tts\n\n✨ مجاني تماماً - بدون تكاليف!",
165
+ ),
131
166
  },
132
167
  { replyTo: msg },
133
168
  );
134
169
  }
135
170
 
136
- let mp3Path = null;
137
- let oggPath = null;
138
-
139
171
  // One status line: it disappears once the voice note is on its way.
140
- const status = await createStatus(sock, chatId, "🎙️ بحوّل النص لصوت...", {
141
- replyTo: msg,
142
- });
172
+ const status = await createStatus(
173
+ sock,
174
+ chatId,
175
+ tr("🎙️ Turning the text into speech...", "🎙️ بحوّل النص لصوت..."),
176
+ {
177
+ replyTo: msg,
178
+ },
179
+ );
143
180
 
144
181
  try {
145
- mp3Path = tmpPath("mp3");
146
- await synthesizeMp3(textToConvert, mp3Path);
147
-
148
- // Try to transcode to Opus for proper PTT delivery.
149
- try {
150
- oggPath = await transcodeToOpus(mp3Path);
151
- } catch (err) {
152
- logger.warn({ err: err?.message }, "[TTS] Opus transcode failed, will fall back to MP3");
153
- oggPath = null;
154
- }
182
+ const voice = await synthesizeVoice(textToConvert);
155
183
 
156
- if (oggPath && fs.existsSync(oggPath)) {
157
- const audioBuffer = await fsp.readFile(oggPath);
184
+ if (voice.ptt) {
158
185
  await sendBotMessage(
159
186
  sock,
160
187
  chatId,
161
188
  {
162
- audio: audioBuffer,
163
- mimetype: "audio/ogg; codecs=opus",
189
+ audio: voice.audio,
190
+ mimetype: voice.mimetype,
164
191
  ptt: true,
165
192
  },
166
193
  { replyTo: msg, typing: false },
@@ -168,13 +195,12 @@ module.exports = {
168
195
  } else {
169
196
  // Fallback: send the raw MP3 with the correct mimetype. Cannot be
170
197
  // PTT — WhatsApp requires Opus for that — but at least it plays.
171
- const audioBuffer = await fsp.readFile(mp3Path);
172
198
  await sendBotMessage(
173
199
  sock,
174
200
  chatId,
175
201
  {
176
- audio: audioBuffer,
177
- mimetype: "audio/mpeg",
202
+ audio: voice.audio,
203
+ mimetype: voice.mimetype,
178
204
  ptt: false,
179
205
  },
180
206
  { replyTo: msg, typing: false },
@@ -187,14 +213,13 @@ module.exports = {
187
213
  logger.info("[TTS] Successfully delivered TTS audio");
188
214
  } catch (error) {
189
215
  logger.error({ err: error }, "[TTS] Error converting text to speech");
190
- await status.fail(error, "حصلت مشكلة وأنا بحوّل النص لصوت");
191
- } finally {
192
- for (const p of [mp3Path, oggPath]) {
193
- if (!p) continue;
194
- try {
195
- await fsp.unlink(p);
196
- } catch {}
197
- }
216
+ await status.fail(
217
+ error,
218
+ tr("Something went wrong turning the text into speech", "حصلت مشكلة وأنا بحوّل النص لصوت"),
219
+ );
198
220
  }
199
221
  },
222
+
223
+ // exported for the AI agent's `speak` tool — one synthesizer, two doors
224
+ _synthesizeVoice: synthesizeVoice,
200
225
  };
@@ -1,11 +1,18 @@
1
1
  // file: /commands/unblock.js (Upgraded with private chat context)
2
2
  const logger = require("../utils/logger.cjs");
3
3
  const normalizeJid = require("../utils/normalizeJid.esm.js");
4
+ const { tr } = require("../utils/i18n.cjs");
4
5
 
5
6
  module.exports = {
6
7
  name: "unblock",
7
- description: "Unblocks a user.",
8
- usage: "unblock [@عضو|رقم] (أو رد على رسالته)",
8
+ description: {
9
+ en: "Unblocks a user.",
10
+ ar: "يلغي حظر مستخدم.",
11
+ },
12
+ usage: {
13
+ en: "unblock [@member|number] (or reply to their message)",
14
+ ar: "unblock [@عضو|رقم] (أو رد على رسالته)",
15
+ },
9
16
  chat: "all",
10
17
 
11
18
  async execute(sock, msg, args) {
@@ -25,7 +32,10 @@ module.exports = {
25
32
  targetJid = `${numberArg.replace(/\D/g, "")}@s.whatsapp.net`;
26
33
  } else {
27
34
  return await sock.sendMessage(remoteJid, {
28
- text: "لفك حظر عضو، استخدم الأمر في شاته الخاص، أو قم بعمل منشن له، أو كتابة رقمه.",
35
+ text: tr(
36
+ "To unblock someone, use this in their private chat, mention them, or type their number.",
37
+ "لفك حظر عضو، استخدم الأمر في شاته الخاص، أو قم بعمل منشن له، أو كتابة رقمه.",
38
+ ),
29
39
  });
30
40
  }
31
41
  }
@@ -46,7 +56,10 @@ module.exports = {
46
56
  } catch (error) {
47
57
  logger.error({ err: error, command: "unblock" }, "Error in !unblock command");
48
58
  await sock.sendMessage(remoteJid, {
49
- text: "حدث خطأ أثناء محاولة فك حظر المستخدم.",
59
+ text: tr(
60
+ "Something went wrong while unblocking the user.",
61
+ "حدث خطأ أثناء محاولة فك حظر المستخدم.",
62
+ ),
50
63
  });
51
64
  }
52
65
  },