| 5 | description: 'Translate text to the specified language.', |
| 6 | usage: '.translate <text> <lang> or reply to a message with .translate <lang>', |
| 7 | async handler(sock, message, args, context) { |
| 8 | const chatId = context.chatId || message.key.remoteJid; |
| 9 | try { |
| 10 | await sock.presenceSubscribe(chatId); |
| 11 | await sock.sendPresenceUpdate('composing', chatId); |
| 12 | let textToTranslate = ''; |
| 13 | let lang = ''; |
| 14 | const quotedMessage = message.message?.extendedTextMessage?.contextInfo?.quotedMessage; |
| 15 | if (quotedMessage) { |
| 16 | textToTranslate = quotedMessage.conversation || |
| 17 | quotedMessage.extendedTextMessage?.text || |
| 18 | quotedMessage.imageMessage?.caption || |
| 19 | quotedMessage.videoMessage?.caption || |
| 20 | ''; |
| 21 | lang = args[0]?.trim(); |
| 22 | } |
| 23 | else { |
| 24 | if (args.length < 2) { |
| 25 | return await sock.sendMessage(chatId, { |
| 26 | text: `*TRANSLATOR*\n\nUsage:\n1. Reply to a message with: .translate <lang> or .trt <lang>\n2. Or type: .translate <text> <lang> or .trt <text> <lang>\n\nExample:\n.translate hello fr\n.trt hello fr\n\nLanguage codes:\nfr - French\nes - Spanish\nde - German\nit - Italian\npt - Portuguese\nru - Russian\nja - Japanese\nko - Korean\nzh - Chinese\nar - Arabic\nhi - Hindi`, |
| 27 | quoted: message |
| 28 | }); |
| 29 | } |
| 30 | lang = args.pop(); |
| 31 | textToTranslate = args.join(' '); |
| 32 | } |
| 33 | if (!textToTranslate) { |
| 34 | return await sock.sendMessage(chatId, { |
| 35 | text: 'No text found to translate. Please provide text or reply to a message.', |
| 36 | quoted: message |
| 37 | }); |
| 38 | } |
| 39 | let translatedText = null; |
| 40 | try { |
| 41 | const response = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${lang}&dt=t&q=${encodeURIComponent(textToTranslate)}`); |
| 42 | if (response.ok) { |
| 43 | const data = await response.json(); |
| 44 | if (data && data[0] && data[0][0] && data[0][0][0]) { |
| 45 | translatedText = data[0][0][0]; |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | catch (e) { |
| 50 | } |
| 51 | if (!translatedText) { |
| 52 | try { |
| 53 | const response = await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(textToTranslate)}&langpair=auto|${lang}`); |
| 54 | if (response.ok) { |
| 55 | const data = await response.json(); |
| 56 | if (data && data.responseData && data.responseData.translatedText) { |
| 57 | translatedText = data.responseData.translatedText; |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | catch (e) { |
| 62 | } |
| 63 | } |
| 64 | if (!translatedText) { |