XIRCDのTwitterコンポーネントをOAuth対応に

月日は百代の過客にして 行き交う年もまた旅人

id:naoyaさんもグリーに移り,Twitterでベーシック認証が使えなくなった今日このごろ皆様いかがおすごしでしょうか.毎日暑いですね.とかこんなこと書いてると,後で見直したときになんのこっちゃ,とか思うんだろうなぁ.
そんなことは置いといて,Basic認証を使っていたXIRCDのTwitterコンポーネントが使えなくなりました.昼休みにちょこっと書き直してみたのでそのまとめです.

XIRCD

普段使っているバージョンはGitHub - tokuhirom/xircdで,これを書き直しました.

package XIRCD::Component::Twitter;
use XIRCD::Component;
use AnyEvent;
use AnyEvent::twitter;
use Encode;

with 'XIRCD::Role::Dedup';

has 'consumer_key'        => ( isa => 'Str', is => 'rw' );
has 'consumer_secret'     => ( isa => 'Str', is => 'rw' );
has 'access_token'        => ( isa => 'Str', is => 'rw' );
has 'access_token_secret' => ( isa => 'Str', is => 'rw' );
has 'retry' => ( isa => 'Int', is => 'rw', default => sub { 60 } );

has ua => (
    is      => 'rw',
    isa     => 'AnyEvent::Twitter',
    lazy    => 1,
    builder => 'build_ua',
);

sub build_ua {
    my $self = shift;
    AnyEvent::Twitter->new(
        consumer_key        => $self->consumer_key,
        consumer_secret     => $self->consumer_secret,
        access_token        => $self->access_token,
        access_token_secret => $self->access_token_secret,
    );
}

sub receive_message {
    my ( $self, $status ) = @_;
    debug "send message $status";

    $self->ua->request(
        api    => 'statuses/update',
        method => 'POST',
        params => { status => $status },
        sub { }
    );

}

sub init {
    my $self = shift;
    debug "read twitter";

    timer(
        interval => $self->retry,
        cb       => sub {
            $self->ua->request(
                api    => 'statuses/friends_timeline',
                method => 'GET',
                sub {
                    my ( $hdr, $res, $reason ) = @_;
                    for my $line ( reverse @{ $res || [] } ) {
                        next if $self->deduper->{ $line->{id} }++;
                        $self->publish_message(
                            $line->{user}->{screen_name} => $line->{text} );
                    }
                },
            );
        },
    );
}

1;

エラー処理はなにもやっていないし,沢山updateがあると取りこぼしてそう.でもとりあえず動いたので使ってみてます.