Unable to Fetch twitter tweets - twitter

I am getting twiiter feeds now a days. I am using tweetinvi Api, my code fetch only latest 200 feeds,and i want all.
my code is
Public Function getTweets()
''Set the credentials
Dim lObjConsumerKey As String = "[REDACTED]"
Dim lObjConsumerSecret As String = "[REDACTED]"
Dim lObjUserAccessToken As String = "[REDACTED]"
Dim lObjUserAccessSecret As String = "[REDACTED]"
Auth.SetUserCredentials(lObjConsumerKey, lObjConsumerSecret, lObjUserAccessToken, lObjUserAccessSecret)
Dim lObjDataTable As New DataTable
lObjDataTable.Columns.Add("Tweets")
lObjDataTable.Columns.Add("CreatedAt")
Dim GetTimelineTweets = Timeline.GetUserTimeline(txtUserName.Text)
For Each lobjGetgetTweets In GetTimelineTweets
Dim drNew = lObjDataTable.NewRow
drNew("Tweets") = lobjGetgetTweets
drNew("CreatedAt") = lobjGetgetTweets.CreatedAt
lObjDataTable.Rows.Add(drNew)
Next
Return lObjDataTable
End Function

This behavior is by design, as per the Twitter REST API documentaion for GetUserTimeline(). In the definition of the count parameter...
Specifies the number of Tweets to try and retrieve, up to a maximum of
200 per distinct request.
To get all tweets, check out Working With Timelines on the Twitter Developer site.

I have created a sample for you in the documentation : https://github.com/linvi/tweetinvi/wiki/Get-All-User-Tweets
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
RateLimit.QueryAwaitingForRateLimit += (sender, args) =>
{
Console.WriteLine($"Query : {args.Query} is awaiting for rate limits!");
};
long userId = <YOUR_USER_ID>;
var lastTweets = Timeline.GetUserTimeline(userId, 200).ToArray();
var allTweets = new List<ITweet>(lastTweets);
var beforeLast = allTweets;
while (lastTweets.Length > 0 && allTweets.Count <= 3200)
{
var idOfOldestTweet = lastTweets.Select(x => x.Id).Min();
Console.WriteLine($"Oldest Tweet Id = {idOfOldestTweet}");
var numberOfTweetsToRetrieve = allTweets.Count > 3000 ? 3200 - allTweets.Count: 200;
var timelineRequestParameters = new UserTimelineParameters
{
// MaxId ensures that we only get tweets that have been posted
// BEFORE the oldest tweet we received
MaxId = idOfOldestTweet - 1,
MaximumNumberOfTweetsToRetrieve = numberOfTweetsToRetrieve
};
lastTweets = Timeline.GetUserTimeline(userId, timelineRequestParameters).ToArray();
allTweets.AddRange(lastTweets);
}
// `allTweets` now contains all the tweets that Twitter can return

Related

NMI Create Subscription Giving Authentication Failed Error

In my project i am configuring NMI Payment gateway in which i create a plan and then customer and now creating subscription against that plan but client giving response of Authentication Failed below is the response of client
response=3&responsetext=Authentication Failed&authcode=&transactionid=0&avsresponse=&cvvresponse=&orderid=&type=&response_code=300
Below is my service code
var addsubscription = "add_subscription";
var date = DateTime.UtcNow;
var year = date.Year.ToString();
var month = date.Month.ToString();
var padedmonth = month.PadLeft(2, '0');
var day = date.Day.ToString();
var padedday = day.PadLeft(2, '0');
var startdate = year + padedmonth + padedday;
string option = $"plan_id={model.Data.StripePlanId}&recurring={addsubscription}&payment_token={model.Data.StripePaymentToken}&ccnumber={model.Data.CCNumber}&ccexp={model.Data.CCExpiry}&start_date={startdate}";
var requester = new NMIGatewayRequester();
var relativeUrl = "https://secure.networkmerchants.com/api/transact.php";
var response = requester.Request(relativeUrl, RestSharp.Method.POST, option);
var customerResponseObj = GetPaymentApiResponseValues(response.Split('&').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]));
public class NMIGatewayRequester
{
private RestClient client;
public string Request(string relativeUrl, RestSharp.Method verb, string option)
{
client = new RestSharp.RestClient($"{relativeUrl}") { Timeout = -1 };
var request = new RestRequest(verb);
request.AddParameter("application/x-www-form-urlencoded", option, ParameterType.RequestBody);
var subResponse = client.Execute(request);
if (!subResponse.IsSuccessful)
{
throw new Exception("Unable to Process Request");
}
return subResponse.Content;
}
}
You need to include a security key in your options:
string option = $"security_key=[...]&plan_id={model.Data.StripePlanId}&[...]";
See documentation here.

