2015年8月20日木曜日

PerlからGoogleのAPI経由でBloggerにポストするサンプル

Google APIでは多数の言語用のライブラリが提供されているにも関わらず、Perl用のライブラリがありません。

ですが、Google::API::ClientというCPANモジュールが便利なので、これを使ってBlogger API v3を叩いて記事を投稿してみようと思います。

ちなみにこのスクリプトを実行する前にGoogle Developer Consoleにて若干の下準備が必要となりますが、ここでは割愛させていただきます。

また、このスクリプトではクライアントIDとクライアントシークレットにJSONファイルを使用しますので、Google Developer Consoleの認証情報からクライアントIDを発行し、JSONファイルをclient_secrets.jsonという名前で保存し、本スクリプトの上の階層に設置しておいてください。

#!/usr/bin/perl
use strict;
use warnings;
use feature qw/say/;

use FindBin;
use JSON;
use Data::Dumper;

use Google::API::Client;
use Google::API::OAuth2::Client;

use Sample::Utils qw/get_or_restore_token store_token/; #This module has been included in the google-api-perl-client-master.zip

my $blogid = 'Insert your BlogID';

my $client = Google::API::Client->new;
my $service = $client->build('blogger', 'v3');

my $file = "$FindBin::Bin/../client_secrets.json";
my $auth_driver = Google::API::OAuth2::Client->new_from_client_secrets($file, $service->{auth_doc});

my $dat_file = "$FindBin::Bin/token.dat";
my $access_token = get_or_restore_token($dat_file, $auth_driver);

my $entry = {
    'kind' => 'blogger#post',
    'blog'=> {
        'id'=> $blogid,
     },
    'title' => 'A test post',
    'content' => 'With <b>HTML</b> content',
};
my $res = $service->posts->insert(blogId => $blogid, body => $entry )->execute({ auth_driver => $auth_driver });
say Dumper($res);

store_token($dat_file, $auth_driver);

__END__

このスクリプトをターミナルで初回起動した時(またはリフレッシュトークンの有効期限が切れた時)はOAuth用のURLが生成されます。 それをブラウザで開いて認証を済ませると、コードがブラウザ上に表示されます。それをターミナルに貼り付けて続行してください。

もしこの記事が貴方のお役に立ったようであれば、コメント欄に何かしら書いていただけると嬉しいです。

0 件のコメント:

コメントを投稿