2009-07-30 14 views
5

私のC#アプリケーションからユーザーのTwitterステータスを更新しようとしています。C#のTwitterステータスを更新する

私はウェブを検索していくつかの可能性を見出しましたが、最近のTwitterの認証プロセスの変更(?)によってちょっと混乱します。私はまた、relevant StackOverflow postのようなものを見つけましたが、それは動作しないコードスニペットに非常に特化しているので、私の疑問に答えることはできません。

私は検索APIではなくREST APIにアクセスしようとしています。これは、より厳しいOAuth認証に対応する必要があることを意味します。

私は2つの解決策を検討しました。 Twitterizer Frameworkは正常に動作しましたが、外部DLLであり、むしろソースコードを使用します。ただ、一例として、それを使用したコードは非常に明確であるので、次のようになります。

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

と基本的に同じコードをしようとしたとき、私もYedda's Twitter libraryを検討したが、これは私が認証プロセスであると信じるものに失敗しました(Yeddaはステータス更新自体のユーザ名とパスワードを期待していますが、他のものはすべて同じものと想定しています)。

私はウェブ上で明確なカット答えを見つけることができなかったので、私はそれをStackOverflowに持ってきています。

C#アプリケーションでTwitterのステータスの更新を行う最も簡単な方法は、外部DLLの依存関係なしですか?

おかげ

答えて

10

あなたはTwitterizer Frameworkが好きならちょうどソースを持っていない好きではない、なぜdownload the source? (または、それが何をしているのかを知りたい場合はbrowse it

+0

まあ、ダムの質問は簡単な答えに値すると思う...どういうわけか彼らのソースが利用可能であったという事実を忘れてしまった。ありがとう:) –

7

私は、ホイールを再発明するファンではありません。特に、求められている機能の100%を提供する製品。私は実際にTwitterizerのソースコードを持っていますので、必要な変更を加えることができるように、私のASP.NET MVCアプリケーションを並べて実行しています。

本当にDLL参照が存在しないようにするには、ここにC#での更新をコード化する方法の例。これをdreamincodeからチェックしてください。

/* 
* A function to post an update to Twitter programmatically 
* Author: Danny Battison 
* Contact: [email protected] 
*/ 

/// <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 */} 
} 
+1

これを行うには、C#のわずか10行で十分ですが、そこにはTwitterの開発フレームワークがあることは驚きです! +1 – nbevans

+5

@ NathanE:コードには約10行しかありませんが、ライブラリに入れるのは良いことがたくさんあります。ストリームのためのステートメントを忘れるなど、愚かな間違いをしたり、例外を飲み込んだりするような愚かな間違いをしないようにします。 –

+3

@NathanE:Jonも可能な限りライブラリを使用し、ライブラリが必要な場合は... – RSolberg

3

私はsucessfully使用している別のTwitterのライブラリは、流暢なAPIを提供しTweetSharp、です。

ソースコードはGoogle codeです。なぜあなたはdllを使いたくないのですか?これは、プロジェクトにライブラリを含めるのが一番簡単な方法です。

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); 
    } 
0

お試しTweetSharpTweetSharp 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"); 
      } 
     } 
1

LINQ To Twitterを試してみてください。Twitter REST API V1.1で動作するメディアの完全なコード例を使用してLINQ To Twitterの更新ステータスを探します。ソリューションはダウンロード可能です。 Twitterのコードサンプルに

LINQ

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); 
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でこの方法を自分で使います。

関連する問題