Google sheet(google-spreadsheet) wrapper for javascript Error 500 internal error - google-sheets

I wanted to ask for some help.
I use for a few months a great library google-spreadsheet(https://www.npmjs.com/package/google-spreadsheet) to write data in google sheet.
all worked excellently till last week.
somehow-i don't know what could happen ( didn't change my code), but now when I try to use this library(the same error occurs also if I use python(another library).
I tried to remove some of the sheets and them its seems that it works..in order to continue, I would like to know if someone encountered this issue or how I can debug/probably some data cause to the issue...
Thanks
This is the error:
"error": {
"code": 500,
"message": "Internal error encountered.",
"status": "INTERNAL"
}
}
attached the code(although I'm almost sure it's not related to the code since other python library to google sheets cause to the same error)
AddToGoogleSheet.js
const { GoogleSpreadsheet } = require('google-spreadsheet');
const doc = new GoogleSpreadsheet('XXXXXXXXXXXXXXXXXXXXXXXXXXX');
async function ReadDate(sheetNum) {
await doc.useServiceAccountAuth(require("./keys.json"));
await doc.loadInfo();
const sheet = doc.sheetsByIndex[sheetNum];
const rows = await sheet.getRows();
console.log(rows.length);}
module.exports = {
addrowtosheet,
ReadDate
};
app.js
let sheetservice = require("./Sheets/AddToGoogleSheet");
//let os = require('os');
sheetservice.ReadDate(0)

Related

Zoho Catalyst Data Store, Functions - Unable to retrieve a row

I'm trying to get a row from datastore, while trying I've got the below error.I've included the script I'm trying.
Output:
{
"status": "failure",
"data": {
"message": "basicio Execution Time Exceeded",
"error_code": "EXECUTION_TIME_EXCEEDED"
}
}
Code Snippet :
let rowData =
{
response: "George Hamilton",
};
const https = require("https");
const axios = require("axios");
const catalyst = require("zcatalyst-sdk-node");
const app = catalyst.initialize(context);
let datastore = app.datastore();
let table = datastore.table('xxxx');
let rowPromise = table.getRow(xxxxx);
basicIO.write(rowPromise + "");
}
Zoho Catalyst Basic IO functions will have an execution timeout of maximum of 30 seconds. Missing of proper exception handling might also lead to a timeout. Enclose your code in a try catch block in order to catch the exceptions and you need to await in table.getRow() since it returns a promise and you have to resolve the promise by using .then().
let rowPromise = await table.getRow('xxxxx');
rowPromise.then((response) => {
console.log(response);
res.status(200).send(JSON.stringify(response));
}).catch((err)=> {
console.log(err);
res.status(500).send(err.toString());
})

cloud Function -> BigQuery: Permission denied while getting Drive credentials. Does work with Cloud console?

