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!
Related
I had installed Jenkins in network and making build successfully.
I want to have authentication for my iPad app, developed with unity. I searched the plugin respective to this, but i can't find it. whether this can be attained by means of plugin or otherways?
As i need to login into my jenkins and afterward use the data of pipelines and all in my app accessed through URL so need login first.
Please do let me know the ways to do. Thanks in advance
After some searching and all i found the solution for this and i used following code to check authentication.
public void TryLogin ()
{
UnityWebRequest req = UnityWebRequest.Get ("Your jenkins login url of network");
req.method = "GET";
req.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String (Encoding.UTF8.GetBytes ("jenkinsId:jenkinsPassword")));
StartCoroutine (WaitForLoginRequest (req));
}
IEnumerator WaitForLoginRequest(UnityWebRequest req)
{
yield return req.Send ();
if (req.isError)
{
Debug.Log ("WWW Error: " + req.error);
}
else
{
Debug.Log("WWW Ok!:");
string response = Encoding.UTF8.GetString (req.downloadHandler.data);
Debug.Log ("Response code = " + req.responseCode);
Debug.Log ("String = " + response);
}
}
And check the response code for authentication.
We are trying to use Exact Online API. It is using Apache OAuth 2.0 framework. For that we followed the below document.
https://developers.exactonline.com/#OAuth_Tutorial.html%3FTocPath%3DAuthentication%7C_____2
I successfully able to get the authorization code but failing to get the access_token with exception like below.
OAuthProblemException{error='invalid_request', description='Missing parameters: access_token', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
My code is like this.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
OAuthClientRequest oAuthrequest = OAuthClientRequest
.tokenLocation("https://start.exactonline.co.uk/api/oauth2/token")
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId("my client id")
.setClientSecret("my client secret")
.setRedirectURI("http://localhost:8080/SampleServlet/AuthServlet")
.setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, "POST",GitHubTokenResponse.class);
out.println("Access Token = " + oAuthResponse.getAccessToken());
} catch (OAuthSystemException ex) {
Logger.getLogger(AuthServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (OAuthProblemException ex) {
Logger.getLogger(AuthServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
Can some one please help me to sort this out.
Finally i resolved this issue with a simple change. The problem is with the line
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, "POST",GitHubTokenResponse.class);
Instead of this we have to use either of the below lines to get the access token properly.
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, OAuth.HttpMethod.POST);
(Or)
OAuthAccessTokenResponse oAuthResponse =oAuthClient.accessToken(oAuthrequest,OAuth.HttpMethod.POST);
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
I have a list of tweets with information about the user who tweeted them that I am using for an undergrad research project. To build a social network graph of these tweets I need to grab their friend and follower lists. I have tried using the GET Follower IDs call through the twitter4j platform. My authentication is Oauth with Read, write, and direct messages. I get a 400 response code with no further error code. I also get the following exception code
exceptionCode=[92c30ec6-19bed99c 70a5018f-1e1c55ac 70a5018f-1e1c55aa], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
This tells me that I'm not authenticated to make this request which from what I have read is because the people are not followers of mine. Is there a way I can request this information without having this relationship with the user?
here is my code
public static void main (String[] args){
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("something")
.setOAuthConsumerSecret("something else")
.setOAuthAccessToken("another thing")
.setOAuthAccessTokenSecret("a secret thing")
.setUseSSL(true)
.setUserStreamRepliesAllEnabled(true);
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
long cursor = -1;
IDs ids = null;
String[] users = new String[16717];
BufferedReader br = null;
try {//getting user screen names
String sCurrentLine;
br = new BufferedReader(new FileReader("users.txt"));
int i = 0;
while ((sCurrentLine = br.readLine()) != null) {
users[i]=sCurrentLine;
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for(int i=0;i<users.length;i++){
System.out.println("==================="+users[i]+"===================");
do {
try {
ids = twitter.getFollowersIDs(users[i], cursor);
for (long id : ids.getIDs()) {
System.out.println(id);
User user = twitter.showUser(id);
System.out.println(user.getName());
}
} catch (TwitterException e) {
e.printStackTrace();
}
} while ((cursor = ids.getNextCursor()) != 0);
}
}
One can obtain the list of followers IDs for any public twitter user using this API from twitter. I don't use twitter4j but it should work fine.
Main thing to be conscious of, outside of authentication, is that twitter allows fetching maximum 5000 IDs in one call and rate limits aggressively (15 calls per app/user token) so your application has to be designed and built to honor those considerations/limitations with appropriate tokens/sleeps etc.
For e.g. if you use the application token and a given user has 100K followers, twitter will start returning rate_limit_exceeded errors after fetching 75K (5K * 15) followers IDs.
In an extremely embarrassing turn of events it turns out that the reason the request could not be made is that the usernames I was searching with had an extra space. So I trimmed each name and it works now.
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.