Google API how do I get one variable from my result - javascript

I want to isolate subscriberCount: '15' to it's own variable but nothing I do works here is all the data I have (some censored for security reasons) please try to help me!
Code
const Youtube = require("youtube-api")
, fs = require("fs")
, readJson = require("r-json")
, Lien = require("lien")
, Logger = require("bug-killer")
, opn = require("opn")
, prettyBytes = require("pretty-bytes")
;
// I downloaded the file from OAuth2 -> Download JSON
const CREDENTIALS = readJson(`${__dirname}/credentials.json`);
// Init lien server
let server = new Lien({
host: "localhost"
, port: 5000
});
// Authenticate
// You can access the Youtube resources via OAuth2 only.
// https://developers.google.com/youtube/v3/guides/moving_to_oauth#service_accounts
let oauth = Youtube.authenticate({
type: "oauth"
, client_id: CREDENTIALS.web.client_id
, client_secret: CREDENTIALS.web.client_secret
, redirect_url: CREDENTIALS.web.redirect_uris[0]
});
opn(oauth.generateAuthUrl({
access_type: "offline"
, scope: ["https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube.readonly"]
}));
// Handle oauth2 callback
server.addPage("/oauth2callback", lien => {
Logger.log("Trying to get the token using the following code: " + lien.query.code);
oauth.getToken(lien.query.code, (err, tokens) => {
if (err) {
lien.lien(err, 400);
return Logger.log(err);
}
Logger.log("Got the tokens.");
oauth.setCredentials(tokens);
lien.end("Eyyy you logged in!");
// var req = Youtube.videos.insert({ });
function execute() {
return Youtube.channels.list({
"part": [
"statistics"
],
"mine": true,
"prettyPrint": true
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
//console.log("Response", response);
//console.log(typeof response.data.items);
//console.log(response.data.items);
//console.log(result);
console.log(response.data.items);
//console.log(response.statistics);
},
function(err) { console.error("Execute error", err); });
}
execute();
});
});
Response From google:
[
{
kind: 'youtube#channel',
etag: '*****',
id: '*****',
statistics: {
viewCount: '506',
subscriberCount: '15',
hiddenSubscriberCount: false,
videoCount: '12'
}
}
]

Jaromanda X gave the solution in a comment:
response.data.items is an Array, by the look of your question, ... so you'd need response.data.items[0].statistics.subscriberCount

Related

Getting ERR_SSL_PROTOCOL Error when trying to send a post request to my Node.js Server in ReactJs

