Unauthorized Twitter Stream Sample - twitter

I'm trying to learn Twitter API using LinqToTwitter. It works fine to connect to Twitter API but not Twitter Stream. As far as I can tell I need special rights to access the firehouse but the sample stream and the filter stream should be accessable. If that's true I can't seem to understand why I get "401 Unauthorized" with the following code:
var auth = new ApplicationOnlyAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
}
};
auth.Authorize();
var twitterCtx = new TwitterContext(auth);
int count = 0;
string response = "";
(from strm in twitterCtx.Streaming
where strm.Type == StreamingType.Filter &&
strm.Track == query
select strm)
.StreamingCallback(strm =>
{
if (strm.Status != TwitterErrorStatus.Success)
{
Console.WriteLine(strm.Error.ToString());
return;
}
response += "<p>" + strm.Content + "</p>";
if (count++ >= 2)
{
strm.CloseStream();
}
})
.SingleOrDefault();

Twitter streams don't support application-only authorization. Try the SingleUserAuthorizer. Also, a 401 error can happen for several reasons and you can review the LINQ to Twitter FAQ for help.

Related

How to get oauth access token in console without authentication prompt

I want to oauth authentication like
Login using Google OAuth 2.0 with C#
But i don't want to authentication prompt popup
i want to get token directly without popup..
public ActionResult CodeLele()
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// This is where you want to add the code if login is successful.
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (WebException ex)
{
try
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
//var messageFromServer = obj.error.message;
//return messageFromServer;
return obj.error_description;
}
catch (Exception exc)
{
throw exc;
}
}
}
}
}
return Content("done");
}
public ActionResult JeClick()
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
return Redirect(Googleurl);
}
The credentials window (popup) is how you ask the user if you can access their data. There is no way to get access to a users data without asking the user first if you may access their data. That is how Oauth2 works.
If you are accessing your own data then you can use something called a Service account. Service accounts are pre authorized. You can take the service account and grant it access to your google calendar, you could give it access to a folder in Google drive. Then you can authenticate using the service account. Service accounts are like dummy users.
My article about service accounts: Google Developer service account

Linq2Twitter Bad Authentication Data Error 215

I'm getting a LinqToTwitter.TwitterQueryException "Bad Authentication Data" with innerException "The remote server returned an error: (400) Bad Request."
I'm using the latest version of LinqToTwitter (v2.1.06) and Twitter API v1.1.
The following code is used for authentication:
private XAuthAuthorizer GetAuthorizer()
{
var auth = new XAuthAuthorizer
{
Credentials = new XAuthCredentials
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
}
};
auth.Credentials.AccessToken = ACCESS_TOKEN;
auth.Credentials.OAuthToken = OAUTH_TOKEN;
auth.Authorize();
return auth;
}
And the error happens on the line of the foreach loop below:
XAuthAuthorizer _auth = GetAuthorizer();
_twitter = new TwitterContext(_auth);
var friendTweets = from tweet in _twitter.Status where tweet.Type == StatusType.Show && tweet.ID == tweetID select tweet;
foreach (var tweet in friendTweets)
{
AddTweetToCache(tweetID, tweet);
return tweet;
}
Any help would be greatly appreciated!
This fixed it. I was using the authentication method.
var auth = new ApplicationOnlyAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET
}
};

Is OAuth a must before using Google+API

I m trying to use get and list method with google plus comment. In official site it said (All API calls require either an OAuth 2.0 token or an API key. ) and I have tried send GET request without the step of OAuth it works it returns json format data. My question is OAuth must require before using google+ API?
It depends on exactly what data you're trying to get.
https://developers.google.com/+/api/oauth documents the benefits of using OAuth, but in general, if you want to get private profile data, or if you wish to use the /me/ URL shortcut, you will need to use OAuth and may, if you wish, use an App Key in addition. If all you're interested in is public data, you can use the App Key.
The short answer to whether you can do it is that you can get comments from Google+ without OAuth.
As for the how would you do this, I'm not sure which language you're doing this in but the following code shows how this is done in JavaScript.
The API calls used here can be experimented with in the API explorer:
Listing Activities
Listing Comments
A demo of this code is here.
You will need an API key (the simple key) for a project with the Google+ APIs from the Google APIs console. When you set up the project, you will only need to enable the Google+ API from the services section.
First, grab the activities using the public data API:
// Gets the activities for a profile
function getActivities(profileID){
var activities = null;
var URL = "https://www.googleapis.com/plus/v1/people/" + profileID + "/activities/public?alt=json&key=" + key;
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log("retrieved activities \n\n");
var activities = jQuery.parseJSON(request.responseText).items;
console.log("Discovered " + activities.length + " activities");
}else{
handleRequestIssue(request);
}
return activities;
}
The following code loops through the activities
for (var i=0; i < activities.length; i++) {
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
console.log(activity.id);
}
Next, you can use the activity IDs to retrieve the comments per activity:
function getCommentsForActivity(activityID){
var comments = "";
var URL = "https://www.googleapis.com/plus/v1/activities/" + activityID + "/comments?alt=json&key=" + key;
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log(request.responseText);
var comments = jQuery.parseJSON(request.responseText).items;
if (debug){
for (comment in comments){
console.log(comment);
}
}
}else{
handleRequestIssue(request);
}
return comments;
}
function manualTrigger(){
var activities = getActivities("109716647623830091721");
}
The following code brings it all together and retrieves activities and comments for a specific post:
$(document).ready(function () {
var renderMe = "";
var activities = getActivities("109716647623830091721");
console.log("activities retrieved: " + activities.length);
for (var i=0; i < activities.length; i++) {
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
renderMe += "<br/><div class=\"article\"><p>" + activity.title + "</p>";
console.log(activity.id);
// get comments
var comments = getCommentsForActivity(activity.id);
for (var j=0; j<comments.length; j++){
renderMe += "<br/><div class=\"comment\">" + comments[j].object.content + "</div>";
}
renderMe += "</div>";
}
console.log("I'm done");
document.getElementById("ac").innerHTML = renderMe;
});

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 { }
}
}

Post message from ASP.NET app to Twitter

I am using very simple code to post message in twitter. The code is as given below:
public void UpdateStatus(string username, string password, string tweetMsg)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweetMsg);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
request.Credentials = new NetworkCredential(username, password);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
string statusUpdate = string.Empty;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
statusUpdate = "status=" + System.Web.HttpUtility.UrlEncode(tweetMsg);
sw.Write(statusUpdate);
}
using (HttpWebResponse resp = (HttpWebResponse) request.GetResponse())
{
// Handle response here
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
catch (WebException ex)
{
Console.WriteLine("Web Error: {0}", ex.Message);
if (ex.Response != null)
{
HttpWebResponse r = (HttpWebResponse)ex.Response;
using (StreamReader esr = new StreamReader(r.GetResponseStream()))
{
Console.WriteLine("Error: {0}", esr.ReadToEnd());
}
}
}
catch (IOException ex)
{
Console.WriteLine("I/O Error: {0}", ex.Message);
}
}
I am not sure why this code is not working. I am getting the exception
The remote server returned an error: (401) Unauthorized.
But, whichever site I am referring, everywhere I find that people are able to post their messages using the same code.
Can anybody please tell me what I am missing in this code? The site that I referred for this code is http://www.dreamincode.net/forums/topic/120468-twitter-api-posting-status/
Thanks in advance....
Hari
The Twitter API no longer supports Basic Auth for authentication. You need to switch to OAuth which uses tokens instead of passwords.
Twitter's guide to transitioning from Basic Auth to OAuth
OAuth homepage

Resources