Google Script check a column if contains a certain word - function

I am new to Google Scripting.
I created a script where Google Spreadsheet should connect to GMail. Everything is working well.
My problem is, I need to check if an email content has the word "ORDER". If yes, it should get the word "ORDER" and the numbers after it.
For example, an email contains "ORDER 90104" in the message body, then the Google script should insert ORDER 90104 to a column in the sheet. An example email could be:
Hi, the customer is requesting for ORDER 90104. Thanks.
Is this even possible? As of now, I used getPlainBody() and I can get all the contents of the email and put it in a column. My plan was to check that column and look for the word ORDER. Though I can't find/end with a solution for it.
Here's my working code getting the email content of the 1st three emails:
function getGMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var threads = GmailApp.getInboxThreads(0,3);
cell = sheet.getRange("A1");
for (var i = 0; i < threads.length; i++) {
threadMessage = threads[i].getMessages();
var emailContent = threadMessage[0].getPlainBody();
cell.offset(i,0).setValue(emailContent);
}
}
Any advice or comments will be greatly appreciated.
Thanks!

Hello theladydevbugger,
As you didn't gave a lot of code my answer will be quite short: yes you can do that!
How: use a regexp: /ORDER [0-9]+/g.
How to use the regexp: bellow a sample code
var emailBody = yourMail.getPlainBody(); // supposing "yourMail" is the mail you retrieved
var isThereAnyOrder = false;
if(mailBody.search(/ORDER [0-9]+/g)>-1){
isThereAnyOrder=true;
var order=mailBody.match(/ORDER [0-9]+/g)>-1)[0];
Logger.log(order);
// do something with the order
}
else{
// there is no order do nothing
}

Related

getting Exception: Invalid ID error, when using getFileById

I am trying to use a script from a tutorial online that will put URLs in a google forms response sheet so I can go back and edit responses after they have been submitted.
The script comes from this guy https://www.youtube.com/watch?v=nqOE_FIMd_w
and his instructions are here: https://docs.google.com/document/d/1m9V_AHZdA24pUAR1xGxQNt_y3k7J9RKoSG5v_9oFvcU/edit
here is the script from the tutorial:
function assignEditUrls() {
var form = FormApp.openById('Your form ke goes here');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Your responses Google Sheet name goes here - The tab name, not the file name');
var data = sheet.getDataRange().getValues();
var urlCol = Column number where URLs get entered goes here;
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
It seems all simple enough, but the script keeps giving me an error:
Invalid ID (line 2, file "getEditLinks")
Seems to be a problem with the document key.
I have already given the script permission and I have concentrated my attemtps to resolve this by grabbing different parts of this URL for the file. (I remember that Google used to need the whole URL at some point in the past)
Mine is
*https://docs.google.com/spreadsheets/d/1pKmad.....VtT3GaM/edit#gid=1905774080*
(where ..... is more of the doc key. I am not putting the whole lot for security reasons)
According to the tutorial, and all other research into this, it seems this part is the correct part from the URL to use.
1pKmad.....VtT3GaM
But this is what bring the error.
I tried the whole URL, the URL just up to the doc key part, and a few other subsets of this, but none work.
Can anyone see what I am doing wrong here?
Issue:
Based on your description you are trying to access a spreadsheet file by its id but you are using FormApp.
Instead you should be using SpreadsheetApp instead:
var form = SpreadsheetApp.openById('1pKmad.....VtT3GaM'); // form is now a spreadsheet object
but the new issue now is that the variable is not form anymore but a spreadsheet object and as a result you will get other errors down the road when calling form.getResponses().
Solution:
You need to use your existing script and put the id of the form instead of the spreadsheet, which can be found on the form url:
var form = FormApp.openById('Form ID here not Spreadsheet ID');
Note:
The form url looks like this:
https://docs.google.com/forms/d/formID/edit
and you can find the form that is attached to the spreadsheet file by the spreadsheet file menu:

Is it even possible to copy data from one sheet to another with a script? ImportRange style?

Ive searched for 2 days, can't seem to find the answer or anyone that is even doing something kinda like this. I am trying to bring my employees sheets over to my "Master sheet" with a script. I need to keep the formatting and the notes in the cells.
Best I can find is I can open their spread sheets and copy it to my master, but for 8 employees this will be a pain if I need to do this multiple times a day. I would like to just build a function that I can run my script from the "master sheet" and have it write over the last data in their tab. But I want to be able to do this from within my master sheet. I am the owner of all the sheets but this is becoming a pain.
function copyCell() {
var os = SpreadsheetApp.openById('1n4iFXGuC7yG1XC-UIbuT9VrQ7rJWngPkDCv0vsvDed4');
var sheets = os.getSheets();
var existingNote;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var jobnumber = sheets.getRange("C2:C").getValues();
for (var i = 0; i < jobnumber.length; i++)
if (jobnumber[i][0] == sheets){
existingNote = sheets.getRange("C" + (i+2)).getNote();
sheets.getRange("C" + (i+2)).ss.setNote(existingNote);
}
};
Someone please let me know if it is possible and maybe reference a script I can see to be able to modify to fit my needs. Thanks for any help.
This is a possible solution for copying the notes associated with a range of cells. And pasting them onto a similar-sized range of cells.
To copy the notes you can use getNotes(). Docs here.
To paste the notes you can use setNotes(). Docs here.
Ths sample code in this documentation is pretty good if you need to add it into your script.
If you have a script you'd like to share am happy to help you make it work properly.
Edit
Something like this:
function transferNotes() {
// Get notes (not comments) from the source spreadsheet
var sourceSpreadheet = SpreadsheetApp.openById('ID_of_source_spreadsheet');
var sourceTab = sourceSpreadheet.getSheetByName('Name_source_tab');
var sourceRange = sourceTab.getRange('Source_range_address'); // e.g. "A:D"
var notes = sourceRange.getNotes();
// Post the notes to the target spreadsheet
var targetSpreadheet = SpreadsheetApp.openById('ID_of_target_spreadsheet');
var targetTab = targetSpreadheet.getSheetByName('Name_target_tab');
var targetRange = targetTab.getRange('Target_range_address'); // Should be the same dimensions as sourceRange
targetRange.setNotes(notes);
}

G.A.S code to limit a pdf generated from a google sheet only to the rows that have data

I use the following Google Script Code to generate a pdf of a google sheet and send it through email. The code works fine except that the generated pdf includes too many blank pages. How can I limit the generated pdf to only the sheet rows that contain data?
function emailReport() {
readyForExport();
var spreadsheet = SpreadsheetApp.getActive();
var subject = spreadsheet.getRange("U1:U1").getValues();
var emailTo = spreadsheet.getRange("V1:V1").getValues();
var message = spreadsheet.getRange("W1:W1").getValues();
var fileName = spreadsheet.getRange("X1:X1").getValues();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName("Students"));
var pdf = DriveApp.getFileById(spreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:fileName[0][0],content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
};
Thanks in advance.
I finally managed to write a code that can successfully remove the empty pages of my pdf attachment by first removing the empty rows from the sheet. :)
I intentionally wrote the code in a way to leave just a single empty row at the end to make it clear to the user that no other data exists in the succeeding rows.
I had to solve a number of bugs because the code ran into errors depending on the number of empty rows that already existed on the page. Finally I managed to deal with all the bugs and come up with a code than runs sleekly and considers all the exceptional cases. :)))
Here is the code:
var firstDelRow = spreadsheet.getSheetByName('Students').getLastRow()+2;
var lastDelRow = spreadsheet.getSheetByName('Students').getMaxRows();
var rowDif = lastDelRow-firstDelRow+1;
if (rowDif == -1) {
spreadsheet.getSheetByName('Students').insertRowAfter(firstDelRow-2);
};
if (rowDif >= 1) {
spreadsheet.getSheetByName('Students').deleteRows(firstDelRow, rowDif);
};

