Get result in from YouTube channel in nodejs - node.js

I am using youtube-node npm to find out all the video list. The documentation is on the link https://www.npmjs.com/package/youtube-node.
But I want that my search only show result of a specific channel i.e if I search hello, then it only give result of AdeleVEVO YouTube channel.
I cant find suitable documentation for that. I don't want to use oauth credentials, I only want to use youtube-node npm.

In package doc you have a sample search, make sure you include in the params parameter an object with the values you want, in your case see in youtube api doc that you need to specify the channelId. Try this way:
var YouTube = require('youtube-node');
var youTube = new YouTube();
youTube.setKey('AIzaSyB1OOSpTREs85WUMvIgJvLTZKye4BVsoFU');
youTube.search('World War z Trailer', 2, {channelId: <string value of the channelId>}, function(error, result) {
if (error) {
console.log(error);
}
else {
console.log(JSON.stringify(result, null, 2));
}
})
;

If you are the owner of the channel, you can use the forMine parameter of the YouTube API for this. Setting this parameter will limit the search to the authorized user's videos. Below is a sample from the official documentation.
IMPORTANT NOTE: Do not use the youtube-node module for this, specifically because--in my experience at least--the addParam() function does not reliably add parameters to the request (e.g., in my code I called youtube_node.addParam('safeSearch', 'strict');, but restricted videos would still be returned in the results.)
Instead, use the YouTube Data API directly as shown in this quickstart example.
// Sample nodejs code for search.list
function searchListMine(auth, requestData) {
var service = google.youtube('v3');
var parameters = removeEmptyParameters(requestData['params']);
parameters['auth'] = auth;
service.search.list(parameters, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
}
//See full code sample for authorize() function code.
authorize(JSON.parse(content), {'params': {'maxResults': '25',
'forMine': 'true',
'part': 'snippet',
'q': 'fun',
'type': 'video'}}, searchListMine);

Related

How to get data from a different channel youtube api node.js

I started using YouTube's API today since I want to make a Discord bot that can display a YouTube channels data. So, I went to the guides on the YouTube API site, followed the node.js guide, but ran into a problem. I do not know how I can get the data from a different channel than Google Developers (which is the channel their pulling data from in the explanation).
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
Above is the code they use. I expected I could change Google Developers to any other YouTube channel and it would return the data from that, but if I change it to, for example Fireship, I get the error below. I searched their API reference, but I don't really understand what I'm doing wrong.
if (channels.length == 0) {
^
TypeError: Cannot read properties of undefined (reading 'length')
What should I do to fix this issue?
Thanks in advance!
If you check the docs for Channel.list you will find that the The parameter forUsername
The forUsername parameter specifies a YouTube username, thereby requesting the channel associated with that username.
so if you want to find it for a different channel or a different user then just change
forUsername: 'GoogleDevelopers'

Create Spreadsheet for read and write using Node js

I Need to create a spreadsheet like a google sheet with user authentication. I have stuck with how to start this project because I couldn't find which NPM module needs to use.
so Kindly help anyone push me in the right direction?
I've been working on similar task few weeks ago.
So here is the mini help for you.
1. Read and follow Node.js Quickstart guide.
Keep an eye on the next concepts like:
Scopes
For example to get a value from a cell we can use spreadsheets.values.get
Scopes for this method are (use 1 of these):
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/spreadsheets.readonly
in node.js it can be an array
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
Token
Once you run for the first time your index.js file the Terminal will ask you for authorization, on finish you will find a token.json in your work directory.
If you change Scopes -> delete token.json from your directory
SpreadsheetId
When you create/edit your spreadsheet you get similar url
https://docs.google.com/spreadsheets/d/1eqRe0ksSwgOoPO0C_mZE6opjS1TlsCU5g1HtkiiILuw/edit#gid=0
1eqRe0ksSwgOoPO0C_mZE6opjS1TlsCU5g1HtkiiILuw is the ID
2. Create custom functions using Google Sheets API Reference
Example how to get cell values:
const sheets = google.sheets({ version: 'v4', auth });
function getCellsValue(cells, callback){
sheets.spreadsheets.values.get({
spreadsheetId: 'spreadsheetId',
range: cells
}, (err, res) => {
if (err) return console.log('Error #1001 : getCellsValue: ' + err);
const output = res.data.values;
if (output.length) {
callback(output);
return output;
} else {
console.log('No data found.');
}
});
}
// here is the example use of this function which output values from D2:D13
getCellsValue("D2:D13", (e) => {
for(let i = 0; i < e.length; i++){
console.log(e[i].toString());
}
}, (err, res) => {
if (err) return console.error('The API returned an error: ', err.message);
})
3. Make a use of Try this API
This is very useful tool.
In case you need more help just use Stackoverflow for more transparency.
Stackoverflow helps you when you make a very detailed question.
I hope this helped you and you can start your Google Sheets API journey.

Twitter returns error 401 on tracking multiple ids

When I track single id using this code snippet
var stream = Twitter.stream('statuses/filter', { follow : '713445685429932032' });
stream.on('tweet', function (tweet, err) {
console.log(tweet);
})
I can successfully follow the twitter id however if I try to follow list of ids
var stream = Twitter.stream('statuses/filter', { follow : ['713445685429932032', '23424']});
stream.on('tweet', function (tweet, err) {
console.log(tweet);
})
I get response status code 401, as per my understanding twitter allows us to track 5000 ids and I am unable to track even two what appears to be the problem.
I am using twitter node js module.

In the FB marketing api, there is an option to export_format: 'csv', how do I download the csv file?

I'm looking to download a CSV from my api call to FB ads, I've set it in the parameters as per the code below, the call works fine but I only get a paginated JSON as a response. I'm not quite sure how to access the CSV report, the response doenst give me any report ID or download link. How can I download this CSV?
Using nodejs facebook-nodejs-ads-sdk
image showing the parameter information 'export_format'
Documentation: https://developers.facebook.com/docs/marketing-api/reference/adgroup/insights/
var getReport = function(){
console.log("API for FB report has been called")
let ads_insights;
let ads_insights_id;
const logApiCallResult = (apiCallName, data) => {
console.log(apiCallName);
if (showDebugingInfo) {
console.log('Data:' + JSON.stringify(data));
}
};
const fields = [
'ad_name',
'impressions',
'reach',
'spend'
];
const params = {
'export_format': 'csv',
'export_name': new Date() + 'fb-download',
'level' : 'ad',
'filtering' : [],
'breakdowns' : [],
'time_range' : {'since':'2018-01-22','until':'2018-01-23'}
};
new AdAccount(ad_account_id).getInsights(
fields,
params).then((result) => {
logApiCallResult('ads_insights api call complete.', result);
console.log("##########" + result + "#####")
ads_insights_id = result[0].id;
}).catch((error) => {
console.log(error);
});
}
Exporting actual report files doesn't seem to be a part of the official Facebook Graph API.
My solution was to make a GET request to the following endpoint:
https://www.facebook.com/ads/ads_insights/export_report/?report_run_id=<REPORT_RUN_ID>&name=<REPORT_FILE_NAME>&format=csv&access_token=<FACEBOOK_API_KEY>
Please note that this endpoint will output a file with columns that constantly change without warning, so its not good for automated data collection. The only way to export standardized reports is in the JSON format.
The docs for this endpoint are sort of hard to find: located here.

check on server side if youtube video exist

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.

Resources