Every Example I can find is either very outdated or always comes back 401.
Can anyone at all provide a working example of posting a status update to twitter?
Even the below always fails.
I get redirected to twitter - great. I can confrim the access codes are correct and match my application, but on acutally posting the update - error is unknown...
What on earth is wrong here? Does matter what app I use or which twitter account.
Using Twitteriser2.dll
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
accesstoken,
"Testing!! It works (hopefully).");
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
}
The TwitterRepsonse object has an "ErrorMessage" property. You should probably start by looking at the information in there to give you some guidance.
Why don't you use Tweetinvi. Tweetinvi will allow you to post in 1 line and get error messages in line too. Here is an example.
TwitterCredentials.SetCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret");
var tweet = Tweet.PublishTweet("Hello!");
if (tweet == null)
{
var exceptionDetails = ExceptionHandler.GetLastException().TwitterExceptionInfos.First().Message;
}
You can find the documentation here : https://tweetinvi.codeplex.com/documentation
Also have a look at https://tweetinvi.codeplex.com/discussions/536895 if you are using it with ASP.NET.
Got it working eventually.
The fault isn't exactly known as I didn't have to change the code but what I did was re-download Twitterizwer and Built it (Required adding a ref to C++ components for what ever reason) and it then worked so I can only see that it was somehow faulty the first time round.
Related
I am using the Microsoft.AspNet.Mvc.Facebook NuGet package. I would like to exchange a regular token for the extended access token (the one that replaced the offline_access permission).
From Googling around I found the URL should be in this format:
https://graph.facebook.com/oauth/access_token?
client_id=[APP_ID]&
client_secret=[APP_SECRET]&
grant_type=fb_exchange_token&
fb_exchange_token=[EXISTING_ACCESS_TOKEN]
So I use the following code:
var longToken = await context.Client.PostTaskAsync("/oauth/access_token",
new
{
client_id = fbApp.AppId,
client_secret = fbApp.AppSecret,
grant_type = "fb_exchange_token",
fb_exchange_token = context.AccessToken
});
This returns a null. No error or anything. Just a null value.
Edit: Also tried the following, which also did not work. But a GET seems more logical than a POST anyway.
dynamic result = context.Client.Get("oauth/access_token",
new
{
client_id = fbApp.AppId,
client_secret = fbApp.AppSecret,
grant_type = "fb_exchange_token",
fb_exchange_token = context.AccessToken
});
var longToken = result.access_token as string;
I have successfully done this as a GET request, not a POST :) Just put the necessary parameters into the URL and request it as a GET request and the response returns the long term access token.
EDIT
When you get the result from this, you should parse the query string first (am not sure in C# but maybe you could use this link: http://msdn.microsoft.com/en-us/library/ms150046(v=vs.110).aspx).
After that try to get the access_token property and I got it right on my end. I was doing it in node.js though, but essentially the same flow.
I have been working with Linq2Twitter (v. 2), using the Search API and
I wanted to switch to the Stream API. I updated to v. 3 but since then I don't manage to authenticate anymore. I don't think the Stream API or the version could be the problem, because I've tried to go back to the previous version, previous authentication methods, and it doesn't work anymore either. I get a 401 : bad authentication data.
So, here is my current code :
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore()
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"],
AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"]
}
};
TwitterContext _twitterCtx = new TwitterContext(auth);
try
{
var verifyResponse =
await
(from acct in _twitterCtx.Account
where acct.Type == AccountType.VerifyCredentials
select acct)
.SingleOrDefaultAsync();
if (verifyResponse != null && verifyResponse.User != null)
{
User user = verifyResponse.User;
Console.WriteLine(
"Credentials are good for {0}.",
user.ScreenNameResponse);
}
}
catch (TwitterQueryException tqe)
{
Console.WriteLine(tqe.Message);
}
Of course, I checked the credentials several times, printed them out and all.
I tried with ApplicationOnlyAuthorizer, v.2, v.3 as well, it doesn't change anything.
What scares me the most is that what used to work (v2 + ApplicationOnly + Search API) doesn't work either.
Through my research I've heard of a problem caused by unsynchronized timestamps, or something like that. But I don't understand how I can change that.
The program is not on a server, it's locally stored.
Thank you for reading.
Here's how to use SingleUserAuthorizer in v3.0:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"]
}
};
Notice here that I'm setting AccessToken and AccessToken secret. I also have a FAQ with suggestions for resolving 401 problems:
https://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
So I've looked at all the of the suggestions from the Linq to Twitter documentation regarding 401 statuses with Oauth and I honestly don't know what I'm doing wrong.
var auth = new PinAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
//OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"], //don't include this
//AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"] //or this for new users.
},
//
UseCompression = true,
GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
GetPin = () =>
{
Console.WriteLine("/nAfter twitter authorizes your application you will be returned here or something/n");
Console.Write("Enter Pin here:");
return Console.ReadLine();
}
};
auth.Authorize();
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/",
"https://search.twitter.com/"))
{
try
{
twitterCtx.Log = Console.Out;
Console.WriteLine("Please provide tweet text");
string tweet = Console.ReadLine();
twitterCtx.UpdateStatus(tweet);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I've ran this using the Pin Authentication method as well as the single user method (providing the oauth keys with config file). I'm able to query tweets but I can't update my status or send direct messages (I receive a 403 forbidden when I try to DM). I've provided a callback URL (albeit fake) so I can't think of why this isn't working. Any help would be appreciated.
PS this runs in Main, not sure if that matters
All you need is this overload of the TwitterContext ctor and it will use the proper base URLs:
new TwitterContext(auth)
The example you're using is for v1.0 URLs and LINQ to Twitter is on Twitter API v1.1 now. It will default to the proper base URLs.
If you're querying okay, but getting errors on update and DM, double check to make sure you aren't trying to tweet the same text. That's why I append a DateTime.Now to the end of test tweets - to guarantee uniqueness.
So i've been using Linq-To-Twitter to add Twitter Integration to my Windows 8 Store App, Moreso for playing around with it, but i've come accross a problem. My current authentication codeblock is
var auth = new WinRtAuthorizer
{
Credentials = new LocalDataCredentials
{
ConsumerKey = "",
ConsumerSecret = ""
},
UseCompression = true,
Callback = new Uri("http://linqtotwitter.codeplex.com/")
};
if (auth == null || !auth.IsAuthorized)
{
await auth.AuthorizeAsync();
}
Which works great, unless I go into the authentication screen and click the back button on the top left, to exit authentication without supplying details. at which point i get a TwitterQueryException: Bad Authentication data at:
var timelineResponse =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Home
select tweet)
.ToList();
Obviously because the Authentication Information was wrong, I'm trying to find a way to stop proceeding to the rest of the code if the authentication fails/is backed out.
I've tried simple boolean checks to no effect. I've been melting my brain over this for hours, so any help would be greatly appreciated. Thanks a bunch!
You can query Account.VerifyCredentials to ensure the user is logged in before performing any other operation. Here's an example:
const int BadAuthenticationData = 215;
var twitterCtx = new TwitterContext(auth);
try
{
var account =
(from acct in twitterCtx.Account
where acct.Type == AccountType.VerifyCredentials
select acct)
.SingleOrDefault();
await new MessageDialog(
"Screen Name: " + account.User.Identifier.ScreenName,
"Verification Passed")
.ShowAsync();
}
catch (TwitterQueryException tqEx)
{
if (tqEx.ErrorCode == BadAuthenticationData)
{
new MessageDialog(
"User not authenticated",
"Error During Verification.")
.ShowAsync();
return;
}
throw;
}
Your error handling strategy will differ from this, which is just a sample, but it shows you how to know that the error occurred and gives you the opportunity to react to the problem before resuming normal operation.
TwitterQueryException will include the Twitter error code in the ErrorCode property. It also sets Message to the error message that Twitter returns. InnerException provides the underlying exception with the original stack trace, which is often a WebException thrown because of the HTTP error code returned from Twitter.
I am using Twitterizer, and am trying to get my ASP.Net app to upload reported traffic incidents to the official Twitter account.
I have looked at similar questions at SO, and the I tried all the recommendations (specify call-back url, check for careless errors and ensure the app has Read-Write permissions), but I still cannot solve the problem. I have some screenshots of the settings and code below. The callback URL does not exist, but is made up. Any help will be greatly appreciated.
Another item to look for is the computer time. Look at the server time in the Twitter response and compare it to the computer you're using. Also, here's a troubleshooting guide from the Twitter site:
https://dev.twitter.com/discussions/204
I came back to this problem, this time I tried regenerating my API keys, and now it is working. Perhaps my previous keys were duds.
public static void UploadTweet(string token, string tokensecreat, byte[] img, string Title)
{
Twitterizer.OAuthTokens tokens = new Twitterizer.OAuthTokens();
tokens.AccessToken = token;
tokens.AccessTokenSecret = tokensecreat;
tokens.ConsumerKey = TWITTER_CONSUMER_KEY;
tokens.ConsumerSecret = TWITTER_CONSUMER_SECRET;
byte[] photo = img;
TwitterResponse<TwitterStatus> response = TwitterStatus.UpdateWithMedia(tokens, Title, photo, new StatusUpdateOptions() { UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/" });
if (response.Result == RequestResult.Success)
{
}
else
{
}
}