Generate qrcode and save to google drive - google-drive-api

I write this script to generate QRCode then save it to google drive, link in column A and file name in column B (with header):
function qrcode() {
var folderid = Browser.inputBox("Folder ID", "Type or copy/paste the folder ID:",Browser.Buttons.OK_CANCEL);
if (folderid === "cancel" || folderid == ""){return;}
var url = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&margin=5&data=";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1];
var lastRow = sheet.getLastRow();
var link = sheet.getRange(2, 1, lastRow).getValues();
var name = sheet.getRange(2, 2, lastRow).getValues();
var folders = DriveApp.getFolderById(folderid);
var count = 0
while (count < lastRow-1){
var response = UrlFetchApp.fetch(url+encodeURIComponent(link[count]));
if (response.getResponseCode() == 200)
{
var blob = response.getBlob().setName(name[count]+".jpg")
DriveApp.getFolderById(folderid).createFile(blob);
}
count = count + 1
}
}
When the script run, this message appear:
Exception: Request failed for https://api.qrserver.com returned code 400. Truncated server response: en: malformed 'create-qr-code' API request. Please consider the API documentation at http://goqr.me/api/doc/create-qr-code/ de: ungültige 'cr... (use muteHttpExceptions option to examine full response)
But the script is working (i get the result ok)
What wrong with my script???

Related

Google Apps Script - Gmail - Error Handling When No Message/Thread

Hoping someone can help me out with handling 'errors' in my script when there is no message/thread found. I thought I had done that with the IF statement based on message.lengh but its not working and still errors when no email is found matching the inputted search criteria (e). It works perfectly every time a message IS found.
Many thanks.
Moz
function ImportCDWFiles(e){
var Threads = GmailApp.search(e,0,1);
var Message = Threads[0].getMessages()[0];
var Attachment = Message.getAttachments()[0];
if (Threads.length >0){
Logger.log(Threads.length);
Logger.log(Attachment.getName())
var SourceFile = Folder.createFile(Attachment.copyBlob())
var SourceID = SourceFile.getId();
var XlsxBlob = Attachment[0]; //
var ConvertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, SourceFile).id; //XlsxBlob
Logger.log("Converted File ID= "+ ConvertedSpreadsheetId)
var Sheet = SpreadsheetApp.openById(ConvertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var Data = Sheet.getDataRange().getValues();
//var Data = Sheet.getDataRange().offset(headerRowNumber, 0, sheet.getLastRow() - headerRowNumber).getValues();
var sheet = SpreadsheetApp.openById('SheetIDHere').getSheetByName('SheetName');
var range = sheet.getRange(LastRow+1, 1, Data.length, Data[0].length);
range.setValues(Data);
Drive.Files.remove(ConvertedSpreadsheetId); // Remove the converted file.
}
}
Modification points:
At var Message = Threads[0].getMessages()[0], when the length of Threads is 0, an error occurs.
If the attachment files are not included, an error occurs.
In your script, Folder and LastRow are not declared.
When these points are reflected in your script, how about the following modification?
Modified script:
function ImportCDWFiles(e) {
var Folder = DriveApp.getFolderById("###"); // Please set your folder ID.
var Threads = GmailApp.search(e, 0, 1);
if (Threads.length == 0) return;
var Message = Threads[0].getMessages()[0];
var Attachment = Message.getAttachments();
if (Attachment.length == 0) return;
Attachment = Attachment[0];
Logger.log(Attachment.getName())
var SourceFile = Folder.createFile(Attachment.copyBlob());
var ConvertedSpreadsheetId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS }, SourceFile).id;
Logger.log("Converted File ID= " + ConvertedSpreadsheetId);
var Sheet = SpreadsheetApp.openById(ConvertedSpreadsheetId).getSheets()[0];
var LastRow = Sheet.getLastRow();
var Data = Sheet.getDataRange().getValues();
var sheet = SpreadsheetApp.openById('###').getSheetByName('###'); // Please set your values.
var range = sheet.getRange(LastRow + 1, 1, Data.length, Data[0].length);
range.setValues(Data);
Drive.Files.remove(ConvertedSpreadsheetId);
}
Note:
Unfortunately, from your question, I cannot know the mimeType of the attachment file. So, I couldn't implement checking the mimeType of the attachment file. If you can know, when this check is implemented, the error related to the mimeType might be able to be avoided.

Google Script on Attaching List of excel files from a Spreadsheet

