All User ID's , -1001199520004 when bot added to group as admin? - telegram-bot

Mybot is saving user ID ect. to google sheets and respond ,but when added to a group it saves all user IDs as -1001199520004 and respond with undefined undefined + answer and saves name & surname as undefined undefined aswell.
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.id.first_name + " " +
data.message.chatid.last_name;
var answer = name + ", whatever " ;
sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new
Date(),id,name,text]);
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]);
}
}

Related

Google App Script - Save Spreadsheet to PDF saved on Google Drive

I'm trying to save all of the sheets on my spreadsheet to google drive as one PDF (ultimately I would like to have them email as well). I'm having trouble saving more than just one of the sheets. I've tried multiple way of doing it. The code below is the best way I've found so far. Again the problem is that it only saves the first page as a PDF, I cant figure out how to get around the delete redundant sheets. All the posts I have seen only want to save 1 page, I have over 24 pages that need to be saved as one PDF. Thanks in advance for your help!
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
By using Drive API, you can convert from a spreadsheet to a PDF which has all sheets in the spreadsheet. In order to use this, so please enable Drive API on Google API Console as follows.
In the script editor, select Resources > Cloud Platform Project
At the bottom of the dialog, click the link for the Google API Console.
In the console, click into the filter box and type part of the name of the API "Drive API", then click the name once you see it.
On the next screen, click Enable API.
Close the Developers Console and return to the script editor. Click OK in the dialog.
I prepared a sample script for creating PDF file from spreadsheet. Please use this to your script.
Script :
var spreadsheetId = "#####";
var folderId = "#####";
var outputFilename = "#####";
var url = "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderId).createFile(response).setName(outputFilename);
About this script, although I confirmed this works fine, if it doesn't work at your environment, please tell me. And if I misunderstand your question, I'm sorry.
Added 1 :
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
// var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
// var newFile = folder.createFile(theBlob);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + destSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Added 2 :
function PDF() {
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var folder = DriveApp.getFolderById(folderID);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + sourceSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
}
Here is the function that creates PDF file from google sheet and function that moves new created file into the folder that id you give to the parameter of the function.
function downloadPDF(fileId, folderId) {
var file = Drive.Files.get(fileId);
var url = file.exportLinks[MimeType.PDF];
var options = {
headers: {
Authorization:"Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions : true
}
var response = UrlFetchApp.fetch(url, options);
var status = response.getResponseCode();
var result = response.getContentText();
if (status != 200) {
// Get additional error message info, depending on format
if (result.toUpperCase().indexOf("<HTML") !== -1) {
var message = strip_tags(result);
}
else if (result.indexOf('errors') != -1) {
message = JSON.parse(result).error.message;
}
throw new Error('Error (' + status + ") " + message );
}
var doc = response.getBlob();
var newFileid = DriveApp.createFile(doc).setName(file.title + '.pdf').getId();
let id = moveFileTo(newFileid, folderId);
return id;
}
function moveFileTo(sourceId, folderId){
let file = DriveApp.getFileById(sourceId)
let blob = file.getBlob();
let id = DriveApp.getFolderById(folderId).createFile(blob).getId();
file.setTrashed(true)
return id;
}

How do I retrieve the URL of a file hosted on Parse-Server through Javascript?

My code so far:
<script type="text/javascript">
var username = sessionStorage.getItem('username', username);
var password = sessionStorage.getItem('password', password);
var Image = Parse.Object.extend("Image");
var query = new Parse.Query(Image);
query.equalTo("username", username);
query.descending("createdAt");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " images.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
var url = (object.get("image").url);
var createdAt = (object.get("createdAt"));
var image = object.get("image");
alert(url + object.id + createdAt + username + image);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
All variables return the expected values except "image" which returns [Object object] and url which returns function url(){ return this._url;}
in order to get the file URL you need to do the following :
var image = object.get("image"); // here you have ParseFile
var imageUrl = image.url(); // now you have the file URL

Creating PDF in Landscape (Google Apps Script)

I'm trying to work out how to create a PDF document through Google Apps Script which is displayed in landscape orientation (A4 size). This is the code I'm using to create the PDF so far, which comes out in portrait orientation.
function pdfSheet() {
var d = new Date();
var cdate = d.getDate();
var cmonth = d.getMonth() + 1;
var cyear = d.getFullYear();
var current = [cdate + "-" + cmonth + "-" + cyear];
var imageBlob = UrlFetchApp.fetch("https://sites.google.com/site/mysite/smalllogo.png").getBlob();
var base64EncodedBytes = Utilities.base64Encode(imageBlob.getBytes());
var logo = "<img src='data:image/png;base64," + base64EncodedBytes + "' width='170'/>";
var html = "<table width='100%'><tr><td align='right'>" + logo + "<br><br><b>Date:</b> " + current + "</td></tr></table>"; //PDF content will carry on here.
var gmailLabels = "PDF";
var driveFolder = "My Gmail";
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
var subject = 'Test PDF';
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
var page = folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf")
tempFile.setTrashed(true);
var link = page.getUrl();
Logger.log(link);
}
I took most of this from another user and edited to have the current days date (in EST) in the email subject and the PDF name. Hope it helps!
// Simple function to send Daily Status Sheets
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
var submenu = [{name:"Send Status", functionName:"exportSomeSheets"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Project Admin', submenu);
}
function creatPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Date set with format in EST (NYC) used in subject and PDF name
var period = Utilities.formatDate(new Date(), "GMT+5", "yyyy.MM.dd");
var url = ss.getUrl();
//remove the trailing 'edit' from the url
url = url.replace(/edit$/, '');
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
//below parameters are optional...
'&size=letter' + //paper size
'&portrait=false' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional headers and footers
'&gridlines=false' + //hide gridlines
'&fzr=false' + //do not repeat row headers (frozen rows) on each page
'&gid=' + sheet.getSheetId(); //the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var blob = response.getBlob().setName(ss.getName() + " " + period + '.pdf');
//from here you should be able to use and manipulate the blob to send and email or create a file per usual.
var email = 'email#co-email.com';
var subject = "subject line " + period ;
var body = "Please find attached your Daily Report.";
//Place receipient email between the marks
MailApp.sendEmail( email, subject, body, {attachments:[blob]});
}

Send an email with attachment and save in Google Drive using Google Apps Script

Hi everyone and thanks a lot for reading this.
I have some code that was based on SendPDF of Jiayao. Original here: SendPDF of Jiayao
I have a Google Spreadsheet that generates a PDF, send email, and save the pdf in Google Drive ( I using Google Apps).
It always worked. However, when I moved to the New Google Drive no longer works.
When I run I get the error:
Request failed http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=1KWJC2tHk6uxrrIYwaf3GOe5NKsPzQRaYQy2pPmwfx_M&exportFormat=pdf&gid=954198957 retornou o código 401. Resposta truncada do servidor:< HTML > < HEAD > < TITLE >Unauthorized < BODY BGCOLOR="#FFFFFF" TEXT="#000000"> < H1 >Unauthorized Error 401 (use a opção muteHttpExceptions para examinar a resposta completa)
Below, my code:
// Copyright 2010 Jiayao Yu
//
// ORIGINAL See usage and updated version on http://gist.github.com/405466
var TOKEN_CELL = 1;
var EMAIL_CELL = 2;
var BCC_CELL = 3;
var SUBJECT_CELL = 4;
var BODY_CELL = 5;
var SHEET_NAME_CELL = 6;
var SHEET_RELATORIO = 7;
var SPREADSHEET_URL = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=";
var DATA_RELATORIO = 8;
var BUSCA_GID = 9;
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
menuEntries = [ {name: "Enviar relatório", functionName: "sendAsPdf"}];
ss.addMenu("Relatório HRT", menuEntries);
var configSheet = getConfigSheet();
configSheet.getRange(1, TOKEN_CELL).setValue("Auth Token");
configSheet.getRange(1, EMAIL_CELL).setValue("Email");
configSheet.getRange(1, BCC_CELL).setValue("Bcc");
configSheet.getRange(1, SUBJECT_CELL).setValue("Subject");
configSheet.getRange(1, BODY_CELL).setValue("htmlBody");
configSheet.getRange(1, SHEET_NAME_CELL).setValue("Export sheet name");
configSheet.getRange(1, SHEET_RELATORIO).setValue("Relatorio");
configSheet.getRange(1, DATA_RELATORIO).setValue("DatadoRelatorio");
configSheet.getRange(1, BUSCA_GID).setValue("BGID");
}
function sendAsPdf() {
// Pergunta se deseja enviar email
var PerguntaEmail = Browser.msgBox('Enviar Email', 'Deseja enviar email para ' + getConfig(EMAIL_CELL) , Browser.Buttons.YES_NO);
if (PerguntaEmail == 'yes' ) {
var configSheet = getConfigSheet();
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = getConfig(SHEET_NAME_CELL);
var arquivoName = getConfig(SHEET_NAME_CELL) + getConfig(SHEET_RELATORIO);
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!dataSheet) {
Browser.msgBox("Can't find sheet named:" + sheetName);
return;
}
// Atualiza a data do Relatório na aba Relatorio_Pneumologia
// Browser.msgBox(getConfig(DATA_RELATORIO));
// var formattedDate = Utilities.formatDate(new Date(), "GMT-3", "dd-MM-yyyy");
dataSheet.getRange(3,2).setValue(getConfig(DATA_RELATORIO));
// Logger.log(formattedDate);
// Browser.msgBox(formattedDate);
// Envia EMAIL
var dataSheetIndex = dataSheet.getIndex() - 1;
// Original: var url = SPREADSHEET_URL + id + "&exportFormat=pdf&gid=" + dataSheetIndex;
var url = SPREADSHEET_URL + id + "&exportFormat=pdf&gid=" + getConfig(BUSCA_GID);
var auth = "AuthSub token=\"" + getConfig(TOKEN_CELL) + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var content = res.getContent();
var responseCode = res.getResponseCode();
if (responseCode != 200 || res.getContentText().indexOf("/ServiceLoginAuth") != -1) {
Logger.log("Fetch url:" + url + " failed with " + responseCode);
Browser.msgBox("Error occurred when exporting spreadsheet to pdf, it might be caused by auth token being expired");
return;
}
var bcc = getConfig(BCC_CELL);
Logger.log("BCC to:" + bcc);
var attachments = [{fileName:arquivoName + ".pdf", content: content, mimeType:"application/pdf"}];
MailApp.sendEmail(getConfig(EMAIL_CELL), getConfig(SUBJECT_CELL),
"", {attachments:attachments, bcc: bcc, htmlBody: getConfig(BODY_CELL)});
Browser.msgBox("Email enviado com sucesso para: " + getConfig(EMAIL_CELL));
// Salvar versao do relatório no Google Drive
var Impressao = Browser.msgBox('Salvar Relatorio', 'Deseja salvar o relatório no Google Drive?', Browser.Buttons.YES_NO);
if (Impressao == 'yes' ) {
// Codigo inspirado em http://stackoverflow.com/questions/12881547/exporting-spreadsheet-to-pdf-then-saving-the-file-in-google-drive
// Salva no Google Drive
var NomedoArquivo = arquivoName + ".pdf"
DocsList.createFile(res).rename(NomedoArquivo);;
Browser.msgBox('Arquivo gravado em seu Google Drive. Pode fechar da planilha.');
}
else { Browser.msgBox('Operação concluída com sucesso. Pode fechar da planilha.')
}
}
// FIM DO THEN do IF se deseja enviar email
else { Browser.msgBox('Ok. Pode fechar da planilha.')
}
// FIM DO IF se deseja enviar email
// FIM DA FUNCAO - sendAsPdf
}
function getConfig(cell) {
var configSheet = getConfigSheet();
return configSheet.getRange(2, cell).getValue();
}
function getConfigSheet() {
var name = "script_config";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
if (!sheet) {
sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(name);
Logger.log("Created sheet " + name);
}
return sheet;
}
I appreciate any suggestions.
The new version of spreadsheets use a different url for file conversion, that's why your script is not working anymore.
You have 2 possible solutions :
Use the advanced drive service as shown in Eric Koleda's answer which can provide multiple export formats
Use the simple getAs('application/pdf') from the Drive service since pdf is the only supported format (for now) and that's what you are using !
The returned value is a blob, you can use it directly to create your file in Drive.

