1
1
12d12122021-11-01 15:28:54
Google Apps Script
12d1212, 2021-11-01 15:28:54

How to get the necessary data from UrlFetchApp or JSON.parse?

According to the logs, the data comes out in this format, you need to get

message_id=53204.0
{result={date=1.635769484E9, message_id=53204.0, from={first_name=IPhoшка [Инфобот], username=infoip4_bot, is_bot=true, id=2.09014609loE9}, , type=supergroup}}, ok=true}


I had an idea, but it didn't work
var takeid = JSON.parse(UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data));
  var idString = takeid.toString();
  var start = 0;
  var searching = "message_id=" + start.toString() + ".0";
  while (idString.indexOf(searching!=-1)){
     start++
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Stoyanov, 2021-11-01
@stomaks

You are moving in the right direction, but there are a few caveats.
First , the request url (in your case: ) does not contain a function to run. It should be like this:'https://api.telegram.org/bot' + token + '/'

'https://api.telegram.org/bot' + token + '/getUpdates'

or or
'https://api.telegram.org/bot' + token + '/getMe'
'https://api.telegram.org/bot' + token + '/sendMessage'

etc.
The second note datais that the second parameter for a fetch(url, data)class function UrlFetchAppmust be an object.
And it is desirable that the request method in this object be post.
Ideally water like this:
{
  "method": `POST`,
  "contentType": `application/json`,
  "muteHttpExceptions": true,
  "payload": JSON.stringify(data)
}

At the same time payload, we indicate if you want to send something to the telegram (depends on the selected function in the request url).
Third , after the method has fetch(url, data)returned a result response, you need to extract data from it by the method response .getContentText(). And ash then parse through JSON.parse.
The complete code looks like this:
/**
   * Простой метод проверки токена авторизации вашего бота. Не требует параметров. Возвращает основную информацию о боте в виде объекта User.
   * 
   * @return {Object.User}
   */
  function getMe() {
    const response = UrlFetchApp
      .fetch(
        `https://api.telegram.org/bot${TOKEN}/getMe`,
        {
          "method": `POST`,
          "contentType": `application/json`,
          "muteHttpExceptions": true
        }
      );

    let result = response
      .getContentText();

    result = JSON
      .parse(result);

    if (!result.ok)
      throw new Error(result.description);

    return result;
  }

Just don't forget to replace the word TOKEN with the variable name with your token.
To send a message to the bot, use:
/**
   * Используйте этот метод для отправки текстовых сообщений. В случае успеха отправленное сообщение возвращается.
   * 
   * @param {String|Number} chatId Уникальный идентификатор целевого чата или имя пользователя целевого канала (в формате @channelusername)
   * @param {String} text Текст отправляемого сообщения, 1-4096 знаков после синтаксического анализа сущностей.
   * @param {Object} options
   * 
   * @return {Object.Message}
   */
  function sendMessage(chatId, text, options) {
    if (!arguments.length)
      throw new TypeError(`Параметры () не соответствуют сигнатуре метода TelegramBot.sendMessage.`);

    const data = {};

    if (!([`string`, `number`].includes(typeof chatId) && String(chatId).trim().length))
      throw new TypeError(`Параметры (${typeof chatId}) не соответствуют сигнатуре метода TelegramBot.sendMessage.`);

    data.chat_id = String(chatId).trim();

    if (!([`string`, `number`].includes(typeof text) && String(text).trim().length))
      throw new TypeError(`Параметры (${typeof chatId}, ${typeof text}) не соответствуют сигнатуре метода TelegramBot.sendMessage.`);

    data.text = String(text).trim();

    if (options) {
      if (typeof options !== `object`)
        throw new TypeError(`Параметры (${typeof chatId}, ${typeof text}, ${typeof options}) не соответствуют сигнатуре метода TelegramBot.sendMessage.`);

      if ((item => typeof item === `string` && item.trim().length)(options.parse_mode))
        data.parse_mode = options.parse_mode;

      if (typeof options.entities === `object`)
        data.entities = options.entities;

      if (typeof options.disable_web_page_preview === `boolean`)
        data.disable_web_page_preview = options.disable_web_page_preview;

      if (typeof options.disable_notification === `boolean`)
        data.disable_notification = options.disable_notification;

      if ((item => typeof item === `number` && Number.isInteger(item) && item > 0)(options.reply_to_message_id))
        data.reply_to_message_id = options.reply_to_message_id;

      if (typeof options.allow_sending_without_reply === `boolean`)
        data.allow_sending_without_reply = options.allow_sending_without_reply;

      if (typeof options.reply_markup === `object`)
        data.reply_markup = options.reply_markup;
    }

    const response = UrlFetchApp
      .fetch(
        `https://api.telegram.org/bot${TOKEN}/sendMessage`,
        {
          "method": `POST`,
          "contentType": `application/json`,
          "muteHttpExceptions": true,
          "payload": JSON.stringify(data)
        }
      );

    let result = response
      .getContentText();

    result = JSON
      .parse(result);

    if (!result.ok)
      throw new Error(result.description);

    return result;
  }

And finally, if you know how to use the gas libraries, here is mine for telegram bots:
TelegramApi (1d78ytTohb5IBskJadNg1hwu-LRyqYONmnQQWbkVUlmX3Ft2Q6AEOgW9m)
(it is still a little raw, but you can use it, there is no documentation yet, sorry, open the code and read the description of the methods)
---
Maxim Stoyanov ( stomaks, developer of Google Apps Script .
g-apps-script.com
stomaks.me

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question