I'm having a little problem figuring out how to follow, like retweet someone's tweet.
As you can probably see I can get all tweet's mentioning justinbieber but i want to be able to put somecode in the function to either retweet or like the status or even follow the user that tweeted it.
If you managed to understand all of that jumble I'd appreciate the help!
What stream.on(...) does is call the function in the second parameter every time a tweet comes up, and it passes the tweet itself as a parameter. So every action you want to do with that tweet, you need to do it in the function.
To see all information on the tweet object you can go on the Twitter API page. You have access to all of this in your anonymous function !
For retweeting every tweet :
...
stream.on('tweet', function(tweet) {
T.post('statuses/retweet/:id', { id: tweet.id_str }, function (err, data, response) {
console.log(data)
})
})
Syntax taken from twit module documentation
First time answering, I hope this helps.
Related
I am a complete newbie to Node.js, Express, and Angular. I have a Node/Express app running on my localhost. I am trying to make this into a Twitter search application, using the Twitter API, so that I can enter a search term and the API returns the search results for this search term. For this, I am using the twitter package. In index.js, I have filled in my Twitter keys and secrets at the Xs as follows:
var Twitter = require('twitter');
var client = new Twitter({
consumer_key: 'X',
consumer_secret: 'X',
access_token_key: 'X',
access_token_secret: 'X'
});
When I then put the following code into index.js, the search results for keyword "awesome" are logged to the console:
var tmpSearch = 'awesome';
client.get('search/tweets', {q: tmpSearch}, function(error, tweets, response){
if (error) throw error;
console.log(tweets);
});
This works. My home page uses a controller myCtrl, which makes sure that when the user presses the Search button (with property ng-click="search(searchTerm)"), the entered search term is assigned to the variable searchTerm (using ng-model="searchTerm" for the input area). The code for the controller is as follows:
app.controller('myCtrl', ['$scope',
function($scope){
$scope.search = function(searchTerm){
console.log("Searching for " + searchTerm);
// Search here...
console.log("Search finished.");
};
}
]);
It logs the search term to the console, but I don't know how to proceed from here. Where it says // Search here... I want to execute the client.get code from above, but I cannot use the client variable from routes/index.js in my public/javascript.js. What do I need to add to my code in order to perform the search?
I have the feeling that I am not understanding a very important part of Node/Express, but I don't know which part that is, so my search for solutions hasn't been very succesful. I have never used APIs before either, and I have spent many hours going through documentation and tutorials both for Node.js and for the Twitter API, but it's only a week ago that I started learning it so most of it isn't making a lot of sense to me yet. I have found a few examples of Node apps using the Twitter API on GitHub (most of them using different packages), of which I tried to understand the code, but I couldn't figure out what I should do. I hope someone will be patient enough to explain to me what I am missing.
You need to think about where each step is happening. The Twitter code you're showing is running in Node, on your server. The myCtrl code is AngularJS code, running in the browser. As you've sensed, there's something missing to connect them.
The flow of control will be like this:
user types in a term and clicks the Search button
your controller sends an HTTP request to your Node.js
your Node.js server makes a call to Twitter
Node.js hands the results back to the client (myCtrl)
the results are displayed to your user
You have pieces of this in place. What's missing is the HTTP request and response. Here's what you do:
add an endpoint, say, /api/twittersearch. You'll do this with Node.js and Express
the implementation of that endpoint will be a function with parameters req and res (request and response; those names are not required but are frequently used); this function will do the new Twitter and client.get code that you have above
the client.get call has a callback function, which you have currently implemented; in your callback, you'll send the tweets back to the client (something like res.send(tweets)
in your controller, your "search here" code will be something like $http.get('/api/twittersearch?term=' + searchTerm)
That last call to $http.get() returns a Promise. You'll follow that up with .then(function(tweets){ ... }).catch(function(errors){ ... }). In the function you pass to then, you'll take the results from your call and update your model.
Scenario = I am slowly but surely wrapping my head around what is going on with Parse's cloud code features. I just need some help from those who would like to answer some short, relatively simple questions about what is going on in some sample cloud code functions.
The code I will use in this example is below
1) cloud code
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.set('new_col', newColText);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
2) called from iOS
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": #"someuseridhere",
#"newColText": #"new text!"
}];
This code was taken from here
Question 1 =
(request, response)
I am confused by what this is. Is this like typecasting in iOS where I am saying (in the iOS call) I want to pass an NSString into this function ("userId") and inside the cloud code function I'm going to call it "request"? Is that what's going on here?
Question 2 =
Parse.Object.extend('_User')
Is this grabbing the "User" class from the Parse database so that a "PFObject" of sorts can update it by creating a new "user" in the line below it?
Is this like a...
PFObject *userObject = [PFObject objectWithClassName:#"User"]?
Question 3 =
user.set('new_col', newColText)
This obviously 'sets' the values to be saved to the PFUser (~I think). I know that the "newColText" variable is the text that is to be set - but what is 'new_col'? Only thing I can think of is that this sets the name of a new column in the database of whatever type is being passed through the "request"?
Is this like a...
[[PFUser currentUser] setObject: forKey:]
Question 4 =
Parse.Cloud.useMasterKey()
Without getting too technical, is this basically all I have to type before I can edit a "User" object from another User?
Question 5 =
user.save().then(function(user) {
response.success(user);
}
Is this like a...
[user saveInBackgroundWithBlock:]?
and if so, is
function(error) {
response.error(error)
just setting what happens if there is an error in the saveInBackgroundWithBlock?
Please keep in mind, I know iOS - not JavaScript. So try to be as descriptive as possible to someone who understands the Apple realm.
Here's my take on your questions:
The request parameter is for you to access everything that is part of the request/call to your cloud function, it includes the parameters passed (request.params), the User that is authenticated on the client (request.user) and some other things you can learn about in the documentation. The response is for you to send information back to the calling code, you generally call response.success() or response.error() with an optional string/object/etc that gets included in the response, again documentation here.
That's a way of creating an instance of a User, which because it is a special internal class is named _User instead, same with _Role and _Installation. It is creating an instance of the user with an ID, not creating a new one (which wouldn't have an ID until saved). When you create an object this way you can "patch" it by just changing the properties you want updated.
Again, look at the documentation or an example, the first parameter is the column name (it will be created if it doesn't exist), the second value is what you want that column set to.
You have to do Parse.Cloud.useMasterKey() when you need to do something that the user logged into the client doesn't have permission to do. It means "ignore all security, I know what I'm doing".
You're seeing a promise chain, each step in the chain allows you to pass in a "success" handler and an optional "error" handler. There is some great documentation. It is super handy when you want to do a couple of things in order, e.g.
Sample code:
var post = new Parse.Object('Post');
var comment = new Parse.Object('Comment');
// assume we set a bunch of properties on the post and comment here
post.save().then(function() {
// we know the post is saved, so now we can reference it from our comment
comment.set('post', post);
// return the comment save promise, so we can keep chaining
return comment.save();
}).then(function() {
// success!
response.success();
}, function(error) {
// uh oh!
// this catches errors anywhere in the chain
response.error(error);
});
I'm pretty much at the same place as you are, but here are my thoughts:
No, these are the parameters received by the function. When something calls the editUser cloud function, you'll have those two objects to use: request & response. The request is basically what the iOS device sent to the server, and response is what the server will send to the iOS device.
Not quite that. It's like creating a subclass of _User.
Think of Parse objects types as a database table and it's instances as rows. The set will set (derp) the value of 'newColText' to the attribute/column 'new_col'.
Not sure, never used that function as I don't handle User objects. But might be that.
Pretty much that. But it's more sort of like (pseudo-code, mixing JS with Obj-C):
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if(error){
response.error(error); // mark the function as failed and return the error object to the iOS device
}
else{
response.success(user); // mark the function call as successful and return the user object to the iOS device
}
}];
Hello i am trying to get the users tagged photos one at the time with javascript.
Here is how i call it:
FB.api('/me?fields=name,picture.type(large),photos.limit(2).type(tagged)', function(response) {
play(response.name, response.picture.data.url, response.photos.data.source);
....
And how i use them:
use: {url: "some url....", params: ['name','fb','photo1', 'photo2']},
The thing is that when i call this i get "Cannot read property 'data' of undefined "
on the photos.limit(2).type(tagged)
The other things work great. Name and profile pic.
Any ideas?
Perhaps i need to sort the results from photos.limit(2).type(tagged) or something but i have no clue o how to do that...
Any help will be awesome.
Thanx
Sounds like you aren't getting any data from the photos endpoint.
Ensure that you have user_photos permission in
FB.login(function(response) {
// handle the response
}, {scope: 'user_photos'});
I'm building an app which allows users to post to Twitter. When they click the submit button we close the posting form. We create a Message object which is saved to the data store and sent to the server. The server creates a Post object, then submits a request to Twitter. The server then updates the Post object, replies back to the UI with the updated information.
That part is already working. But I need to know if it's NOT working so that I can alert the user that their message did not go through and keep the posting form open. Here's some pertinent information about my app.
Social.Message = DS.Model.extend({
text: DS.attr("string"),
created: DS.attr("date"),
isPending: DS.attr("boolean"),
posts: DS.hasMany("Social.Post")
});
Social.Post = DS.Model.extend({
text: DS.attr("string"),
status: DS.attr("string"),
created: DS.attr("date"),
message: DS.belongsTo("Social.Message"),
msgStatus: function() {
return ((this.get('status') === 'S') ? true : false);
}.property('status')
});
The lifecycle of a post (status) goes from P (pending) to Q (queued) to S (sent), E (error) is also a possibility, and the status that I'm really looking for. Here's the saveMessage method:
saveMessage: function(text){
var acct = Social.Account.find(this.get("id")),
msg = Social.store.createRecord(
Social.Message,
{
text: text,
created: new Date()
}
);
acct.get("messages").addObject(msg);
Social.store.commit();
Ember.run.later(this, function() {
msg.get('posts').forEach(function(p){
p.reload();
});
}, 1000);
}
You can see that I pause for a second to let the server process, then attempt to reload the Post object with the response from Twitter. Those last few lines are where I think this new code would go, but I'm not sure how to listen to something that might not come back. I'd rather not "wait" for a second, instead it would be nice if the message could just update. Not sure how to accomplish that though.
Thoughts?
You need to run your code as a callback after the record is created. This is how:
msg.one('didCreate', function() {
// transition to new route showing data just created
});
Social.store.commit();
This will add a one time call on the record for when it is created. There are also 'didUpdate' and 'didDelete' hooks as well. You need to add these callbacks before the create is called (obviously).
I'm not sure how to handle the error condition as I haven't looked into that yet.
Edit: this is actually broken, per https://github.com/emberjs/data/issues/405, so waiting may be the only option currently.
It sounds like you don't want the two-way data binding here and you might benefit from one-way instead. Here is a great full length blog post that explains it a bit more in depth
http://www.solitr.com/blog/2012/06/ember-input-field-with-save-button/
I have read many Twitter & jQuery questions on here but none seem to answer my question. I am simply trying to grab 5 "tweets" from a public user. I am not doing anything with the data at this step, but my callback function never fires.
$.getJSON("https://api.twitter.com/1.1/statuses/user_timeline.json?callback=?",
{
screen_name: 'dojo',
count: '5'
},
function (data) {
alert("IT WORKED!");
});
Here is the same code on jsFiddle
Thank you for your help
That isn't going to work because Twitter has now required that you authenticate in order to fetch tweets for a given user.
Reference: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline Look at 'Authentication' info.
You'll want to use a library to help get an oauth signature and make the request.