I want to get tweets by particular user by entering its userId.
I can search for a text by:
Query query = new Query("Hi");
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() +
" - " + tweet.getText());
}
} while ((query = result.nextQuery()) != null);
but how can I search for the tweets by entering particular userId, is there any direct method or I have to apply logic ?
I am trying:
Status status = twitter.showStatus(id);
if (status != null){
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());}
where id is userId, but by doing this, I am getting the error:
Failed to search tweets: 404:The URI requested is invalid or the
resource requested, such as a user, does not exists. Also returned
when the requested format is not supported by the requested method.
message - No status found with that ID. code - 144
Can anyone please help me with this?
With the Twitter API you can get up to ~3200 tweets from an user, to do this you can get the time line from an specific user, see those questions
Get tweets of a public twitter profile
Twitter4J: Get all statuses from Twitter account
By the way, you are getting that error because you are using twitter.showStatus(id); with an userid, you need to call twitter.showUser(id) and you won't get that error
Related
I have troubles using the default template that implements Facebook login (and other providers).
I can get logged to the app, however logged I would like to arrive on a register form, pre-filled with Facebook data (in order to complete the profile).
I don't have issue to get the default claims (email, names), however I can't add birthday or location.
My startup has the following lines:
fo.Scope.Add("public_profile");
fo.Scope.Add("email");
fo.Scope.Add("user_birthday");
fo.Scope.Add("user_location");
...
app.UseFacebookAuthentication(fo);
This works, but does not ask for these permissions during the login process.
And if I add
fo.Fields.Add("location"); or
fo.Fields.Add("user_birthday");
The login process in the callback fails.
The external login call is the default one:
var redirectUrl = Url.Action("ExternalLoginCallback", Name, new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
And the callback is the following:
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
return RedirectToAction(nameof(Login));
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
if (result.IsLockedOut)
return View("Lockout");
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
Console.WriteLine("Debug claims!");
foreach (var c in info.Principal.Claims)
Console.WriteLine("---> " + c.Subject + ":" + c.Value + " " + c.ToString());
Console.WriteLine("End Debug claims!");
I never got anything more than the default claims and got some exceptions like this when adding the Fields on startup
An unhandled exception has occurred: Response status code does not indicate success: 400 (Bad Request).
System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.AspNetCore.Authentication.Facebook.FacebookHandler.<CreateTicketAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Authentication.OAuth.OAuthHandler`1.<HandleRemoteAuthenticateAsync>d__5.MoveNext()
Any idea on how to do this? (not via the graph API, even if it is much easier)
I have been searching for hours and cannot find anything else than "email" issues.
The two issues are:
1. Why at login, the scopes set on startup are not required?
2. How to retreive the fields from Facebook? (birthday, gender, location)
There seems to be many different tutorials and examples out there to allow for tweets to be pulled into Processing from one specific user.
And yet I'm still having problems getting any code to work. I have managed to get tweets by searching with hashtags, so the twitter4j library (latest) is working within Processing (also latest software). I still a complete coding novice...
I've found the following code to do exactly what I need, but unfortunately it isn't complete, where I'm assuming you need to declare your Consumer Keys and Access tokens... But I've no idea how to do this with this code. Is this something that someone is able to provide and explain?
Essentially, I need the full sketch... Any help would be greatly appreciated!
Code from elsewhere:
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken accessToken = new AccessToken(TWITTER_TOKEN,
TWITTER_TOKEN_SECRET);
twitter.setOAuthAccessToken(accessToken);
try {
Status status = twitter.showStatus(Long.parseLong(tweetID));
if (status == null) { //
// don't know if needed - T4J docs are very bad
} else {
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException e) {
System.err.print("Failed to search tweets: " + e.getMessage());
// e.printStackTrace();
// DON'T KNOW IF THIS IS THROWN WHEN ID IS INVALID
}
EDIT: This is how I've added the consumer/access keys - is this right?
twitter.setOAuthConsumer("MyConsumerKey", "MyConsumerSecret");
AccessToken accessToken = new AccessToken("MyAccessToken", "MyAccessTokenSecret");
twitter.setOAuthAccessToken(accessToken);
EDIT2: This is what I have now to get the User's tweets. But produced the error: 'cannot convert from ResponseList to Status'
String user="USER ID";
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("MY CONSUMER KEY", "MY CONSUMER KEY SECRET");
AccessToken accessToken = new AccessToken("MY TWITTER TOKEN", "MY TWITTER TOKEN SECRET");
twitter.setOAuthAccessToken(accessToken);
try {
Status status = twitter.getUserTimeline(user);
if (status == null) { //
// don't know if needed - T4J docs are very bad
} else {
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException e) {
System.err.print("Failed to search tweets: " + e.getMessage());
// e.printStackTrace();
// DON'T KNOW IF THIS IS THROWN WHEN ID IS INVALID
}
you need first to create a twitter app, to do so go to https://apps.twitter.com/, from there you can get all the infos needed to get your credentials.
in your code just replace the 'CONSUMER_KEY','CONSUMER_KEY_SECRET','Access Token','Access Token Secret' by the credentials.
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("XXXXX")
.setOAuthConsumerSecret("XXXXXX")
.setOAuthAccessToken("XXXX-XXXXX")
.setOAuthAccessTokenSecret("XXXXXXX");
hope this help!
I do some analysis on twitter users features like number of following , number of retweet, number of friend , etc
I have all my information from Twitter Rest API
But there is an Rate Limit Exceeded error occurred when I tried to retrieve all data
can I have all these data from Twitter Streaming API , if I can , how I can you it?
If not what Is the Solution?
Thanks for Help
On each response you can call getRateLimitStatus() to get a RateLimitStatus and if remaining calls is 0, sleep the thread till time limit is over.
do {
TwitterResponse response = twitter.getFollowersIDs(userId, cursor);
RateLimitStatus status = response.getRateLimitStatus();
if(status.getRemaining() == 0) {
try {
Thread.sleep(status.getSecondsUntilReset() * 1000);
}
catch(InterruptedException e) {
// ...
}
}
} while(cursor > 0);
Twitter API update limits error 403
When executing a twitter query i get a 403 error, the error message is below, however my other queries work perfectly and are executed prior to this one, can anyone spot what may be wrong here:
TWITTER EXCEPTION: TwitterException{exceptionCode=[f3acd3ed-00581fa3], statusCode=403, retryAfter=0, rateLimitStatus=null, version=2.1.5-SNAPSHOT(build: d372a51b9b419cbd73d416474f4a855f3e889507)}
this occurs when i execute a search from my app, im not overdoing the limits as i can execute my other searches perfectly its just this one, any help would be appreciated, the code is listed below. im using a combination of Twitter4j and Processing with controlP5 to handle the input like the search.
void setup(){
...
cp5.addTextfield("SEARCH")
.setPosition(30,20)
.setSize(100,20)
.setFocus(true)
.setColor(color(255,0,0))
.setGroup(g2)
;
}
public void SEARCH(String theText) {
qm.srch = true;
qm.theText = theText;
qm.userSearch();
qm.srch = false;
// automatically receives results from controller input
println("a textfield event for controller 'input' : "+theText);
}
void userSearch() {
try {
if (srch) {
ConfigurationBuilder cb9 = new ConfigurationBuilder();
cb9.setOAuthConsumerKey("XXXXXXXXXXXXXXXXXXXXXX");
cb9.setOAuthConsumerSecret("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx");
cb9.setOAuthAccessToken("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
cb9.setOAuthAccessTokenSecret("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
println("Connected");
Twitter twitter = new TwitterFactory(cb9.build()).getInstance();
Query srchh = new Query(theText2);
srchh.setRpp(5);
QueryResult srchhRes = twitter.search(srchh);
ArrayList srchhTwe = (ArrayList) srchhRes.getTweets();
for (int i = 0; i < srchhTwe.size(); i++) {
Tweet t = (Tweet) srchhTwe.get(i);
String user = t.getFromUser();
GeoLocation l = t.getGeoLocation();
String locNam = t.getLocation();
String msg = t.getText();
wholeTweetsL.add(msg);
println("\nMessage: " + msg);
println("\nLocation: " + locNam);
}
}
}
catch(TwitterException e) {
println("TWITTER EXCEPTION: " + e);
}
}
From twitter at https://dev.twitter.com/docs/error-codes-responses
403 Forbidden The request is understood, but it has been refused or access is not allowed. An accompanying error message will explain why. This code is used when requests are being denied due to update limits.
With google, you can fetch the user's email like this:
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
request.AddExtension(fetch);
and get it back like this:
var fetch = response.GetExtension<FetchResponse>();
string email = "";
if (fetch != null)
{
email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
}
When writing a provider, how can I return the values asked for?
The OpenIdProviderWebForms sample that comes with DotNetOpenAuth includes returning user attributes. Have you checked it out?