0

I want to use Google App Script to let a Telegram Bot post a message in a chat. That works fine, when I use this line of Code:

var message = UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + chat_id_Testgruppe + "&text=HelloWorld");

But if I replace the "HelloWorld" with a variable like this:

var body = threads[i].getMessages().pop().getPlainBody();  // Gets the message-String from a Gmail-Thread
var message = UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + chat_id_Testgruppe + "&text=" + body);

Then I get an invalid Argument error, even if the argument, which is shown me as an illegal argument for the fetch function, works, if I copy and paste it to my browser.

R.J. Dunnill
  • 2,049
  • 3
  • 10
  • 21
  • 1
    We can't troubleshoot this without at least seeing what your other variables are. – ross Jul 23 '19 at 15:26
  • added my declaration of body, the other two variables are hardcoded Strings, and they work as they should in other contexts – blackdra_gon Jul 23 '19 at 15:55
  • What is logged if you do `Logger.log(body);`? Also have you tried using `body.toString()`? – ross Jul 23 '19 at 15:56
  • 1
    See [this more general question](https://stackoverflow.com/questions/31197659/how-we-should-send-query-to-telegram-bot-api) as well as [this one](https://stackoverflow.com/questions/12183817/google-apps-script-urlfetch-encoding-url) -- Try `encodeURIcomponent()` on `body`; also keep in mind that [there may be issues with the length of the message](https://stackoverflow.com/questions/812925/what-is-the-maximum-possible-length-of-a-query-string) – sinaraheneba Jul 23 '19 at 16:10

2 Answers2

0

The Telegram API reference specifies that getMessages() returns you a LIST of messages - that is an array. You need to access a single message (an array entry of the list) in order to obtain its content as a string.

ziganotschka
  • 25,866
  • 2
  • 16
  • 33
0

I needed to use encodeURIComponent() on my variable, that solved the problem.