CommentThreads amount changes by order

CommentThreads amount changes by order
Hi I'm trying to fetch all comments of a video. For testing purpose I'm using this video Id U55NGD9Jm7M.
When I order by time I get 1538 comments the last wrote on the 02.05.2015.
If I’m using the relevance I only receive 1353 comment and the last was wrote on the 29.04.2015
This doesn’t seem right to me. I expected to receive the same comments but in a different order and not different comments.
I also tried this on a different video and the results were the same.
My code cut down to minimum
Thank you for your help
public class foo
{
public void bar(string videoId)
{
var allTopLevelComments = new List<CommentThread>();
var searchListResponse = getThread(videoId);
allTopLevelComments.AddRange(searchListResponse.Items);
string nextPage = searchListResponse.NextPageToken;
while (!String.IsNullOrEmpty(nextPage))
{
searchListResponse = getThread(videoId, searchListResponse.NextPageToken);
nextPage = searchListResponse.NextPageToken;
allTopLevelComments.AddRange(searchListResponse.Items);
}
var first = allTopLevelComments.OrderBy(c => c.Snippet.TopLevelComment.Snippet.PublishedAt).First();
}
private CommentThreadListResponse getThread(string videoId, string nextPageToken = "")
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer
{
ApiKey = "my key",
ApplicationName = "my app"
});
var searchListRequest = youtubeService.CommentThreads.List("id, replies, snippet");
searchListRequest.VideoId = videoId;
searchListRequest.MaxResults = 100;
searchListRequest.Order = CommentThreadsResource.ListRequest.OrderEnum.Time;
searchListRequest.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText;
if (!String.IsNullOrEmpty(nextPageToken))
{
searchListRequest.PageToken = nextPageToken;
}
return searchListRequest.Execute();
}
}

Retrieving OAuth Verification Code via .NET HttpWebRequest

I'm attempting to replicate the OAuth steps normally done via the "Connect to QuickBooks" button using HttpWebRequest/HttpWebResponse.
It's easy at first grabbing the request token and generating the authorization link:
private const string oauthBaseUrl = "https://oauth.intuit.com/oauth/v1";
private const string urlRequestToken = "/get_request_token";
private const string urlAccessToken = "/get_access_token";
private const string verifyUrl = "https://appcenter.intuit.com";
private const string authorizeUrl = "https://appcenter.intuit.com/Connect/Begin";
...
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(ckSS),
ConsumerSecret = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(csSS),
SignatureMethod = SignatureMethod.HmacSha1
};
IOAuthSession session = new OAuthSession(consumerContext, oauthBaseUrl + urlRequestToken, authorizeUrl, oauthBaseUrl + urlAccessToken);
IToken requestToken = session.GetRequestToken();
string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);
Then I walk through grabbing the request verification code that is generated in the set-cookie string when requesting the site at the authorization link:
var requestAuth = (HttpWebRequest) WebRequest.Create(authorizationLink);
requestAuth.Method = "GET";
requestAuth.ContentType = "application/x-www-form-urlencoded";
requestAuth.Accept = "text/html, application/xhtml+xml, */*";
requestAuth.Headers.Add("Accept-Encoding", "gzip, deflate");
requestAuth.Headers.Add("Accept-Language", "en-us");
requestAuth.Host = "appcenter.intuit.com";
requestAuth.KeepAlive = true;
var responseAuth = (HttpWebResponse) requestAuth.GetResponse();
Stream answerAuth = responseAuth.GetResponseStream();
var _answerAuth = new StreamReader(answerAuth);
string htmlAuth = _answerAuth.ReadToEnd();
// Need to grab the request verification code embedded in the set-cookie string
string cookies = responseAuth.Headers.Get("Set-Cookie");
int idx = cookies.IndexOf("__RequestVerificationToken", StringComparison.Ordinal);
if (idx > 0)
{
int startIndex = cookies.IndexOf("=", idx, StringComparison.InvariantCultureIgnoreCase);
int endIndex = cookies.IndexOf(";", startIndex + 1, StringComparison.InvariantCultureIgnoreCase);
requestVerificationCode = cookies.Substring(startIndex + 1, endIndex - (startIndex + 1));
postDataString += requestVerificationCode;
}
As I understand it, the request verification code is needed in order to get the OAuth verification code that is returned in the postdata appended to the callback URL, which is in turn needed to get the access token.
This is where the difficulty begins. Using Fiddler2, I find that the login URL for generating the OAuth verification code is https://appcenter.intuit.com/Account/LogOnJson. But no matter how much I try to replicate the HTTP POST using HttpWebRequest, all I get in return is a 500 error. I'm wondering if anyone has a working example of this step? Is this even possible? I hope so, because the alternative of pulling up IE and walking through the same steps like a macro is too ugly.
Any help on this? Thanks!
You can download the dotnet sample app for understanding how the OAUTH flow works:
https://github.com/IntuitDeveloperRelations/IPP_Sample_Code
Set your app keys in web.config.

