Extracting Google Meet URL from Google Calendar API [duplicate] - google-apps-script

I want to create a line notify which can send the event detail from my google calendar everyday.
I can get the title, description, location...etc, but I don't see the conference data in calendar API.
I use Google Apps Script to run the code.
Here is my code.
const Now = new Date();
const Start = new Date(new Date().setHours(0, 0, 0, 0));
const End = new Date(new Date().setHours(23, 59, 59, 999));
const calendarData = calendar.getEvents(Start, End);
function Notify() {
var NotifyContents = '';
var i = 1;
calendarData.forEach(item =>{
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i+". "+ item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n": "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i+". "+ item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
if (typeof NotifyContents === 'string' && NotifyContents.length === 0) {
return;
}
NotifyTokens.forEach(function(value){
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", {
"method" : "post",
"payload" : {"message" : NotifyContents},
"headers" : {"Authorization" : "Bearer " + value}
});
});
}
Reference - Calendar API Link

In order to retrieve the meet link from the event, it seems that in the current stage, Calendar API is required to be used. When this is reflected in your script, how about the following modification?
Modified script:
Before you use this script, please enable Calendar API at Advanced Google services.
From:
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i + ". " + item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
To:
const eventList = Calendar.Events.list(calendar.getId(), { timeMin: Start.toISOString(), timeMax: End.toISOString(), maxResults: 2500 }).items.reduce((o, e) => (o[e.id] = e.conferenceData.entryPoints.map(({ uri }) => uri).join(","), o), {});
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
var eventId = item.getId().split("#")[0];
NotifyContents += eventList[eventId] != "" ? ("\n" + i + ". " + eventList[eventId]) : ("No Conference\n");
i++;
}
});
In this modification, it supposes that calendar has already been declaread. Please be careful about this.
Reference:
Events: list

Related

spreadsheets.values.batchUpdate() completes successfully, but the destination sheet is still empty

The script doesn't throw any errors, but rarely completely works - i.e. complete successfully with all of the expected data in the destination tab. The results breakdown is generally:
no results in the destination sheet - this happens ~50-75% of the time
all of the results in the destination sheet, except in cell A1 - ~25% of the time
100% completely works - ~15-25% of the time
code snippet of the batchupdate() call
var data = [
{
range: (ss.getSheetName() + "!A1:AQ" + valueArray.length)
,values: valueArray
}
];
const resource = {
valueInputOption: "RAW"
,data: data
};
Logger.log("request = " + JSON.stringify(resource)
+ "\n" + "valueArray = " + valueArray.length
);
Logger.log(" Sheets.Spreadsheets.Values.batchUpdate(params, batchUpdateValuesRequestBody) ");
var response = Sheets.Spreadsheets.Values.batchUpdate(resource, spreadsheetId);
Logger.log("response = " + response.toString());
and the response
response = {
"totalUpdatedRows": 37776,
"responses": [{
"updatedCells": 1482389,
"updatedRange": "BatchUpdateDestination!A1:AP37776",
"updatedColumns": 42,
"spreadsheetId": "adahsdassadasdsadaasdasdasdasdasdasdasdasdas",
"updatedRows": 37776
}
],
"spreadsheetId": "adahsdassadasdsadaasdasdasdasdasdasdasdasdas",
"totalUpdatedCells": 1482389,
"totalUpdatedSheets": 1,
"totalUpdatedColumns": 42
}
Its obviously a very large dataset, but I've pruned the destination spreadsheet to ensure there is ample room for the data, and from earlier testing, I believe that a specific size error would be returned if that was the blocker.
How can I troubleshoot, or better yet, prevent these incomplete executions? is there any way to inspect the batch jobs that these requests initiate?
Answering my own question...
After toiling with this a little more, I couldn't figure out any way to troublshooting or inspect the odd, seemingly successfully batchUpdate() jobs. Thus, I resorted to batching the batchUpdate() calls into batches of 15000. This seems to work consistently, though maybe a bit slower:
// This is the very large 2D array that is populated elsewhere
var valueArray = [];
var maxRows = valueArray.length;
var maxCols = valueArray[0].length;
var batchSize = 15000;
var lastBatchSize = 1;
for (var currentRowCount = 1; currentRowCount <= maxRows; ++currentRowCount) {
if( currentRowCount % batchSize == 0
|| currentRowCount == maxRows
)
{
Logger.log("get new valuesToSet");
valuesToSet = valueArray.slice(lastBatchSize - 1, currentRowCount -1);
var data = [
{
range: (ss.getSheetName() + "!A" + lastBatchSize + ":AQ" + (lastBatchSize + valuesToSet.length))
,values: valuesToSet
}
];
const resource = {
valueInputOption: "RAW"
,data: data
};
Logger.log("request = " + JSON.stringify(resource).slice(1, 100)
+ "\n" + "valuesToSet.length = " + valuesToSet.length
);
try {
var checkValues = null;
var continueToNextBatch = false;
for (var i = 1; i <= 3; ++i) {
Logger.log("try # = " + i
+ "\n" + " continueToNextBatch = " + continueToNextBatch
+ "\n" + " make the batchUpdate() request, then sleep for 5 seconds, then check if there are values in the target range."
+ "\n" + " if no values, then wait 5 seconds, check again."
+ "\n" + " if still not values after 3 tries, then resubmit the batchUpdate() requestion and recheck values"
+ "\n" + "range to check = " + "A" + lastBatchSize + ":AQ" + lastBatchSize
);
Logger.log(" Sheets.Spreadsheets.Values.batchUpdate(params, batchUpdateValuesRequestBody) ");
var response = Sheets.Spreadsheets.Values.batchUpdate(resource, spreadsheetId);
Logger.log("response = " + response.toString());
/// loop and check for data in newly written range
for (var checks = 1; checks <= 3; ++checks) {
Utilities.sleep(5000);
var checkValues = ss.getRange(("A" + lastBatchSize + ":AQ" + lastBatchSize)).getValues();
Logger.log("new cell populated - checks # = " + checks
+ "\n" + "range to check = " + "A" + lastBatchSize + ":AQ" + lastBatchSize
+ "\n" + "checkValues.length = " + checkValues.length
+ "\n" + "checkValues = " + checkValues
);
if(checkValues.length > 1)
{
Logger.log("checkValues.length > 1, so continue to next batch"
+ "\n" + "range to check = " + "A" + lastBatchSize + ":AQ" + lastBatchSize
+ "\n" + "checkValues.length = " + checkValues.length
+ "\n" + "checkValues = " + checkValues
);
continueToNextBatch = true;
continue;
}
else
{
Logger.log("checkValues.length is still not > 1, so try the request again"
+ "\n" + "range to check = " + "A" + lastBatchSize + ":AQ" + lastBatchSize
);
}
}
if(continueToNextBatch)
{
continue;
}
}
}
catch (e) {
console.error("range.setValues(valuesToSet) - yielded an error: " + e
+ "\n" + "valuesToSet = " + valuesToSet.length
+ "\n" + "maxRows = " + maxRows
+ "\n" + "maxCols = " + maxCols
+ "\n" + "currentRowCount = " + currentRowCount
+ "\n" + "current range row start (lastBatchSize) = " + lastBatchSize
+ "\n" + "current range row end (j - lastBatchSize) = " + (currentRowCount - lastBatchSize)
);
}
lastBatchSize = currentRowCount;
}
}

