This code is working fine in replit compilator.
I want to put the same thing in twilio studio flow function, but I can't do it.
I just want to take the date/month and add the event in my google calendar.
can someone help me with it?
clientMonth, clientDay this variable are dynamic , thos two digis is similar.
Dependensis is googleapis-^65.0.0
Assets=auth.json
Env variable is calendarId-***** and GOOGLE_CREDENTIALS = /auth.json
const {google} = require('googleapis');
require('dotenv').config();
const fs = require('fs').promises;
exports.handler = async function (context, _event, callback) {
// Google calendar API settings
const SCOPES = 'https://www.googleapis.com/auth/calendar';
const authJson = JSON.parse(
await fs.readFile(Runtime.getAssets()[context.GOOGLE_CREDENTIALS].path)
);
const auth = new google.auth.JWT(
authJson.client_email,
null,
authJson.private_key,
SCOPES
);
const calendar = google.calendar({version : "v3",auth});
const TIMEOFFSET = '+02:00';
var clientMonth = 5;
var clientDay = 23;
var todayDate = new Date();
var clientDate = new Date(todayDate.getFullYear(), clientMonth-1,
clientDay);
const dateTimeForCalander = () => {
//let todayDate = new Date();
let year = clientDate.getFullYear();
let month = clientDate.getMonth()+1;
if (month < 10) {
month = `0${month}`;
}
let day = clientDate.getDate() ;
if (day < 10) {
day = `0${day}`;
}
let hour = todayDate.getHours();
if (hour < 10) {
hour = `0${hour}`;
}
let minute = todayDate.getMinutes();
if (minute < 10) {
minute = `0${minute}`;
}
let newDateTime = `${year}-${month}-${day}T${hour}:${minute}:00.000${TIMEOFFSET}`;
let event = new Date(Date.parse(newDateTime));
let startDate = event;
// Delay in end time is 1
let endDate = new Date(new
Date(startDate).setHours(startDate.getHours()+1));
return {
'start': startDate,
'end': endDate
};
};
let dateTime = dateTimeForCalander();
console.log(dateTime);
// Event for Google Calendar
let Clientevent = {
'summary': `This is the summary.`,
'description': `This is the description.`,
'start': {
'dateTime': dateTime.start,
'timeZone': 'Europe/Tirane'
},
'end': {
'dateTime': dateTime.end,
'timeZone': 'Europe/Tirane'
}
};
function insertEvent (eventi) {
let response = calendar.events.insert({
auth: auth,
calendarId: context.calendarId,
resource: eventi
});
}
response.setBody({
success: true,
message: insertEvent(Clientevent),
})
return callback(null,response );
}
Iām on my phone, so apologies for a brief answer. I believe the issue is that you are performing an asynchronous task to add the event to the calendar, but you are returning the callback synchronously on the last line of the function. When you call the callback function, all processes started within the function are terminated. So if you still have an asynchronous API call running, calling the callback will end that call.
Make sure that you only call the callback when all asynchronous tasks that you perform within the function are completed. I think the asynchronous call you need to wait for is the call to calendar.events.insert .
Related
I want to run a Script every 6 Hours
const { IgApiClient } = require("instagram-private-api")
const ig = new IgApiClient()
const USERNAME = "abc"
const PASSWORD = "xyz"
ig.state.generateDevice(USERNAME)
const main = async () => {
var birthday = new Date(2069, 05, 14);
var today = new Date();
birthday.setFullYear(today.getFullYear());
if (today > birthday) {
birthday.setFullYear(today.getFullYear() + 1);
}
var daystill = Math.floor((birthday - today) / (1000*60*60*24))
await ig.simulate.preLoginFlow()
await ig.account.login(USERNAME, PASSWORD)
process.nextTick(async () => await ig.simulate.postLoginFlow())
await ig.account.setBiography(`${daystill} Days till my Birthday, Today is ${new Date().getDate()}/${new Date().getMonth()}/${new Date().getFullYear()}. (AutoGenerated)`)
}
main()
instagram-private-api
About Script: update my Instagram Bio with Async Await
Problem / Goal:
I Tried using node-cron, but It returns some Error (I think Async is causing the Problem), I also tried while loops and setInterval()s
I want this Script/File to run every 6 Hours, I have a heroku account (if that helps)
Error when i use node-cron:
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
Code for node-cron:
cron.schedule('* * * * *', () => { // this is not every 6hrs
const main = async () => {
//same as above
}
main()
})
Doing it the async await way as the title says.
// used to measure time
import { performance } from 'perf_hooks';
const interval = 1000; // in ms
(async function main(){
let start_time = performance.now();
// do stuff
let stop_time = performance.now();
let timeout = interval - (stop_time - start_time);
setTimeout(main, timeout);
})();
edit:
To explain the syntax behind the main function.
()(); will automatically call the function inside of first braces on script start.
im new at cloud functions
i just want to disable my targets after countdown end. this function works correctly but updates after 3 min after function finished
what am i missing?
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.timecontroller = functions.firestore.document("DigitalTargets/{digitalTargetID}").onCreate((snap, context) => {
const id = snap.id
const date = new Date(snap.data().endDate.toDate())
var countDownDate = date.getTime();
var myfunc = setInterval(function () {
var now = new Date().getTime();
var timeleft = countDownDate - now;
if (timeleft < 0) {
db.collection("DigitalTargets").doc(id).update({ isActive: false })
clearInterval(myfunc);
}
}, 1000);
})
Since you pay for the time that your Cloud Functions code executes, the container tries to execute your code and terminate as quickly as possible. Unless you tell it otherwise, that means that it terminates the code as soon as the final statement before the closing } executes.
But since you are executing an asynchronous operation with your setInterval call, the code actually needs to continue to run after the closing }.
To allow that you'll need to return a promise that resolves when the code is complete. Something like:
exports.timecontroller = functions.firestore.document("DigitalTargets/{digitalTargetID}").onCreate((snap, context) => {
const id = snap.id
const date = new Date(snap.data().endDate.toDate())
var countDownDate = date.getTime();
return new Promise((resolve, reject) => { // š This tells Cloud Functions to wait
var myfunc = setInterval(function () {
var now = new Date().getTime();
var timeleft = countDownDate - now;
if (timeleft < 0) {
db.collection("DigitalTargets").doc(id).update({ isActive: false })
clearInterval(myfunc);
resolve(); // š This tells Cloud Functions that you're done
}
}, 1000);
})
})
I recommend reading (and watching the videos in) the Firebase documentation on asynchronous behavior in Cloud Functions.
Why when i call this function Stripe generate 2 invoice?
I want to set a custom price % for the invoice and not using a fixed price as suggested on the documentation.
I want that the invoice is automatically payed by the customer.
exports = module.exports = functions.https.onRequest(
async (request, response) => {
let data = request.body;
var imponibile = 100;
const { stripe } = require("./stripe");
const { db } = require("./admin");
const invoiceItem = await stripe.invoiceItems.create({
customer: data.customerId,
description: data.description,
amount: imponibile,
currency: "eur",
});
const invoice = await stripe.invoices.create({
customer: data.customerId,
auto_advance: true, // Auto-finalize this draft after ~1 hour
collection_method: "charge_automatically",
});
const payinvoice = await stripe.invoices.pay(invoice.id);
return payinvoice;
}
);
Solved, the problem was that i was returning the actual payment function recursively.
Solution :
return respond.status(200).send('ok')
I'm using node for fetching a list of events with a date range.
I've seen there's a pagination limit within Google's API, however I'm looking for a way to get all events on the calendar each time the app runs.
This is what I've tried so far, but not luck with looping through the response pages from google.
const runSample = async () => {
const pushDate = new Date("2019-12-22T08:28:19.593Z")
const toDate = new Date()
toDate.setDate(pushDate.getDate() + 3)
let syncToken = null
let pageToken = null
const events = []
const eventlist = await calendar.events.list({
calendarId: '***_***#group.calendar.google.com',
timeMin: pushDate,
timeMax: toDate,
showDeleted: false,
singleEvents: true
})
events.push(eventlist.data.items)
pageToken = await eventlist.data.nextPageToken
while (pageToken != null) {
let list = await calendar.events.list({
calendarId: '***_***#group.calendar.google.com',
nextPageToken: pageToken
})
events.push(list.data.items)
}
pageToken = await eventlist.data.nextPageToken
syncToken = await eventlist.data.nextSyncToken
const anotherlist = null
console.log(events)
console.log(syncToken)
console.log(pageToken)
}
runSample().catch(console.error)
Is there a way to get all the events in one call?
The app runs every x hours with a cron job and I need each time the event array for the given time range.
I am creating an Alexa factskill that asks the user for some information on their health, and users respond with a score from 1-10 depending on the level of pain in different areas. I then input the data into a DynamoDB table, which stores the information(score out of 10) for the four health questions (swelling, feeling, sleeping, breathing) and the user ID. However, the entries are not giving a timestamp for when they were created. I was wondering if there was a way to make a timestamp for preferably every health question response, but also a timestamp for the entire entry would help. Would I have to use any external SDKs, as I was looking up DynamoDB documentations and didn't find out any way to add a timestamp.
Below is my index.js code for my Lambda function that is used for my Alexa skill.
'use strict';
const Alexa = require('alexa-sdk');
const SKILL_NAME = 'Home Assist';
const HELP_MESSAGE = 'You can say I want to input my data';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
const handlers = {
'LaunchRequest': function () {
this.emit('HomeAssistQuestions');
},
'HomeAssistQuestions': function () {
this.attributes.healthscores = {
'patientID' : 0,
'scores': {
'feeling': {
'score': 0
},
'sleeping': {
'score': 0
},
'breathing': {
'score': 0
},
'swollen': {
'score': 0
}
}
};
if(this.event.request.dialogState !== 'COMPLETED'){
this.emit(':delegate');
}
else{
const feelingScore = this.event.request.intent.slots.feelingRating.value;
const sleepingScore = this.event.request.intent.slots.sleepingRating.value;
const breathingScore = this.event.request.intent.slots.breathingRating.value;
const swollenScore = this.event.request.intent.slots.SwollenRating.value;
const id = this.event.request.intent.slots.id.value;
this.attributes.healthscores.patientID = id;
this.attributes.healthscores.scores['feeling'].score = feelingScore;
this.attributes.healthscores.scores['sleeping'].score = sleepingScore;
this.attributes.healthscores.scores['breathing'].score = breathingScore;
this.attributes.healthscores.scores['swollen'].score = swollenScore;
this.response.speak("Health Scores Recorded");
this.emit(':responseReady');
}
},
'AMAZON.HelpIntent': function () {
const speechOutput = HELP_MESSAGE;
const reprompt = HELP_REPROMPT;
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');
},
'AMAZON.CancelIntent': function () {
this.response.speak(STOP_MESSAGE);
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
this.response.speak(STOP_MESSAGE);
this.emit(':responseReady');
},
'SessionEndedRequest': function(){
this.emit('saveState', true);
}
};
exports.handler = function (event, context, callback) {
const alexa = Alexa.handler(event, context, callback);
alexa.dynamoDBTableName = 'HealthScores';
alexa.APP_ID = "amzn1.ask.skill.d5b8d597-eb50-41c6-a22d-b0f18c23b544";
alexa.registerHandlers(handlers);
alexa.execute();
};
You can try something like this:
...
this.attributes.healthscores.scores['swollen'].score = swollenScore;
this.attributes.healthscores.timestamp = Date.now();
this.response.speak("Health Scores Recorded");
...