# Telegram bot webhook integration http-functions.js

**URL:** <https://forum.wixstudio.com/t/telegram-bot-webhook-integration-http-functions-js/70264>\
**Category:** Ask the community\
**Tags:** http-functions, code, wix, question\
**Created:** [April 11, 2025, 7:45pm UTC](https://forum.wixstudio.com/t/telegram-bot-webhook-integration-http-functions-js/70264 "2025-04-11T19:45:36Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tustramites-consulta](https://sea1.discourse-cdn.com/wix/user_avatar/forum.wixstudio.com/tustramites-consulta/32/84650_2.png) [@tustramites-consulta](https://forum.wixstudio.com/u/tustramites-consulta)\
**Post date:** [April 11, 2025, 7:45pm UTC](https://forum.wixstudio.com/t/telegram-bot-webhook-integration-http-functions-js/70264/1 "2025-04-11T19:45:36Z")

</div>

**Question:**  
using http-functions.js with http post function webhook replies allways Error 500 to telegram. Anybody knows if it is needed to configure something in wix environment?

**Product:**  
Wix Editor

**What are you trying to achieve:**  
I am trying to configure a telegram bot via Telegram API, get the bot updates from telegram using a webhook via HTTP post received from telegram platform.

I have implemented the http-functions.js to send the contents to the bot. I could receive the telegram request, but wix back end send an answer with error 500. this scenario stuck the telegram updates in a loop of request repeat and the comands queue increse and not **new messages** are sent to the webhook from telegram update. however the telegram retry calls are processed by the webhook in wix backend.

**What have you already tried:**

this is a test function for the webhook to validate the backend response.  
No error is printed on console message, but Response (“OK”, status: 200) is not received by telegram. i have tested with telegram and with postman and the error 500 answer is instantaneous.  
I have programmed the code with try/catch protection to avoid uncotrolled exceptions that could produce error 500.

**This is the minimum webhook to test**

```javascript
export async function post_telegramWebhook(request) {
  try {
    console.log("Solicitud recibida:", request);
    return new Response("OK", { status: 200 });
  } catch (error) {
    console.log("Error en el webhook:", error);
    return new Response("Error interno del servidor", { status: 500 });
  }
}

```

**this is the postman result**

 ![The image is a screenshot of a POST request in a social media monitoring tool, showing an error message. (Captioned by AI)](https://us1.discourse-cdn.com/wix/original/3X/0/f/0f42e14f2bfa8b33138e824f53aa6bad73236a20.png)

**this is the real webhook**

```javascript
xport function post_telegramWebhook(request) {

  const tokenEncoded = request.path[0];
  let tokenDecoded;
  try{
     tokenDecoded = decodeURIComponent(tokenEncoded);
  }
  catch (e){
    console.log ("error ----------------------",e);
  }

console.log ("--------------request",request);

  let earlyResponse= new Response("OK", { status: 200 });
console.log ("--------------earlyResponse",earlyResponse);
  

  return request.body.json()
    .then(async (body) => {
      try {
        const message = body.message || {};
        const chatId = message.chat?.id;
        const text = message.text;
        const username = message.from?.username || "desconocido";

        

        const ahora = Math.floor(Date.now() / 1000);
         const antiguedad = ahora - message.date;

        if (antiguedad > 10) {
          console.log(`⚠️ Comando viejo ignorado (${antiguedad}s): ${text}`);
          return new Response("OK", { status: 200 });
        }

        if (!chatId || !text) {
          console.log("⚠️ --------------Mensaje incompleto recibido. Ignorado.", JSON.stringify(body));

          try{
          await agregarAlLogTelegram(`--------------- Mensaje sin texto recibido del chat ${chatId || "desconocido"}\n`);
        
           } catch (logError) {
              console.log("❌ Error al guardar log del fallo:", logError);
          }
          return new Response("OK", { status: 200 });
        }

        const resultado = await obtenerBotonesPorComando(text, tokenDecoded);
        console.log("---------botones por comando:", resultado);

        const payload = resultado.success
          ? {
              chat_id: chatId,
              text: resultado.mensaje,
              reply_markup: {
                inline_keyboard: resultado.botones
              }
            }
          : {
              chat_id: chatId,
              text: "-------------------Error No se encontraron contenidos para este comando."
            };

        const responseSendMessage = await fetch(`https://api.telegram.org/bot${tokenDecoded}/sendMessage`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        });

        let dataSendMessage;
        try {
          dataSendMessage = await responseSendMessage.json();
        } catch (e) {
          console.log("❌ Error procesando respuesta de Telegram:", e);
          dataSendMessage = { error: "No se pudo parsear" };
        }
        console.log("📨 Respuesta de Telegram:", dataSendMessage);

          const logEntry = `
                      [${new Date().toISOString()}]
                      De: @${username} (Chat ID: ${chatId})
                      Mensaje: ${text}
                      Respuesta: ${payload.text}
                      Estado: ${resultado.success ? " OK" : " Falla"}
                      -------------------------------`;

            console.log("---------------logEntry: ",logEntry);

          try{
          await agregarAlLogTelegram(logEntry);
           } catch (logError) {
            console.log("❌ Error al guardar log del fallo:", logError);
          }

       const contenido = "OK";
        const respuesta = new Response(contenido, { status: 200 });

          console.log("Contenido enviado:", contenido); // 🔍 esto sí se ve
        return respuesta;

      } catch (error) {
        console.log(" Error en el webhook:", error);

          try {
              await agregarAlLogTelegram(`[${new Date().toISOString()}] Error: ${error.message}\n`);
          } catch (logError) {
              console.log("❌ Error al guardar log del fallo:", logError);
          }
        return new Response("OK", { status: 200 });
      }
    })
    .catch(async (err) => {
      console.log(" Error al parsear JSON:", err);

    try {
        await agregarAlLogTelegram(`[${new Date().toISOString()}] Error al parsear JSON: ${err.message}\n`);
        } catch (logError) {
        console.log("❌ Error al guardar log del fallo:", logError);
        }

     return new Response("OK", { status: 200 });
    });
}

```

**this is the telegram bot receiving the repeated webhook content originated by telegram retries**  
I have put a filter to ignore the old messages retry (more the 10 sec are ignored so telegram bot receive only 3 messages.

 ![image](https://us1.discourse-cdn.com/wix/original/3X/a/6/a68112633ad454a2877a7676125f5af028744791.jpeg)
