i made a bot for telegram using Apps script
i have a spreadsheet which has a database... 3 columns 500 rows
ID , Username, Full Name
i want to make a command for tg bot like when i send /who "ID NUMBER"
it looks up in the spreadsheet in first columns for that specific ID NUMBER and sends back the Full name of it
here is my apps script
var ssId = "16Rw-ilDTdozSHOn73I0fhXeaTJuixyQOp7BDDXfY9Cs";
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
}
function sendMessage(id, text,) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
}
function doPost(s) {
var contents = JSON.parse(s.postData.contents);
var id = contents.message.from.id; // user ID
var name = contents.message.from.first_name; // Sender First name
var uname = contents.message.from.username; // Sender Username
var text = contents.message.text; // Message Text
if (text.includes("/who")) {
var result = text.substr(text.indexOf(" ") + 1);; // this line removes the first word from the Message
Related
I started with this project hoping to be able to have the Google Places API automate the look up of specific business and place information. While I started with individual functions, I see that this created an inordinate amount of requests that blew through my free monthly Google Cloud credit. This was because I wrote functions which were being recalled every time the Sheet was opened in any instance.
Instead, I want to only have the functions run when I use the custom UI button to call it. But how can I specify that it should only run when places do not have their information already populated in the Sheet?
I would have entered the name of a place in Column A, and in Columns B - F, I will have the function find the requested information. My script looks at the name of the place in Column A and finds the Google Place ID. From there, it formats a URL for that Google Places entry and pulls in the requested information from the concatenated URL.
Here is my current code:
// This location basis is used to narrow the search -- e.g. if you were
// building a sheet of bars in NYC, you would want to set it to coordinates
// in NYC.
// You can get this from the url of a Google Maps search.
const LOC_BASIS_LAT_LON = "37.7644856,-122.4472203"; // e.g. "37.7644856,-122.4472203"
function COMBINED2(text) {
var API_KEY = 'AxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxQ';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.formatted_address,
place.formatted_phone_number,
place.website,
place.url,
weekdays.trim()
] ];
return data;
}
// add menu
// onOpen is a special function
// runs when your Sheet opens
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu("Custom Menu")
.addItem("Get place info","COMBINED2")
.addToUi();
}
I received help on a separate post which advised that I use another function to call COMBINED2 but I am not sure whether that still applies with my change of plans.
// this function calls COMBINED2()
function call_COMBINED2() {
var ss = SpreadsheetApp.getActiveSheet();
var text = ss.getRange("A2").getValue();
var data = COMBINED2(text);
var dest = ss.getRange("B2:F2");
dest.setValues(data);
}
Should it make a difference, my plan for down the road will be to have two buttons in the custom UI. One will work to do the initial lookup of place data. The second will do a refresh. If a change is detected and a cell is changed/updated, then it will highlight in some fashion so that I can make note of this.
The project is part of how I travel. I will often make running Google Sheet lists of recommended and vetted places of interest, bars, and restaurants so that I can import the Sheet into a Google MyMap for reference when we're actually visiting. Over time, these Sheets/MyMaps tend to become obsolete with changes (especially with COVID). I hope this serves to future-proof them and make updating them easier.
The onOpen trigger in your script is only for adding the Custom Menu in your Sheet. The function will only get executed when the user selected an Item in the menu that is associated with the function. In your example, clicking Get place info will execute the COMBINED2 function.
Also, executing the script only when the place information is not present in the sheet is not possible, you have to run the script to get the identifier of the place and compare it to the data in the Sheet. In your example, place.url can be used as identifier. The only thing you can do is to prevent the script from populating the Sheet.
Here I updated your script by changing the function associated to the Get place info to writeToSheet(). writeToSheet() will call COMBINED2(text) to get the place information and use TextFinder to check if the place url exists in the Sheet. If the result of TextFinder is 0, it will populate the Sheet.
// const LOC_BASIS_LAT_LON = "40.74516247433546, -73.98621366765811"; // e.g. "37.7644856,-122.4472203"
const LOC_BASIS_LAT_LON = "37.7644856,-122.4472203";
function COMBINED2(text) {
var API_KEY = 'enter api key here';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [
place.name,
place.formatted_address,
place.formatted_phone_number,
place.website,
place.url,
weekdays.trim()
];
return data;
}
function getColumnLastRow(range){
var ss = SpreadsheetApp.getActiveSheet();
var inputs = ss.getRange(range).getValues();
return inputs.filter(String).length;
}
function writeToSheet(){
var ss = SpreadsheetApp.getActiveSheet();
var lastRow = getColumnLastRow("A1:A");
var text = ss.getRange("A"+lastRow).getValue();
var data = COMBINED2(text);
var placeCid = data[4];
var findText = ss.createTextFinder(placeCid).findAll();
if(findText.length == 0){
ss.getRange(lastRow,2,1, data.length).setValues([data])
}
}
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu("Custom Menu")
.addItem("Get place info","writeToSheet")
.addToUi();
}
Output:
Example 1:
After clicking custom menu:
Example 2:
After clicking custom menu:
Note: Since we are using lastRow, new entry must be inserted below the last row of column A. Otherwise it will overwrite the last entry.
Reference:
Custom Menu
Place Details
I have a function that successfully extracts file attachments from new emails. But it is unable to detect hyperlinked attachments like this email from our office scanner:
Would anyone know of an approach to address this?
UPDATE:
I found a similar case in How to download file from a download link on Gmail and uploading it to Google Drive using Google Apps Script
and revised my code below.
Here's the result:
a) extracting a hyperlinked attachment using this publicly available URL (people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv) as my sample attachment works OK and saves it in my preferred filename, but
b) for the actual email from our scanner I get this error message when it executes UrlFetchApp.fetch(url):
Exception: Bad request: http://10.87.38.21:8000/cmj/asd/download?dev=...
What could be causing this issue?
(my revised code below):
//===================================
function ExtractEmailAttachmentsJP() {
//===================================
var spr = SpreadsheetApp.getActiveSpreadsheet();
var ss = SpreadsheetApp.getActiveSheet();
var sheet = SS.getSheetByName("UPLOADER");
var logsheet = SS.getSheetByName("Documents Uploaded");
TEMPFOLDERID = PropertiesService.getDocumentProperties().getProperty('TEMPFOLDERID');
TEMPFOLDER = DriveApp.getFolderById(TEMPFOLDERID);
//do not overwrite, just append to the last non-empty (max) row
var startRow = lastNonblankRow("N",SSID,"UPLOADER")+1
COUNTER = 0; //initialize file attachment counter
var gmailLabels = "PeopleDoc";
var threads = GmailApp.search("label:" + gmailLabels + " is:Unread", 0, 3);
if (threads.length > 0) {
SS.toast("New emails found. Extracting attachment(s)...");
/*Iterate through the threads of emails*/
for (var t=0; t<threads.length; t++) {
var msgs = threads[t].getMessages();
//Iterate through each mail
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
var data = msg.getPlainBody();
var urlField = data.indexOf('http://');
var url = data.substr(urlField, 117);
var fileUrl = UrlFetchApp.fetch(url);
var fileBlob = fileUrl.getBlob();
COUNTER = COUNTER + 1;
var timestamp = Utilities.formatDate(new Date(msg.getDate()), "GMT+8", 'dd MMM hh:mm');
var pdfID = TEMPFOLDER.createFile(fileBlob).setName("attachment" + COUNTER + " " + timestamp).getId();
//show each generic file row by row
sheet.getRange(startRow-1+COUNTER, 10).setFormula('=HYPERLINK(\"https://drive.google.com/file/d/' + pdfID + '\", \"' + "attachment" + COUNTER + " " + timestamp + '\")');
sheet.getRange(startRow-1+COUNTER, 15).setValue(pdfID);
sheet.getRange(startRow-1+COUNTER, 16).setValue("Gmail Inbox");
}
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.
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.
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!