I two spreadsheet Main and AddFiles wherein Add file has Two columns Subject and Attachments where under attachments is the list of excel file names with like file1.xlsx and file2.xlsx. Where I uploaded this file in my Google Drive under the Report folder.
I used the code below but always got an error on the last execution. It doesn't recognize the .getAs(MimeType.xlsx)
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange(2,1,1,1)
data = dataRange.getValues()
var e = data[0][0]
for (var i = 0; i < (e-1); i++) {
draftmail();
}
function draftmail(){
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange(1,1,1,1)
var data = dataRange.getValues()
var msg = data[0][0]
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("AddFiles");
var startRowx = 1
var numRowx = 1
var dataRangeTox = sheet.getRange(startRowx,3,numRowx,1)
var datax = dataRangeTox.getValues()
for (x in datax) {
var rowx = datax[x];
var to = rowx[0];
var Starta = 2 + i
var numRowa = 1
var dataRangeToa = sheet2.getRange(Starta,1,1,1)
var dataa = dataRangeToa.getValues()
for (a in dataa) {
var rowa = dataa[a];
var subject = rowa[0];
var Startb = 2 + i
var numRowb = 1
var dataRangeTob = sheet2.getRange(Startb,2,1,1)
var datab = dataRangeTob.getValues()
for (b in datab) {
var rowb = datab[b];
var datafile = rowb[0];
var file = DriveApp.getFilesByName(datafile)
var startRowy = 1
var numRowy = 1
var dataRangeToy = sheet.getRange(startRowy,4,numRowy,1)
var datay = dataRangeToy.getValues()
for (y in datay) {
var rowy = datay[y];
var carboncopy = rowy[0];
if (file.hasNext()){
GmailApp.createDraft(to,subject,msg,{ cc: carboncopy}, {
attachments: [file[0].getAs(MimeType.xlsx)],
})
}
}
}
}
}
}
Modification points:
Assuming that everything else works properly in your code, you should make the following changes:
cc and attachments should be passed as a single json object.
file[0] should be file.next().
MimeType.xlsx should be MimeType.MICROSOFT_EXCEL.
Solution:
GmailApp.createDraft(to,subject,msg,
{ cc: carboncopy,
attachments: [file.next().getAs(MimeType.MICROSOFT_EXCEL)]
})
References:
Class GmailApp
Google Apps Script: XLSX from Gmail to Google Sheets: invalid mime type. Content type seems to be application/octet?
Class FileIterator
When you call
file = DriveApp.getFilesByName(datafile)
it returns a FileIterator collection, which is not indexed like an array (file[0]) but rather requires you to call file.next() to get the next file.
In addition, the MimeType Enum for an .xlsx file is MimeType.MICROSOFT_EXCEL.
So change
attachments: [file[0].getAs(MimeType.xlsx)]
to this instead:
attachments: [file.next().getAs(MimeType.MICROSOFT_EXCEL)]

Exception: Failed to send email: no recipient (line 38, file "Code")" error in Google Sheets

Any ideas why I'm getting an "Exception: Failed to send email: no recipient (line 38, file "Code")" error? This is my script from Google Sheets. I get the popup asking if I want to send an email but it never sends. The macro compiles OnEdit but not on send.Emails. I do have correct data on line 150 in my Active Sheet.
function onEdit(e)
{
var sheet = SpreadsheetApp.getActiveSheet();
var editRange = sheet.getActiveRange();
var editRow = editRange.getRow();
var editCol = editRange.getColumn();
var monitorCol = 17 // Set this to the number column you want to monitor
if (editCol == monitorCol)
{
var response = Browser.msgBox('Notify User?', 'You have updated the status for this job, do you want to email user with this update?', Browser.Buttons.YES_NO);
// Process the user's response.
if (response == 'Yes') {
sendEmails()
}
}
}
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A150:F150");
var data = dataRange.getValues();
data.forEach(function (rowData) {
var recipient2 = rowData[4];
var emailAddress = rowData[6];
var status = rowData[17];
if (status == 'Finished') {
return
}
var greeting = 'Hi ' + recipient2 + ',\n'
var finishedMessage = 'Your Makerspace project is complete. You can pick it up Wednesdays 11:00AM - 1:00PM or Friday 4:00PM - 5:30PM.';
var keepMakingMessage = 'Keep making!!';
var signatureMessage = 'UCA Makerspace Staff!!';
var message = [greeting, finishedMessage, keepMakingMessage, signatureMessage].join('\n');
var subject = 'Good news, your Makerspace project is complete';
MailApp.sendEmail(emailAddress, subject, message);
})
}
Data Range is: var dataRange = sheet.getRange("A150:F150"); six columns
var emailAddress = rowData[6]; is column 7
solution might be: var dataRange = sheet.getRange("A150:G150");
or
var emailAddress = rowData[5];
Not enough information to know which.
I presume you are also missing var status = rowData[17];

