Write from Google Firebase to Google Sheets using Google Apps script - google-apps-script

Trying to retrieve form entries which are stored in google firebase under the node called entries and append to a google sheet using the script editor in google sheets.
I have added the FirebaseApp library to google sheet script editor. Then my code looks like this:
function getAllData() {
var firebaseUrl = "https://myapp.firebaseio.com/";
var secret = "pCOCwKCC582jpqdZe2EqPqnW3IAd3UyO9oB4uaEL2";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var data = base.getData();
Logger.log(data);
}
when I run this nothing happens. Any ideas?
Next I need to add the returned data from firebase to the google sheet. I was using this code to do this via the sheets api, however I'm not sure how this works in the google script editor?
function addEntries() {
gapi.client.sheets.spreadsheets.values.append({
spreadsheetId: '10lyQpQtEA7euCfdU2isrqB_bgPuy-eSbW74h7oDP3ko',
range: "Sheet1!A1:D100",
majorDimension: "ROWS",
"values": [
["testa", "testb", "testc", "testd"]
],
valueInputOption: 'USER_ENTERED'
}).then(function(response) {
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}

I'm using the newest Firebase version. This snippet code works for me.
function getFacturasClientesExistentes() {
var firebaseUrl = "https://test.firebaseio.com/FacturasBLP/clienteExistente";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var data = base.getData();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Facturas Clientes Existentes");
var num = 2;
range = sheet.getRange("A"+num+":F"+num+"");
for(var i in data) {
var values = [
[ data[i].fecha, data[i].sucursal, data[i].cantidad, data[i].cliente, data[i].correo, data[i].estatus ]
];
range.setValues(values);
num += 1;
range = sheet.getRange("A"+num+":F"+num+"");
}
}
Some notes:
I have previously write the headers for my data in the spreadsheet
In the line range = sheet.getRange("A"+num+":F"+num+""); from A to F I have my headers

I hope this helps someone, this worked for me.
function writeSheets() {
var ss = SpreadsheetApp.openById("10lyQpQtEA7euCfdU2isrqB_bgPuy-eSbW74h7oDP3ko");
var sheet = ss.getSheets()[0];
var firebaseUrl = "https://myapp.firebaseio.com/";
var secret = "pCOCwKCC582jpqdZe2EqPqnW3IAd3UyO9oB4uaEL2"; // get this from firebase project settings
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var data = base.getData();
var keys = Object.keys(data.entries);
var sheetRow = [];
var entryKeys;
for (index in keys) {
sheetRow = [];
entryKeys = Object.keys(data.entries[keys[index]])
for (i in entryKeys) {
sheetRow.push(data.entries[keys[index]][entryKeys[i]]);
}
//Logger.log(sheetRow);
sheet.appendRow(sheetRow);
}
}
Note: in order for this code to work, you need to install the firebaseapp library in the script editor as per these instructions, https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase

Related

Copy data from download URL using Google Script

I'm new to App scripts and need help with copying the data to spreadsheet from URL.
However, URL is not a website but link which after clicking with directly download csv file into the computer. Also, its not ending with .csv as I have seen in other examples here.
URL basically coming to my inbox at a specific time. I'm trying to use Fetch URL but its not working at all.
Sample URL -
https://docs.google.com/spreadsheets/d/1oPUPPUmy7psliSznUItT0DnHvilXwZHzyrmdyHpHi18/export?format=csv
function ABC () {
const searchQuery = 'XYZ';
const threads = GmailApp.search(searchQuery, 0,1);
const urls = [];
threads.forEach(thread => {
const messages = thread.getMessages();
messages.forEach(message => {
const body = message.getBody();
var re = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’]))/i;
const match = body.match(re);
if (match) { urls.push(match[1]); }
});
}) ;
Logger.log(urls);
url = urls.toString().replace("[","").replace("]","") ;
Logger.log(url);
function getData() {
var attValue = '';
// making a call to the target website
var response = UrlFetchApp.fetch(url);
//logging response from target website - In Script Editor > View > Logs
Logger.log(response.getContentText());
//parsing the response data from website
//https://developers.google.com/apps-script/reference/url-fetch/http-response
var rawData = response.getContentText();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[1]);
var cell = sheet.getRange(1, 1);
cell.setValue(rawData);
}
};
Kindly help so that I can copy the data directly into spreadsheet or store the file in Google Drive with filename as combination of text and date.
Thanks
SUGGESTION
You can try the tweaked script below.
In my understanding, here is your goal:
Get your email messages that contain URLs (CSV file) via "XYZ" search terms.
Process the URL using URLFetchApp service
Place the CSV data into your second sheet tab.
Note: If there's anything else missing or something may have been misunderstood, feel free to let me know.
Tweaked Script
function ABC() {
/**TWEAKED: Created a function call method called "getData" */
const url = {
getData: function () {
const searchQuery = 'XYZ';
const threads = GmailApp.search(searchQuery, 0, 1);
const urls = [];
threads.forEach(thread => {
const messages = thread.getMessages();
messages.forEach(message => {
const body = message.getBody();
var re = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’]))/i;
const match = body.match(re);
if (match) { urls.push(match[1]); }
});
});
Logger.log(urls);
/**TWEAKED: Instead of using the redundant replace method,
* used "regex" inside a single replace method to replace
* all [ and ] characters */
var geturl = urls.toString().replace(/\[|]/gm, "");
console.log(geturl)
return geturl;
}
}
var attValue = '';
/**TWEAKED: Call the "url" variable's "getData" function that will return the URL */
var response = UrlFetchApp.fetch(url.getData.call());
//logging response from target website - In Script Editor > View > Logs
Logger.log(response.getContentText());
//parsing the response data from website
//https://developers.google.com/apps-script/reference/url-fetch/http-response
var rawData = response.getContentText();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[1]);
var cell = sheet.getRange(1, 1);
cell.setValue(rawData);
};
Demonstration
After running the ABC() function on the Apps Script editor, the second sheet tab gets populated with the CSV data:
The Apps Script execution log view
References:
JavaScript Function call()

