how to communicate telegram bot with google sheet - google-apps-script

i have problem for communication with telegram bot and google Spreadsheet , yesterday i work with that , and work very good, but today it can't work.
i create another google account and and another Bot, but not work.
this is my google script :
var token="123197063:AAH04kulz7tRqPz3vbDcgYdVje18WH2Pv-4";
var telegramUrl= "https://api.telegram.org/bot"+token;
var webAppUrl = "https://script.google.com/macros/s/AKfycbwqvJWsWcm_5_Y1vhYEkSN2G9dxiDBzQIvYvbte-3_HfGcGFN3a/exec";
function getMe(){
var url = telegramUrl+"/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl+"/setWebhook?url="+webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e){
return HtmlService.createHtmlOutput("hi this is my first project");
}
function dePost(e){
GmailApp.sendEmail(Session.getEffectiveUser().getEmail(), "message from bot", JSON.stringify(e, null, 4));
}
in this code when i write anything in telegram bot , google sheet must send an email to me, but it can't work today.
and this is my Bot address: #irmec_bot
do you have idea that it not work?
please help to me
thanks

You may follow the instructions in this video tutorial: How to connect your Telegram Bot to a Google Spreadsheet (Apps Script) Script in Description.
//
// FILL IN THE GLOBAL VARIABLES token, webAppUrl and ssId
//
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILL IN YOUR GOOGLE WEB APP ADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e) {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name + ", thank you for your comment " + text;
sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var comment = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,comment,answer]);
}
}
Here's an additional reference which might also help: Telegram Bot with Apps Script

If this is a new script for the same bot, you should set the web hook to the new link.
1) After you publish as app, copy the given a url (some thing like > https://script.google.com/macros/s/... )
2) Replace the url on line 3 var webAppUrl = INSERT_URL_HERE
3) Save the script
4) Run the setWebhook() function by clicking Run > Run Function > setWebhook()
Hope this helps!

Related

Connecting telegram bot to google spreadsheet

function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
var obj = JSON.parse(response)
Logger.log(obj);
}
function getUpdates() {
var url = telegramUrl + "/getUpdates";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendMessage(chat_id, text){
var url = telegramUrl + "/sendMessage?chat_id=" + chat_id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
}
function doPost(e){
var contents = JSON.parse(e.postData.contents)
var chat_id = contents.message.from.id;
sendMessage(chat_id, "Hi, Message Recieved")
}
The problem is the doPost function. Google script keeps saying postData is a type error. Therefore, my sendMessage function does not work too.
However, I don't know what is wrong with my codes.

Saving Telegram Bot messages into google spreadsheet

I'm a beginner, so I'll try my best to explain what happends in the code and what I want to do. I've created a telegram bot and I want to save all the message log into google spreadsheets. I'm using Google App Scripts for this. The problem is that when I'm using the following code, only the messages that I write are saved into google sheets, it happends in the "doPost" function. What I want to do is to save also the messages I receive from the bot. I tried adding the same code the I used in "doPost" and worked into the function "sendText" but I'm still unable to save the messages that the bot sends. How can I do this? here's my code:
var token = "..."; // 1. FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "..."; // 2. FILL IN YOUR GOOGLE WEB APP ADDRESS
var ssId = "..."; // 3. FILL IN THE ID OF YOUR SPREADSHEET
var adminID = "..."; // 4. Fill in your own Telegram ID for debugging
// connect to bot
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
// make the bot to send a message
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + encodeURIComponent(text);
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
try {
// this is where telegram works
var data = JSON.parse(response.getContentText());
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name;
// sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var newText = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,newText,answer]);
sendText(id,"your text '" + newText + "' is now added to the sheet '" + sheetName + "'");
}
} catch(e) {
sendText(adminID, JSON.stringify(e,null,4));
}
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
// send a message from me to the bot
function doPost(e) {
try {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name;
// sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var newText = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,newText,answer]);
sendText(id,"your text '" + newText + "' is now added to the sheet '" + sheetName + "'");
}
} catch(e) {
sendText(adminID, JSON.stringify(e,null,4));
}
}
Thank you.

Why some of emails which sent by Google Apps Script with Form-submission trigger send twice?

