从.NET应用程序发布“Hello World”到twitter

时间:2010-05-17 13:38:06

标签: c# twitter

我的客户希望我使用.NET发布到Twitter,并建议我使用C#。

问:如何使用C#将“Hello World”发布到Twitter?

This post提到了一个名为twitterizer的库。没有使用第三方库,是不是有本地方法呢? (也许不是因为身份验证是其中一项要求)。

6 个答案:

答案 0 :(得分:15)

只需将此实现的包装器用于Twitter API:

https://github.com/danielcrenna/tweetsharp

    var twitter = FluentTwitter.CreateRequest()   
    .AuthenticateAs("USERNAME", "PASSWORD")   
    .Statuses().Update("Hello World!")   
    .AsJson();   

    var response = twitter.Request();  

来自:http://code-inside.de/blog-in/2009/04/23/howto-tweet-with-c/

There is even a DotNetRocks interview with the developers.

答案 1 :(得分:6)

我创建了一个视频教程,详细说明如何在twitter中设置应用程序,使用nuget安装API库,接受用户的访问令牌并代表该用户发布:

视频: http://www.youtube.com/watch?v=TGEA1sgMMqU

教程:http://www.markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet

如果您不想离开此页面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Twitterizer;

namespace PostFansTwitter
{
    public partial class twconnect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var oauth_consumer_key = "gjxG99ZA5jmJoB3FeXWJZA";
            var oauth_consumer_secret = "rsAAtEhVRrXUTNcwEecXqPyDHaOR4KjOuMkpb8g";

            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.");
                }
            }
        }
    }
}

答案 2 :(得分:5)

是的,你可以在没有任何第三方库的情况下完成。查看我在IronPython sample网站上发布的IronPython Cookbook,其中详细说明了具体方法。即使你没有在IronPython中编程,下面也会重复代码的主要部分,并且很容易移植到C#:

ServicePointManager.Expect100Continue = False 
wc = WebClient(Credentials = NetworkCredential(username, password))
wc.Headers.Add('X-Twitter-Client', 'Pweeter')
form = NameValueCollection()
form.Add('status', status)
wc.UploadValues('http://twitter.com/statuses/update.xml', form)

基本上,这会向http://twitter.com/statuses/update.xml发送HTTP POST,其中包含一个名为status的HTML FORM字段,其中包含username标识的帐户的状态更新文本(和{{1} }})。

答案 3 :(得分:0)

我建议您阅读http://developer.twitter.com/start上的文档。它包含您需要的所有信息。

答案 4 :(得分:0)

Twitter有自己的API来做那个

答案 5 :(得分:0)

整夜搜索后发现的最佳示例是以下链接:

Simplest C# code to post a tweet using OAuth

首先,您需要转到developer.twitter.com并创建一个包含API密钥和访问令牌(在“详细信息”>“密钥和令牌”下)的Twitter应用。

课程:

/// <summary>
/// Simple class for sending tweets to Twitter using Single-user OAuth.
/// https://dev.twitter.com/oauth/overview/single-user
/// 
/// Get your access keys by creating an app at apps.twitter.com then visiting the
/// "Keys and Access Tokens" section for your app. They can be found under the
/// "Your Access Token" heading.
/// </summary>
class TwitterApi
{
    const string TwitterApiBaseUrl = "https://api.twitter.com/1.1/";
    readonly string consumerKey, consumerKeySecret, accessToken, accessTokenSecret;
    readonly HMACSHA1 sigHasher;
    readonly DateTime epochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    /// <summary>
    /// Creates an object for sending tweets to Twitter using Single-user OAuth.
    /// 
    /// Get your access keys by creating an app at apps.twitter.com then visiting the
    /// "Keys and Access Tokens" section for your app. They can be found under the
    /// "Your Access Token" heading.
    /// </summary>
    public TwitterApi(string consumerKey, string consumerKeySecret, string accessToken, string accessTokenSecret)
    {
        this.consumerKey = consumerKey;
        this.consumerKeySecret = consumerKeySecret;
        this.accessToken = accessToken;
        this.accessTokenSecret = accessTokenSecret;

        sigHasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", consumerKeySecret, accessTokenSecret)));
    }

    /// <summary>
    /// Sends a tweet with the supplied text and returns the response from the Twitter API.
    /// </summary>
    public Task<string> Tweet(string text)
    {
        var data = new Dictionary<string, string> {
            { "status", text },
            { "trim_user", "1" }
        };

        return SendRequest("statuses/update.json", data);
    }

    Task<string> SendRequest(string url, Dictionary<string, string> data)
    {
        var fullUrl = TwitterApiBaseUrl + url;

        // Timestamps are in seconds since 1/1/1970.
        var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds);

        // Add all the OAuth headers we'll need to use when constructing the hash.
        data.Add("oauth_consumer_key", consumerKey);
        data.Add("oauth_signature_method", "HMAC-SHA1");
        data.Add("oauth_timestamp", timestamp.ToString());
        data.Add("oauth_nonce", "a"); // Required, but Twitter doesn't appear to use it, so "a" will do.
        data.Add("oauth_token", accessToken);
        data.Add("oauth_version", "1.0");

        // Generate the OAuth signature and add it to our payload.
        data.Add("oauth_signature", GenerateSignature(fullUrl, data));

        // Build the OAuth HTTP Header from the data.
        string oAuthHeader = GenerateOAuthHeader(data);

        // Build the form data (exclude OAuth stuff that's already in the header).
        var formData = new FormUrlEncodedContent(data.Where(kvp => !kvp.Key.StartsWith("oauth_")));

        return SendRequest(fullUrl, oAuthHeader, formData);
    }

    /// <summary>
    /// Generate an OAuth signature from OAuth header values.
    /// </summary>
    string GenerateSignature(string url, Dictionary<string, string> data)
    {
        var sigString = string.Join(
            "&",
            data
                .Union(data)
                .Select(kvp => string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)))
                .OrderBy(s => s)
        );

        var fullSigData = string.Format(
            "{0}&{1}&{2}",
            "POST",
            Uri.EscapeDataString(url),
            Uri.EscapeDataString(sigString.ToString())
        );

        return Convert.ToBase64String(sigHasher.ComputeHash(new ASCIIEncoding().GetBytes(fullSigData.ToString())));
    }

    /// <summary>
    /// Generate the raw OAuth HTML header from the values (including signature).
    /// </summary>
    string GenerateOAuthHeader(Dictionary<string, string> data)
    {
        return "OAuth " + string.Join(
            ", ",
            data
                .Where(kvp => kvp.Key.StartsWith("oauth_"))
                .Select(kvp => string.Format("{0}=\"{1}\"", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)))
                .OrderBy(s => s)
        );
    }

    /// <summary>
    /// Send HTTP Request and return the response.
    /// </summary>
    async Task<string> SendRequest(string fullUrl, string oAuthHeader, FormUrlEncodedContent formData)
    {
        using (var http = new HttpClient())
        {
            http.DefaultRequestHeaders.Add("Authorization", oAuthHeader);

            var httpResp = await http.PostAsync(fullUrl, formData);
            var respBody = await httpResp.Content.ReadAsStringAsync();

            return respBody;
        }
    }
}

并使用它:

var twitter = new TwitterApi(ConsumerKey, ConsumerKeySecret, AccessToken, AccessTokenSecret);
var response = await twitter.Tweet("This is my first automated tweet!");
Console.WriteLine(response);

也可以与.NET Core配合使用(即,不引用System.Web等)。

此处存在一个类似但更深入的示例(例如,上传图片)

C# / .NET Core, publish to Twitter