Convert a JSON object to a particular CSV format

I want to convert this
{
"Name A":{
"Name B":{
"Name C":"Value C",
"Name D":"Value D",
"Name E":"Value E"
}
}
}
to this
Name A,,,
,Name B,,
,, Name C,Value C
,, Name D,Value D
,,Name E,Value E
It will look like this when opened in excel
I'm attempting to achieve this by running a small script, but before that I wanted to check if there is any node package or tool that can achieve this easily. Any clues?
Might be you can try with this npm module csvjson.
The link is here:- https://www.npmjs.com/package/csvjson
I solved this by writing my own script. I had to tweak a little to fit my necessity according to the format of the data. It is not the most elegant solution. It was quick dirty solution I got working. Still it's a good reference if anyone wants to try writing their own script to convert JSON to CSV
var fs = require('fs');
var file = 'templateEn.json';
var content = fs.readFileSync(file, { encoding: 'binary' });
var obj = JSON.parse(content);
var jsonString = ""
var lineEnd = "\r\n";
var firstLevelKeys = Object.keys(obj);
jsonString += firstLevelKeys[0] + ",,,,," + lineEnd;
var secondLevelKeys = Object.keys(obj["en"]);
secondLevelKeys.forEach(key => {
jsonString += ',' + key +',,,,'+ lineEnd
var thirdLevelKeys = Object.keys(obj["en"][key]);
thirdLevelKeys.forEach(key2=>{
if (typeof obj["en"][key][key2] === "string"){
jsonString += ",," + key2 + ',"' + obj["en"][key][key2]+'",,'+ lineEnd;
}
else if (typeof obj["en"][key][key2] === "object"){
var fourthLevelKeys = Object.keys(obj["en"][key][key2]);
jsonString += ',,' + key2 + ',,,' + lineEnd
fourthLevelKeys.forEach(key3 => {
if (typeof obj["en"][key][key2][key3] === "string") {
jsonString += ",,," + key3 + ',"' + obj["en"][key][key2][key3] + '",' + lineEnd;
}
else if (typeof obj["en"][key][key2][key3] === "object") {
var fifthLevelKeys = Object.keys(obj["en"][key][key2][key3]);
jsonString += ',,,' + key3 + ',,' + lineEnd
fifthLevelKeys.forEach(key4 => {
if (typeof obj["en"][key][key2][key3][key4] === "string") {
jsonString += ",,,," + key4 + ',"' + obj["en"][key][key2][key3][key4] + '"' + lineEnd;
}
})
}
})
}
});
});
fs.writeFileSync("generated.csv", jsonString, "utf8");

