Twitter getMentionTimeLine - java

how to use time/count in twitter getmentiontime line
I am able to get time line of user but now
I want to get mention time line of last 30 minutes.
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRET)
.setOAuthAccessToken(ACCESS_TOKEN)
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
User user = twitter.verifyCredentials();
List<Status> statuses = twitter.getMentionsTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s mentions.");
Please suggest me what changes I need to have.

You can use the Paging object's max_id parameter to step back through the timeline you are processing:
max_id
Returns results with an ID less than (that is, older than) or equal to the specified ID.
For instance, choose a reasonable number of statuses to fetch (the maximum is 200 at a time for mentions), e.g.:
Paging paging = new Paging();
paging.count(100);
Fetch the mentions:
final List<Status> statuses = twitter.getMentions(paging);
Then record the id of the earliest Status and then use that id for the max_id attribute of the next call:
paging.maxId(id - 1); // subtract one to make max_id exclusive
final List<Status> statuses = twitter.getMentions(paging);
And so on until you hit your thirty minute threshold.
For more information, see Twitter's documentation on Working with Timelines. Additionally, be aware that you could hit rate limiting with this API call.

I found out the way by using getCreatedAt for status, get the status upto last 30 minutes as you needed in loop and then put break from that.
List<Status> statuses = twitter.getMentionsTimeline();
System.out.println("Showing #" + user.getScreenName()
+ "'s mentions.");
for (Status status : statuses) {
// setting 30 min from now to date
Calendar c = Calendar.getInstance();
c.setTime(new java.util.Date());
c.add(Calendar.MINUTE, -30);
System.out.println(c.getTime());
// setting created date of status to date
Date createdDate = status.getCreatedAt();
Calendar now = Calendar.getInstance();
now.setTime(createdDate);
System.out.println(now.getTime());
if (now.compareTo(c) == -1) {
System.out.println(" in zero");
break;
}
// User is class with getter setter methods
user2 = User();
user2.setUsername(status.getUser().getScreenName());
user2.setMessage(status.getText());
list.add(user2);
System.out.println(status.getUser().getScreenName());
}
I am able to get the mentionTimeLine for last 30 minutes using this code.

Related

how to get the full tweet of the user timeline with twitter4j?

