VS2010 C# コンソール : Twitter ツイート & リツイート


  VS2010_Twitter.cs






VS2010_Twitter twitter =
	new VS2010_Twitter(
		"Consumer key",
		"Consumer secret",
		"Access token",
		"Access token secret"
);

switch (cmd) {
	case "tweet":
		// 投稿
		json = twitter.Tweet(text);
		break;
	// retweet:id でリツイート
	default:
		// id を取得する為に、":" で配列に分解
		string[] param = cmd.Split(new[] { ":" }, StringSplitOptions.None);
		// id でリツイート
		json = twitter.ReTweet(param[1]);
		break;
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Diagnostics;
using System.Security.Cryptography;

namespace TryApp_Tweet1
{
	class VS2010_Twitter
	{
		private string _consumer_key;
		private string _consumer_secret;
		private string _token;
		private string _secret;

		private string _tweet_api = "https://api.twitter.com/1.1/statuses/update.json";

		public VS2010_Twitter(
			string consumer_key,
			string consumer_secret,
			string token,
			string secret
			)
		{
			_consumer_key = consumer_key;
			_consumer_secret = consumer_secret;
			_token = token;
			_secret = secret;
		}

		public string Tweet(string text)
		{

			WebClient wc = new WebClient();

			// ソートされるリスト
			SortedList<string, string> sl = new SortedList<string, string>();
			sl.Add("oauth_consumer_key", _consumer_key);
			sl.Add("oauth_nonce", Nonce());
			sl.Add("oauth_signature_method", "HMAC-SHA1");
			sl.Add("oauth_timestamp", TimeStamp());
			sl.Add("oauth_token", _token);
			sl.Add("oauth_version", "1.0");
			sl.Add("status", Uri.EscapeDataString(text));

			// http ヘッダ用シグネチャ作成
			string work = "";
			foreach (KeyValuePair<string, string> kvp in sl) {
				if (work != "") {
					work += "&";
				}
				work += kvp.Key + "=" + kvp.Value;
			}

			string work2 = "";
			// メソッド
			work2 += "POST" + "&";
			// API URL
			work2 += Uri.EscapeDataString(_tweet_api) + "&";
			// Oauth + データ
			work2 += Uri.EscapeDataString(work);

			// OAuth tool チェック用
			Debug.WriteLine(work2);

			string oauth_signature = Signature(work2);

			// ヘッダ情報を作成
			work = "";
			foreach (KeyValuePair<string, string> kvp in sl) {
				// oauth_* のみを使用する
				if (work != "") {
					if ((kvp.Key + "      ").Substring(0, 6) == "oauth_") {
						work += ", ";
					}
				}
				if ((kvp.Key + "      ").Substring(0, 6) == "oauth_") {
					work += kvp.Key + "=" + Dd(kvp.Value);
				}
			}
			// シグネチャを追加( ヘッダーはソートの必要は無い )
			work += ", oauth_signature=" + Dd(Uri.EscapeDataString(oauth_signature));

			// OAuth tool チェック用
			Debug.WriteLine(work);

			// フォーマットは、 OAuth tool で確認。
			wc.Headers["Authorization"] = "OAuth " + work;
			// POST 用ヘッダ
			wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

			// 投稿
			string result = wc.UploadString(new Uri(_tweet_api), "POST", "status=" + sl["status"]);

			return result;

		}

		public string ReTweet(string id)
		{
			string _tweet_api =
				"https://api.twitter.com/1.1/statuses/retweet/" + id + ".json";

			WebClient wc = new WebClient();

			// ソートされるリスト
			SortedList<string, string> sl = new SortedList<string, string>();
			sl.Add("id", id);
			sl.Add("oauth_consumer_key", _consumer_key);
			sl.Add("oauth_nonce", Nonce());
			sl.Add("oauth_signature_method", "HMAC-SHA1");
			sl.Add("oauth_timestamp", TimeStamp());
			sl.Add("oauth_token", _token);
			sl.Add("oauth_version", "1.0");

			// http ヘッダ用シグネチャ作成
			string work = "";
			foreach (KeyValuePair<string, string> kvp in sl) {
				if (work != "") {
					work += "&";
				}
				work += kvp.Key + "=" + kvp.Value;
			}

			string work2 = "";
			// メソッド
			work2 += "POST" + "&";
			// API URL
			work2 += Uri.EscapeDataString(_tweet_api) + "&";
			// Oauth + データ
			work2 += Uri.EscapeDataString(work);

			// OAuth tool チェック用
			Debug.WriteLine(work2);

			string oauth_signature = Signature(work2);

			// ヘッダ情報を作成
			work = "";
			foreach (KeyValuePair<string, string> kvp in sl) {
				// oauth_* のみを使用する
				if (work != "") {
					if ((kvp.Key + "      ").Substring(0, 6) == "oauth_") {
						work += ", ";
					}
				}
				if ((kvp.Key + "      ").Substring(0, 6) == "oauth_") {
					work += kvp.Key + "=" + Dd(kvp.Value);
				}
			}
			// シグネチャを追加( ヘッダーはソートの必要は無い )
			work += ", oauth_signature=" + Dd(Uri.EscapeDataString(oauth_signature));

			// OAuth tool チェック用
			Debug.WriteLine(work);

			// フォーマットは、 OAuth tool で確認。
			wc.Headers["Authorization"] = "OAuth " + work;
			// POST 用ヘッダ
			wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

			// 投稿
			string result = wc.UploadString(new Uri(_tweet_api), "POST", "id=" + sl["id"]);

			return result;

		}


		// ダブルクォートで挟む
		private string Dd(string base_string)
		{
			return "\"" + base_string + "\"";
		}

		private string Nonce()
		{
			Random rand = new Random();
			int nonce = rand.Next(1000000000);
			return nonce.ToString();
		}

		// タイムスタンプ
		private string TimeStamp()
		{
			TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
			return Convert.ToInt64(ts.TotalSeconds).ToString();
		}

		// シグネチャ
		private string Signature(string target)
		{
			string work = _consumer_secret + "&" + _secret;
			byte[] bin = Encoding.UTF8.GetBytes(target);

			HMACSHA1 hmacsha1 = new HMACSHA1();
			hmacsha1.Key = Encoding.UTF8.GetBytes(work);
			byte[] hash = hmacsha1.ComputeHash(bin);

			return Convert.ToBase64String(hash);
		}
	}
}


関連する記事

VS2010 コンソール : Twitter ツイートとリツイート

▼ テンプレートダウンロード
SkyDrive へ移動

※ VS2010 用










yahoo  google  MSDN  MSDN(us)  WinFAQ  Win Howto  tohoho  ie_DHTML  vector  wdic  辞書  天気 


[sh_dotnet]
Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
24/04/20 02:46:44
InfoBoard Version 1.00 : Language=Perl

1 BatchHelper COMprog CommonSpec Cprog CprogBase CprogSAMPLE CprogSTD CprogSTD2 CprogWinsock Cygwin GameScript HTML HTMLcss InstallShield InstallShieldFunc JScript JScriptSAMPLE Jsfuncs LLINK OldProg OracleGold OracleSilver PRO PRObrowser PROc PROconePOINT PROcontrol PROftpclient PROjscript PROmailer PROperl PROperlCHAT PROphp PROphpLesson PROphpLesson2 PROphpLesson3 PROphpfunction PROphpfunctionArray PROphpfunctionMisc PROphpfunctionString PROsql PROvb PROvbFunction PROvbString PROvbdbmtn PROvbonepoint PROwebapp PROwin1POINT PROwinSYSTEM PROwinYOROZU PROwindows ProjectBoard RealPHP ScriptAPP ScriptMaster VBRealtime Vsfuncs a1root access accreq adsi ajax amazon argus asp aspSample aspVarious aspdotnet aw2kinst cappvariety centura ckeyword classStyle cmaterial cmbin cmdbapp cmenum cmlang cmlistbox cmstd cmstdseed cmtxt cs daz3d db dbCommon dbaccess dnettool dos download flex2 flex3 flex4 framemtn framereq freeWorld freesoft gimp ginpro giodownload google hdml home hta htmlDom ie9svg install java javaSwing javascript jetsql jquery jsp jspTest jspVarious lightbox listasp listmsapi listmsie listmsiis listmsnt listmspatch listmsscript listmsvb listmsvc memo ms msde mysql netbeans oraPlsql oracle oracleWiper oraclehelper orafunc other panoramio pear perl personal pgdojo pgdojo_cal pgdojo_holiday pgdojo_idx pgdojo_ref pgdojo_req php phpVarious phpguide plsql postgres ps r205 realC realwebapp regex rgaki ruby rule sboard sc scprint scquest sdb sdbquest seesaa setup sh_Imagick sh_canvas sh_dotnet sh_google sh_tool sh_web shadowbox shgm shjquery shvbs shweb sjscript skadai skywalker smalltech sperl sqlq src systemdoc tcpip tegaki three toolbox twitter typeface usb useXML vb vbdb vbsfunc vbsguide vbsrc vpc wcsignup webanymind webappgen webclass webparts webtool webwsh win8 winofsql wmi work wp youtube