401 error calling REST service from mvc controller

I am trying to make a request to a REST method and recieve the data in XML but this all goes well but when i want to use credentials for a method, because for this method you need to give credentials.
https://handshake:16a144bc5f480692d5c8d926068d2db5#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=236750347X6d2ee7
But when i use this one in the browser it work but this is not working from my controller.
//
// GET: /Home/Succes
public ActionResult Succes(string orderId)
{
string token = PaymentCalls.Login();
ViewBag.Token = token;
string _URL = "https://handshake:" + token + "#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=" + orderId;
NetworkCredential cr = new NetworkCredential("handshake", token);
XDocument doc = XDocument.Load(_URL);
var output = from feed in doc.Descendants("data")
select new Status
{
amount = feed.Element("amount").Value,
consumerAccountNumber = feed.Element("consumerAccountNumber").Value,
consumerCity = feed.Element("consumerCity").Value,
consumerEmail = feed.Element("consumerEmail").Value,
consumerName = feed.Element("consumerName").Value,
consumerZipcode = feed.Element("consumerZipcode").Value,
countryCode = feed.Element("countrCode").Value,
entranceCode = feed.Element("entranceCode").Value,
ipAddress = feed.Element("ipAddress").Value,
orderId = feed.Element("orderId").Value,
statsAdded = feed.Element("statsAdded").Value,
paymentSessionId = feed.Element("paymentSessionId").Value,
result = feed.Element("result").Value,
statusAction = feed.Element("statusAction").Value
};
return View(output);
So when we call this controller we get an 401 error but using the same url in the browser works. So i dont know but how can i set to pass credentials or something?

Get all tweets with specific hashtag

I've been experimenting with the Twitter API because I want to display a few lists of tweets on a special page.
Among those lists is a list with all tweets containing a specific hashtag (e.g. #test)
However I cannot find how to get that list in either XML or JSON (preferably the latter), does anyone know how? It is also fine if it can be done in TweetSharp
You can simply fetch http://search.twitter.com/search.json?q=%23test to get a list of tweets containing #test in JSON, where %23test is #test URL encoded.
I'm not familiar with TweetSharp, but I guess there must be a search command that you can use to search for #test, and then transform the resulting tweets into JSON yourself.
First install TweetSharp using github
https://github.com/danielcrenna/tweetsharp
Here is the code to do a search
TwitterService service = new TwitterService();
var tweets = service.Search("#Test", 100);
List<TwitterSearchStatus> resultList = new List<TwitterSearchStatus>(tweets.Statuses);
If you have more then one page results you can setup a loop and call each page
service.Search("#Test", i += 1, 100);
It seems like there is a change in the API since last few months. Here is the updated code:
TwitterSearchResult res = twitter.Search(new SearchOptions { Q = "xbox" });
IEnumerable<TwitterStatus> status = res.Statuses;
u access with this url for your tweet searchs. But u have to use OAuth protocols.
https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi
I struggled with the same problem. Here is my vague solution . Enjoy Programming.
It will get out of the function whenever your required number of tweets are acquired/fetched.
string maxid = "1000000000000"; // dummy value
int tweetcount = 0;
if (maxid != null)
{
var tweets_search = twitterService.Search(new SearchOptions { Q = keyword, Count = Convert.ToInt32(count) });
List<TwitterStatus> resultList = new List<TwitterStatus>(tweets_search.Statuses);
maxid = resultList.Last().IdStr;
foreach (var tweet in tweets_search.Statuses)
{
try
{
ResultSearch.Add(new KeyValuePair<String, String>(tweet.Id.ToString(), tweet.Text));
tweetcount++;
}
catch { }
}
while (maxid != null && tweetcount < Convert.ToInt32(count))
{
maxid = resultList.Last().IdStr;
tweets_search = twitterService.Search(new SearchOptions { Q = keyword, Count = Convert.ToInt32(count), MaxId = Convert.ToInt64(maxid) });
resultList = new List<TwitterStatus>(tweets_search.Statuses);
foreach (var tweet in tweets_search.Statuses)
{
try
{
ResultSearch.Add(new KeyValuePair<String, String>(tweet.Id.ToString(), tweet.Text));
tweetcount++;
}
catch { }
}
}

Resources