I am creating a DHL API for checking shipment rates. I have uploaded my Node.js Server using putty and it is running correctly when I enter my IP address and port number.
In development, there are no erros or issues and I get back the response and get the rates back from the form I have set up for my users.
but in Production, when I upload my website to Hostinger I get this error " Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR"
In production, it sends my post request with HTTPS instead of HTTP. And even when I change the HTTPS to HTTP in the browser I get another error saying "Cannot GET /api/dhl"
Here are some images to help make it more clear:
The Errors.
When my website submits the post request with HTTPS instead of HTTP.
When I manually change the URL from HTTPS to HTTP
What am I doing wrong? Why is this happening and how can I fix it?
Here is my code:
const express = require('express');
const port = 3001
app.post('/api/dhl', (req, res) => {
const accountNum = req.body.accountNum
const fromCountriesCode = req.body.fromCountriesCode
const fromCountriesCapital = req.body.fromCountriesCapital
const fromCity = req.body.fromCity
const fromPostalCode = req.body.fromPostalCode
const toCountriesCode = req.body.toCountriesCode
const toCountriesCapital = req.body.toCountriesCapital
const toCity = req.body.toCity
const toPostalCode = req.body.toPostalCode
const weight = parseInt(req.body.weight)
const plannedShippingDate = req.body.date
const len = "5"
const width = "5"
const height = "5"
const isCustomsDeclarable = 'false'
const unitOfMeasurement = 'metric'
console.log(weight)
console.log(fromCountriesCode)
console.log(toCountriesCode)
console.log(fromCity)
console.log(toCity)
var options = { method: 'POST',
url: 'https://express.api.dhl.com/mydhlapi/rates',
headers:
{ 'postman-token': '',
'cache-control': 'no-cache',
authorization: 'Basic myauthkey',
'content-type': 'application/json' },
body:
{ customerDetails:
{ shipperDetails:
{ postalCode: fromPostalCode,
cityName: fromCity,
countryCode: fromCountriesCode,
addressLine1: '0' },
receiverDetails:
{ postalCode: toPostalCode,
cityName: toCity,
addressLine1: '0',
countryCode: toCountriesCode }
},
accounts: [ { typeCode: 'shipper', number: 'my account number' } ],
plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//Might need to change later
unitOfMeasurement: 'metric',
isCustomsDeclarable: true,
monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
requestAllValueAddedServices: false,
returnStandardProductsOnly: false,
nextBusinessDay: false,
packages: [ { weight: weight, dimensions: { length: 5, width: 5, height: 5 } } ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.send(body)
console.log(body);
});
});
//Start the Server
app.listen(port, () => {
console.log(`Server running at :${port}/`);
});
My Check-Rates File:
const getRateEstimate = () => {
axios.post('http://MY_IP:3001/api/dhl', {
fromCity,
fromCountriesCapital,
fromCountriesCode,
fromPostalCode,
toCountriesCapital,
toCountriesCode,
toPostalCode,
toCity,
weight,
}).then(response => {
console.log(response)
setData(response.data);
}).catch(e => {
console.log(e)
});
}

Getting error while reading outlook mails in Node.js

Goal: I am trying to read the mails (outlook) with certain filters like 'from specified user','read','sent' etc. Used a module "IMAP" for parsing. I have to read the mail and download and store attachments from the mail in a certain location (preferably local). But my code is failing to connect to the mail server.
Below is my code which results in 'Auth:timeout error' when I ran.
Please let me know what is wrong with my code. Thanks in advance!
var Imap = require('imap'),
inspect = require('util').inspect;
var fs = require('fs'), fileStream;
var buffer = '';
var myMap;
var imap = new Imap({
user: "put user id here",
password: "put your password here",
host: "outlook.office365.com", //this may differ if you are using some other mail services like yahoo
port: 993,
tls: true,
// connTimeout: 10000, // Default by node-imap
// authTimeout: 5000, // Default by node-imap,
debug: console.log, // Or your custom function with only one incoming argument. Default: null
tlsOptions: true,
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments
});
function openInbox(cb) {
imap.openBox('INBOX', false, cb);
}
imap.once('ready', function () {
openInbox(function (err, box) {
if (err) throw err;
imap.search(['UNSEEN', ['SUBJECT', 'Give Subject Here']], function (err, results) {
if (err) throw err;
var f = imap.fetch(results, { bodies: '1', markSeen: true });
f.on('message', function (msg, seqno) {
console.log('Message #%d' + seqno);
console.log('Message type' + msg.text)
var prefix = '(#' + seqno + ') ';
msg.on('body', function (stream, info) {
stream.on('data', function (chunk) {
buffer += chunk.toString('utf8');
console.log("BUFFER" + buffer)
})
stream.once('end', function () {
if (info.which === '1') {
console.log("BUFFER" + buffer)
}
});
console.log(prefix + 'Body');
stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt'));
});
msg.once('attributes', function (attrs) {
console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
});
msg.once('end', function () {
console.log(prefix + 'Finished');
});
});
f.once('error', function (err) {
console.log('Fetch error: ' + err);
});
f.once('end', function () {
console.log('Done fetching all messages!');
imap.end();
});
});
});
});
imap.once('error', function (err) {
console.log(err);
});
imap.once('end', function () {
console.log('Connection ended');
});
imap.connect();
It's not exactly what you asked for but an alternative implementation that uses ImapFlow module instead of node-imap, and that I just verified to work against Outlook looks like the script below. If you still get timeouts etc. then it is probably a firewall issue.
const { ImapFlow } = require("imapflow");
const fs = require("fs").promises;
const client = new ImapFlow({
host: "outlook.office365.com",
port: 993,
secure: true,
auth: {
user: "example.user#hotmail.com",
pass: "secretpass",
},
logger: false, // set to true if you want to see IMAP transaction logs
});
// can't run await in main scope, have to wrap it to an async function
async function main() {
// establish the connection and log in
await client.connect();
// open INBOX folder
let mailbox = await client.mailboxOpen("INBOX");
// list messages matching provided criteria
for await (let msg of client.fetch(
{
// search query to filter messages
// https://imapflow.com/global.html#SearchObject
seen: false,
subject: "Give Subject Here",
},
{
// attributes to request for
// https://imapflow.com/global.html#FetchQueryObject
uid: true,
flags: true,
internalDate: true,
bodyStructure: true,
// include full message body in the response as well
source: true,
}
)) {
// extract variables
let { seq, uid, flags, bodyStructure, internalDate, source } = msg;
console.log(`#${seq} Attributes:`, { seq, uid, flags, bodyStructure, internalDate });
// store message body as an eml file
await fs.writeFile(`msg-${seq}.eml`, source);
}
// close the connection
await client.logout();
}
main().catch(console.error);

Invoke AWS REST API in java-script

I am trying to execute AWS Endpoint using nodejs (aws-sdk). First, I am able to generate session token for Service Account which has access to execute the API.
var AWS = require('aws-sdk');
AWS.config.update({ "accessKeyId": "<>", "secretAccessKey": "<>", "region": "us-west" });
var sts = new AWS.STS();
var response = {};
sts.assumeRole({
RoleArn: 'arn:aws:iam::170000000000:role/service-account',
RoleSessionName: 'AssumtaseRole'
}, function(err, data) {
if (err) { // an error occurred
var error = {}
response.message = err.originalError.message,
response.errno = err.originalError.errno,
response.code = 404;
console.log(response);
} else { // successful response
response.code = 200,
response.accesskey = data.Credentials.AccessKeyId,
response.secretkey = data.Credentials.SecretAccessKey,
response.sessiontoken = data.Credentials.SessionToken,
console.log(response);
}
});
Now I am trying to execute the endpoint using the above session token. If test session token using postman, I am able to execute the API but not sure how to do it using (aws-sdk) or ('aws-api-gateway-client')
I tried to execute using simple HTPPS request but getting error: Here is the code:
var AWS = require('aws-sdk');
var apigClientFactory = require('aws-api-gateway-client').default;
AWS.config.update({ "accessKeyId": "<>", "secretAccessKey": "<>", "region": "us-west" });
var sts = new AWS.STS();
var response = {};
sts.assumeRole({
RoleArn: 'arn:aws:iam::170000000000:role/service_account',
RoleSessionName: 'AssumtaseRole'
}, function(err, data) {
if (err) { // an error occurred
var error = {}
response.message = err.originalError.message,
response.errno = err.originalError.errno,
response.code = 404;
console.log(response);
} else { // successful response
response.code = 200,
response.accesskey = data.Credentials.AccessKeyId,
response.secretkey = data.Credentials.SecretAccessKey,
response.sessiontoken = data.Credentials.SessionToken,
console.log(response);
var apigClient = apigClientFactory.newClient({
invokeUrl: "https://some-endpoint.com", // REQUIRED
accessKey: data.Credentials.AccessKeyId, // REQUIRED
secretKey: data.Credentials.SecretAccessKey, // REQUIRED
sessiontoken: data.Credentials.SessionToken,
region: "us-west", // REQUIRED: The region where the AapiKeyloyed.
retries: 4,
retryCondition: (err) => { // OPTIONAL: Callback to further control if request should be retried. Uses axon-retry plugin.
return err.response && err.response.status === 500;
}
});
var pathParams = "";
var pathTemplate = "/agent/registration"; // '/api/v1/sites'
var method = "post"; // 'POST';
var additionalParams = ""; //queryParams & Headers if any
var body = {
"agent_number": "1200",
"agent_name": "Test"
};
apigClient.invokeApi(pathParams, pathTemplate, method, additionalParams, body)
.then(function(result) {
console.log(result)
}).catch(function(error) {
console.log(error)
});
// console.log(output);
}
});
Here is the error:
data:
{ message: 'The security token included in the request is invalid.' } } }
Thanks in advance.
Thank You Kiran
Please change sessiontoken to sessionToken. that will fix your issue. I have tested the code on my machine.
When i tested with sessiontoken i also received the error The security token included in the request is invalid.. It worked when i changed it to the correct key which is sessionToken.
here is simplified code. When i tested, I have hard coded accessKey, secretKey and sessionToken.
var apigClientFactory = require('aws-api-gateway-client').default;
var apigClient = apigClientFactory.newClient({
invokeUrl:'https://api-url.com', // REQUIRED
accessKey: '', // REQUIRED
secretKey: '', // REQUIRED
sessionToken: '', //OPTIONAL: If you are using temporary credentials you must include the session token
region: 'ap-southeast-2', // REQUIRED: The region where the API is deployed.
systemClockOffset: 0, // OPTIONAL: An offset value in milliseconds to apply to signing time
retries: 4, // OPTIONAL: Number of times to retry before failing. Uses axon-retry plugin.
retryCondition: (err) => { // OPTIONAL: Callback to further control if request should be retried. Uses axon-retry plugin.
return err.response && err.response.status === 500;
}
});
(() => {
apigClient.invokeApi(null, `/hello`, 'GET')
.then(function(result){
console.log('result: ', result)
//This is where you would put a success callback
}).catch( function(result){
console.log('result: ', result)
//This is where you would put an error callback
});
})()

