雑記 - otherwise

最近はDQ10しかやっていないダメ技術者がちまちまと綴る雑記帳

PowerShell で Twitter クライアント(ある意味詐欺版)

考えてみたら、 C# で TwitterClient クラスを作って PowerShell から LoadFile すればいいだけなんじゃ。。。
つまりは、 TwitterClient.dll とか作っておいて、

[Reflection.Assembly]::LoadFile($pwd.path + "\TwitterClient.dll")
$twitter = New-Object TwitterClient("userid", "password")
$twitter.GetFriendsTimeline(3)
# friends_timline の 3 ページ目を表示
$twitter.Post("がおー")
$twitter.GetFriendsTimeline()

なんて出来たらいいかも。
……と思い立ったので、かなり怪しいクラスをでっち上げてみた。

  • TwitterClient.cs
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Linq;

namespace Jp.Mkns.Twitter {
  public class TwitterClient {
    WebClient _client;
    string _name;

    public TwitterClient(string userid, string password) {
      this._name = userid;
      this._client = new WebClient();
      this._client.Credentials = new NetworkCredential(userid, password);
      this._client.Encoding = Encoding.UTF8;
      this._client.Headers.Add("User-Agent", "PowerShellTools/1.0(http://mk-net.jp/)");
    }

    public object[] GetFriendsTimeline() {
      return this.GetFriendsTimeline(1);
    }

    public object[] GetFriendsTimeline(int page) {
      IFormatProvider culture = new CultureInfo("en-US");
      var xml = this._client.DownloadString("http://twitter.com/statuses/friends_timeline/" + this._name + ".xml?page=" + page.ToString());
      var reader = new StringReader(xml);
      var xdoc = XDocument.Load(reader);
      var items = from status in xdoc.Root.Elements()
          where status.Name.LocalName.Equals("status")
          select new {
              Name = status.Element("user").Element("name").Value,
              Text = status.Element("text").Value ,
              Date = DateTime.ParseExact(status.Element("created_at").Value, "ddd MMM dd HH:mm:ss zzzz yyyy", culture)
          };
      var data = items.ToArray();
      return data;
    }

    public bool Post(string text) {
      var post = "status=" + Uri.EscapeUriString(text);
      var response = this._client.UploadString("http://twitter.com/statuses/update.xml", "POST", post);
      return true;
    }
  }
}

使い方は前述した通りでいける(ハズ)。(クラス名はフルパス [Jp.Mkns.Twitter.TwitterClient] でよろしく)
以下、注意事項。

  • at your own risk でお好きにお使いください。
  • GetFriendsTimeline(int) と Post しかできません。他は勝手に実装してください。そして追加したものを公開してください。 :p
  • 一応、軽くはテストしてありますが、サーバエラーになった場合は残念な事になります。
  • エラー処理してません。
  • ポストの結果もチェックしてません。