今回もLINQ to Twitterを使って、自分のタイムラインを取得します。
前回、ユーザー名とパスワードでの認証したので、今回は認証にOAuthを使用していますが、LinqToTwitterDemo の InitializeOAuthConsumerStrings をそのまま使用しているだけです。
準備
1.「Applications Using Twitter」にアクセスし、「Register a new application ≫」をクリックしてアプリケーションを登録します。
2.アプリケーションの内容を適当に入力して、今回はコンソールアプリでテストしますので「Application Type」は「Client」を選択し、「保存する」をクリックします。
3.「Consumer key」と「Consumer secret」が表示されるのでメモっておきます。
4.プロジェクトを作成し、「LinqToTwitter.dll」を参照に追加します。
5.アプリケーション構成ファイル(App.Config)を作成し、取得した「Consumer key」と「Consumer secret」を設定に追加します。
app.config
<configuration>
<appSettings>
<add key="twitterConsumerKey" value="[Consumer key]" />
<add key="twitterConsumerSecret" value="[Consumer secret]" />
</appSettings>
</configuration>
サンプルコード(C#)
using System;
using System.Linq;
using LinqToTwitter;
using System.Configuration;
class Program
{
// 認証
private static void InitializeOAuthConsumerStrings(TwitterContext twitterCtx)
{
var oauth = (DesktopOAuthAuthorization)twitterCtx.AuthorizedClient;
oauth.GetVerifier = () =>
{
Console.WriteLine("Next, you'll need to tell Twitter to authorize access.\nThis program will not have access to your credentials, which is the benefit of OAuth.\nOnce you log into Twitter and give this program permission,\n come back to this console.");
Console.Write("Please enter the PIN that Twitter gives you after authorizing this client: ");
return Console.ReadLine();
};
if (oauth.CachedCredentialsAvailable)
{
Console.WriteLine("Skipping OAuth authorization step because that has already been done.");
}
}
static void Main(string[] args)
{
ITwitterAuthorization auth = new DesktopOAuthAuthorization();
TwitterContext twitterCtx = new TwitterContext(auth, "https://twitter.com/", "http://search.twitter.com/");
InitializeOAuthConsumerStrings(twitterCtx);
auth.SignOn();
// タイムラインを取得して出力
var tweets = from tweet in twitterCtx.Status
where tweet.Type == StatusType.Friends
select tweet;
foreach (var tweet in tweets)
{
Console.WriteLine("User Name: {0}, Tweet: {1}",
tweet.User.Name,
tweet.Text);
}
twitterCtx.Dispose();
Console.ReadLine();
}
}
実行
1.初回実行時にブラウザが起動し、「ユーザー名やメールアドレス」と「パスワード」の入力ページが表示されますので、入力して「許可する」をクリックします。
2. ページが移動して番号が表示されますので、表示された番号をコンソールに入力します。
3.認証が通ればタイムラインを取得しコンソールに出力されます。