_checkLang.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const translationCache = new Map();
  2. export async function tr(baseText) {
  3. const m = global.currentMessageContext;
  4. const targetLang = m ? global.db?.data?.users[m.sender]?.language || global.lang : global.lang;
  5. if (targetLang === 'es') return baseText;
  6. const cacheKey = `${baseText}:${targetLang}`;
  7. if (translationCache.has(cacheKey)) {
  8. return translationCache.get(cacheKey);
  9. }
  10. const translatedText = await translateText(baseText, targetLang);
  11. translationCache.set(cacheKey, translatedText);
  12. if (translationCache.size > 1000) {
  13. const firstKey = translationCache.keys().next().value;
  14. translationCache.delete(firstKey);
  15. }
  16. return translatedText;
  17. }
  18. export async function translateText(text, targetLang) {
  19. if (typeof text !== 'string' || !text.trim()) return text;
  20. try {
  21. const textRegex = /\b(?![\w.]*\.[\w.]*)([\p{L}0-9][\p{L}0-9\s]*)\b/gu;
  22. const translatableParts = [...text.matchAll(textRegex)].map(match => match[1].trim()).filter(Boolean);
  23. if (translatableParts.length === 0) {
  24. return text;
  25. }
  26. const res = await fetch("https://tr.skyultraplus.com/translate", {
  27. method: "POST",
  28. headers: { "Content-Type": "application/json" },
  29. body: JSON.stringify({
  30. q: translatableParts.join("\n"),
  31. source: "auto",
  32. target: targetLang
  33. }),
  34. timeout: 5000
  35. });
  36. const contentType = res.headers.get('content-type');
  37. if (!contentType || !contentType.includes('application/json')) {
  38. console.log("Invalid content type:", contentType);
  39. return text;
  40. }
  41. const data = await res.json();
  42. const translated = data.translatedText?.split("\n") || translatableParts;
  43. let index = 0;
  44. const translatedText = text.replace(textRegex, (match, group1) => {
  45. const current = translated[index++];
  46. return current ? current : match;
  47. });
  48. return translatedText;
  49. } catch (err) {
  50. console.error("Error en traducción:", err);
  51. return text;
  52. }
  53. }