mixiエコーのスクリプトをオブジェクトの書き方にしてみた
オブジェクト指向の勉強のひとつで、以前自分が書いたmixiエコーに投稿できるスクリプトがありますが、それをオブジェクトの形で書き換えてみました。
パッケージ名は、適当に「WWW::Mixi::Echo」にしてみました。
package WWW::Mixi::Echo; use strict; use warnings; use LWP::UserAgent; use HTML::TreeBuilder; use Data::Dumper; use Encode; { #各URL設定 my $NEXT_URL = "/home.pl"; my $LOGIN_URL = 'https://mixi.jp/login.pl'; my $HOME_URL = 'http://mixi.jp/recent_echo.pl'; my $ECHO_URL = 'http://mixi.jp/add_echo.pl'; sub getNextUrl { $NEXT_URL }; sub getLoginUrl { $LOGIN_URL }; sub getHomeUrl { $HOME_URL; }; sub getEchoUrl { $ECHO_URL }; } sub new { my ($class, @arg) = @_; my $ua = new LWP::UserAgent(); $ua->cookie_jar({}); my $self = bless { _ua => $ua, _next_url => $class->getNextUrl, _login_url => $class->getLoginUrl, _home_url => $class->getHomeUrl, _echo_url => $class->getEchoUrl, _email => $arg[0], _pwd => $arg[1], }, $class; return $self; } sub login { my $self = shift; my $ua = $self->{ _ua }; my $login_url = $self->{ _login_url }; my $info = { next_url => $self->{ _next_url }, email => $self->{ _email }, password => $self->{ _pwd }, }; my $res = $ua->post($login_url, $info); if($res->is_success){ return 1; }else{ return 0; } } sub getKey { my $self = shift; my $ua = $self->{ _ua }; my $home_url = $self->{ _home_url }; my $res_con = $ua->get($home_url); my $p = HTML::TreeBuilder->new_from_content($res_con->content); my @echo = $p->look_down( id => 'EchoComment', ); my @post_key; for my $echo(@echo){ @post_key = $echo->parent->parent->look_down( name => 'post_key', ); } my $post_key; for my $key_body(@post_key){ $post_key = $key_body->attr('value'); } $self->{ _post_key } = $post_key; } sub postEcho{ my $self = shift; my ($echo_comment) = @_; my $ua = $self->{ _ua }; my $echo_url = $self->{ _echo_url }; my $post_url = $self->{ _post_url }; my $post_key = $self->{ _post_key }; $echo_comment = encode('euc-jp',decode('utf-8',$echo_comment)); my $post_info = { body => $echo_comment, x => 0, y => 0, redirect => 'home', post_key => $post_key, }; my $post_res = $ua->post($echo_url => $post_info); if($post_res->is_success){ #投稿成功 return 0; }else{ #投稿失敗 return 1; } }
一応、こんな感じで動きますが、こんなんでいいのかな????