I am fairly new to javascript and telegram bot. I have managed to link my telegram bot to google sheets and want to save the name of the senders sending messages to my bot in google sheets. The function works great if the bot is not part of a group chat, but if it is, it gives a negative value for the user ID and an undefined message for the username.
My code is as follows (i removed the actual info for the sheet and bot):
var token = ""; //Token of Telegram Bot
var telegramUrl = "https://api.telegram.org/bot" + token;
//connects bot and telegram chat
var webAppUrl = "";
var ssId = "";
function getMe() //gets the bot info
{
var url = telegramUrl + "/getme";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() //links url of project
{
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) //sends confirmation text
{
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doPost(e) //
{
var data = JSON.parse(e.postData.contents);
var str = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new
Date(),id,name,str]);
}
Use data.message.from.
Besides, last_name of user may be blank that the property would be undefined in the event object. Which you have to handle.
var data = JSON.parse(e.postData.contents);
var str = data.message.text;
var id = data.message.from.id;
var name = data.message.from.first_name + (data.message.from.last_name ? " " + data.message.from.last_name : "");