如何使用 C# 在我的推特帐户上发布推文 [英] How to post a tweet on my twitter account using C#

查看:24
本文介绍了如何使用 C# 在我的推特帐户上发布推文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一项功能,以便在 MVC 应用程序中在我的 Twitter 帐户上发布推文.

I'm trying to develop a feature to post tweets on my Twitter account, in an MVC application.

为此,我在 Twitter 中创建了一个应用程序,因此已经有了以下内容:消费者 API 密钥、消费者 API 秘密密钥、访问令牌、访问令牌秘密.

For this, I have created an App in Twitter, and so have the following already: Consumer API Key, Consumer API Secret Key, Access token, Access token secret.

在应用详情中,网址为http://example.com,回调网址字段为空.

In the App details, the website URL is http://example.com and the callback URL field is empty.

权限设置为 - 读取、写入和直接消息.

The permission is set to - Read, Write and Direct messages.

这是我的代码:

public static void Tweet(string message)
        {
            string twitterURL = "https://api.twitter.com/1.1/statuses/update.json"; 

            string oauth_consumer_key = GlobalConstants.TWConsumerAPIKey;
            string oauth_consumer_secret = GlobalConstants.TWConsumerAPISecretKey;
            string oauth_token = GlobalConstants.TWAccessToken;
            string oauth_token_secret = GlobalConstants.TWAccessTokenSecret;

            // set the oauth version and signature method
            string oauth_version = "1.0";
            string oauth_signature_method = "HMAC-SHA1";

            // create unique request details
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            System.TimeSpan timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            // create oauth signature
            string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";

            string baseString = string.Format(
                baseFormat,
                oauth_consumer_key,
                oauth_nonce,
                oauth_signature_method,
                oauth_timestamp, oauth_token,
                oauth_version,
                Uri.EscapeDataString(message)
            );

            string oauth_signature = null;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(Uri.EscapeDataString(oauth_consumer_secret) + "&" + Uri.EscapeDataString(oauth_token_secret))))
            {
                oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes("POST&" + Uri.EscapeDataString(twitterURL) + "&" + Uri.EscapeDataString(baseString))));
            }

            // create the request header
            string authorizationFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " + "oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " + "oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " + "oauth_version=\"{6}\"";

            string authorizationHeader = string.Format(
                authorizationFormat,
                Uri.EscapeDataString(oauth_consumer_key),
                Uri.EscapeDataString(oauth_nonce),
                Uri.EscapeDataString(oauth_signature),
                Uri.EscapeDataString(oauth_signature_method),
                Uri.EscapeDataString(oauth_timestamp),
                Uri.EscapeDataString(oauth_token),
                Uri.EscapeDataString(oauth_version)
            );

            HttpWebRequest objHttpWebRequest = (HttpWebRequest)WebRequest.Create(twitterURL);
            objHttpWebRequest.Headers.Add("Authorization", authorizationHeader);
            objHttpWebRequest.Method = "POST";
            objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            using (Stream objStream = objHttpWebRequest.GetRequestStream())
            {
                byte[] content = ASCIIEncoding.ASCII.GetBytes("status=" + Uri.EscapeDataString(message));
                objStream.Write(content, 0, content.Length);
            }

            var responseResult = "";

            try
            {
                //success posting
                WebResponse objWebResponse = objHttpWebRequest.GetResponse();
                StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
                responseResult = objStreamReader.ReadToEnd().ToString();
            }
            catch (Exception ex)
            {
                responseResult = "Twitter Post Error: " + ex.Message.ToString() + ", authHeader: " + authorizationHeader;
            }
        }

在catch块中,有这个异常:

In the catch block, there is this exception:

远程服务器返回错误:(401) Unauthorized.

The remote server returned an error: (401) Unauthorized.

我在这里做错了什么.

此外,我们如何知道消息将发布到特定帐户.是不是因为我使用的是使用我的 Twitter 凭据创建的 APP 中的 API 密钥.但它也允许我创建另一个应用程序.

Also, how do we know that the message is going to be posted to a particular account. Is it because I'm using the API keys from an APP created with my twitter credentials. But it allows me to create another app too.

推荐答案

我复制了您的代码并对其进行了测试,效果很好.

I copied your code and tested it, and it worked perfectly.

除了使用我的帐户的密钥外,我没有更改任何内容(回答您的问题,是的,所有应用程序都绑定到您用于创建开发帐户的 Twitter 帐户).如果您希望您的用户在他们的个人帐户上发推文,您必须先征得他们的许可:https://developer.twitter.com/en/docs/basics/authentication/overview/oauth.html

I didn't change anything except the keys to use my account (to answer your question yes all the applications are bound to your twitter account used to created your dev account). If you want your users to tweet on their personal account you'll have to ask them permission first : https://developer.twitter.com/en/docs/basics/authentication/overview/oauth.html

我设法在两种情况下得到您的错误:

I managed to get your error in two cases :

  • 错误的密钥:我在没有重新生成密钥的情况下更改了权限.
  • 权限错误:我将权限更改为只读并重新生成密钥.

这篇关于如何使用 C# 在我的推特帐户上发布推文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