C# TweetSharp 不发送推文

C# TweetSharp not sending Tweets

我正在使用 TweetSharp 向用​​户发送推文(目前正在测试),但它总是返回错误的身份验证数据

{"errors":[{"code":215,"message":"Bad Authentication data."}]}

我检查了我的应用程序设置,它具有完整的读写权限。我也尝试过重新生成我的消费者密钥,但还是不行。

这是我的代码

public ActionResult AccessToken()
{

     string oauth_consumer_key = "<consumer key>";
     string oauth_consumer_secret = "<consumer secret>";

     var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);

     // Now we need the Token and TokenSecret
     OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37808/");
     string authURL = service.GetAuthorizationUri(requestToken).ToString();

     Process.Start(authURL);

     SendTweetOptions options = new SendTweetOptions();
     options.Status = "Hello there Twitter";

     service.SendTweet(options);

     var re = service.Response.Response;

     return View();            
    }

我做错了什么吗?

我认为您不能仅作为消费者发送推文,推文必须由用户帐户 "owned" 发送。您需要注册一个 Twitter 帐户,然后执行完整的 oauth 身份验证过程以获取访问令牌(除了消费者令牌),然后使用这两个令牌重新授权 TweetSharp 服务。

你上面的代码差不多到那里了(我想)。在 Process.start 调用之后,需要有逻辑来使用浏览器中返回的验证器(用户登录后显示的数字)来完成身份验证过程并充当该用户。目前,您的代码已完成该过程的一半但并未完成,因此当您尝试发布推文时,您的 TweetSharp 服务仅作为应用而非用户授权。

原始 TweetSharp readme.md 确实包含缺失的代码位。第3步需要登录后浏览器返回的实际验证者:

// 第 3 步 - 将请求令牌交换为访问令牌

字符串验证器=“123456”; // <-- 这是您的用户输入到您的应用程序中的

OAuthAccessToken 访问 = service.GetAccessToken(requestToken, verifier);

// 第 4 步 - 用户使用访问令牌进行身份验证 service.AuthenticateWith(access.Token, access.Token秘密);

//现在你的 tweet 调用应该可以在这里工作了。

您似乎也在服务器上的 Web 应用程序中执行此操作?在这种情况下,您使用的是完全错误的 oauth 流程(我相信)。这是为桌面应用程序设计的,因此调用会启动一个新的浏览器进程供用户登录。我不完全确定网络流程是如何工作的,因为我从未使用过它,但我相信你需要将用户重定向到你收到的授权 url,并且在 Twitter 上注册的回调应该指向你的地点。我认为有某种状态参数可以通过 oauth 流程传回,因此您可以实现自己的逻辑,根据会话 ID 或类似内容从您离开的地方继续。

问题终于解决了,效果很好。基于 Yort 的评论。

public ActionResult AccessToken()
{
        // Step 1 - Retrieve an OAuth Request Token
        TwitterService service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"], ConfigurationManager.AppSettings["TwitterConsumerSecret"]);

        // This is the registered callback URL
        OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37808/Twitter/OToken");

        // Step 2 - Redirect to the OAuth Authorization URL
        Uri uri = service.GetAuthorizationUri(requestToken);
        return new RedirectResult(uri.ToString(), false /*permanent*/);
        //return View();
}

public ActionResult OToken()
{
        return View();
}

public ActionResult UserInfo(string oauth_token, string oauth_verifier)
{

        var requestToken = new OAuthRequestToken { Token = oauth_token };

        // Step 3 - Exchange the Request Token for an Access Token
        TwitterService service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"], 
                                                    ConfigurationManager.AppSettings["TwitterConsumerSecret"]);
        OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);

        // Step 4 - User authenticates using the Access Token
        service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
        TwitterUser user = service.VerifyCredentials(new VerifyCredentialsOptions());
        ViewBag.Message = string.Format("{0}", user.ScreenName);

        // Step 5 - Send Tweet to User TimeLine
        SendTweetOptions options = new SendTweetOptions();

        string URL = "file:\C:\Users\<User>\Desktop\test.jpg";
        string path = new Uri(URL).LocalPath;        

        // Sending with Media
        using (var stream = new FileStream(path, FileMode.Open))
        {
            service.SendTweetWithMedia(new SendTweetWithMediaOptions
            {
                Status = "<status>",
                Images = new Dictionary<string, Stream> { { path, stream } }
            });
        }

        var responseText = service.Response.StatusCode;

        if (responseText.ToString() == "OK")
        {
            ViewBag.Message = "Tweet Successful";
        }
        else
        {
            ViewBag.Message = "Tweet Unsuccessful";
        }            
        return View();
    }                                      
}

我以前研究过这个主题。您必须在发送推文之前注册开发者帐户,因为您需要令牌和密钥。这是我的 windows 服务项目。 我在 App.config

中写下了我的令牌和密钥代码
 <appSettings>
<add key="twitterAccessToken" value="*****"/>
<add key="twitterAccessTokenSecret" value="*****"/>
<add key="twitterConsumerKey" value="*****"/>
<add key="twitterConsumerSecret" value="*****"/>

  public static void SendTweet()
    {
        try
        {
            GetPixelImageFile();

            string key = ConfigurationSettings.AppSettings.Get("twitterConsumerKey");
            string secret = ConfigurationSettings.AppSettings.Get("twitterConsumerSecret");
            string token = ConfigurationSettings.AppSettings.Get("twitterAccessToken");
            string tokenSecret = ConfigurationSettings.AppSettings.Get("twitterAccessTokenSecret");

            string message = "Color, Colorful, Pixel, Art, PixelColouring, Follow";

            var service = new TweetSharp.TwitterService(key, secret);
            service.AuthenticateWith(token, tokenSecret);
            using (var stream = new FileStream(@"C:\Images\Pixel.png", FileMode.Open))
            {
                var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
                {
                    Status = message,
                    Images = new Dictionary<string, Stream> { { "john", stream } }
                });
                SendMail("SendTweet", (result == null ? "" : result.Text));
            }
        }
        catch (Exception ex)
        {
            SendMail("SendTweet", ex.Message);
        }

    }