Please i need help on how to fetch data from twitter api for a week.
i'm using nodeJs to write the code and it doesn't seem to work well.
I'm using the twit module in nodeJs btw.
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1; //January is 0!
var year = today.getFullYear();
let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (let i = 0; i < 7; i++) {
if (day > 0) {
day--;
}
if (day == 0) {
month = month - 1;
day = months[month - 1];
}
console.log(day, month, year);
}
let params = {
q: `to:${firstBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
count: 5000,
language: 'en',
entities: false
};
let param = {
q: `to:${secondBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
count: 5000,
language: 'en',
entities: false
};
t.get('search/tweets', params, dataGotten);
Assuming all your setup is done correctly:
const Twit = require('twit')
const T = new Twit({
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...',
timeout_ms: 60*1000, // optional HTTP request timeout to apply to all requests.
});
I would try this:
t.get('search/tweets', params, function(err, data) {
console.log(data);
});
By the way, params is optional argument, so first of all try how it works without them:
t.get('search/tweets', function(err, data) {
console.log(data);
});
Related
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 .
I am trying to extract the AWS CloudTrail lookup events by calling the lookupEvents method provided in the Nodejs sdk. My code is below. I am able to extract the events but from the beginning of the time but not from the dates I have specified.
What should be the format of StartTime and EndTime.
I tried the one shown in the documentation.
EndTime: new Date || 'Wed Dec 31 1969 16:00:00 GMT-0800 (PST)' || 123456789,
let params = {
LookupAttributes: [
{
AttributeKey: "EventName",
AttributeValue: event.EventName
},
{
AttributeKey: "EventSource",
AttributeValue: event.EventSource
},
{
AttributeKey: "StartTime",
AttributeValue: "Tue Mar 09 2021 00:00:00 GMT+0000"
},
{
AttributeKey: "EndTime",
AttributeValue: "Tue Mar 11 2021 00:00:00 GMT+0000"
}
]
};
const cloudtrail = new AWS.CloudTrail({ region: event.region });
let data;
let count = 0;
console.log(`params are ${JSON.stringify(params)}`)
try {
do {
console.log(`Before method...`)
data = await cloudtrail.lookupEvents(params).promise();
console.log(`data so far is ${data}`);
if (data) {
console.log(`data retrieved is ${JSON.stringify(data)}`);
count += data.Events.length;
if (data.NextToken) {
params.NextToken = data.NextToken;
}
}
} while (data.NextToken);
console.log(`The count of Events matching criteria are ${count}.`);
} catch (err) {
console.error(`Error is ${err.stack}`);
}
According to Documentation, StartTime and EndTime are not part of LookupAttributes, they are just regular parameters along side LookupAttributes.
Here is a working example:
let params = {
LookupAttributes: [
{
AttributeKey: "EventName",
AttributeValue: "CreateLogStream",
},
{
AttributeKey: "EventSource",
AttributeValue: "logs.amazonaws.com",
},
],
StartTime: "2021-03-01T01:03:38.141Z",
EndTime: "2021-03-02T01:03:38.141Z",
};
const cloudtrail = new AWS.CloudTrail({ region: "us-east-1" });
cloudtrail.lookupEvents(params, (err, result) => {
console.log("err", err, "result", result);
});
Like Balu mentioned in the previous answer, the StartTime and EndTime are not part of LookUpAtributes. They are to be mentioned separately in the params as key-value pairs.
The following is my AWS Lambda code which is more generic and can take any EventName and EventSource as well as the region as part of JSON input received by the Lambda.
The code is written to avoid callback.
const AWS = require('aws-sdk');
exports.handler = async event => {
console.log(new Date().toUTCString() + "\n");
const today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
const utcToday = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0));
const yesterday = new Date(today.getTime());
yesterday.setDate(yesterday.getDate() - 1);
const utcYesterday = new Date(Date.UTC(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 0, 0, 0, 0));
console.log(`today is ${today.toString()}.`);
console.log(`yesterday is ${yesterday.toString()}.`);
console.log(`utcToday is ${utcToday.toString()}.`);
console.log(`utcYesterday is ${utcYesterday.toString()}.`);
let params = {
LookupAttributes: [
{
AttributeKey: "EventName",
AttributeValue: event.EventName
},
{
AttributeKey: "EventSource",
AttributeValue: event.EventSource
}
],
StartTime: utcYesterday.getTime() / 1000,
EndTime: utcToday.getTime() / 1000
};
const cloudtrail = new AWS.CloudTrail({ region: event.region });
let data;
let count = 0;
console.log(`params are ${JSON.stringify(params)}`)
try {
do {
console.log(`Before method...`)
data = await cloudtrail.lookupEvents(params).promise();
console.log(`data so far is ${data}`);
if (data) {
console.log(`data retrieved is ${JSON.stringify(data)}`);
count += data.Events.length;
if (data.NextToken) {
params.NextToken = data.NextToken;
}
}
} while (data.NextToken);
console.log(`The count of Events matching criteria are ${count}.`);
} catch (err) {
console.error(`Error is ${err.stack}`);
}
}
I have a node.js app that connects and saves to a mongodb collection.
var durations = []
for (i = 0; i < 5; i++) {
var start = performance.now();
//do stuff
var end = performance.now();
durations.push(end - start);
}
var sum, avg = 0;
if (durations.length)
{
sum = durations.reduce(function(a, b) { return a + b; });
avg = sum / durations.length;
}
objectToSave.durationAverage = avg;
console.log(durations);
console.log(avg);
//Add the object to the database through Ajax
$.ajax({
type:'POST',
url:'/add',
data:JSON.stringify(objectToSave),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
On the console :
console.log(durations);
[0.10000000111176632, 0, 0, 0, 0]
console.log(avg);
0.020000000222353265
In my collection:
{ durationAverage : 0 }
How can i save the value with 4 digits after the decimal from node.js to mongodb?
Thank you
I am trying to get the real time tag subscription to work but it seems like the real time update only update within a minute. Here are my code, can you please point out what I am missing?
var Instagram = require('instagram-node-lib');
app.get('/GetInstagram', function(request, response){
// The GET callback for each subscription verification.
var params = url.parse(request.url, true).query;
response.send(params['hub.challenge'] || 'No hub.challenge present');
});
app.post('/GetInstagram', function (req, res) {
var tagName = 'love';
Instagram.set('client_id', 'clientID');
Instagram.set('client_secret', 'ClientSecret');
Instagram.tags.subscribe ({ object_id: tagName,access_token: null, client_id: 'clientid', client_secret: 'clientsecret', callback_url: 'http://myURL/GetInstagram', complete: function()
{
console.log('begin fetching');
Instagram.tags.recent({ name: tagName,aspect: 'media', complete: function(data, pagination )
{
var chunk = { 'pagination': pagination, 'data': data };
console.log (chunk.data.length);
var len = 0;
for (var i = 0, len = chunk.data.length; i < len; i++)
{
var url = '"' + chunk.data[i].images.standard_resolution.url + '"';
console.log('image from instagram image # ' + i + ' image URL' + chunk.data[i].images.standard_resolution.url );
}
res.end();
}
});
}
});
});
pretty sure you're not using the right method -- you want to use Instagram.subscriptions.subscribe for a real-time feed, not tags.subscribe
How to find a distance between two geopoints(set of langitude and longitude) using node.js.
I have code in client side javascript using google maps distance matrix service.
I want to do same thing in serversidejavascript(In node.js router.js or datamodel.js).
My Client Side Javascript code:
function calculateDistances() {
var gs =require('googlemaps');
var latlong = { 'latitude': 52.5112, 'longitude': 13.45155};
var origin1 = gs.LatLng(13.125511084202,80.029651635576);
var origin2 = new google.maps.LatLng(12.9898593006481,80.2497744326417);;
var destinationA = new google.maps.LatLng(13.125511084202,80.029651635576);;
var destinationB = new google.maps.LatLng(12.9898593006481,80.2497744326417);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '';
}
}
console.log(outputDiv);
}
}
Can u suggest me to do samething in node.js package with distance matrix sample code.
Maybe this package? https://github.com/manuelbieh/geolib
And this method:
geolib.getDistance(object start, object end, [int accuracy])
Check out https://github.com/edwlook/node-google-distance
var distance = require('google-distance');
distance.get(
{
origin: 'San Francisco, CA',
destination: 'San Diego, CA'
},
function(err, data) {
if (err) return console.log(err);
console.log(data);
});
This will output:
{
index: null,
distance: '807 km',
distanceValue: 807366,
duration: '7 hours 30 mins',
durationValue: 26981,
origin: 'San Francisco, CA, USA',
destination: 'San Diego, CA, USA',
mode: 'driving',
units: 'metric',
language: 'en',
avoid: null,
sensor: false
}