I am trying to call Twilio services into my node application.
According to docs I am calling list of messages service like bellow
var accountSid = 'ACe622fda3d3cd03b3b975d8d92f7c794b';
var authToken = "your_auth_token";
var client = require('twilio')(accountSid, authToken);
client.messages.list(function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body);
});
});
As a result I am getting first 50 messages with complete details.
Now my issue is how to get previous messages(pagination), conversations between two numbers and using further filters like date.
Twilio developer evangelist here.
List resources return pagination information, including the next and previous pages' URLs. You can also set the page size.
So, for a first pass you can get more than 50 messages by setting the PageSize to the maximum 1000.
client.messages.list({ PageSize: 1000 }, function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body);
});
});
If you need to go beyond that, then you can use the next page url to get the next page:
var url = require("url");
client.messages.list(function(err, data) {
if (data.next_page_uri) {
// deal with page 1
var query = url.parse(data.next_page_uri, true).query;
client.messages.list(query, function(err, data) {
// and so on
}
}
});
Adam Varga shared a solution he was using on GitHub (it's for phone numbers, but lists all act the same on Twilio). Also, look out for the release of version 3 of the Node.js library, which will include pagination helpers.
Related
Good afternoon, I'm developing an application in Node.js, this application returns the total views of my projects in JSON.
My question is: how do I get the total views of a specific page or URL. Bearing in mind that this will become an attribute for my function later.
async function getTopPosts(customUrl) { /* I need the Custom URL to be used as a filter */
try {
await jwt.authorize();
const response = await google.analytics("v3").data.ga.get({
auth: jwt,
ids: "ga:" + VIEW_ID,
"start-date": "2019-01-01",
"end-date": "today",
dimensions: "ga:pagePath,ga:pageTitle",
metrics: "ga:pageviews",
sort: "-ga:pageviews",
"max-results": "10",
filters: "ga:medium==organic",
});
let data = response.data
console.log(data)
} catch (err) {
console.log(err);
}
};
I tried to see the GA-API documentations GA-API but I was not successful.
I hope it returns a JSON containing only the total views of a specific page or URL of my Google Analytics project.
Google Slides Api (Node JS / JavaScript) - is it possible to create a duplicate of a specific slide like for example assuming slide no 5 needs to be duplicated 3 times?
I believe your goal and your current situation as follows.
You want to copy the specific slide in Google Slides several times.
In your question, you want to copy No. 5 slide 3 times.
You want to achieve this using googleapis for Node.js.
You have already been able to get and put values for Google Slides using Slides API.
In this case, I thought that the method of batchUpdate in Slides API can be used.
Sample script:
In this sample script, please use auth retrieved from your script. If you want to see the script for authorizing for Node.js, you can see Quickstart for Node.js. Ref In this case, please use the scope of https://www.googleapis.com/auth/presentations.
const presentationId = "###"; // Please set the presentation ID (Google Slides ID).
const pageNumber = 5; // Please set the page number. In your question, it's 5.
const numberOfCopy = 3; // Please set the number of copy. In your question, it's 3.
const slides = google.slides({ version: "v1", auth: auth });
slides.presentations.get(
{
presentationId: presentationId,
fields: "slides(objectId)",
},
(err, res) => {
if (err) {
console.log(err);
return;
}
const pageObjectId = res.data.slides[pageNumber - 1].objectId;
const requests = [];
for (let i = 0; i < numberOfCopy; i++) {
requests.push({ duplicateObject: { objectId: pageObjectId } });
}
slides.presentations.batchUpdate(
{
presentationId: presentationId,
resource: { requests: requests },
},
(err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.data);
}
);
}
);
When above script is run, the page object ID of No. 5 slide is retrieved from the Google Slides using the get method, and create the request body for copying 3 times and request it using the batchUpdate method.
Note:
In this sample script, it supposes that auth retrieved from your authorization script can be used. Please be careful this.
References:
Method: presentations.get
Method: presentations.batchUpdate
DuplicateObjectRequest
When retrieving feeds of a facebook page, we can at most get 100 feeds.
How can we parse all available feeds with graph API and node.js?
If it was recursive, we could test on paging and next elements when getting the response.
For example, this code retrieves only two last feed pages, but I want to retrieve all feeds.
// note: you might want to prevent the callback hell :)
graph.get('likes', {limit: 2, access_token: "foobar"}, function(err, res) {
if(res.paging && res.paging.next) {
graph.get(res.paging.next, function(err, res) {
// page 2
});
}
});
if you want to get a data. you must be set user_post permission on graph explorer.
Code.
FB.api(
'/mosaiquefm/feed',
'GET',
{},
function(response)
{
// here print response. this response according to screenshot.
}
);
I have just begun to learn node.js. Over the last two days, I've been working on a project that accepts userinput and publishes a ICS file. I have all of that working. Now consider when I have to show this data. I get a router.get to see if I am at the /cal page and..
router.get('/cal', function(req, res, next)
{
var db = req.db;
var ical = new icalendar.iCalendar();
db.find({
evauthor: 'mykey'
}, function(err, docs) {
docs.forEach(function(obj) {
var event2 = ical.addComponent('VEVENT');
event2.setSummary(obj.evics.evtitle);
event2.setDate(new Date(obj.evics.evdatestart), new Date(obj.evics.evdateend));
event2.setLocation(obj.evics.evlocation)
//console.log(ical.toString());
});
});
res.send(ical.toString());
// res.render('index', {
// title: 'Cal View'
// })
})
So when /cal is requested, it loops through my db and creates an ICS calendar ical. If I do console.log(ical.toString) within the loop, it gives me a properly formatted calendar following the protocol.
However, I'd like to END the response with this. At the end I do a res.send just to see what gets published on the page. This is what gets published
BEGIN:VCALENDAR VERSION:2.0
PRODID:calendar//EN
END:VCALENDAR
Now the reason is pretty obvious. Its the nature of node.js. The response gets sent to the browser before the callback function finishes adding each individual VEVENT to the calendar object.
I have two related questions:
1) Whats the proper way to "wait" till the callback is done.
2) How
do I use res to send out a .ics dynamic link with
ical.toString() as the content. Do I need to create a new view for
this ?
edit: I guess for number 2 I'd have to set the HTTP headers like so
//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
but how do I do this when using views.
Simply send the response, once you got the neccessary data! You are not required to end or send directly in your route but can do it in a nested callback as well:
router.get('/cal', function(req, res, next) {
var db = req.db;
var ical = new icalendar.iCalendar();
db.find({
evauthor: 'mykey'
}, function(err, docs) {
docs.forEach(function(obj) {
var event2 = ical.addComponent('VEVENT');
event2.setSummary(obj.evics.evtitle);
event2.setDate(new Date(obj.evics.evdatestart), new Date(obj.evics.evdateend));
event2.setLocation(obj.evics.evlocation)
});
res.type('ics');
res.send(ical.toString());
});
});
I also included sending the proper Content-Type by using res.type.
Also: Don't forget to add proper error handling. You can for example use res.sendStatus(500) if an error occured while retrieving the documents.
How to check if youtube video exists on node.js app server side:
var youtubeId = "adase268_";
// pseudo code
youtubeVideoExist = function (youtubeId){
return true; // if youtube video exists
}
You don't need to use the youtube API per-se, you can look for the thumbnail image:
Valid video = 200 - OK:
http://img.youtube.com/vi/gC4j-V585Ug/0.jpg
Invalid video = 404 - Not found:
http://img.youtube.com/vi/gC4j-V58xxx/0.jpg
I thought I could make this work from the browser since you can load images from a third-party site without security problems. But testing it, it's failing to report the 404 as an error, probably because the content body is still a valid image. Since you're using node, you should be able to look at the HTTP response code directly.
I can't think of an approach that doesn't involve making a separate HTTP request to the video link to see if it exists or not unless you know beforehand of a set of video IDs that are inactive,dead, or wrong.
Here's an example of something that might work for you. I can't readily tell if you're using this as a standalone script or as part of a web server. The example below assumes the latter, assuming you call a web server on /video?123videoId and have it respond or do something depending on whether or not the video with that ID exists. It uses Node's request library, which you can install with npm install request:
var request = require('request');
// Your route here. Example on what route may look like if called on /video?id=123videoId
app.get('/video', function(req, response, callback){
var videoId = 'adase268_'; // Could change to something like request.params['id']
request.get('https://www.youtube.com/watch?v='+videoId, function(error, response, body){
if(response.statusCode === 404){
// Video doesn't exist. Do what you need to do here.
}
else{
// Video exists.
// Can handle other HTTP response codes here if you like.
}
});
});
// You could refactor the above to take out the 'request.get()', wrap it in a function
// that takes a callback and re-use in multiple routes, depending on your problem.
#rodrigomartell is on the right track, in that your check function will need to make an HTTP call; however, just checking the youtube.com URL won't work in most cases. You'll get back a 404 if the videoID is a malformed ID (i.e. less than 11 characters or using characters not valid in their scheme), but if it's a properly formed videoID that just happens to not correspond to a video, you'll still get back a 200. It would be better to use an API request, like this (note that it might be easier to use the request-json library instead of just the request library):
request = require('request-json');
var client = request.newClient('https://www.googleapis.com/youtube/v3/');
youtubeVideoExist = function (youtubeId){
var apikey ='YOUR_API_KEY'; // register for a javascript API key at the Google Developer's Console ... https://console.developers.google.com/
client.get('videos/?part=id&id='+youtubeId+'&key='+apikey, function(err, res, body) {
if (body.items.length) {
return true; // if youtube video exists
}
else {
return false;
}
});
};
Using youtube-feeds module. Works fast (~200ms) and no need API_KEY
youtube = require("youtube-feeds");
existsFunc = function(youtubeId, callback) {
youtube.video(youtubeId, function(err, result) {
var exists;
exists = result.id === youtubeId;
console.log("youtubeId");
console.log(youtubeId);
console.log("exists");
console.log(exists);
callback (exists);
});
};
var notExistentYoutubeId = "y0srjasdkfjcKC4eY"
existsFunc (notExistentYoutubeId, console.log)
var existentYoutubeId = "y0srjcKC4eY"
existsFunc (existentYoutubeId, console.log)
output:
❯ node /pathToFileWithCodeAbove/FileWithCodeAbove.js
youtubeId
y0srjcKC4eY
exists
true
true
youtubeId
y0srjasdkfjcKC4eY
exists
false
false
All you need is to look for the thumbnail image. In NodeJS it would be something like
var http = require('http');
function isValidYoutubeID(youtubeID) {
var options = {
method: 'HEAD',
host: 'img.youtube.com',
path: '/vi/' + youtubeID + '/0.jpg'
};
var req = http.request(options, function(res) {
if (res.statusCode == 200){
console.log("Valid Youtube ID");
} else {
console.log("Invalid Youtube ID");
}
});
req.end();
}
API_KEY is not needed. It is quite fast because there is only header check for statusCode 200/404 and image is not loaded.