Script to unzip attachment - google-apps-script

I was trying to create a Google Apps Script, that takes attachment of e-mails, unzips it a forwards it. I saw unpacking feature in Google Drive (you can upload a file there, open it and copy individual files to you drive). Is this functionality accessible from Google Apps Script somehow?

First you need to write a script for automatically makes attachments of an email as directly uploaded on user's Google Drive after this trigger run this piece of code shown below
function testzip(){
var files=DocsList.getRootFolder().find('Sans titre.txt.zip');
var zipblob=files[0].getBlob();
var unzipblob = Utilities.unzip(zipblob);
var unzipstr=unzipblob[0].getDataAsString();// it is a text file
DocsList.createFile('Sans titre.txt',unzipstr);// I kept the original name to make it simple
}
Check this code. Don't blame me if it won't work. It's just a proposal.

Comment: Files are blobs so need to call getBlob(). Anything that has a getBlob() function can be used as a blob directly. You can replace
var zipblob=files[0].getBlob();
var unzipblob = Utilities.unzip(zipblob);
with this:
var zipfile=files[0];
var unzipblob = Utilities.unzip(zipfile);
I tried to edit the other answer, but someone who apparently didn't try the code rejected the edit as incorrect.

Related

Apps Script - Search Gmail label for all attachments and overwrite files to google drive folder

Using prior articles and questions found within stack overflow I was able to find a snippet of App Script that searches Gmail labels for attachments and moves them to a specific folder in Google Drive.
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('xxosi2');
var userId = "please.thanks#gmail.com";
var query = "label:thankyoucards-reports";
var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName());
});
});
}
I need to modify this code to perform the following additional functions:
If file exists, overwrite and retain version history
I have also played around with the answer found in the following thread to no avail as I believe this is hard coded in some way and too specific to the one file type (xlsx) Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script.
I believe your goal is as follows.
You want to check this using the filename between the existing file in the folder and the attachment file.
You want to overwrite the existing file with the attachment file.
In this case, how about the following modification? In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
From:
folder.createFile(a.copyBlob()).setName(a.getName());
To:
var filename = a.getName();
var files = folder.getFilesByName(filename);
if (files.hasNext()) {
Drive.Files.update({}, files.next().getId(), a.copyBlob(), {supportsAllDrives: true});
} else {
folder.createFile(a.copyBlob()).setName(filename);
}
When this modified script is run, the existing file is searched from the folder using the filename of the attachment file. When the file is found, the file is overwritten by the attachment file. When the file is not found, the file is created as a new file.
Note:
In this modified script, the existing file is overwritten. So, please be careful about this. I would like to recommend using a sample file for testing the script.
Reference:
Files: update of Drive API v2

Can I add a script to a Google Sheet using another script?

I have a script populate() to run an automation script on Google Sheets. I want this script to be run on over a hundred Google Sheets files. Is there a way to write a script to add to (or at least run) my populate() script on all those files? I prefer to be able to add the script to each file because we may need to run the scripts multiple times for each file. Otherwise, I will have to manually copy/paste the script to each sheet, which takes time.
Update: Removed the part about converting Excel files to Google Sheets because I found the answer for that on another thread here.
Solution
From what I have understood from your post, your question is about how to convert a series of Excel files inside a Drive folder into Google Sheets to then execute a function in them.
For that, you could iterate over all the files of your folder and convert them with the use of Drive.insert from the Drive API. For that, you will have to enable in your script the Advanced Google Services. If you do not know how to do so, please follow these indications.
The follow script performs what I think you are aiming for, it has self explanatory comments:
function convertExcelToGoogleSheets() {
// Id of the folder where you have all your excel files
var folderId = 'FOLDERID';
var folder = DriveApp.getFolderById(folderId);
// Get all the files in your folder and iterate over them
var files = folder.getFiles();
// For each file:
while (files.hasNext()){
var file = files.next();
// Get its blob (content)
var blob = file.getBlob();
// Create the resource to insert the Google Sheet file. Put the same name
// as the original and set the type of the file to Google sheets and its
// parent folder to where the excel files are located
var resource = {
title: file.getName(),
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: folderId}],
};
// User Drive API to insert the actual file and get its ID
var id = Drive.Files.insert(resource, blob).getId();
// Whatever function you want to perform in the newly created Google Sheet
// pasing the parameter of the file id
myScript(id);
}
}
// Set the first cell of all the converted sheets to "IT WORKED"
function myScript(id){
SpreadsheetApp.openById(id).getActiveSheet().getRange('A1').setValue('IT WORKED!');
}
EDIT: If you want to run a script for each of this converted sheets you can simply call it in the while loop and pass the new file id as a parameter to then be able to use the script (remember to encapsulate this script in a function).
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