I want to get tweets from certain user timelines using java library twitter4j, currently I have source code which can get ~ 3200 tweets from user time line but I can't get full tweet. I have searched in various sources on the internet but I can't find a solution to my problem. anyone can help me or can anyone provide an alternative to get a full tweet from the user timeline with java programming?
my source code :
public static void main(String[] args) throws SQLException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("aaa")
.setOAuthConsumerSecret("aaa")
.setOAuthAccessToken("aaa")
.setOAuthAccessTokenSecret("aaa");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
int pageno = 1;
String user = "indtravel";
List statuses = new ArrayList();
while (true) {
try {
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(user, page));
System.out.println("***********************************************");
System.out.println("Gathered " + twitter.getUserTimeline(user, page).size() + " tweets");
//get status dan user
for (Status status: twitter.getUserTimeline(user, page)) {
//System.out.println("*********Place Tweets :**************\npalce country :"+status.getPlace().getCountry()+"\nplace full name :"+status.getPlace().getFullName()+"\nplace name :"+status.getPlace().getName()+"\nplace id :"+status.getPlace().getId()+"\nplace tipe :"+status.getPlace().getPlaceType()+"\nplace addres :"+status.getPlace().getStreetAddress());
System.out.println("["+(no++)+".] "+"Status id : "+status.getId());
System.out.println("id user : "+status.getUser().getId());
System.out.println("Length status : "+status.getText().length());
System.out.println("#" + status.getUser().getScreenName() +" . "+status.getCreatedAt()+ " : "+status.getUser().getName()+"--------"+status.getText());
System.out.println("url :"+status.getUser().getURL());
System.out.println("Lang :"+status.getLang());
}
if (statuses.size() == size)
break;
}catch(TwitterException e) {
e.printStackTrace();
}
}
System.out.println("Total: "+statuses.size());
}
Update :
After the answer given by #AndyPiper
the my problem is every tweet that I get will be truncated or not complete. a tweets that I get will be truncated if the length of tweet more than 140 characters. I found the reference tweet_mode=extended, but I do not know how to use it. if you know something please tell me.
Your Configuration should be like this:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("aaa")
.setOAuthConsumerSecret("aaa")
.setOAuthAccessToken("aaa")
.setOAuthAccessTokenSecret("aaa")
.setTweetModeExtended(true);
It is explained well here
The Twitter API limits the timeline history to 3200 Tweets. To get more than that you would need to use the (commercial) premium or enterprise APIs to search for Tweets by a specific user.
if you are streaming tweets
fist: you have to add .setTweetModeExtended(true); into your configurationbuilder
second(here is the code)
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
System.out.println("-------------------------------");
if(status.isRetweet()){
System.out.println(status.getRetweetedStatus().getText());
}
else{
System.out.println(status.getText());
}`
its totally works for me.
take care yourself :)
If you are implementing twitter api using twitter4j.properties file and getting truncated timeline text value,simply add the below property in it at the end.
tweetModeExtended=TRUE

twitter4j setpage() not working

I'm using twitter4j version 2.2.5. setPage() doesn't seem to work if I use it with setSince() and setUntil(). See the following code:
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
AccessToken accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
twitter.setOAuthAccessToken(accessToken);
int page = 1;
while(true) {
Query query = new Query("from:someUser");
query.setSince("2012-01-01");
query.setUntil("2012-07-05");
query.setRpp(100);
query.setPage(page++);
QueryResult qr = twitter.search(query);
List<twitter4j.Tweet> qrTweets = qr.getTweets();
if(qr.getTweets().size() == 0) break;
for(twitter4j.Tweet t : qrTweets) {
System.out.println(t.getId() + " " + t.getText());
}
}
The code inside the loop is only executed once if I use setSince() and setUntil() methods. But without them, setPage() seems to work and I get more tweet results.
Any ideas why this is happening?
Your code appears to be working for me. It only returns tweets from the past nine days, but that's expected (approximately) according to your comment.
You mentioned in the question that the loop only ran once with rpp=100, and you said in a comment that all 80 of the user's tweets were returned when rpp=40. I think that would indicate that the code is working as expected. If the user only has 80 tweets, the loop only should run once when rpp=100, and it should execute twice and display all their tweets when rpp=40. Try displaying the page number as soon as you enter the while loop so you can see how many times the loop runs.

Payment works but the user never knows if it was a subscription or one time payment on the Paypal page

So I've integrated the Paypal in my payment flow and this is what happens:
User comes on the page. Clicks the Payment Button
User Is first redirected to a page which calls SetExpressCheckout and is redirected to Paypal. (He is to be billed one time for say, $77 and then every month for 1 year for the same amount. Hence I don't set the initial amount, instead deduct it directly.)
On returning, he clicks the confirm button and one time payment is deducted using DoExpressCheckout and billing profile is created.
Everything works fine. I get the payment every month. The user is not billed twice at the start.
The PROBLEM: When the user was redirected to Paypal, he only sees the ITEM NAME and DESCRIPTION I've set. I.e. There is not description from Paypal whether the transaction is one time or subscription like there is when you use a simple subscription button for payment. Paypal only mentions the amount but not the type of transaction.
NVPEncoder encoder = new NVPEncoder();
encoder.add("METHOD","SetExpressCheckout");
encoder.add("RETURNURL",returnURL);
encoder.add("CANCELURL",cancelURL);
encoder.add("CURRENCYCODE","USD");
encoder.add("AMT",amt);
encoder.add("BILLINGPERIOD", "Month");
encoder.add("BILLINGFREQUENCY", "1");
encoder.add("PROFILESTARTDATE",dateFormatGmt.format(new Date()));
encoder.add("L_BILLINGTYPE0", "RecurringPayments");
encoder.add("L_BILLINGAGREEMENTDESCRIPTION0",package_name);
encoder.add("L_NAME0",package_name);
encoder.add("L_AMT0",amt);
encoder.add("L_QTY0","1");
String strNVPRequest = encoder.encode();
String ppresponse = (String) caller.call(strNVPRequest);
NVPDecoder resultValues = new NVPDecoder();
resultValues.decode(ppresponse);
String strAck = resultValues.get("ACK");
if (strAck !=null && !(strAck.equals("Success") ||
strAck.equals("SuccessWithWarning"))) {
response.sendRedirect("APIError.jsp");
} else {
response.sendRedirect(redirectUrl);
}
Are you including L_BILLINGTYPE0=RecurringPayments?
This is what should change the wording on the PayPal landing page.
To recap; call the following API calls, with (at least) the following parameters:
SetExpressCheckout:
$nvps = array();
$nvps["VERSION"] = "80.0";
$nvps["METHOD"] = "SetExpressCheckout";
$nvps["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
$nvps["PAYMENTREQUEST_0_AMT"] = "1.00";
$nvps["PAYMENTREQUEST_0_CURRENCYCODE"] = "GBP";
$nvps["PAYMENTREQUEST_0_ITEMAMT"] = "1.00";
$nvps["L_BILLINGTYPE0"] = 'RecurringPayments';
$nvps["L_BILLINGAGREEMENTDESCRIPTION0"] = "the subscription";
$nvps["L_PAYMENTREQUEST_0_NUMBER0"] = 1;
$nvps["L_PAYMENTREQUEST_0_NAME0"]= "subscription";
$nvps["L_PAYMENTREQUEST_0_AMT0"]= 1.00;
$nvps["L_PAYMENTREQUEST_0_QTY0"]= 1;
And CreateRecurringPaymentsProfile with:
$nvps["PROFILESTARTDATE"] = "2011-07-08T17:40:00Z";
$nvps["BILLINGPERIOD"] = "Month";
$nvps["BILLINGFREQUENCY"] = "1";
$nvps["AMT"] = "1.00";
$nvps["CURRENCYCODE"] = "GBP";
$nvps["DESC"] = "the subscription";

Extracting events from Google Calendar

Today I created code:
// Create a CalenderService and authenticate
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("j...#gmail.com", "mypassword");
// Send the request and print the response
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
System.out.println("Your calendars:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
This code gives out the list of all calendars. At me - a box calendar, a calendar of birthdays of friends and a calendar of holidays. I need to receive all events occurring today - i.e. both my notes, and birthdays of friends, and holidays. How I am able to do it?
This code returns event for specified data range, but it is work for private calendar only; i tried to replace "private" for "allcalendars", but it doesn't work:
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2006-03-16T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2006-03-24T23:59:59"));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("jo#gmail.com", "mypassword");
// Send the request and receive the response:
CalendarEventFeed resultFeed = myService.query(myQuery, Feed.class);
Your problem is in the your feed url. The one you are using is getting the events on the default calendar.
To get the other calendars you should replace default in the url by the calendar's id, for example:
feedUrl = new URL("https://www.google.com/calendar/feeds/xxxxxxxxxxxxxxxxx#group.calendar.google.com/private/full");

Google Calendar API

I have the code:
// Create a CalenderService and authenticate
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("j...#gmail.com", "mypassword");
// Send the request and print the response
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
System.out.println("Your calendars:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
This code gives out the list of all calendars. At me - a box calendar, a calendar of birthdays of friends and a calendar of holidays. I need to receive all events occurring today - i.e. both my notes, and birthdays of friends, and holidays. How I am able to do it?
You need to execute a date range query starting and ending of that day. See
http://code.google.com/apis/calendar/data/2.0/developers_guide_java.html#RetrievingDateRange
(I'm not 100% sure , but I think with the url https://www.google.com/calendar/feeds/default/allcalendars/full you should get results for all your calendars)

Categories