Google App Script to sync gmail inbox with sheets

I have a script pulling out data from a gmail account. The script scans the inbox for mails and finds the relevant lines of text and puts it in a Google sheet.
The email looks something like:
Vehicle: 5761364, Position: (URL to Google Maps)
The script i use to get the data to sheets is:
function processInboxToSheet() {
var start = 0;
var threads = GmailApp.getInboxThreads(start, 100);
var sheet = SpreadsheetApp.getActiveSheet();
var result = [];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
var content = messages[0].getPlainBody();
if (content) {
var tmp;
tmp = content.match(/Vehicle:\s*([A-Za-z0-9\s]+)(\r?\n)/);
var username = (tmp && tmp[1]) ? tmp[1].trim() : 'No vehicle';
tmp = content.match(/Map Link:\s*([A-Za-z ][A-Za-z0-9!##$%?=^.,:&*/ ]+)/);
var comment = (tmp && tmp[1]) ? tmp[1] : 'No url';
sheet.appendRow([username, comment]);
Utilities.sleep(500);
}
}
};
Would it be possible to make a kind of synchronization function, where the Google sheet gets updated automatically with the emails in the inbox. Right now it makes duplicates every time it runs.
Also, could someone tell me if it is possible to get the script to delete the lines created if the email is deleted. So the sheet list always is in sync with the inbox?
Please ask me if it does not make sense.
To solve the issue of duplicate emails, you need to check whether a message is unread or not. If it is unread, then read it and make it as read afterwards. I have made video series on YouTube to explain how this is possible and published the full code on github. You may watch it here:
https://youtu.be/nI1OH3pAz6s?t=9
You can also get the full code from GitHub from the following link:
GitHub: Get Gmail Emails into Google Sheet
GitHub: Extract Body Contents from Gmail Emails
You could run your script from a timebased trigger and if you just rewrote the entire sheet each time then that would take care of eliminating the entries from deleted emails. If you could add the received date to the spreadsheet then you could order them by date.

Google App Script- Docs/images in tables?

I have searched and searched for the syntax to place an image in a table cell with Google App Script in a Google Doc (not Sheet). This is what I am trying to do:
var resp01 = UrlFetchApp.fetch("http://www.example.com/image01.png");
var resp02 = UrlFetchApp.fetch("http://www.example.com/image02.png");
var cells = [[resp01.getBlob()], [resp02.getBlob()]];
copyBody.appendTable(cells);
This yields simply the word "Blob" in my table.
I can do this all day long with a paragraph:
Body.getChild(x).asParagraph().appendInlineImage(resp01.getBlob());
But for some reason, the "parallel" syntax in a table won't cut it? Does anyone know what I am missing?
Thank You
You need to call TableCell's insertImage() method and provide the child index and the blob source of the image as parameters.
Hope that helps!
Thank You for the input KRR.
I was able to get my project where I wanted it to go, part of which involved inserting images in a table in a Google Doc using Google App Script. After much reading, I settled on the syntax that follows. I hope this helps anyone else trying to learn:
function createDoc() {
var doc = DocumentApp.create('Sample Document');
var body = doc.getBody();
var resp01 = UrlFetchApp.fetch("http://www.cincinnati-oh.gov/cityofcincinnati/assets/Image/Logos/cityofcincinnati.png");
var rowsData = [["City of Cincinnati IMAGE:", ""]];
table = body.insertTable(1, rowsData);
var row = table.getRow(0);
var cell = row.getCell(1);
cell.appendImage(resp01.getBlob());
}