Determining the extension of an e-mail attachment automatically (whether it's XLSX or CSV) and applying the right parsing technique

I have two Google Script codes that automate the process of importing email attachments from Gmail (it's automatically labeled) into Google Sheets. So far I managed to make it work for CSV and XLSX files separately. Please see both codes below. My question is: how do I combine those two codes into one, so that it could determine the file extension automatically and apply the right parsing technique when copying the contents of the files in the respective Google Sheet. Thank you!
For XLSX files:
function getXLSX() {
var thread = GmailApp.getUserLabelByName("Invoicing").getThreads(0,1);
/* var message = thread[0].getMessages()[0]; // Get first message */
var messages = thread[0].getMessages();
var len = messages.length;
var message=messages[len-1] //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var xlsxBlob = attachments[0]; // Is supposes that attachments[0] is the blob of xlsx file.
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var data = sheet.getDataRange().getValues();
Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet_new = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
/*for (var i = 0; i > sheet_new.length; i++) {
var range = sheet_new[i].getRange("A:I");
range.clearContents();
}*/
sheet_new.clearContents();
var range = sheet_new.getRange(1,1, data.length,data[0].length);
range.setValues(data);
}
For CSV files:
function getCSV() {
var thread = GmailApp.getUserLabelByName("Invoicing").getThreads(0,1);
/* var message = thread[0].getMessages()[0]; // Get first message */
var messages = thread[0].getMessages();
var len = messages.length;
var message=messages[len-1] //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var csv = attachments[0].getDataAsString();
var data = Utilities.parseCsv(csv);
var a = data.length ;
var b = data[0].length;
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
sheet.getRange("A:J").clear();
var range_final = sheet.getRange(1,1, data.length,data[0].length);
range_final .setValues(data);
}
How about this modification? In this modification, the mimeType is compared and each script is run. Please think of this as just one of several answers.
Modified script:
function myFunction() {
var thread = GmailApp.getUserLabelByName("Invoicing").getThreads(0,1);
var messages = thread[0].getMessages();
var len = messages.length;
var message = messages[len-1]; //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var blob = attachments[0]; // Is supposes that attachments[0] is the blob of xlsx file.
blob.setContentTypeFromExtension();
if (blob.getContentType() == MimeType.MICROSOFT_EXCEL) {
// Process for XLSX
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, blob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var data = sheet.getDataRange().getValues();
Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
var sheet_new = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
sheet_new.clearContents();
var range = sheet_new.getRange(1,1, data.length,data[0].length);
range.setValues(data);
} else if (blob.getContentType() == MimeType.CSV) {
// Process for CSV
var csv = blob.getDataAsString();
var data = Utilities.parseCsv(csv);
var a = data.length ;
var b = data[0].length;
var sheet = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
sheet.getRange("A:J").clear();
var range_final = sheet.getRange(1,1, data.length,data[0].length);
range_final.setValues(data);
}
}
Note:
This modified script supposes as follows.
The index of 0 of attachment files is the file you need.
The index of 0 of attachment files is XLSX file or CSV file.
Filenames of XLSX and CSV files have the extension of .xlsx and .csv, respectively.
Reference:
setContentTypeFromExtension()
If I misunderstood your question and this was not the result you want, I apologize.

How to write google script to automatically call data from a google folder drive that contains a CSV file into one Google Sheets

I am trying to write a google script that will allow me to go into my google drive folder called "MeadJohsnon" and pull 'Temperature Calibration.csv' to google sheets. I have never used google script before. Currently I have the "Save Email and Attachment" Add-ons. This add-on is pulling .cvs files that my team is sending me from the field. They use "TapForms" and then send the form via email to my gmail. So, I got the email sending that attachment to my google drive but I need help with the script, so Drive will automatically get those .cvs files and put the information into one google sheet. I say ONE google sheet because although I have a team sending in forms, all the forms have the same information on them.
This is what I have done so far. The fourth line gives me a
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
I would just like feedback on how to fix my error or what I could do instead. As stated this is my first time using google script, my specialty is ASP.net lol not script. Thank you.
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'Temperature Calibration.csv';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
Okay this will append the files to the active spreadsheet you'll probably have to open the spreadsheet by id and use getSheetByName to get the sheet you want because this spreadsheet probably won't be active all the time when the trigger is running. I assume the the files all end in .csv. I rename them to .old after reading the data so that the program won't read them multiple times.
function appendingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
var drng = sht.getDataRange();
var lastRow = drng.getLastRow();
var data = loadFiles();
var dataA =Utilities.parseCsv(data);
if(dataA.length>0)
{
var rng = sht.getRange(lastRow + 1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
else
{
SpreadsheetApp.getUi().alert('No Data Returned from LoadFiles');
}
}
function loadFiles(folderID)
{
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var files = fldr.getFiles();
var s='';
var re = /^.*\.csv$/i;
while (files.hasNext())
{
var file = files.next();
var filename = file.getName();
if(filename.match(re))
{
s += file.getBlob().getDataAsString() + '\n';
file.setName(filename.slice(0,-3) + 'old');
}
}
return s;
}