R.A. Epigonos et al.

[perl] Hatena::Bookmark にポスト

SBMというものがはやっているらしい。delicuousにアカウント取ったらOAuthでないとポストできない様子。面倒なのではてブにする。WebService::Hatena::Bookmark::Lite モジュールを使えばすぐに出来る。

WebService::Hatena::Bookmark::Liteをインストールしておく

# cpan -i WebService::Hatena::Bookmark::Lite

あとは、本家に載っているサンプルスクリプトを踏襲。これで、標準入力からURLを受けてポスト出来る。addメソッドは成功すれば文字列が帰ってくるけど、失敗するとundefが帰ってくる。

$ perl hatenabookmark.pl
http://search.cpan.org/~masartz/WebService-Hatena-Bookmark-Lite-0.03/lib/WebService/Hatena/Bookmark/Lite.pm
$VAR1 = bless( do{\(my $o = 'http://search.cpan.org/~masartz/WebService-Hatena-Bookmark-Lite-0.03/lib/WebService/Hatena/Bookmark/Lite.pm')}, 'URI::http' );
$VAR1 = 'atom/edit/20442734';
^C
#!/usr/bin/perl
use strict;
use warnings;
use WebService::Hatena::Bookmark::Lite;

my $bookmark = WebService::Hatena::Bookmark::Lite->new(
                username  => 'hoge',
                password  => 'fuga',
                );

while (<STDIN>) {
        print $bookmark->add(url => $_);
}

このままだとログイン情報をハードコーディングしているし、エラー処理しないし、無駄処理もするので、お色直ししておく。ログイン情報を外部ファイル(JSON)にして、標準入力がURIで無い場合にはポスト処理をしない。

$ cat $HOME/.accounts/hatena.json
{"password":"fuga","username":"hoge"}
$ perl hatenabookmark.pl --config $HOME/.accounts/hatena.json
http://search.cpan.org/~masartz/WebService-Hatena-Bookmark-Lite-0.03/lib/WebService/Hatena/Bookmark/Lite.pm
$VAR1 = bless( do{\(my $o = 'http://search.cpan.org/~masartz/WebService-Hatena-Bookmark-Lite-0.03/lib/WebService/Hatena/Bookmark/Lite.pm')}, 'URI::http' );
$VAR1 = 'atom/edit/20442734';
^C
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use URI;
use JSON;
use IO::File;
use WebService::Hatena::Bookmark::Lite;
use Getopt::Long;

my $file = '';
GetOptions('config=s' => \$file);

my $io = IO::File->new();
$io->open($file, 'r') or die $!;
my $account = decode_json(join '', $io->getlines);
$io->close;

my $bookmark = WebService::Hatena::Bookmark::Lite->new(%$account);

while (<STDIN>) {
        chomp;
        if ($_ ne '') {
                my $uri = URI->new($_);
                print Dumper $uri;
                if (defined $uri->scheme && defined $uri->host) {
                        my $edit_ep = $bookmark->add(url => $uri);
                        print Dumper $edit_ep;
                }

        }
}

exit;

リファレンス

  1. WebService::Hatena::Bookmark::Lite - search.cpan.org
  2. perl 引数 オプション - Google 検索
  3. Perl スクリプトでのコマンドラインオプション処理
  4. Getopt::Long - perldoc.perl.org
  5. URIモジュールのメモ - Unknown::Programming
  6. perl勉強メモ
  7. URLを触る時は、URI(perlモジュール名)が超便利だと思う。 - perl-mongers.org
  8. URLを触る時は、URI(モジュール名)以外も知っておくと吉 - perl-mongers.org
  9. Perlメモ/IO::Fileモジュール - Walrus, Digit.
  10. パスワード設定をコードに書かない(Config::Pit) - モダンなPerl入門 - モダンなPerl入門

ソーシャルブックマーク

  1. はてなブックマーク
  2. Google Bookmarks
  3. del.icio.us

ChangeLog

  1. Posted: 2009-04-30T16:29:44+09:00
  2. Modified: 2009-04-30T16:29:44+09:00
  3. Generated: 2023-08-27T23:09:17+09:00