Js if is not work in setInterval()

Hello!
I have This in my website:
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
alert('In next prompt enter "admin".')
var admin = prompt('Name?')
docCookies.setItem('name',admin);
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
But this is not work:
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
Why thi is not work:
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
What in page not work and why?
I
<script type="text/javascript">
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
alert('In next prompt enter "admin".')
var admin = prompt('Name?')
docCookies.setItem('name',admin);
setInterval(function() {if (docCookies.getItem('name')){}else{var a = 2}}, 1000)
The variable is declared locally in the function, so it only exists inside that scope, and only while the function is running.
Declare the variable in the global scope, so that you can set it and read it anywhere:
var a;
setInterval(function() {
if (!docCookies.getItem('name')) {
a = 2;
}
}, 1000)

Get total rows filtered by if() statement in google apps scripts

I've got this fn().
Is there any simple way to return the number of filtered rows by this conditional statement in Google app scripts?
function getGlobers(globers, project){
var body = "";
var data = globers.getValues();
for( i = 0; i < data.length; i++ ){
if( data[i][2] == project ){
body += "<tr><td style=" + STYLE.TD + ">" + data[i].join("</td><td style=" + STYLE.TD + ">") + "</td></tr>";
}
}
return body;
}
Thanks.
for example (see comments in code)
function getGlobers(globers, project){
var body = "";
var n = 0; // use a variable to count
var data = globers.getValues();
for( i = 0; i < data.length; i++ ){
if( data[i][2] == project ){
n++;// increment each time condition is true
body += "<tr><td style=" + STYLE.TD + ">" + data[i].join("</td><td style=" + STYLE.TD + ">") + "</td></tr>";
}
}
return [body,n];// return an array of 2 values
}
Usage :
var result = getGlobers(range,project);
Logger.log('array result = '+result);
Logger.log('body (string) = '+result[0]);
Logger.log('length (integer) = '+result[1]);
note : instead of an array you could also return an object with 2 properties... a matter of choice.
EDIT : an example using object properties :
function getGlobers(globers, project){
var body = "";
var n = 0;
var result = {};
var data = globers.getValues();
for( i = 0; i < data.length; i++ ){
if( data[i][2] == project ){
n++;
body += "<tr><td style=" + STYLE.TD + ">" + data[i].join("</td><td style=" + STYLE.TD + ">") + "</td></tr>";
}
}
result['body'] = body;
result['length'] = n;
return result;
}
Usage :
var result = getGlobers(range,project);
Logger.log('body = '+result.body);
Logger.log('length = '+result.length);

AS: if statement evaluating incorrectly

I have a very simple piece of logic as follows:
var divert:Number = 0;
for (var connection in _connections) {
trace("target: " + _connections[connection].target + " || i: " + (i + 1));
if(int(_connections[connection].target) != (i + 1)) {
trace("bad connection");
divert++;
}
}
The problem is that when i + 1 and int(_connections[connection].target) are equal the if statement is returning true as can be seen in the output of my trace() statements below:
target: 0 || i: 1
bad connection
target: 1 || i: 1
bad connection
Can anyone see what could be causing this to happen?
EDIT: The function this is contained in as per request:
public function loadListener(i:Number, onProgress:Function, onComplete:Function):Void
{
trace("load listening to: "+i);
trace("next in queue: " + _queues["lower"][0] + " | " + _queues["upper"][0]);
_functions[i] = {onProgress:onProgress, onComplete:onComplete};
if (_queues["lower"][0] != i + 1 || _queues["upper"][0] != i + 1) {
var divert:Number = 0;
for (var connection in _connections) {
trace("target: "+_connections[connection].target+" || i: "+(i+1));
if(int(_connections[connection].target) != (i + 1)) {
trace("bad connection");
divert++;
}
}
if (divert == _connections.length) {
_diversion = i + 1;
trace("divert: "+divert+" || connections: "+_connections.length);
}
}
}
First of all, why use a for(var) loop when you can use
var divert:Number = 0;
for each(var connection in _connections) {
trace("target: " + connection.target + " || i: " + (i + 1));
if(int(connection.target) != (i + 1)) {
trace("bad connection");
divert++;
}
}
To debug further, replace
trace("target: " + connection.target + " || i: " + (i + 1));
with
trace("target: " + int(connection.target) + " || i: " + (i + 1));
If this traces zero, you know where the issue is.
You could try doing
if(connection.target.toString() != (i + 1).toString()) {