Telegram Bot sendMessage not working on google apps scripts - google-apps-script

var token="yourtoken";
var url = "https://api.telegram.org/bot" + token;
var webAppUrl = "https://script.google.com/macros/s/tokenappscript/exec";
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 sendMessage(id, text) {
var response = UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + id + "&text=" + text);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Ciao" + JSON.stringify(e));
}
function doPost(e) {
var contents = JSON.parse(e.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.fist.name + " " + contents.message.from.last_name;
sendMessage(id, "Hi " + name);
}
I'll trying for now only send a message from the bot in response to my hi. But when i type hi nothing happened, the bot not responding with hi. I see my message when i type and get the log in my email.

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.

Google Workspace email sending with Google Appscript is giving error. Message blocked Your message to has been blocked

My script was working fine with normal Gmail account but is giving error with Google Workspace account.
I have read somewhere that I need to use GmailApp in place of MailApp, I have already done that. It seems that mail is sent but after that it is blocked.
I am getting the following error:
Message blocked
Your message to xxxxxxx has been blocked.
See technical details below for more information.
LEARN MORE
The script is as below:
function exportPartAsPDF(selectedRanges,shId,regNo) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheets()[shId];
var selectedRange = sheet.getRange(selectedRanges);
var pdfNameValue = sheet.getRange(regNo).getValue();
var pdfName = (pdfNameValue || "export") + ".pdf";
try {
var blob = _getAsBlob(spreadsheet.getUrl(), sheet, selectedRange);
blob.setName(pdfName);
_sendMail(blob);
} catch (e) {
console.log(e);
}
return;
}
function _getAsBlob(url, sheet, range) {
var rangeParam = "";
var sheetParam = "";
if (range) {
rangeParam =
"&r1=" +
(range.getRow() - 1) +
"&r2=" +
range.getLastRow() +
"&c1=" +
(range.getColumn() - 1) +
"&c2=" +
range.getLastColumn();
}
if (sheet) {
sheetParam = "&gid=" + sheet.getSheetId();
}
var exportUrl =
url.replace(/\/edit.*$/, "") +
"/export?exportFormat=pdf&format=pdf" +
"&size=A4" + //A3/A4/A5/B4/B5/letter/tabloid/legal/statement/executive/folio
"&portrait=true" +
'&scale=4' +
"&fitw=true" +
"&top_margin=0.5" +
"&bottom_margin=0.5" +
"&left_margin=0.5" +
"&right_margin=0.5" +
"&gridlines=false" + //true/false
"&horizontal_alignment=CENTER" + //LEFT/CENTER/RIGHT
"&vertical_alignment=TOP" + //TOP/MIDDLE/BOTTOM
"&sheetnames=false&printtitle=false" +
"&pagenum=false" +
"&gridlines=false" +
"&fzr=FALSE" +
sheetParam +
rangeParam;
Logger.log("exportUrl=" + exportUrl);
var response = UrlFetchApp.fetch(exportUrl, {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken(),
},
});
return response.getBlob();
}
function _sendMail(blob) {
var toEmail = "xxxxxx#gmail.com,xxxx#print.epsonconnect.com";
var htmlBody = "Payment Recieved";
var subject = "Reciept";
var options = {
attachments: blob,
htmlBody: htmlBody,
};
GmailApp.sendEmail(toEmail, subject, "html content only", options);
}

How to wait for new input from user in Telegram Bot?

I'm building a bot for Telegram to be able to users add to a spreadsheet "friends".
The idea is that when they start the bot they can simply write the name of the "friends" (e.g., #friend1 #friend2 #friend3), and they will be added to a new spreadsheet.
I'm writing in the Google Spreadsheet Script Editor.
Started to declare the variables, and set up the webhook.
var token = "token";
var url = "https://api.telegram.org/bot" + token;
var webAppUrl = "spreadhsheetURL"
var ssId = "spreadsheeID";
var myID = "$$$$$$$"
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 sendText(id, text) {
var response = UrlFetchApp.fetch(url + "/sendMessage?chat_id=" + id + "&text=" + encodeURIComponent(text));
Logger.log(response.getContentText());
}
function doGet(e){
return HtmlService.createHtmlOutput("Hello " + JSON.stringify(e));
}
All is functioning but when I tell BOT to ask the user if the wants to add new friends the program doesn't wait for the user to write and gives the "Error" of the last else.
function doPost(e){
try{
var contents = JSON.parse(e.postData.contents);
var text = contents.message.text;
var id = contents.message.from.id;
var name = contents.message.from.username;
sendText(id, "Hi " + name + " do you want to add more friends? (Yes/No)");
if(text == "Yes"){
sendText(id, "Add new friends (e.g., #friend1 #friend2 #friend3)).");
var sheetName = name;
var newText = text.split(" ").slice(1).join(" ");
//check if already exist the spreadshet
var sheet = ss.getSheetByName(sheetName) ? ss.getSheetByName(sheetName) : ss.insertSheet(sheetName);
// check the number of words (friends)
var str_len = newText.split(" ").length;
// Print friends per row
for (i=0; i<str_len; i++){
sheet.appendRow([new Date(), id, name, newText.split(" ")[i]]);
}
sendText(id,"The user " + newText + " was added to your list " + sheetName + " with success.");
}else{
if(text == "No"){
sendText(id, "Thank you.")
}else{
sendText(id, "Error.")
}
}
var ss = SpreadsheetApp.openById(ssId);
}catch(e){
sendText(myID, JSON.stringify(e,null,4));
}
}
Want to know if anyone could help me.
Thanks
The problem is that you are doing one delivery for two processes at once, and each process needs to be responded to at its own time, so you have to separate each response from each process.
You can use the reply_markup parameter with ForceReply for data input needs, which is available in almost all send methods.
A little improvement, modified version to solve the problem:
function doPost(e){
try {
var contents = JSON.parse(e.postData.contents);
var text = contents.message.text;
var id = contents.message.from.id;
var name = contents.message.from.username;
var answer = ["Yes","No"];
if ( text === "/start" ) {
sendText(id, "Hi " + name + " do you want to add more friends? (Yes/No)");
} else if ( answer.includes( text ) ) {
if ( text === "Yes" ) {
//force user to input
var dataForceReply = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String( contents.message.chat.id ),
text: "Add new friends (e.g., #friend1 #friend2 #friend3))",
reply_markup: JSON.stringify({
"force_reply": true
})
}
};
UrlFetchApp.fetch( url + "/", dataForceReply );
} else sendText(id, "Thank you.");
//When the user provides feedback input
} else if ( (( contents || {} ).message || {}).reply_to_message ) {
//Make sure the user's answer is for the same question
if ( contents.message.reply_to_message.chat.id == contents.message.chat.id ) {
var ss = SpreadsheetApp.openById(ssId);
var sheetName = name;
var newText = text.split(" ").slice(1).join(" ");
//check if already exist the spreadshet
var sheet = ss.getSheetByName(sheetName) ? ss.getSheetByName(sheetName) : ss.insertSheet(sheetName);
//check the number of words (friends)
var str_len = newText.split(" ").length;
// Print friends per row
for (i=0; i<str_len; i++){
sheet.appendRow([new Date(), id, name, newText.split(" ")[i]]);
}
sendText(id,"The user " + newText + " was added to your list " + sheetName + " with success.");
} else sendText(id, "Error.");
}
} catch(e) {
sendText( myID, e );
}
}

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.

how to communicate telegram bot with google sheet

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!