How to remove Google Sheets Chart from Google Slide if Chart has no data

I am inserting an embedded chart from Sheets to Slides using app script. But I would like to remove the chart from the slide if on Google Sheets the chart is empty/has no data.
I want to remove the chart from slides ONLY when it doesn't have data. But keep the chart if there is data
Can you please help me add the right line that would create this condition ?
This is my chart code:
function onOpen() {
// Get the Ui object.
var ui = SpreadsheetApp.getUi();
// Create a custom menu.
ui.createMenu('Present Data')
.addItem("Generate Report","generateLandingPagesReport")
.addToUi();
}
function generateLandingPagesReport() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Copy of Overall Performance 1');
var values = sheet.getRange('A2:J23').getValues();
var chartRegion1 = sheet.getCharts()[0];
var chartGender1 = sheet.getCharts()[1];
// Access the template presentation
var templateId = "1bXAYGCKkpZhksXz8gTCgFYbNoI1BIhAZakd68VlXHeo";
var template = SlidesApp.openById(templateId);
var templateSlides = template.getSlides();
// Create a Slides presentation, removing the default
// title slide.
var presentationTitle =
ss.getName() + " Presentation";
var slides = SlidesApp.create(presentationTitle);
var defaultSlides = slides.getSlides();
defaultSlides.forEach(function(slide) {
slide.remove()
});
var defaultSlide = defaultSlides [1];
// Insert slides from template
var index = 0;
templateSlides.forEach(function(slide) {
var newSlide = slides.insertSlide(index);
var elements = slide.getPageElements();
elements.forEach(function(element) {
newSlide.insertPageElement(element);
});
index++;
});
values.forEach(function(page){
if(page[0]){
var landingPage = page[0];
var sessions = page[1];
var newSessions = page[2];
var pagesPer = page[5];
var goalRate = page[7];
var goalValue = page[9];
// Insert slides from template
var index = 0;
templateSlides.forEach(function(slide) {
var newSlide = slides.insertSlide(index);
var elements = slide.getPageElements();
elements.forEach(function(element) {
newSlide.insertPageElement(element);
});
index++;
});
defaultSlides = slides.getSlides(); //update the slides array for
indexes and length
defaultSlide = defaultSlides[1];
newSlide = defaultSlide;
newSlide2 = defaultSlides[2];
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}',landingPage);
shape.getText().replaceAllText('{{sessions}}',sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
shape.getText().replaceAllText('{{pages per session}}',pagesPer);
shape.getText().replaceAllText('{{goal rate}}',goalRate);
shape.getText().replaceAllText('{{goal value}}',goalValue);
})
var shapes = (newSlide2.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}',landingPage);
shape.getText().replaceAllText('{{sessions}}',sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
shape.getText().replaceAllText('{{pages per session}}',pagesPer);
shape.getText().replaceAllText('{{goal rate}}',goalRate);
shape.getText().replaceAllText('{{goal value}}',goalValue);
});
presLength = defaultSlides.length;
newSlide.move(presLength);
newSlide2.move(presLength);
defaultSlides[0].remove();
defaultSlides[3].remove();
} // end our conditional statement
}); //close our loop of values
//Get the charts
var defaultSlides=slides.getSlides();
var defaultSlide = defaultSlides [1]
var position = {right: 490, bottom: 190};
var size = {height: 140, width: 230};
defaultSlide.insertSheetsChart(
chartRegion1,
position.right,
position.bottom,
size.width,
size.height);
var defaultSlides=slides.getSlides();
var defaultSlide = defaultSlides [1]
var position = {right: 200, bottom: 190};
var size = {height: 140, width: 230};
defaultSlide.insertSheetsChart(
chartGender1,
position.right,
position.bottom,
size.width,
size.height);
// Create and display a dialog telling the user where to
// find the new presentation.
var slidesUrl = slides.getUrl();
var html = "<p>Find it in your home Drive folder:</p>"
+ "<p><a href=\"" + slidesUrl + "\" target=\"_blank\">"
+ presentationTitle + "</a></p>";
SpreadsheetApp.getUi().showModalDialog(
HtmlService.createHtmlOutput(html)
.setHeight(120)
.setWidth(350),
"Report Generated!"
);
}
Thank you for your help.
I believe your current situation and your goal are as follows.
You have Google Slides including some charts.
When the chart is "No data", you want to remove the chart from the Google Slides.
You want to achieve this using Google Apps Script.
From your sample Spreadsheet including the sample "No data" chart, your "No data" chart has no values.
In this case, how about the following sample script?
Sample script:
Please copy and paste the following script to the script editor of the Google Spreadsheet including the charts. And, please set the Google Slides ID to presentationId.
function myFunction() {
const presentationId = "###"; // Please set the Google Slides ID.
// 1. Retrieve the charts with "No data".
const ss = SpreadsheetApp.getActiveSpreadsheet();
const obj = ss.getSheets().reduce((o, sheet) => {
sheet.getCharts().forEach(chart => {
const check = chart.getRanges().some(e => {
const temp = e.getDisplayValues();
return temp[0].map((_, c) => temp.map(r => r[c])).some(col => col.join("") == "");
});
if (check) o[chart.getChartId()] = check;
});
return o;
}, {});
// 2. Remove the charts with "No data".
const slides = SlidesApp.openById(presentationId).getSlides();
slides.forEach(slide => {
slide.getSheetsCharts().forEach(chart => {
if (obj[chart.getChartId()]) chart.remove();
});
});
}
When this script is run, first, the charts of "No data" are retrieved in an object. And, using this object, the charts in Google Slides are removed.
Note:
This sample script is for your sample Spreadsheet. If the condition of "No data" is changed, this script might not be able to be used. So, please be careful about this.
References:
reduce()
forEach()
remove() of Class SheetsChart

