在C#中更新Twitter状态

时间:2009-07-30 17:44:23

标签: c# twitter

我正在尝试从我的C#应用​​程序更新用户的Twitter状态。

我在网上搜索并找到了几种可能性,但我对Twitter的身份验证过程中最近的(?)更改感到有些困惑。我还发现了似乎是relevant StackOverflow post的内容,但它根本没有回答我的问题,因为它是超级特定的,无法使用代码片段。

我正在尝试访问REST API,而不是搜索API,这意味着我应该采用更严格的OAuth身份验证。

我看了两个解决方案。 Twitterizer Framework工作正常,但它是一个外部DLL,我宁愿使用源代码。举个例子,使用它的代码非常清晰,看起来像这样:

Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");

我还检查了Yedda's Twitter library,但是当我尝试基本上与上面相同的代码时,这个我认为是认证过程失败了(Yedda期望状态更新本身的用户名和密码,但其他一切都是应该是一样的。)

由于我无法在网上找到明确的答案,我将它带到StackOverflow。

在没有外部DLL依赖的情况下,在C#应用程序中使用Twitter状态更新的最简单方法是什么?

由于

7 个答案:

答案 0 :(得分:10)

如果您喜欢Twitterizer Framework,但又不喜欢没有源代码,那么为什么不download the source? (或browse it如果你只是想看看它在做什么......)

答案 1 :(得分:7)

我不是重新发明轮子的粉丝,特别是在已经存在提供100%所需功能的产品方面。我实际上有Twitterizer的源代码并行运行我的ASP.NET MVC应用程序,以便我可以进行任何必要的更改...

如果你真的不想存在DLL引用,这里有一个关于如何用C#编写更新代码的例子。从dreamincode开始查看。

/*
 * A function to post an update to Twitter programmatically
 * Author: Danny Battison
 * Contact: gabehabe@hotmail.com
 */

/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
public static void PostTweet(string username, string password, string tweet)
{
    try {
        // encode the username/password
        string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
        // determine what we want to upload as a status
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
        // connect with the update page
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
        // set the method to POST
        request.Method="POST";
        request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
        // set the authorisation levels
        request.Headers.Add("Authorization", "Basic " + user);
        request.ContentType="application/x-www-form-urlencoded";
        // set the length of the content
        request.ContentLength = bytes.Length;

        // set up the stream
        Stream reqStream = request.GetRequestStream();
        // write to the stream
        reqStream.Write(bytes, 0, bytes.Length);
        // close the stream
        reqStream.Close();
    } catch (Exception ex) {/* DO NOTHING */}
}

答案 2 :(得分:3)

我成功使用的另一个Twitter库是TweetSharp,它提供了一个流畅的API。

源代码位于Google code。你为什么不想用dll?这是迄今为止在项目中包含库的最简单方法。

答案 3 :(得分:1)

将内容发布到Twitter的最简单方法是使用basic authentication,这不是很强大。

    static void PostTweet(string username, string password, string tweet)
    {
         // Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication
         WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = username, Password = password } };

         // Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body
         ServicePointManager.Expect100Continue = false;

         // Construct the message body
         byte[] messageBody = Encoding.ASCII.GetBytes("status=" + tweet);

         // Send the HTTP headers and message body (a.k.a. Post the data)
         client.UploadData("http://twitter.com/statuses/update.xml", messageBody);
    }

答案 4 :(得分:1)

试试LINQ To Twitter。使用适用于Twitter REST API V1.1的媒体完整代码示例查找LINQ To Twitter更新状态。解决方案也可供下载。

LINQ To Twitter代码示例

var twitterCtx = new TwitterContext(auth);
string status = "Testing TweetWithMedia #Linq2Twitter " +
DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool PossiblySensitive = false;
const decimal Latitude = StatusExtensions.NoCoordinate; 
const decimal Longitude = StatusExtensions.NoCoordinate; 
const bool DisplayCoordinates = false;

string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");

var mediaItems =
       new List<media>
       {
           new Media
           {
               Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
               FileName = "test.jpg",
               ContentType = MediaContentType.Jpeg
           }
       };

 Status tweet = twitterCtx.TweetWithMedia(
    status, PossiblySensitive, Latitude, Longitude,
    null, DisplayCoordinates, mediaItems, null);

答案 5 :(得分:0)

试试TweetSharp。查找TweetSharp update status with media complete code example适用于Twitter REST API V1.1。解决方案也可供下载。

TweetSharp代码示例

//if you want status update only uncomment the below line of code instead
        //var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
        Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
        if (img != null)
        {
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Seek(0, SeekOrigin.Begin);
            Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
            //Twitter compares status contents and rejects dublicated status messages. 
            //Therefore in order to create a unique message dynamically, a generic guid has been used

            var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
            if (result != null && result.Id > 0)
            {
                Response.Redirect("https://twitter.com");
            }
            else
            {
                Response.Write("fails to update status");
            }
        }

答案 6 :(得分:0)

这是使用优秀AsyncOAuth Nuget软件包和Microsoft HttpClient使用最少代码的另一种解决方案。此解决方案还假设您代表自己发布,因此您已经拥有访问令牌密钥/密码,但即使您没有流量也很容易(请参阅AsyncOauth文档)。

using System.Threading.Tasks;
using AsyncOAuth;
using System.Net.Http;
using System.Security.Cryptography;

public class TwitterClient
{
    private readonly HttpClient _httpClient;

    public TwitterClient()
    {
        // See AsyncOAuth docs (differs for WinRT)
        OAuthUtility.ComputeHash = (key, buffer) =>
        {
            using (var hmac = new HMACSHA1(key))
            {
                return hmac.ComputeHash(buffer);
            }
        };

        // Best to store secrets outside app (Azure Portal/etc.)
        _httpClient = OAuthUtility.CreateOAuthClient(
            AppSettings.TwitterAppId, AppSettings.TwitterAppSecret,
            new AccessToken(AppSettings.TwitterAccessTokenKey, AppSettings.TwitterAccessTokenSecret));
    }

    public async Task UpdateStatus(string status)
    {
        try
        {
            var content = new FormUrlEncodedContent(new Dictionary<string, string>()
            {
                {"status", status}
            });

            var response = await _httpClient.PostAsync("https://api.twitter.com/1.1/statuses/update.json", content);

            if (response.IsSuccessStatusCode)
            {
                // OK
            }
            else
            {
                // Not OK
            }

        }
        catch (Exception ex)
        {
            // Log ex
        }
    }
}

由于HttpClient的性质,这适用于所有平台。我自己在Windows Phone 7/8上使用这种方法来获得完全不同的服务。