Telegram Logger bot

Sharing guidance & code for setting up a Telegram logger bot. It logs all data entered to the bot into a Google Spreadsheet.


Bot in action

Steps

  1. Create Telegram bot using botfather.
  2. Set up a Spreadsheet for logging data.
  3. Set up Google Apps Script. Copy code below.
  4. Deploy as web app. Set access to “Anyone, even anonymous”
  5. Initialise bot token, spreadsheet id & web app url values in code
  6. Set web hook by running the setWebhook() function.

Notes

  • Each time you make changes to the code, make sure your deploy as web app again (and also have the version number changed when you do so).
  • If you change the name of your sheet, make sure to have it also reflected in your code. Sheet1 is the default value of sheet in a new spreadsheet.

Code

// initialise these values
var ssID = "1J-rID8K6DNt2jeMZ7DWOH5YA7baYKTiWl1pJ3iE"; //change this to id of sheet
var token = "5672193:AAEhKCprHAOc9XfQ4HKilPyU"; //insert your bot token here
var webAppUrl = "https://script.google.com/macros/s/AKfycbzSnIgGodPMOnqE8Az/exec";//change this url once you set up the webhookvar url = "https://api.telegram.org/bot" + token;function doPost (e){

var contents = JSON.parse(e.postData.contents);
var text = contents.message.text;
var id = contents.message.from.id;
var name = contents.message.from.first_name + " " + contents.message.from.last_name;
var first_name = contents.message.from.first_name;var ss = SpreadsheetApp.openById(ssID);
ss.getSheetByName('Sheet1').appendRow([new Date(),id, first_name,text]);
sendText(id, "Added to sheet");

}

function sendText(id, text) {
var response = UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + id + "&text=" + text);
Logger.log(response.getContentText());
}// run this function one time for setting web hook
function setWebhook() {
var response = UrlFetchApp.fetch(url + "/setWebhook?url=" + webAppUrl);
Logger.log(response.getContentText());
}

Improvements that can be made to code

  • Create spreadsheet through code itself.
  • Have key values set as project properties & masked.

Screengrabs


Create Telegram bot using botfather

Deploy as web app

Select access as “Anyone, even anonymous”

Initialise project variables

set webhook by running the function

Bot in action