Add video to Youtube playlist NodeJS

I am currently working through the code to programmatically create a youtube playlist using a nodejs server that I received from a previous question I had and am using the working code below to do so:
var google = require('googleapis');
var Lien = require("lien");
var OAuth2 = google.auth.OAuth2;
var server = new Lien({
host: "localhost"
, port: 5000
});
var oauth2Client = new OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:5000/oauthcallback'
);
var scopes = [
'https://www.googleapis.com/auth/youtube'
];
var youtube = google.youtube({
version: 'v3',
auth: oauth2Client
});
server.addPage("/", lien => {
var url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes
});
lien.end("<a href='"+url+"'>Authenticate yourself</a>");
})
server.addPage("/oauthcallback", lien => {
console.log("Code obtained: " + lien.query.code);
oauth2Client.getToken(lien.query.code, (err, tokens) => {
if(err){
return console.log(err);
}
oauth2Client.setCredentials(tokens);
youtube.playlists.insert({
part: 'id,snippet',
resource: {
snippet: {
title:"Test",
description:"Description",
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
lien.end(data);
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
});
});
I am now moving on to the part of my project where I am in need of a way to add videos to this playlist once I have created it. The sample code that I am following along with is only written in JS and does not detail nodejs and I am therefore stuck on how to achieve this implementation with nodejs. How could I create a method like this (received from the JS implementation from the link above):
function addToPlaylist(id, startPos, endPos) {
var details = {
videoId: id,
kind: 'youtube#video'
}
if (startPos != undefined) {
details['startAt'] = startPos;
}
if (endPos != undefined) {
details['endAt'] = endPos;
}
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
$('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
});
}
in the NodeJS language using the implementation I have already started?
I get what you mean now.If you want to add a video on your playlist then you can do that in Node using this.
youtube.playlistItems.insert({
part: 'id,snippet',
resource: {
snippet: {
playlistId:"YOUR_PLAYLIST_ID",
resourceId:{
videoId:"THE_VIDEO_ID_THAT_YOU_WANT_TO_ADD",
kind:"youtube#video"
}
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
lien.end(data);
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
If you want to render the result as HTML, First you need to use a view engine like (jade or pug) then create a template then lastly render it along with the response.
Base on your example you can do it this way:
First Create a template( Im using Pug) Save it as results.pug
html
head
title= title
body
h1= title
p=description
img(src=thumbnails.medium.url)
Then update your code below:
var google = require('googleapis');
var Lien = require("lien");
var OAuth2 = google.auth.OAuth2;
var pug = require('pug')
var server = new Lien({
host: "localhost"
, port: 5000,
views:{
path:__dirname,
name:'pug'
}
});
var oauth2Client = new OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:5000/oauthcallback'
);
var scopes = [
'https://www.googleapis.com/auth/youtube'
];
var youtube = google.youtube({
version: 'v3',
auth: oauth2Client
});
server.addPage("/", lien => {
var url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes
});
lien.end("<a href='"+url+"'>Authenticate yourself</a>");
})
server.addPage("/oauthcallback", lien => {
console.log("Code obtained: " + lien.query.code);
oauth2Client.getToken(lien.query.code, (err, tokens) => {
if(err){
return console.log(err);
}
oauth2Client.setCredentials(tokens);
youtube.playlists.insert({
part: 'id,snippet',
resource: {
snippet: {
title:"Test",
description:"Description",
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
//lien.end(data);
lien.render('results',data.snippet)
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
});
});
The things that I update on your code are:
var server = new Lien({
host: "localhost"
, port: 5000,
views:{
path:__dirname,
name:'pug'
}
});
And
//lien.end(data);
lien.render('results',data.snippet)

Telegram bot and CouchDB insert new user to DB

How Can I insert New Telegram Bot user to CouchDB?
I inserted a Sample Data jack johnsin db and was ok, But I Don't Know How Should I Take Telegram users Username and Put That in Db.
This is My Code:
import 'babel-polyfill';
import './env';
import TelegramBot from 'node-telegram-bot-api';
const bot = new TelegramBot(process.env.BOT_TOKEN, {polling: true});
/////////////////////////////////// Sample Data
var server = require('couch-db')('http://localhost:5984');
var db = server.database('users');
db.destroy(function(err) {
// create a new database
db.create(function(err) {
// insert a document with id 'jack johns'
db.insert({ _id: 'jack johns', name: 'jack' }, function(err, body) {
if (err) {
console.log('insertion failed ', err.message);
return;
}
console.log(body);
// body will like following:
// { ok: true,
// id: 'jack johns',
// rev: '1-610953b93b8bf1bae12427e2de181307' }
});
});
});
//////////////////////////////
bot.onText(/^[\/!#]start$/, msg => {
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [['Store username']],
resize_keyboard:true,
one_time_keyboard: true
})
};
bot.sendMessage(msg.chat.id, 'You Are Exist in DB', opts);
});
Solved By Myselfe,
For User ID You Can Use User_ID: msg.from.id
This is My Code:
bot.onText(/^[\/!#]start$/, msg => {
db.insert({ _id: msg.from.username }, function(err, body) {
if (err) {
console.log('insertion failed ', err.message);
return;
}
console.log(body);
});
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [['Store username']],
resize_keyboard:true,
one_time_keyboard: true
})
};
bot.sendMessage(msg.chat.id, 'You Are Exist in DB', opts);
});

Categories

Resources