I'm building a chatbot that retrieves a youtube link based on what the user has asked.
I'm using Dialogflow for the bot and using nodejs for the coding.
Right now, everything works perfectly but my problem is retrieving the link from the API response.
using console.dir(results), shows the following:
This is how the response looks like:
[ { id: 'gWNUg_v25dw',
link: 'https://www.youtube.com/watch?v=gWNUg_v25dw',
kind: 'youtube#video',
publishedAt: '2017-08-24T14:00:11.000Z',
channelId: 'UCDZ56yQ05d_ikcwcTG9bAiA',
channelTitle: 'Code to Create',
title: 'How to make a Chatbot with Dialogflow - API.ai',
description: 'In this video, Google Developer Expert, Faisal Abid will show us how to create a chatbot with Google\'s latest API.ai API.ai can be integrated with multiple chat ...',
thumbnails: { default: [Object], medium: [Object], high: [Object] } } ]
I have tried using results.link to retrieve the link but Im getting undefined, so my question is how to retrieve the link from the response block?
search(txt1, opts, function(err, results) {
//var data1 = JSON.parse(results);
//srchRes = data1.link;
if(err) return console.log(err);
console.dir(results);
});
uncommenting the 2 lines above and console.dir(srchRes) returns this error:
SyntaxError: Unexpected token u in JSON at position 0
We don't have your API call code logic so from here, we could only assume results is the API's response and given your exemple about how the response look like, then we see results is an array of object.
JSON.parse actually deserialize a string which represent an object given the JSON format.
JSON.stringify is the contrary, it serialize your object to a string with the JSON format.
Your goal is to reach the link properties of a particular object within the array, which is why JSON.parse(results) makes no sense.
You should be able to reach linkproperties for each object by simply iterate over the array of object results
for (const result of results) {
console.log(`the link : ${result.link}`)
}
Related
I am doing this for learning purpose. I have url to RSS feed that I'd like to work further. This feed contains too much information. I'm interested only in all "item", their "title", "description" and "pubDate". I am using "firebase deploy --only functions" and then checking url for deployment where I expect to see cleaned data. For some reason I am getting error in cloud functions logs: "TypeError: Cannot read property 'channel' of undefined
at cleanUp (/user_code/lib/index.js:19:29)"
I tried this with another URL which surprisingly worked: https://www.theguardian.com/uk/london/rss
Here is the URL to RSS feed I want to use:
https://polisen.se/aktuellt/rss/hela-landet/handelser-i-hela-landet/
Here is my cleanUp function:
function cleanUp(data) {
const items = []
const channel = data.rss.channel
channel.item.forEach(element => {
items.push({
title: element.title,
description: element.description,
date: element.pubDate
})
});
return items
}
I expect to see all items with children title, description and pubdate after deployment. Instead I get "Error: could not handle the request" and when I check my logs in google cloud functions I see:
"TypeError: Cannot read property 'channel' of undefined
at cleanUp (/user_code/lib/index.js:19:29)"
To do so I would recommend working with JSON objects. So what I did is to get the RSS feed and convert it to a JSON object. Then parse item by item and log the data you need.
I have did a little bit of coding my self. Follow the steps below to get an idea of my example and then modify the code according to your needs:
Create a new Google Cloud Function
Trigger: HTTP
Runtime: Node.js 8
Add dependencies in package.json:
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"rss-to-json": "^1.0.4"
}
}
In index.js replace the code with my GitHub code example.
I have tested the code my self and it logged 200 items using the link you provided. Basically I take the RSS and convert it to JSON object. Then I iterate through all the items and log each item's property.
I am trying to display a list of objects stored in my AWS S3 bucket on the front-end. I can easily retrieve the list of objects using the listObjects() method.
Only problem is that I have some metadata associated with each object that I also want to retrieve and display along with the list. The listObjects() method does not retrieve the metadata of each object. It seems the only way to retrieve the metadata of an object is by using the headObject() method.
However, headObject() only fetches the metadata of one object at a time and it obviously requires me to iterate over the list of objects returned by listObjects() and then retrieve the metadata for each object using headObject(). I was wondering if there is a way to retrieve the list of objects plus the metadata associated with each object with one API call? The solution mentioned above works but slows down the performance of the application considerably.
listObjectsV2() returns the following data:
/* The following example retrieves object list. The request specifies max keys to limit response to include only 2 object keys. */
var params = {
Bucket: "examplebucket",
MaxKeys: 2
};
s3.listObjectsV2(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
/*
data = {
Contents: [
{
ETag: "\"70ee1738b6b21e2c8a43f3a5ab0eee71\"",
Key: "happyface.jpg",
LastModified: <Date Representation>,
Size: 11,
StorageClass: "STANDARD"
},
{
ETag: "\"becf17f89c30367a9a44495d62ed521a-1\"",
Key: "test.jpg",
LastModified: <Date Representation>,
Size: 4192256,
StorageClass: "STANDARD"
}
],
IsTruncated: true,
KeyCount: 2,
MaxKeys: 2,
Name: "examplebucket",
NextContinuationToken: "1w41l63U0xa8q7smH50vCxyTQqdxo69O3EmK28Bi5PcROI4wI/EyIJg==",
Prefix: ""
}
*/
});
Does that suit your use case? If not, perhaps an architectural solution would help. Set up webhooks on the bucket which update a dynamodb document, then query once for the document. Alternately, set up a lambda which abstracts away the S3 queries and returns the combined results.
I am delving into spotify and javascript is not my main programming language so I managed to get some snippets together from a code that uses ajax (which I would rather not use) but still it returns nothing so I am wondering if some more experienced people out there could help me get started with a template to call the api.
My goal for this test is to search an artist name and get the first result (I expect many names will return multiple artists)
Most of what is in the documentation is curl and I didn't find the demos very helpful.
What I have so far is something like this:
function getArtistName (artistName) {
var artistID;
var searchArtists = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'artist',
'accessToken': 'BQBvW70gHJ20Flc8cHErqg8s72bfTePbssblED-gpEuHFr_Yezesbthok8qaKBmjzo2WjWo9J7ZcTpSwvV8MZ_cW_E7UkrG_HF2R6gFQcqfdupgYGmoYsdRdt1q3tq2NU3pPgauuzmFLkUpdAuNp3shdVXJz2SzvnA',
'query': artistName,
limit: '1.'
},
success: function (response) {
//resultsPlaceholder.innerHTML = template(response);
}
});
};
console.log(searchArtists);
return artistID;
}
Some points of confusion:
The key seems to expire. I have a client ID on my profile but I am not sure where I can generate this token other than the "try it out" demo on the site.
What does this actually return, an ID or a JSON?
Here is a demo app that searches tracks using Node.js, or server-side Javascript: https://spotify-quicksearch.glitch.me/
If you click the "Remix this on Glitch" link on the page, you can see and edit the source.
The call to the API is made in server.js. First, we set the client ID and client secret, which are from the dashboard, as you've noted. In this example, we use those to get an access token using the Client Credentials Flow. You can read about all the authentication flows here: https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/
This particular example uses an API wrapper called spotify-web-api-node, which just makes it easier to interact with the API through Javascript functions. To search for artists instead, just change searchTracks to searchArtists.
To answer your second question - all calls to the Spotify API return JSON. You can see the format of the full JSON response here: https://beta.developer.spotify.com/documentation/web-api/reference/search/search/. Roughly, it looks like this:
artists: {
items: [
{
id: <id>,
name: <name>,
...
}
...
]
}
To get the ID from the JSON, you need to parse the JSON object. You can see how I do this in the example in line 21 of client.js. You can modify that code to get just the ID of the first artist like this:
data.artists.items[0].id
Update: made an example that should be even more relevant:
https://spotify-search-artist.glitch.me/
In my user collection, I have an object that contains an array of contacts.
The object definition is below.
How can this entire object, with the full array of contacts, be written to the user database in Meteor from the server, ideally in a single command?
I have spent considerable time reading the mongo docs and meteor docs, but can't get this to work.
I have also tried a large number of different commands and approaches using both the whole object and iterating through the component parts to try to achieve this, unsuccessfully. Here is an (unsuccessful) example that attempts to write the entire contacts object using $set:
Meteor.users.update({ _id: this.userId }, {$set: { 'Contacts': contacts}});
Thank you.
Object definition (this is a field within the user collection):
"Contacts" : {
"contactInfo" : [
{
"phoneMobile" : "1234567890",
"lastName" : "Johnny"
"firstName" : "Appleseed"
}
]
}
This update should absolutely work. What I suspect is happening is that you're not publishing the Contacts data back to the client because Meteor doesn't publish every key in the current user document automatically. So your update is working and saving data to mongo but you're not seeing it back on the client. You can check this by doing meteor mongo on the command line then inspecting the user document in question.
Try:
server:
Meteor.publish('me',function(){
if (this.userId) return Meteor.users.find(this.userId, { fields: { profile: 1, Contacts: 1 }});
this.ready();
});
client:
Meteor.subscribe('me');
The command above is correct. The issue is schema verification. Simple Schema was defeating the ability to write to the database while running 'in the background'. It doesn't produce an error, it just fails to produce the expected outcome.
I am trying to retrieve UUIDs of devices connected to 'my_channel'.
I was using pubnub-3.16.4.js and I was able to get the UUID array using "Here Now".
Now I upgraded to pubnub.4.1.1.js, I followed the example on this site
https://www.pubnub.com/docs/javascript/presence-sdk-v4
when I use Here Now function I do get a response, which includes all state and UUIDs information.
Object {totalChannels: 1, totalOccupancy: 2, channels: Object}
channels:Object
mychannel:Object
name:"my_channel"
occupancy:2
occupants:Array[3]
0: Object
state:null
uuid:"000000003d425f88"
__proto__:Object
1: Object
state:null
uuid:"newmanager" ......................
But what I need is only UUID array, which the sdk example shows.
Any idea how get only UUID array, or is there an easy way to retrieve the UUIDs from the above response?
Thank you.
PubNub Presence Here Now - without state data
pubnub.hereNow(
{
channels: ["ch1"],
includeUUIDs: true,
includeState: false
},
function (status, response) {
// handle status, response
}
);
See full Node SDK hereNow docs for full parameter details and sample code.