How to Extract link from a sentence in google document with appscript

I have a table in google doc, in which I want to extract the hyperlinked text and its link using appscript
Suppose : The community is here to help you with specific coding, algorithm, or language problems.
I have a code for google spreadsheet which can extract links from the text, however the same code is not usuable in google docs.
function myFunction() {
var sheet= SpreadsheetApp.getActiveSheet();
var isCell4Blank1 = sheet.getRange("A1").isBlank();
if (!isCell4Blank1) {
var linkData = sheet.getRange("A1").getRichTextValue().getRuns().reduce((ar, e) => {
var url = e.getLinkUrl();
Logger.log(url);
if (url) {
var color = e.getTextStyle().getForegroundColor();
var startIndex = e.getStartIndex();
var endIndex = e.getEndIndex();
var text = e.getText()
//ar.push(color);
ar.push(text);
ar.push(startIndex);
ar.push(endIndex);
//ar.push(url);
}
return ar;
}, [])
}
}
How to modify it for google docs ?

Need a way to extract specific data from Firebase RealtimeDB to Google Sheets

I'm trying to transfer Firebase RealtimeDB data into Google Sheets using AppScript.
I need a way to extract ID, Department, and Surname strings from the DB while it is received as such from the Logs below.
I use .childByAutoID() which has the following effect on the DB.
My database:
Desired result in spreadsheet:
function writeSheets() {
var firebaseUrl = "<my-database>.firebaseio.com/Attendees";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var data = base.getData();
console.log(JSON.stringify(data));
var ss = SpreadsheetApp.openById("<my-spreadsheet>");
var sheet = ss.getSheetByName("Sheet1");
var num = 2;
range = ss.getRange("A"+num+":C"+num+"");
for(var i in data) {
var values = [[data[i][0], data[i][1], data[i][2]]];
range.setValues(values);
num += 1;
range = sheet.getRange("A"+num+":C"+num+"");
}
}
base.getData() reads it as:
{
"-M4PTaIESKhQZhreHSE6":
{"Department":"HR",
"ID":"1009",
"Surname":"Blanc"},
"-M4PTgaNIE8BDqAcMr5y":
{"Department":"Accounting",
"ID":"1002",
"Surname":"Sandler"},
"-M4PTmOxxNge0Xfe_ez0":
{"Department":"Creative",
"ID":"1009",
"Surname":"Tolkien"}
}
I
Logs:
[20-04-09 00:11:31:653 HKT] {"-M4PTaIESKhQZhreHSE6":{"Department":"HR","ID":"1009","Surname":"Blanc"},"-M4PTgaNIE8BDqAcMr5y":{"Department":"Accounting","ID":"1002","Surname":"Sandler"},"-M4PTmOxxNge0Xfe_ez0":{"Department":"Creative","ID":"1010","Surname":"Tolkien"}}
Use Object.values and Array.map :
const data = {
"-M4PTaIESKhQZhreHSE6":
{"Department":"HR",
"ID":"1009",
"Surname":"Blanc"},
"-M4PTgaNIE8BDqAcMr5y":
{"Department":"Accounting",
"ID":"1002",
"Surname":"Sandler"},
"-M4PTmOxxNge0Xfe_ez0":
{"Department":"Creative",
"ID":"1009",
"Surname":"Tolkien"}
};
const out = Object.values(data).map(Object.values);
//or to change order: Object.values(data).map(({Department:dp,ID,Surname:sn})=>[ID,dp,sn]);
console.info(out);