Slightly modify lat/lng for gmap api v3

Have a quick question. On my website I have a form that allows users to input their city, state, and country. This information is converted to $lat and $lng, which is used to create a marker on a google map. Problem is, I have multiple users that select the same city. Clustering is a HUGE pain... to be honest, I can't seem to find a good tutorial and I'm feeling a bit hopeless.
So I thought I'd just modify each $lat and $lng slightly. For example, this is the info I get for Travis AFB, CA: lat="38.263065" lng="-121.949699". Wondering if it's possible to add a bit of code that might let me modify those last bits. Any suggestions???
Here's how I geocode $address (combination of $city, $state, $country):
$geocodestring=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' . urlencode($address) );
$geocodedinfo=json_decode($geocodestring);
$lat = $geocodedinfo->results[0]->geometry->location->lat;
$lng = $geocodedinfo->results[0]->geometry->location->lng;
And that information goes into my SQL database. This is the code that actually creates the map (pretty straightforward).
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 2);
map.enableScrollWheelZoom();
GDownloadUrl("world_xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var first_name = markers[i].getAttribute("first_name");
var last_name = markers[i].getAttribute("last_name");
var email = markers[i].getAttribute("email");
var affiliation = markers[i].getAttribute("affiliation");
var status = markers[i].getAttribute("status");
var service = markers[i].getAttribute("service");
var rank = markers[i].getAttribute("rank");
var specialty = markers[i].getAttribute("specialty");
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var country = markers[i].getAttribute("country");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country) {
var marker = new GMarker(point);
var html = "" + rank + " " + first_name + " " + last_name + " " + service + ", " + status + " " + specialty + " " + affiliation + " " + city + ", " + state + " " + country + " " + email + " " + " ";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Any help/suggestions would be much appreciated!!!
Jeremy
markerclusterer for v2 may solve your problem.
Find code and examples here
http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0/