Google App Scripts Remove ALL Files in Drive

Good morning, I am running into some issues when creating a google app scripts to remove all files/folders from the root of the Google Drive. I have found the following code but it appears to error out when running;
function deleteFile(idToDLET) {
idToDLET = 'the File ID';
//This deletes a file without needing to move it to the trash
var rtrnFromDLET = Drive.Files.remove(idToDLET);
}
Error Code = Script function not found; myFunction
Thanks
Thanks to #CTOverton answer, I've created another version as I noticed that a File has the setTrashed method, which moves the file in the trash bin.
If the Drive has important files saved, I'd suggest to move files to trash instead of doing a permanent deletion, it may save you from a disaster while doing scripting experiments :-)
This version uses a folder id which you can get with: folder.getId().
You can use CTOverton's code to delete all files on your Drive (commented).
function emptyFolder(folderId) {
const folder = DriveApp.getFolderById(folderId);
while (folder.getFiles().hasNext()) {
const file = folder.getFiles().next();
Logger.log('Moving file to trash: ', file);
file.setTrashed(true);
// Delete File
//Drive.Files.remove(file.getId())
}
}
Cheers
As #James D said, you are missing the myFunction which is the default function in order to run the script. Make sure to save your script first.
Here is the code to get all the files and delete them.
function myFunction() {
// Get all files in Drive
var files = DriveApp.getFiles();
// Delete every file
while (files.hasNext()) {
var file = files.next();
Logger.log('Deleting file "%s"',
file.getName());
// Delete File
Drive.Files.remove(file.getId())
}
}
In order to use DriveAPI, you need to add it through the Resources>Advanced Google Services menu. Set the Drive API to ON. AND make sure that the Drive API is turned on in your Google Developers Console. If it's not turned on in BOTH places, it won't be available.
WARNING
Apps scripts are stored as files in Google Drive...
This script upon running will remove any and all files in the connected google drive account, including itself.
Hope this helps!

Using Google Apps Scripts to generate shareable links of new files

I recently discovered this Google Apps Scripts feature and am wondering if my issue can be addressed by using that.
Let's say I have a machine generating new files (screenshots or videos taken from a capture card) that are being saved in a folder that is sync'd to my Google Drive. What I would like to do is somehow automatically generate a shareable link for each NEW file that gets added and send it to an email address (may or may not be a Gmail address).
Is this something that I can use Google Apps Scripts for? I tried looking into batch files first but I can't generate the shareable link automatically (or couldn't figure out how).
I don't have any code yet, just looking at potential approaches.
Thanks in advance!
Yes almost everything is possible in GAS. However, you are likely to find better answers when you post some code that you have tried yourself before asking the answer here.
However, if the machine automatically saves the files in a folder in google drive you can scan that folder with a script and find the links. Attach a trigger to it with a, for example, 5 minute interval and write those links on a spreadsheet.
an example:
function links(){
var sheet = SpreadsheetApp.getActive.getActiveSpreadsheet();
var folder = DriveApp.getFolderById('put google folder id here');
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
var vals = file.getUrl();
sheet.getRange(your range you want to paste the link).setValues(vals);
}
}
This will find the links of all the files in the folder and paste that onto a google spreadsheet where the code is linked to.
Use that spreadsheet as a database and send an email by using that database.

Convert Google Sheets to .xls

Would anyone have any pointers as to how to convert a Google sheets file to a .xls file through Google App Script?
Many thanks
Here's what I theorized, but the logic is flawed. I've also attempted the Blobs approach as well and it seems most files are defaulted to application/pdf.
function gs2xls() {
var gSheets = DocsList.getFilesByType('spreadsheet');
for(var i = 0; i < gSheets.length; i++){
var gSheetFile = gSheets[i]; //File
var gSheetSS = SpreadsheetApp.open(gSheetFile); //Spreadsheet of gs file
var gSheet = gSheetSS.getActiveSheet();
var xlsSS = SpreadsheetApp.create(gSheetFile.getName() + ".xls");
xlsSS.setActiveSheet(gSheet);
}
}
Google Apps Script can't export anything else than pdf natively but the document API does so you can use urlFetch with parameters to get what you want.
The code is shown with explanations in this post : Google apps script to email google spreadsheet excel version
It works pretty well.
That approach will never work because:
1) You are creating and empty google spreadsheet, not a file of type xls.
2) you are setting as active sheet an invalid sheet (from another spreadsheet whivh is not what setactivesheet does).
The most you will be able to achieve is to show the user an export link that downloads the file as xls. Google how to make the export link.