How to get data from a different channel youtube api node.js - 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'

Related

slack how to know if bot recently posted

I am using botkit, i have a bot that responses to a certain word.
But i don't want the bot to response if it recently did so.
Currently i am using channels.history method to retrieve 4 recent messages then find the bot id, if its there it won't reply. This is not pretty, i've been searching for useful methods to use but i can't find any. I just want to find out if the bot recently posted or not and do actions base on it.
const targetBotID = 'GKALXJCM6'
bot.api.channels.history({
channel: message.channel,
latest: message.ts,
count: 4,
inclusive: 1,
}, function(err, response) {
if(err) { bot.reply(message, 'Something is wrong with me, check log if there is??'); }
if(response){
const recentPostFound = response.messages.filter(function (member) {
return member.user === targetBotID;
});
if(recentPostFound){
return bot.reply();
}
return bot.reply(answer) // Answer if no matching id found
}
});
I can see two solutions to your issue:
Record previous actions of your bot in some kind of app context (e.g. database). Then you can verify each time if your bot already answered.
Consider using Events API instead of loading the chat history each time. Then your bot gets exactly one event request for each new message in a channel and you can be sure that your bot will only react once.

Chatbot messages do not show up in Facebook Messenger chat heads

I am developing a chatbot for Facebook Messenger using Microsoft Bot Framework. The bot sends the user proactive messages (reminders). Unfortunately, for some reason the messages never show up in a chat head (the Android widget for conversations), nor pop up a chat head if it wasn't present on the screen before. It does happen for other chatbots (Jarvis, for example).
This is the code that sends the reminders:
Reminder.find({ next_reminder: { $lte: new Date() } }, (err, res) => {
if (err !== null) {
return console.error(err);
}
res.forEach(reminder => {
// Build a notification message and address it to user who created the reminder
const msg = new builder.Message().text('...');
bot.beginDialog(reminder.user_address, '*:/sendReminder', {message: msg, nudnik: nudnik});
});
});
};
};
I have also tried bot.send(msg, () => ....) and session.beginDialog('sendReminder', msg). However, there is still no indication from Messenger when the message is received. What could go wrong here?
OK, I figured it out! Apparently, the default notification setting for a Facebook message is not to show a notification. To change it, in NodeJS you should add channel-specific data to the message with the following code:
msg = msg.sourceEvent({
facebook:
{notification_type: 'REGULAR'}
});
You can discover more in official documentation by Microsoft (here and here) and also in this Github discussion.

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.

Get result in from YouTube channel in nodejs

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);

How to publish sns to a specific endpoint?

I have a issue with publishing sns to a specific endpoint.
My code:
var AWS = require('aws-sdk');
AWS.config.loadFromPath('/web/config.json');
var sns = new AWS.SNS();
sns.publish({
// TopicArn:'arn:aws:sns:us-west-2:302467918846:MyTestTopik',
TargetArn: 'arn:aws:sns:us-west-2:302467918846:MyTestTopik:613ee49c-d4dc-4354-a7e6-c1d9d8277c56',
Message: "Success!!! ",
Subject: "TestSNS"
}, function(err, data) {
if (err) {
console.log("Error sending a message " + err);
} else {
console.log("Sent message: " + data.MessageId);
}
});
When I use TopicArn, everything is fine. But when I try to send notification to a specific endpoint I take error:
Error sending a message InvalidParameter: Invalid parameter: Topic Name
And I have no idea what kind of parameters it is and from where.
Something similar is working fine for me.
I'm able to publish to a specific endpoint using: Apple Push Notification Service Sandbox (APNS_SANDBOX)
You might also want to try and update the aws-sdk, current version is 1.9.0.
Here's my code, TargetArn was copied directly from the SNS console. I omitted some of the data, like &
var sns = new AWS.SNS();
var params = {
TargetArn:'arn:aws:sns:us-west-2:302467918846:endpoint/APNS_SANDBOX/<APP_NAME>/<USER_TOKEN>'
Message:'Success!!! ',
Subject: 'TestSNS'
};
sns.publish(params, function(err,data){
if (err) {
console.log('Error sending a message', err);
} else {
console.log('Sent message:', data.MessageId);
}
});
You might have an invalid Region. Check you Region for the Topic and set it accordingly. For example if you are us-west-2 you could do something like
var sns = new aws.SNS({region:'us-west-2'});
None of this will work if you don't massage the payload a bit.
var arn = 'ENDPOINT_ARN';
console.log("endpoint arn: " + arn);
var payload = {
default: message_object.message,
GCM: {
data: {
message: message_object.message
}
}
};
// The key to the whole thing is this
//
payload.GCM = JSON.stringify(payload.GCM);
payload = JSON.stringify(payload);
// Create the params structure
//
var params= {
TargetArn: arn,
Message: payload,
MessageStructure: 'json' // Super important too
};
sns.publish(params , function(error, data) {
if (error) {
console.log("ERROR: " + error.stack);
}
else {
console.log("data: " + JSON.stringify(data));
}
context.done(null, data);
});
So, it turns out that you have to specify the message structure (being json). I tried to publish to endpoint from the AWS console and it worked great as long as I selected JSON. Using RAW would do nothing.
In my script was doing was the previous posts were doing:
var params = {
TargetArn: arn,
Message:'Success!!! ',
Subject: 'TestSNS'
};
And even though CloudWatch was logging success, I never once got the message.
As soon as I added the MessageStructure data and that I properly formatted the payload, it worked like a charm.
The [default] parameter is not useful but I left it in there to show what the structure could look like.
If you don't stringify the payload.GCM part, SNS will barf and say that your message should include a "GCM" element.
The only thing that is annoying is that you are required to know what the endpoint is. I was hoping that you didn't have to format the message based on the endpoint, which really defeats the purpose of SNS in some ways.
Are you trying endpoints other that push notifications such as sms? Direct addressing is currently only available for push notifications endpoints. That is the error you will get when you try to publish to a specific endpoint that does not allow direct direct addressing!
http://aws.amazon.com/sns/faqs/#Does_SNS_support_direct_addressing_for_SMS_or_Email
I was having the exact same issue as you. The problem is the TargetArn that you're using, there's not clear documentation about it. Error happens if you try to put the Application ARN in the TargetArn.
That will produce the error: Invalid parameter: TargetArn Reason: >arn:aws:sns:us-west-2:561315416312351:app/APNS_SANDBOX/com.APP_NAME_HERE.app is >not a valid ARN to publish to.
All you need to do is to put the EndpointArn in the TargetArn.
If you need to see the EndpointArn, you can:
Call listPlatformApplications() to get all your applications ARN's.
Call listEndpointsByPlatformApplication() with the App ARN to get the EndpointArn's list.
Enjoy!

Resources