0

I have this url. Which basically sends a message in telegram with a bot when you paste it in the browser.

https://api.telegram.org/botsomeKEY/sendMessage?chat_id=-someID&text= TEST

My problem is that it is not letting me deploy this function and is giving me an error of "Function failed on loading user code. This is likely due to a bug in the user code".

export const sendMessage = functions.pubsub
.schedule("every 1 minutes") // run everyday "0 0 * * *" or every 1 minutes
.timeZone("America/Chicago")
.onRun((context) => {

  const xhr = new XMLHttpRequest();
  xhr.open("POST", httpAddress, true);
  xhr.setRequestHeader("Content-Type", "application/json");
  return xhr.send(JSON.stringify({
    text: "TEST",
  }));

});

1 Answer 1

1

If you look into the logged messages above that error message, you should see what is causing your function to crash. In this case, it is likely your attempted use of XMLHttpRequest() which is not a native node.js API, but a browser API. While you could import a library such as xhr to bring this to node, you are better off making use of a Promise-based networking API because the Firebase Functions SDK is also Promise-based. Examples of suitable libraries include axios, gaxios and node-fetch.

node-fetch and gaxios are used internally by the Firebase SDK, so these are good choices.

import fetch from "node-fetch";

export const sendMessage = functions.pubsub
.schedule("every 1 minutes") // run everyday "0 0 * * *" or every 1 minutes
.timeZone("America/Chicago")
.onRun(async (context) => {
  const response = await fetch(httpAddress, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      text: "TEST"
    })
  });

  if (response.status !== 200) {
    // potential error (make sure to look out for other codes like 201-204, 301, 302)
    console.error(`Server responded with unexpected status code ${response.status}: ${await response.text()}`);
    return;
  }

  // Get response body and parse it as JSON
  const responseBody = await response.json();

  // do something with responseBody
  // see https://core.telegram.org/bots/api#message
  
  console.log("Sent bot message successfully!");
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you! I've been stuck on this for a while too. Also were you the one who sent the message through the bot? xD
yeah :D You've gotta be careful with stuff like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.