不想多说了,全是调试信息了,百度的翻译坑比较多,坑踩完了,留文记录,等下删完调试信,就没几行了。但不要误以为我是程序员,因为我有ChatGPT.

image-1703416855258

const telegramAuthToken = "6******9:AA*********X4";
const webhookEndpoint = "/endpoint";
const baiduTranslateAppId = "2*******36";
const baiduTranslateKey = "Q4*********G9";
const baiduTranslateApiUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate";

addEventListener("fetch", (event) => {
  event.respondWith(handleIncomingRequest(event));
});

async function handleIncomingRequest(event) {
  try {
    let url = new URL(event.request.url);
    let path = url.pathname;
    let method = event.request.method;
    let workerUrl = `${url.protocol}//${url.host}`;

    if (method === "POST" && path === webhookEndpoint) {
      const update = await event.request.json();
      event.waitUntil(processUpdate(update));
      return new Response("Ok");
    } else if (method === "GET" && path === "/configure-webhook") {
      const url = `https://api.telegram.org/bot${telegramAuthToken}/setWebhook?url=${workerUrl}${webhookEndpoint}`;
      const response = await fetch(url);

      if (response.ok) {
        return new Response("Webhook set successfully", { status: 200 });
      } else {
        throw new Error(`Failed to set webhook: ${response.status}`);
      }
    } else {
      return new Response("Not found", { status: 404 });
    }
  } catch (error) {
    return new Response(`Error: ${error.message}`, { status: 500 });
  }
}


async function generateBaiduTranslateSignature(text, timestamp) {
  try {
    // Simulate an asynchronous operation, replace this with the actual logic
    const asyncResult = await performAsyncOperations(text);

    // Assume this result is used in generating the signature
    const signature = md5(`${baiduTranslateAppId}${asyncResult}${timestamp}${baiduTranslateKey}`);

    return signature;
  } catch (error) {
    console.error(`Error generating Baidu Translate signature: ${error.message}`);
    throw error;
  }
}

async function performAsyncOperations(text) {
  // Simulate an asynchronous operation, replace this with the actual logic
  return new Promise((resolve) => {
    // Simulate an asynchronous operation that takes some time
    setTimeout(() => {
      const asyncResult = text; // Replace with the actual logic to fetch data or perform operations
      resolve(asyncResult);
    }, 1000); // Simulate a delay of 1000 milliseconds
  });
}

async function processUpdate(update) {
  try {
    const chatId = update.message.chat.id;
    const userText = update.message.text;

    const sendMessage = async (message) => {
      const url = `https://api.telegram.org/bot${telegramAuthToken}/sendMessage?chat_id=${chatId}&text=${encodeURIComponent(message)}`;
      await fetch(url);
    };

    await sendMessage('Translation process started.');

    const currentTimestamp = Date.now().toString();
    await sendMessage(`Current timestamp: ${currentTimestamp}`);

    const sign = await generateBaiduTranslateSignature(userText, currentTimestamp);
    await sendMessage('Generated Baidu Translate signature.');

    const params = new URLSearchParams({
      q: userText,
      from: 'en',
      to: 'zh',
      appid: baiduTranslateAppId,
      salt: currentTimestamp,
      sign: sign,
    });

    const translateUrl = `${baiduTranslateApiUrl}?${params.toString()}`;
    await sendMessage(`Built Baidu Translate API URL: ${translateUrl}`);

    const apiCheckResponse = await fetch(translateUrl);

    if (!apiCheckResponse) {
      const debugInfo = 'Translation API check failed: Response is null or undefined';
      await sendMessage(`Translation process completed with failed API check: ${JSON.stringify(debugInfo)}`);
      return;
    }

    if (!apiCheckResponse.ok) {
      const response = await apiCheckResponse.json();
      const debugInfo = {
        translationApiUrl: translateUrl,
        translationApiResponse: response,
        translationApiStatusCode: apiCheckResponse.status,
      };

      await sendMessage(`Translation API check failed: ${JSON.stringify(debugInfo)}`);
      return;
    }

    const response = await apiCheckResponse.json();
    let translationResult;

    if (response.trans_result && response.trans_result.length > 0) {
      translationResult = response.trans_result[0].dst;

      if (typeof translationResult === 'undefined') {
        const debugInfo = 'Translation result is undefined';
        await sendMessage(`Translation process completed with undefined result: ${JSON.stringify(debugInfo)}`);
        return;
      }
    } else {
      const debugInfo = 'Translation API response does not contain expected data';
      await sendMessage(`Translation process completed with unexpected response: ${JSON.stringify(debugInfo)}`);
      return;
    }

    await sendMessage(`Translation result: ${translationResult}`);
    const responseText = `You said: ${userText}. Translated to Chinese: ${translationResult}`;
    await sendMessage(responseText);

    await sendMessage('Translation process completed successfully.');
  } catch (error) {
    console.error(`Error processing update: ${error.message}`);
  }
}



 
async function md5(value) {
  // Convert the value to a Uint8Array
  const encoder = new TextEncoder();
  const data = encoder.encode(value);

  // Calculate the MD5 hash
  const hashBuffer = await crypto.subtle.digest('MD5', data);

  // Convert the hash buffer to a hex string
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');

  return hashHex;
}

async function translateText(text, fromLang, toLang) {
  const sign = await md5(text + Date.now().toString());
  return { translationResult: sign, debugInfo: null };
}

worker部署后,需要在worker的url后,手动调用/configure-webhook.

image-1703417190941

删除调试信息后的效果

image-1703418268579

web-hook 参考 web-hook项目

原创文章,转载请附上出处。