I'm trying to create a small website which takes user's twitter username and retrieve the basic information from it like: screen name, created date, number of followers, etc... and display it. But I couldn't find a new helpful working tutorial or example of how to work with twitter API. Can someone please recommend something for me or just give some instructions of how should I start and work please? I prefer it to be done with Java or PHP.
Also I have a problem, when creating my application access key in twitter, I can't create the access token! the button is not shown! how can I solve this?
You Can use below code-
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterSearch {
private static final String CATEGORY = "Mobile";
private static final String SOURCE = "Twitter";
public static void main(String ...args) throws TwitterException, IOException
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(TwitterConfig.OATH_CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterConfig.OATH_CONSUMER_SECRET)
.setOAuthAccessToken(TwitterConfig.OATH_ACCESS_TOKEN)
.setOAuthAccessTokenSecret(TwitterConfig.OATH_ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
System.out.println("Product to be searched " + args[0]);
Query query = new Query(args[0]);
query.setLang("en");
query.setLocale("en_IN");
query.setCount(100);
QueryResult result = twitter.search(query);
System.out.println("Output File "+ args[1]);
System.out.println(result.getTweets());
for(Status tweet : result.getTweets())
{
System.out.println(tweet.getText());
}
}
}
result.getTweets() return a List, and you can iterate over that list and can print tweet.getText() to print tweet.
Use this maven dependency-
<dependency><groupId>org.twitter4j</groupId><artifactId>twitter4j-core</artifactId><version>[4.0,)</version></dependency>
Refer below link for keys-
https://dev.twitter.com/oauth/overview
Related
I have some parameters stored in environment variables -- certainly those environment variables work with powershell.
Do I need slightly different parameters to authenticate with Twitter4J, perhaps?
powershell script output:
thufir#dur:~$
thufir#dur:~$ pwsh /home/thufir/powershell/helloPSTwitterAPI/twitter.ps1
RT #adamdriscoll: Today is the last day to sign up for the #Powershell #UniversalDashboard #udemy course at a discount rate. Check it out h…
RT #DirectoryRanger: Invoke-CommandAs
htt...
RT #adamdriscoll: Just added some #UniversalAutomation documentation about pre-defined variables in UA jobs. htt....
RT #adamdriscoll: #PowerShell #UniversalDashboard 2.8.2 is now available on the PowerShell Gallery. Lots of fixes, some improvements to Adm…
#psdevuk #adamdriscoll #psdbatools 👀
#adamdriscoll 🔥
#BillKindle #McDonalds #Wendys Sad, but that’s what I’m going to do next time. It should be ‘BigMac with Bacon Bits… htt...
I was excited to try out the new BigMac with Bacon... but horrible portion.. looks like cesar salad bacon bits...… htt...
#WindosNZ PSTwitterAPI? ;)
#Marioperator Thanks for the shoutout ❤️
RT #adamdriscoll: Nice! Financial charts for UD! htt.... #powershell htt...
#TomatoApp1 Constantly having to bind/unbind MiaoMiao device. And now the app won’t even open after trying reinstal… htt....
#adamdriscoll It shall get indexed and searchable in 15 minutes! I can just imagine your amazon shopping suggestions...
#adamdriscoll #LeeAlanBerg Pics or it didn’t happen
#SwiftOnSecurity #adbertram Did you end up finding a more elegant solution?
RT #racheldianeb: Had cake and wine tonight. 2 things I said I wouldn’t consume in Jan and would generally limit in 2020. It’s Jan 1st. So…
#adilio #sstranger Someone would probably be wrong.. 😝
#AndrewPlaTech #sstranger You have nothing to lose.. I mean, clearly I lost.. ;)
Someone’s mother has four sons. North, South and East. What is the name of the fourth son. Private message me the n… htt....
RT #EssentialSign_: For whoever needs this this evening. htt....
done
thufir#dur:~$
powershell script source:
thufir#dur:~$
thufir#dur:~$ cat /home/thufir/powershell/helloPSTwitterAPI/twitter.ps1
Import-Module PSTwitterAPI
#Set-TwitterOAuthSettings -ApiKey $env:ApiKey -ApiSecret $env:ApiSecret -AccessToken $env:AccessToken -AccessTokenSecret $env:AccessTokenSecret
Set-TwitterOAuthSettings -ApiKey $env:oAuthConsumerKey -ApiSecret $env:oAuthConsumerSecret -AccessToken $env:oAuthAccessToken -AccessTokenSecret $env:oAuthAccessTokenSecret
$TwitterStatuses = Get-TwitterStatuses_UserTimeline -screen_name 'mkellerman'
Foreach ($status in $TwitterStatuses) {
Write-Host $status.text
}
Write-Host "done"
thufir#dur:~$
java crash:
thufir#dur:~/java/helloTwitter4J$
thufir#dur:~/java/helloTwitter4J$ gradle clean run
> Task :run FAILED
Jan. 29, 2020 4:16:31 P.M. helloTwitter4J.App runQuery
INFO: {oAuthAccessToken=abc, oAuthConsumerKey=def, oAuthConsumerSecret=ghi, oAuthAccessTokenSecret=jkl}
Exception in thread "main" java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details
at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:201)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1966)
at twitter4j.TwitterImpl.search(TwitterImpl.java:293)
at helloTwitter4J.App.runQuery(App.java:52)
at helloTwitter4J.App.main(App.java:60)
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':run'.
> Process 'command '/home/thufir/.sdkman/candidates/java/12.0.1-zulu/bin/java'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
4 actionable tasks: 4 executed
thufir#dur:~/java/helloTwitter4J$
java source:
package helloTwitter4J;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class App {
private static final Logger log = Logger.getLogger(App.class.getName());
private final Properties properties = new Properties();
private void loadProperties() throws InvalidPropertiesFormatException, IOException {
properties.loadFromXML(App.class.getResourceAsStream("/twitter.xml"));
log.fine(properties.toString());
Set<Object> keySet = properties.keySet();
String key = null;
String value = null;
for (Object obj : keySet) {
key = obj.toString();
value = System.getenv(key);
log.fine(key + value);
properties.setProperty(key, value);
}
}
private void runQuery() throws TwitterException, InvalidPropertiesFormatException, IOException {
loadProperties();
log.info(properties.toString()); //this matches what powershell uses
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true)
.setOAuthConsumerKey(properties.getProperty("oAuthConsumerKey"))
.setOAuthConsumerSecret(properties.getProperty("oAuthConsumerSecret"))
.setOAuthAccessToken(properties.getProperty("oAuthAccessToken"))
.setOAuthAccessTokenSecret(properties.getProperty("oAuthAccessTokenSecret"));
Twitter twitter = TwitterFactory.getSingleton();
Query query = new Query("source:twitter4j yusukey");
QueryResult result = twitter.search(query);
// for (Status status : result.getTweets()) {
// log.info("#" + status.getUser().getScreenName() + ":" + status.getText());
// }
}
public static void main(String[] args) throws InvalidPropertiesFormatException, IOException, TwitterException {
new App().runQuery();
}
}
I've also printed the properties file to the console and it looks correct. Certainly the variables are getting picked up, I'm just not entirely sure they're what Twitter4J requires. Perhaps a specific twitter.properties file would help.
whoops, need to actually build the factory properly:
https://www.dummies.com/web-design-development/mobile-apps/how-to-make-a-configurationbuilder-to-talk-to-the-twitter-server-with-your-android-app/
working hello world type code:
package helloTwitter4J;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class App {
private static final Logger log = Logger.getLogger(App.class.getName());
private Properties loadProperties() throws IOException {
Properties properties = new Properties();
properties.loadFromXML(App.class.getResourceAsStream("/twitter.xml"));
log.fine(properties.toString());
Set<Object> keySet = properties.keySet();
String key = null;
String value = null;
for (Object obj : keySet) {
key = obj.toString();
value = System.getenv(key);
log.fine(key + value);
properties.setProperty(key, value);
}
return properties;
}
private TwitterFactory configTwitterFactory() throws IOException {
Properties properties = loadProperties();
log.info(properties.toString()); //this matches what powershell uses
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true)
.setOAuthConsumerKey(properties.getProperty("oAuthConsumerKey"))
.setOAuthConsumerSecret(properties.getProperty("oAuthConsumerSecret"))
.setOAuthAccessToken(properties.getProperty("oAuthAccessToken"))
.setOAuthAccessTokenSecret(properties.getProperty("oAuthAccessTokenSecret"));
TwitterFactory twitterFactory = null;
twitterFactory = new TwitterFactory(configurationBuilder.build());
return twitterFactory;
}
private void getHomeTimeLine() throws TwitterException, IOException {
Twitter twitter = configTwitterFactory().getInstance();
List<Status> statuses = null;
statuses = twitter.getHomeTimeline();
System.out.println("Showing home timeline.");
if (statuses != null) {
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":"
+ status.getText());
}
}
}
public static void main(String[] args) throws TwitterException, IOException {
new App().getHomeTimeLine();
}
}
also see https://github.com/nisrulz/twitterbot-java/blob/master/src/github/nisrulz/bot/TwitterBot.java
I'm trying to generate a list of all my saved reddit items using JRAW.
I've gone through the Quickstart , and successfully managed to login and retrieve information, and I can get a list of items on the Frontpage from the Cookbook, but I can't work out how I would get a list of my saved items (comments and posts) or a list of my own posts (also comments and posts).
The saved items are at https://www.reddit.com/user/<username>/saved/, but I don't know how to get jraw to retrieve and parse that, or if the api uses a different URL.
Edit: I think I probably need to use a UserContributionPaginator, but I haven't quite worked out exactly how to get it to work yet.
Worked it out.
package com.jraw;
import net.dean.jraw.RedditClient;
import net.dean.jraw.http.UserAgent;
import net.dean.jraw.http.oauth.Credentials;
import net.dean.jraw.http.oauth.OAuthData;
import net.dean.jraw.http.oauth.OAuthException;
import net.dean.jraw.models.Contribution;
import net.dean.jraw.models.Listing;
import net.dean.jraw.paginators.UserContributionPaginator;
public class printSaved {
public static void main(String [] args) {
UserAgent myUserAgent = UserAgent.of("desktop", "com.jraw.printSaved", "v0.01", "user");
RedditClient redditClient = new RedditClient(myUserAgent);
String username = "username";
Credentials credentials = Credentials.script(username, "<password>", "<clientId>", "<clientSecret>");
OAuthData authData = null;
try {
authData = redditClient.getOAuthHelper().easyAuth(credentials);
} catch (OAuthException e) {
e.printStackTrace();
}
redditClient.authenticate(authData);
UserContributionPaginator saved = new UserContributionPaginator(redditClient,"saved",username);
Listing<Contribution> savedList = saved.next();
for (Contribution item : savedList) {
System.out.println(item);
}
}
}
i'm trying to handle my Google Agenda by using the Google Calendar APi V3( Java ).
However, i'm quite new to this and to OAUTH2 .. then i've searched for examples and i found one here :
Google Calendar API V3 Java: Unable to use 'primary' for Calendars:get
Here is the code :
import java.io.IOException;
import java.util.Collections;
import java.util.Scanner;
import java.util.Set;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.extensions.auth.helpers.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.Calendar.CalendarList;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.CalendarListEntry;
public class App {
public static void main(String[] args) throws IOException{
//Two globals that will be used in each step.
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
//Create the authorization code flow manager
Set<String> scope = Collections.singleton(CalendarScopes.CALENDAR);
String clientId = "xxxxxx.apps.googleusercontent.com";
String clientSecret = "xxxxxxxxxxx";
//Use a factory pattern to create the code flow
AuthorizationCodeFlow.Builder codeFlowBuilder =
new GoogleAuthorizationCodeFlow.Builder(
httpTransport,
jsonFactory,
clientId,
clientSecret,
scope
);
AuthorizationCodeFlow codeFlow = codeFlowBuilder.build();
//set the code flow to use a dummy user
//in a servlet, this could be the session id
String userId = "ipeech";
//"redirect" to the authentication url
String redirectUri = "https://www.example.com/oauth2callback";
AuthorizationCodeRequestUrl authorizationUrl = codeFlow.newAuthorizationUrl();
authorizationUrl.setRedirectUri(redirectUri);
System.out.println("Go to the following address:");
System.out.println(authorizationUrl);
//use the code that is returned as a url parameter
//to request an authorization token
System.out.println("What is the 'code' url parameter?");
String code = new Scanner(System.in).nextLine();
AuthorizationCodeTokenRequest tokenRequest = codeFlow.newTokenRequest(code);
tokenRequest.setRedirectUri(redirectUri);
TokenResponse tokenResponse = tokenRequest.execute();
//Now, with the token and user id, we have credentials
com.google.api.client.auth.oauth2.Credential credential = codeFlow.createAndStoreCredential(tokenResponse, userId);
//Credentials may be used to initialize http requests
HttpRequestInitializer initializer = credential;
//and thus are used to initialize the calendar service
Calendar.Builder serviceBuilder = new Calendar.Builder(
httpTransport, jsonFactory, initializer);
serviceBuilder.setApplicationName("Example");
Calendar calendar = serviceBuilder.build();
//get some data
String calendarID = "xxxxxxxxxxx";
getCalendarListSummary(calendarID,calendar);
getAllCalendarListSummary(calendar);
//getCalendarSummary(calendarID,calendar);
}
public static void getCalendarListSummary(String calendarID, Calendar calendar) throws IOException{
CalendarListEntry calendarListEntry = calendar.calendarList().get(calendarID).execute();
System.out.println(calendarListEntry.getSummary());
}
public static void getAllCalendarListSummary (Calendar calendar) throws IOException{
Calendar.CalendarList.List listRequest = calendar.calendarList().list();
com.google.api.services.calendar.model.CalendarList feed = listRequest.execute();
for(CalendarListEntry entry:feed.getItems()){
System.out.println("ID: " + entry.getId());
System.out.println("Summary: " + entry.getSummary());
}
}
When i launch the programm, it asks me to give the authorization code ("What is the 'code' url parameter?") but i don't know where to find it .. Any ideas ?
In this example, there is a part that says "Go to the following address:" you have to copy that url, paste it in the browser and then you will receive the authorization code. Copy that code and paste it after "What is the 'code' url parameter?" and press "Enter" so the program can continue.
This is a basic example and that why the OAuth 2 flow is done that way.
Here is a complete example of a Google calendar java program. I would suggest to first understand how OAuth 2 works, how to create projects in the Developer console and how to create credentials for those projects. Then it would be easier to understand and use the complete example.
this is what is the code and i get the problem in marked lines(BOLD), i think it is because of the jar version but i am not sure about this. if this is because of jar version please do let me know the right one.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
public class NamexTweet {
private final static String CONSUMER_KEY = "xxxxxxxxxxxxx";
private final static String CONSUMER_KEY_SECRET = "yyyyyyyyyyyyyyy";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
**RequestToken requestToken = twitter.getOAuthRequestToken();**
System.out.println("Authorization URL: \n"
+ requestToken.getAuthorizationURL());
AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) {
try {
System.out.print("Input PIN here: ");
String pin = br.readLine();
**accessToken = twitter.getOAuthAccessToken(requestToken, pin);**
} catch (TwitterException te) {
System.out.println("Failed to get access token, caused by: "
+ te.getMessage());
System.out.println("Retry input PIN");
}
}
System.out.println("Access Token: " + accessToken.getToken());
System.out.println("Access Token Secret: "
+ accessToken.getTokenSecret());
twitter.updateStatus("hi.. im updating this using Namex Tweet for Demo");
}
public static void main(String[] args) throws Exception {
new NamexTweet().start();// run the Twitter client
}
}
Make sure the jar is actually in the build path (if I knew your IDE I might have given more concrete instructions).
If this doesn't solve the problem, search these classes and methods in that jar. If they're there - try to perform step 1 above better... If it's not there - then you have the wrong jar.
twitter4j 2.2.4 is the reliable version, which can be used.
You have to attach following libraries:
twitter4j-core-4.0.4.jar
twitter4j-stream-4.0.4.jar
I would like to pre-fill and periodically put data to the Google Appengine database.
I would like to write a program in java and python that connect to my GAE service and upload data to my database.
How can I do that?
Thanks
Please use RemoteAPI for doing this programmatically.
In python, you can first configure the appengine_console.py as described here
Once you have that, you can launch and write the following commands in the python shell:
$ python appengine_console.py yourapp
>>> import yourdbmodelclassnamehere
>>> m = yourmodelclassnamehere(x='',y='')
>>> m.put()
And here is code from the java version which is self explanatory (directly borrowed from the remote api page on gae docs):
package remoteapiexample;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;
import java.io.IOException;
public class RemoteApiExample {
public static void main(String[] args) throws IOException {
String username = System.console().readLine("username: ");
String password =
new String(System.console().readPassword("password: "));
RemoteApiOptions options = new RemoteApiOptions()
.server("<your app>.appspot.com", 443)
.credentials(username, password);
RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options);
try {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
System.out.println("Key of new entity is " +
ds.put(new Entity("Hello Remote API!")));
} finally {
installer.uninstall();
}
}
}