Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Google Sheet and the Telegram bot setup.) However, for some reason, when I input data into the Telegram bot, nothing gets saved in the Google Sheet.

Can anyone help me with this issue?

var token="<<BOT-TOKEN>>";
var url="https://api.telegram.org/bot" + token ;
var webAppUrl="https://script.google.com/macros/s/<<secret>>/exec";
var spId='<<secret>>';
function getme() {
  var response=UrlFetchApp.fetch(url + "/getme");
  Logger.log(response.getContentText());
}
function getupdates() {
  var response=UrlFetchApp.fetch(url + "/getupdates");
  Logger.log(response.getContentText());
} 

function setwebhook() {
  var response=UrlFetchApp.fetch(url + "/setWebhook?url=" + webAppUrl);
  Logger.log(response.getContentText());
}

function setwebhook() {
  var response=UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + id + "&text" + text);
  Logger.log(response.getContentText());
}

function doGet(m){ 
  return HtmlService.createHtmlOutput("Hello" + JSON.stringify(m));
}
function doPost(m){
    var contents = JSON.parse(m.PostData.contents);
GmailApp.sendEmail(Session.getEffectiveUser().getEmail(),"Telegram Bot Update",JSON.stringify(contents,null,4));
  var text = contents.message.text;
  var id = contents.message.from.id;
  var name = contents.message.from.first_name + ' ' + contents.message.from.last_name;
  sendText(id, "HI" + name);
SpreadsheetApp.openById(spId).appendRow([new Date(),id,text,contents,name]);
  SpreadsheetApp.openById(spId).appendRow([1,2,3,4,5]);
}
/*
{  
    "parameter": {},
    "contextPath": "",
    "contentLength": 310,
    "queryString": "",
    "parameters": {},
    "postData": {
        "type": "application/json",
        "length": 310,
        "contents": "{\"update_id\":*,\n\"message\":{\"message_id\":12,\"from\":{\"id\":*,\"is_bot\":false,\"first_name\":\"*\\*\",\"username\":\"*\",\"language_code\":\"fa\"},\"chat\":{\"id\":*,\"first_name\":\"*\\*\",\"username\":\"*\",\"type\":\"private\"},\"date\":1558331571,\"text\":\"salaaaaaaaaaaaaam\"}}",
        "name": "postData"

}
*/

I expected this code to save everything typed by the Telegram bot and display the data in Google Sheet rows. Unfortunately, it's not working as intended and doesn't show anything in the sheet cells.

Answer №1

From my experience, utilizing App Script to interact with a spreadsheet may not be the most flexible option, especially when considering scalability and adding more features to your application.

I recently completed a project designed to assist educators in managing attendance registers through Telegram, automatically updating a spreadsheet in the process. Instead of using App Script, I relied on the official Google Spreadsheet API, which offers excellent documentation and greater flexibility compared to App Script.

You can access the code for this project on GitHub. Within the project, functions tailored for the spreadsheet can be found in the modules folder and the spreadSheetController. While the project may seem extensive, I am happy to provide guidance on how it can align with your specific requirements.

Key Prerequisites:

  1. Utilize a library for interfacing with the Telegram API rather than manually handling POST and GET requests. Options include node-telegram-bot-api or other preferred libraries

  2. Authenticate access to your Google spreadsheet using the respective API. Follow the comprehensive instructions in the quick start guide provided by Google to enable programmable functionality. Instructions are tailored for Node.js implementation.

Upon fulfilling these two prerequisites, the aforementioned project can serve as a valuable resource. Should you require further clarification, feel free to reach out. While I refrain from sharing all the project code here due to its volume, the attendance automation solution should offer insights independently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery encountering error when uploading multiple files upon loading

I'm having trouble with this jQuery plugin ( ). Whenever I try to set the events on it, I keep getting an error message saying "Function expected". Can someone provide assistance? Everything seems to be working fine except for binding to the events. ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

The error message received was: "npm encountered an error with code ENOENT while trying to

About a week ago, I globally installed a local package using the command npm i -g path. Everything was working fine until today when I tried to use npm i -g path again and encountered the following error: npm ERR! code ENOENT npm ERR! syscall rename npm ER ...

Trouble with virtual canvas when attempting to put image data

I am new to the virtual canvas concept and I'm having trouble with the code below. Can anyone help me figure out why it's not working? <script type="text/javascript"> $(document).ready(function () { var c1 = docu ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

Typescript: The property isComposing is not found on Event type

While working on a React app with Typescript, I encountered a Typescript error both during compile time and in the editor: TS2339: Property isComposing does not exist on type Event This issue arises when handling an OnChange event in an HTML Input element ...

Browse the string on the web browser

Is there a way for me to continuously read and capture a string as it is being written in the browser, retrieving its value every 5 seconds? I need to be able to monitor the changing value while it is being input. In PHP, I have the following code snippet ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

Exploring alternative methods of iterating over the values in a key-value pair within an AngularJS framework

My key-value pair consists of a long list of file names stored in the variable $ctrl.displayData- 143:"/this/is/a/very/long/fil22↵/this/is/a/very/long/file/path.php↵anotherone.php↵newfilel123.php" When I use ng-repeat to display these file names, t ...

The system encountered an issue: "Property 'add' is not defined and cannot be read."

I'm facing a dilemma with my exercise. Despite the numerous inquiries regarding this problem, I haven't been able to find a solution. I am hopeful that you can provide some assistance! Below is the code snippet in question: let myDivs = docume ...

How can I transfer a JavaScript value to PHP for storage in an SQL database?

<script> var latitudeVal = document.getElementById("latitude"); var longitudeVal = document.getElementById("longitude"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); ...

Preventing file overwriting using fs.writefile method

Encountering an issue where the data being saved from a chat room built with socket.io in nodejs is constantly overwritten upon submission of a message. The desired outcome is to append both the username and message to the JSON file as an object, rather th ...

Angular-Slickgrid: Some filters may not display on the header row

After thorough investigation and experimentation, I was able to identify both the issue and a suitable solution: The problem stemmed from our dataset's usage of numeric IDs (e.g. 1,2,3,...). Within the code, there was an error where the grid misinter ...

Utilizing PHP to send arrays through AJAX and JSON

-I am facing a challenge with an array in my PHP file that contains nested arrays. I am trying to pass an integer variable (and may have to handle something different later on). -My objective is to make the PHP file return an array based on the incoming v ...

Utilize JavaScript to enclose every piece of text within single quotes in a span element

I have a tiny snippet of text: "some sample text" just a little more "additional text" I am trying to figure out how to wrap all the content between quotation marks in a span container, similar to what hilight.js does. I've been struggling to make it ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

Having trouble integrating a custom dialog with DirtyForms plugin

I have successfully implemented DirtyForms, a plugin that triggers a confirmation dialog when a user tries to navigate away from a page. The base functionality of the plugin is working as intended. Now, I am trying to integrate jQuery UI's Dialog for ...

Troubles with concealing dropdown menu when hovering

I have noticed that this issue has been raised before, but none of the solutions provided seem to fix my problem specifically. The submenu in my menu is not functioning as intended. It should be displayed when hovered over and hidden when not being hovere ...

React.js implementation of a checkout feature using in-game currency

I am currently working on a game that involves in-game currency, but I'm facing some confusion. It seems like I might be overcomplicating things. In my store, users can purchase items using the gold (max variable) they have. The shopping cart function ...