I've noticed my sent email from Google App Script with Form-Submission Triggered and found that 3 in almost 300 of my emails are sent twice!
I have no idea about this and here is what i wrote.
function emailAsExcel(spreadsheetId,subject,message,fileName,link) {
var ss = SpreadsheetApp.openById(spreadsheetId);
var fileId = ss.getId();
var data = ss.getActiveSheet().getRange('A2:D2').getValues();
var url = 'https://docs.google.com/spreadsheets/d/'+fileId+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
})
var blobs = response.getBlob().setName(fileName+'.xlsx');
var picblobs = DriveApp.getFileById(getIdFromUrl(link)).getBlob().setName(fileName + '.jpg');
var sender = "xxx#gmail.com"+","+ "yyy#gmail.com";
var email = sender;
MailApp.sendEmail(email,subject,message,{attachments: [blobs, picblobs]});
}
function genFile(){
var ss = SpreadsheetApp.openById('xxxxxxxxxxxx');
var sheet = ss.getSheetByName('yyyyy');
var lastRow = sheet.getRange(1,9,sheet.getLastRow()).getValues().filter(String).length;
Logger.log(lastRow);
var date = sheet.getRange('A'+lastRow).getValue();
var name = sheet.getRange('J'+lastRow).getValue();
var surname = sheet.getRange('K'+lastRow).getValue();
var number = sheet.getRange('E'+lastRow).getValue();
var prov = sheet.getRange('F'+lastRow).getValue();
var brand = sheet.getRange('G'+lastRow).getValue();
var link = sheet.getRange('I'+lastRow).getValue();
var subject = name+'_'+surname;
var message =
'customer fullname : '+ name +' '+surname+'\n'
+'num : '+ number + prov+'\n'
+'bra : '+ brand +'\n'
var fileName = name+ ' ' +surname;
Logger.log(link);
var destination = DriveApp.getFileById('aaaaaaaaaaaaaaaa').makeCopy().getId();
var newFile = SpreadsheetApp.openById(destination);
var newSheet = newFile.getSheetByName('bbbbbbbbb');
newSheet.getRange('A2').setValue(date);
newSheet.getRange('B2').setValue(name+' '+surname);
newSheet.getRange('C2').setValue(number);
newSheet.getRange('D2').setValue(prov);
newSheet.getRange('E2').setValue(brand);
newFile.setName(fileName);
emailAsExcel(destination,subject,message,fileName,link);
}
function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }
genFile();
}
I try to figure it out but I still do not know what happened, so I need you guys' advice.
Thank you in advance!
This likely happens when you (or another Google account that has access to this script) has created multiple triggers.
Go to https://script.google.com/home/triggers, choose your project and remove any duplicate onSubmit triggers.

how to make this template code work from sheets app

I'm trying to make this script to work on google sheets app so it sends a pdf copy to my email when I type Send in cell L6
the code work perfect on computer but not on ipads , anyway to do this from app ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
The way it worked for me by " installed Trigger "
from the script editor : Edit - current project Triggers
I added new trigger that will run the code below based on " On edit " and voila it worked , from sheets app if I typed " Send " in Cell L6 it will send a PDF copy of the active sheet to the email listed in the code.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
Create a Google Script in the very same Spreadsheet or in another one (Tools / Script editor), add the script you already have, grant the authorizations required, and trigger it with a simple form (Tools / Create a form) (trigger → Edit / Current project's triggers). The long URL to view the form can be easily opened by means of a URL shortener or something by the sort. Forms work in cell phones too and without need to sign in to your account. With this method you can even add a useless conditional password to run the script.
function createPDF(e) {
var input = e.values[1];
if (input == 'my_password'){
// your scripts to create and send the PDF goes here
}
}
It's a simplistic solution, but it works.

Connect telegram bot with google apps script

I have setup a bot on telegram bot and connected it with google spreadsheets via apps script by following this tutorial. Here is the code:
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILL IN YOUR GOOGLE WEB APP ADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e) {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name + ", thank you for your comment " + text;
sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var comment = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,comment,answer]);
}
}
Now I encountered the following issue; I use my bot to store messages from my home automation system. Therefore I send those messages from the system to telegram bot via HTTP GET request:
https://api.telegram.org/bot[BOT_API_KEY]/sendMessage?chat_id=[MY_CHANNEL_NAME]&text=[MY_MESSAGE_TEXT]
Currently these messages sent through http get request seem to be ignored by the script. Does anyoene know how I can solve this issue?
Judging from your question and comments, it seems you are struggling with sending info from your script to your bot on Telegram. Here are the steps to do that:
1.- Create a bot: on Telegram's search look for #BotFather. Click start, write /newbot, give it a name and a username. You should get a token to access the HTTP API. Save this token.
2.- Find your bot on Telegram with its username. Write something to it e.g. 'test'. This will come in handy later.
3.- Test access to the bot from your code
var token = "123456:kioASDdjicOljd_ijsdf"; // Fill this in with your token
var telegramUrl = "https://api.telegram.org/bot" + token;
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
You should get something resembling this:
{"ok":true,"result":{"id":<somenumber>,"is_bot":true,"first_name":"<name of your bot>","username":"<username of your bot>","can_join_groups":true,"can_read_all_group_messages":false,"supports_inline_queries":false}}
4.- Write the sendMessage function
function sendMessage(chat_id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + chat_id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
Known is the text you want to send e.g. 'testing bot', but chat_id is unknown. Where do we get this?
5.- Find the chat_id. Before running this function, make sure that you have at least written one message to your bot on Telegram (step 2)
function getChat_id(){
var res = UrlFetchApp.fetch(telegramUrl+"/getUpdates").getContentText();
var res = JSON.parse(res);
Logger.log(res.result[0].message.chat.id.toString());
}
6.- Run sendMessage with the chat_id you found in step 5 and the message you want to send.