めもめも

このブログに記載の内容は個人の見解であり、必ずしも所属組織の立場、戦略、意見を代表するものではありません。

Perl スクリプトから取り急ぎ Tweet する方法

いろんな所に書かれている情報ではありますが・・・。実際に使って便利だったので、まとめておきます。

Net::Twitter::Lite の導入

CPAN から導入できます。

# cpan  Net::Twitter::Lite

/usr/lib/perl5/5.8.8/CPAN/Config.pm initialized.

CPAN is the world-wide archive of perl resources. It consists of about
100 sites that all replicate the same contents all around the globe.
Many countries have at least one CPAN site already. The resources
found on CPAN are easily accessible with the CPAN.pm module. If you
want to use CPAN.pm, you have to configure it properly.

If you do not want to enter a dialog now, you can answer 'no' to this
question and I'll try to autoconfigure. (Note: you can revisit this
dialog anytime later by typing 'o conf init' at the cpan prompt.)

Are you ready for manual configuration? [yes] no

### この後は全ての質問に [Enter] を入力

Twitter アカウントへのアプリケーションの登録

Twitter にアプリケーションを登録して、以下の 4 つのキーを取得します。

・CONSUMER_KEY
・CONSUMER_SECRET
・ACCESS_TOKEN
・ACCESS_TOKEN_SECRET

登録手順は、Last.fm のサイトに記載のものを引用させていただきます。

                    • -

1. ここにアクセス。
2. Create an applicationをクリック
3. Twitterアカウントを入力してログイン
4. 必要事項を記入
    1. アプリケーション名: - アプリケーション名を記入("APIから"の部分)
    2. アプリケーションのウェブサイトURL - 好きなURLを入れたらいいと思います。 
    3. 所属会社/団体 - 空欄でOK
    4. コールバックURL: - 空欄でOK
    5. Default Access type: - "Read & Write"にチェック
    6. アプリケーションのアイコン - 何でもおk
5. 規約を読んで「I Accept」をポチ
6. 右側にある"View your applications"をクリック
Consumer keyとConsumer secretをメモする
7. このページの右側にある"My Access Token "をクリック
Access Token (oauth_token)とAccess Token Secret (oauth_token_secret)をメモする

                    • -

Tweet の実行

こんな感じの Perl スクリプトで OK です。漢字は UTF8 でお願いします。HOGE の部分は取得したキーです。

#!/usr/bin/perl

use Net::Twitter::Lite;
use utf8;
use strict;

my $Consumer_key = 'HOGE';
my $Consumer_key_secret = 'HOGE';
my $Access_token = 'HOGE';
my $Access_token_secret = 'HOGE';

my $Tw = Net::Twitter::Lite->new(
  consumer_key    => $Consumer_key,
  consumer_secret => $Consumer_key_secret,
);
$Tw->access_token($Access_token);
$Tw->access_token_secret($Access_token_secret);

sub twitter_post {
  my $post = $_[ 0 ];
  eval{ $Tw->update( { status =>$post } ); };
  warn "Failed to tweet: $@\n" if ( $@ );
}

MAIN: {
  my $message = "\@enakai00 Twitter による通知のテストです。";
  twitter_post( $message );
}