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

Navigating Parent Menus While Submenus are Expanded in React Using Material-UI

My React application includes a dynamic menu component created with Material-UI (@mui) that supports nested menus and submenus. I'm aiming to achieve a specific behavior where users can access other menus (such as parent menus) while keeping a submenu ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

Vue JS - Unable to locate module (datepicker)

Today marks my first time delving into the world of vue.js, and as expected, I've encountered an error that has me stumped. I recently incorporated the v-md-date-range-picker module into my project: (. The setup instructions provided me with the f ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

What is the best approach in VueJS to implement a skeleton loader and an empty page condition for my orders page simultaneously?

I have implemented a skeleton loader to display while the data is loading. However, I want to also show an empty order page if there is no data or orders coming in. I am trying to figure out the conditions for both scenarios - displaying the loader and t ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Creating a spy object in Jasmine for the forEach method of router.events

I have been attempting to create a test case for a component in an application and am having trouble with the constructor. Here is how it looks: constructor(private router: Router, public dialog: MatDialog, private tlsApiServi ...

What is the method for modifying the chosen color using a select option tag instead of a list?

element, I have a Vue component that features images which change color upon clicking a list item associated with that color. <div class="product__machine-info__colors"> <ul> <li v-for="(color, index) in machine.content[0] ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

Functions have been successfully deployed, but they are not appearing on the Azure Portal

I am experiencing difficulties deploying basic Typescript functions to Azure. Despite a successful deployment using VS code and confirmation in the Output window, I cannot see any functions listed in the Azure Portal under the Function App: https://i.stac ...

Exploring data visualization and time zones with highcharts on a React platform

I am working on a chart component in React that is populated with data from an API. The array of objects I receive contains rows structured like this: Rows: [ { EffectiveTime: "06-Nov-2020 00:00:00", FieldName: "GEN_EXP", Re ...

Only the initial element within the specified class is targeted by JQuery

Currently, I am utilizing Kendo UI to refresh multiple charts by class without having to access each one individually. Here is the code snippet I am using: $(".k-chart").data("kendoChart").refresh(); The issue I am encountering is that only the first cha ...

Editing rows directly within the ng table interface

Hey there, I'm currently working on implementing inline row editing using ng table After clicking the edit icon and changing values, I encounter an error upon clicking the save icon: TypeError: Cannot read property 'untrack' of undefined ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: Below is the code snippet: import React, { useState, Fragment } from "react"; import Sidebar from "../../User/Sid ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Learn how to smooth out a path in d3.js before removing it during the exit transition

Description: My interactive multiple line chart allows users to filter which lines are displayed, resulting in lines entering and exiting dynamically. Desired effect: I aim to smoothly transition a line to align perfectly with the x-axis before it disappe ...

Having difficulty retrieving data despite providing the correct URL

I am encountering an issue with a fetch function designed to retrieve a JSON web token. Despite verifying the correctness of the URL, the function is not functioning as expected. Below is the front-end function: const handleSubmit = async (e) => { ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...