Pushing a simple Log string from a Google Ad Script to a Google Sheet

I am trying to set up a script which can push data from an App Script into a Google Sheet.
I have the script successfully logging what I want, which goes in the following format Account budget is 12344, but now I want to push this into a Google Sheet. I have set up a variable containing the URL and another variable containing the sheet name, and also a clear method to delete anything already there.
Find the code I have below:
// - The link to the URL
var SPREADSHEET_URL = 'abcdefghijkl'
// - The name of the sheet to write the data
var SHEET_NAME = 'Google';
// No to be changed
function main() {
var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = spreadsheet.getSheetByName(SHEET_NAME);
sheet.clearContents();
}
function getActiveBudgetOrder() {
// There will only be one active budget order at any given time.
var budgetOrderIterator = AdsApp.budgetOrders()
.withCondition('status="ACTIVE"')
.get();
while (budgetOrderIterator.hasNext()) {
var budgetOrder = budgetOrderIterator.next();
Logger.log("Budget Order Amount " + budgetOrder.getSpendingLimit());
}
}
Assuming you want to clear the entire Sheet every time you extract the data this should work for you. You will need to set the url and shtName variables.
function getActiveBudgetOrder() {
var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxx/';
var shtName = 'Sheet1';
var arr = [];
var sht = SpreadsheetApp.openByUrl(url).getSheetByName(shtName);
// There will only be one active budget order at any given time.
var budgetOrderIterator = AdsApp.budgetOrders()
.withCondition('status="ACTIVE"')
.get();
while (budgetOrderIterator.hasNext()) {
var budgetOrder = budgetOrderIterator.next();
arr.push(["Budget Order Amount " + budgetOrder.getSpendingLimit()]);
}
sht.clearContents();
sht.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}