M
M
Medoed2019-12-03 02:01:52
Bots
Medoed, 2019-12-03 02:01:52

TypeError: Cannot read property 'postData' of undefined object. (line 3, file Code)?

I created a bot according to the instructions, but an error is thrown TypeError: Unable to read the "postData" property of the undefined object. (line 3, file Code), help me figure it out.

function doPost(e) {
  // получаем сигнал от бота
  var update = JSON.parse(e.postData.contents);


  // проверяем тип полученного, нам нужен только тип "сообщение"
  if (update.hasOwnProperty('message')) {
    var msg = update.message;
    var chatId = msg.chat.id;

    // проверяем, является ли сообщение командой к боту
    if (msg.hasOwnProperty('entities') && msg.entities[0].type == 'bot_command') {

      // проверяем на название команды - /lastpost
      if (msg.text == '/lastpost') {

        // если все проверки пройдены - запускаем код, который ниже, 
        // открываем оглавление нашего канала 
        var sheet = SpreadsheetApp.openById('1u0aRlwb0rQHbjE9avbgCqIJSQ3EvPfTxT-h54jTQh8I').getSheets()[0]

        // достает последний пост
        var lastpost = sheet.getRange(sheet.getLastRow(), 1, 1, 3).getValues()[0]
        var message = ' <strong>' + lastpost[1] + '</strong> \n' + lastpost[2]

        //формируем с ним сообщение
        var payload = {
          'method': 'sendMessage',
          'chat_id': String(chatId),
          'text': message,
          'parse_mode': 'HTML'
        }
        var data = {
          "method": "post",
          "payload": payload
        }

        // и отправляем его боту (замените API на свой)
        var API_TOKEN = '1012129526:AAFUTGqj5FssGbqACYOtXQo6ErPzWQcPn##'
        UrlFetchApp.fetch('https://api.telegram.org/bot' + API_TOKEN + '/', data);
      }
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2019-12-05
@oshliaer

A doPost(e)request from an external source is only passed to when your service has been published and a POST request has been sent.
To test this part, you need to send requests to your endpoint, for example, with this https://www.getpostman.com/
The error you are seeing can be reproduced in only one way - by calling it doPostfrom the code editor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question