This is what I have.
For my project I have A cloud Function that gets triggered by Pub/Sub.
The function selects data from BigQuery table to which a Google sheet is connected. So my data is inside Google sheet and BiqQuery is used to query my data.
The same function the inserts the selected data into another table inside BigQuery. All the selecting and Inserting is done with BigQuery Jobs.
Here is the problem
When the function is triggered I get the following error message.
Error: Access Denied: BigQuery BigQuery: Permission denied while getting Drive credentials. at new ApiError (/workspace/node_modules/#google-cloud/common/build/src/util.js:73:15) at Util.parseHttpRespBody (/workspace/node_modules/#google-cloud/common/build/src/util.js:208:38) at Util.handleResp (/workspace/node_modules/#google-cloud/common/build/src/util.js:149:117) at /workspace/node_modules/#google-cloud/common/build/src/util.js:479:22 at onResponse (/workspace/node_modules/retry-request/index.js:228:7) at /workspace/node_modules/teeny-request/build/src/index.js:226:13 at processTicksAndRejections (internal/process/task_queues.js:95:5)
The things that do work
When the same function is run via Cloud console selecting and inserting into BigQuery table work.
Querying the Google sheet via BigQuery page inside Google Cloud does also works as it should.
What I have tried
I followed everything inside this: Querying Drive data documentation.
I have have all the required permissions.
Is this a bug or am I doing something wrong?
Edit
I forgot to add my code.
This is the part where I select the data
Something happens with the Tag_Data which triggers the catch.
const Select_Tag_Info_query = `SELECT * FROM \`project.Dataset.table\` where TagId = "${tag}"`;
console.log(Select_Tag_Info_query); // outputs: "SELECT * FROM `pti-tag-copy.ContainerData2.PTI-tags` where TagId = "tag-1"
const Tag_Data = SelectJob(Options(Select_Tag_Info_query));
console.log(`This is Tag-Data: ${Tag_Data}`); // outputs: "This is Tag-Data: [object Promise]"
Tag_Data.catch((error) => {
console.log(`Something went wrong with selecting tag data from the spreadsheet`);
console.error(error);
});
//The resolve is not called because of the error above
Promise.resolve(Tag_Data).then(function (Tag_Data) {
let returned_tag = Tag_Data.TagId;
let returnd_country = Tag_Data.Country;
let returned_location = Tag_Data.Location;
let returned_poleId = Tag_Data.PoleId;
console.log(`this is tag: ${returned_tag}`);
console.log(`this is country: ${returnd_country}`);
console.log(`this is location: ${returned_location}`);
console.log(`this is poleid: ${returned_poleId}`);
});
This is how the BigQuery Jobs function looks like.
function Options(query) {
const options = {
configuration: {
query: {
query: query,
useLegacySql: false,
},
location: 'EU'
},
};
return options;
}
// This function is for selecting the tag data from spreadsheet via bigquery
async function SelectJob(options) {
// Run a BigQuery query job.
console.log(`select job is called.`) // This part is outputed
const [job] = await bigquery.createJob(options); // something goes wrong here.
const [rows] = await job.getQueryResults();
console.log(`${rows[0]["TagId"]}`); // This part is not outputed
console.log(`${rows[0]["Country"]}`); // This part is not outputed
console.log(`${rows[0]["Location"]}`); // This part is not outputed
console.log(`${rows[0]["PoleId"]}`); // This part is not outputed
if (rows.length < 1) {
console.log("array is empty");
} else {
console.log(`selected tag data from spreadsheet`);
return {
TagId: rows[0]["TagId"],
Country: rows[0]["Country"],
Location: rows[0]["Location"],
PoleId: rows[0]["PoleId"]
}
}
}
I think something goes wrong at this part of the code inside the Select Job(). because the other console.logs are not outputed. My reason for saying that is because inside BigQuery project history I don't see the query. I only see a red circle with a white ! mark. see the photo BigQuery project history.
const [job] = await bigquery.createJob(options);
const [rows] = await job.getQueryResults();

Play example from documentation results in "Invalid Content-Type"

The example is found in documentation here: https://www.twilio.com/docs/autopilot/actions/play
The example on the site is:
exports.handler = function(context, event, callback) {
let actions = [];
let play = {
"play":
{
"loop": 2,
"url": "https://api.twilio.com/cowbell.mp3"
}
}
actions.push(play);
let respObj = {
"actions": actions
};
callback(null, respObj);
};
If you test it, it results in an error that shows in the debugger as: Invalid Content-Type.
When I call it to test it says "we're sorry, an application error has occured. good bye"
I tested out the example above and it works. Are you pointing Autopilot to this Actions URL? The red arrow points to the URL/PATH of your Twilio Function.

"ReferenceError: calendar is not defined" encountered in NodeJS but same code works in API Test Console in Google

Trying to follow this blog post Create a Smart Voicemail with Twilio, JavaScript and Google Calendar
When I run the code in Google Developer API Test Console, it works. However, the same parameters called within Twilio Function which runs NodeJS returns an error "ReferenceError: calendar is not defined"
I've made the Google Calendar events public and I've tried viewing it using the public URL and it works too. For someone reason calling it withing Twilio Functions is resulting in an error.
const moment = require('moment');
const { google } = require('googleapis');
exports.handler = function(context, event, callback) {
// Initialize Google Calendar API
const cal = google.calendar({
version: 'v3',
auth: context.GOOGLE_API_KEY
});
//Read Appointment Date
let apptDate = event.ValidateFieldAnswer;
var status = false;
const res = {
timeMin: moment().toISOString(),
timeMax: moment().add(10, 'minutes').toISOString(),
items: [{
id: context.GOOGLE_CALENDAR_ID
}]
};
console.log(res);
cal.freebusy.query({
resource: res
}).then((result) => {
const busy = result.data.calendars[calendar].busy;
console.log("Busy: " + busy);
if (busy.length !== 0) {
let respObj1 = {
"valid": false
};
console.log("Failed");
callback(null, respObj1);
} else {
let respObj1 = {
"valid": true
};
console.log("Success");
callback(null, respObj1);
}
}).catch(err => {
console.log('Error: checkBusy ' + err);
let respObj1 = {
"valid": false
};
callback(null, respObj1);
});
};
Have you encountered this before or is anyone able to identify the issue here?
Thanks
This line seems to be the issue:
const busy = result.data.calendars[calendar].busy;
As far as I can tell, calendar is never defined. This should work instead:
const busy = result.data.calendars[context.GOOGLE_CALENDAR_ID].busy;
It looks like this line of the code is different between the "Google Calendar FreeBusy Queries" and "Recording VoiceMails" sections of the tutorial and needs to be updated in the latter code sample.

Using Google Assistant Change Firebase Database Value

I Created a android app in which if a press a button and value changes in Firebase database (0/1) , i want to do this using google assistant, please help me out, i searched out but didn't found any relevant guide please help me out
The code to do this is fairly straightforward - in your webhook fulfillment you'll need a Firebase database object, which I call fbdb below. In your Intent handler, you'll get a reference to the location you want to change and make the change.
In Javascript, this might look something like this:
app.intent('value.update', conv => {
var newValue = conv.prameters.value;
var ref = fbdb.ref('path/to/value');
return ref.set(newValue)
.then(result => {
return conv.ask(`Ok, I've set it to ${newValue}, what do you want to do now?`);
})
.catch(err => {
console.error( err );
return conv.close('I had a problem with the database. Try again later.');
});
return
});
The real problem you have is what user you want to use to do the update. You can do this with an admin-level connection, which can give you broad access beyond what your security rules allow. Consult the authentication guides and be careful.
I am actually working on a project using Dialogflow webhook and integrated Firebase database. To make this posible you have to use the fulfilment on JSON format ( you cant call firebasedatabase in the way you are doing)
Here is an example to call firebase database and display a simple text on a function.
First you have to take the variable from the json.. its something loike this (on my case, it depends on your Entity Name, in my case it was "tema")
var concepto = request.body.queryResult.parameters.tema;
and then in your function:
'Sample': () => {
db.child(variable).child("DESCRIP").once('value', snap => {
var descript = snap.val(); //firebasedata
let responseToUser = {
"fulfillmentMessages": [
{ //RESPONSE FOR WEB PLATFORM===================================
'platform': 'PLATFORM_UNSPECIFIED',
"text": {
"text": [
"Esta es una respuesta por escritura de PLATFORM_UNSPECIFIED" + descript;
]
},
}
]
}
sendResponse(responseToUser); // Send simple response to user
});
},
these are links to format your json:
Para formatear JSON:
A) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Platform
B) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Message#Text
And finally this is a sample that helped a lot!!
https://www.youtube.com/watch?v=FuKPQJoHJ_g
Nice day!
after searching out i find guide which can help on this :
we need to first create chat bot on dialogflow/ api.pi
Then need to train our bot and need to use webhook as fullfillment in
response.
Now we need to setup firebase-tools for sending reply and doing
changes in firebase database.
At last we need to integrate dialogflow with google assistant using google-actions
Here is my sample code i used :
`var admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.hello = functions.https.onRequest((request, response) => {
let params = request.body.result.parameters;
database.ref().set(params);
response.send({
speech: "Light controlled successfully"
});
});`

Resources