ブログ アーカイブ

ラベル Blogger の投稿を表示しています。 すべての投稿を表示
ラベル Blogger の投稿を表示しています。 すべての投稿を表示

2008年6月4日水曜日

ブログの投稿を自動化する

PythonとGoogle APIに慣れてきたところで、Bloggerの投稿を自動化してみようと思います。
投稿内容を書いたテキストファイルを準備してコマンドを実行すれば投稿が実行されるようにしました。

#!/usr/bin/python
import getpass
import os
import re
import sys
import atom
import gdata.service

# validating arguments
if len(sys.argv) < 6:
print 'usage:%s email blog_name title label file [encoding]' % sys.argv[0]
print '"label" is a commma separated label list'
print '"encoding" is encoding of console. (ex. Shift_JIS, utf-8, ...)'
print 'file encoding must be utf-8.'
exit()

email = sys.argv[1]
blog_name = sys.argv[2]
title = sys.argv[3]
label = sys.argv[4]
article = sys.argv[5]
if len(sys.argv) > 6:
encoding = sys.argv[6]
title = unicode(title, encoding)
title = title.encode('utf-8')

if not os.path.exists(article):
print '"%s" is missing.' % article
exit()

if not os.path.isfile(article):
print '"%s" is not a file.' % article
exit()

contents = open(article, 'r').read()
password = getpass.getpass()

# authentication
blogger_service = gdata.service.GDataService(email, password)
blogger_service.service = 'blogger'
blogger_service.server = 'www.blogger.com'
blogger_service.ProgrammaticLogin()

# retrieving blog id
query = gdata.service.Query()
query.feed = '/feeds/default/blogs'
feed = blogger_service.Get(query.ToUri())
blog_id = None
for entry in feed.entry:
if entry.title.text == blog_name:
blog_id = entry.GetSelfLink().href.split('/')[-1]
if blog_id == None:
print 'Blog "%s" does not exist.' % blog_name
exit()

# post blog
entry = gdata.GDataEntry()
if len(label) != 0:
entry.category.append(atom.Category(label, 'http://www.blogger.com/atom/ns#'))
entry.title = atom.Title(title_type='xhtml', text=title)
entry.content = atom.Content(content_type='html', text=contents)
blog_entry = blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id)

使い方は以下のようにします。
$ ./blogger-post.py foo.bar@gmail.com 'hoge blog' 'post title' 'Label1, Label2' post.txt Shift_JIS
引数は下記の通りです。
  1. GMailのアドレス(パスワードはコマンド実行後のプロンプトで入力します)
  2. ブログのタイトル
  3. 投稿記事のタイトル
  4. 投稿記事のラベル(複数指定する場合はカンマ区切り、省略する場合は空文字にします)
  5. 投稿記事が書かれたテキストファイル
  6. コンソールのエンコーディング(utf-8の場合は省略可能です)

2008年6月3日火曜日

ブログに複数の画像を簡単に投稿する(その2)

前回の続きです。
画像を一括アップロードして画像のHTMLを生成するPythonスクリプトを作成しました。

#!/usr/bin/python
import getpass
import os
import re
import sys
import gdata.photos.service

# validating arguments
if len(sys.argv) < 3:
print 'usage:%s email photo_dir' % (sys.argv[0])
exit()

email = sys.argv[1]
photo_dir = sys.argv[2]

if not os.path.exists(photo_dir):
print 'Directory "%s" is missing.' % (photo_dir)
exit()

if not os.path.isdir(photo_dir):
print '"%s" is not a directory.' % (photo_dir)
exit()

album_name = os.path.basename(os.path.abspath(photo_dir))
password = getpass.getpass()

# authentication
gd_client = gdata.photos.service.PhotosService()
gd_client.email = email
gd_client.password = password
gd_client.ProgrammaticLogin()

# creating new album
album_entry = gd_client.InsertAlbum(title=album_name, summary='Blogger resources', access='private')
album_url = '/data/feed/api/user/%s/album/%s' % (email, album_entry.name.text)

# adding photos
for photo in os.listdir(photo_dir):
photo_path = '%s/%s' % (photo_dir, photo)
if re.search(r'\.jpe?g', photo_path.lower()) != None:
print 'Uploading "%s"...' % (photo_path)
photo_entry = gd_client.InsertPhotoSimple(album_url, 'Blogger resource', 'Uploaded using the API', photo_path, content_type='image/jpeg')

# generate html
album_feed = gd_client.GetFeed('%s?kind=photo' % (album_url))
for photo in album_feed.entry:
photo_url = photo.GetMediaURL()
print '<span><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="%s"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px;" src="%s" border="0" alt="" /></a>\n</span>' % (photo_url, photo_url)

スクリプトの引数はGmailアドレスとアップロードする画像が入っているディレクトリの2つです。
パスワードはスクリプト実行後に標準入力から読み込みます。
Googleの認証が成功したら、引数のディレクトリの名称でPicasaウェブアルバムに新しいアルバムを作成します。
そしてそのディレクトリにあるJPEGファイルをすべてアップロードします。
JPEGファイルかどうかは拡張子で判定しています。
アップロードが終了したらそれらの画像をBloggerに貼り付けるためのHTMLを標準出力に出力します。

ブログに複数の画像を簡単に投稿する(その1)

Bloggerを始めるにあたって、複数の画像を使って簡単に書き込みできる方法を考えてみました。


画像を縦に並べて、その横に説明文をつらつら書いていくようなレイアウトにしたいのですが、Bloggerの機能を使って1ファイルずつ画像をアップしていくのは面倒です。

いろいろと試行錯誤した結果、
  1. Picasaに画像を一括アップロード
  2. アップロードした画像のURLを取得
  3. 画像のURLからBloggerに投稿するHTMLを生成

という手順を自動化できれば投稿が簡単になりそうです。
画像のHTML生成まで自動化できれば、あとは文章を書き込むだけです。

ということで、これらの処理をGoogle APIを使って実装してみます。
Picasa ウェブ アルバム データ APIというものです。
http://code.google.com/intl/ja/apis/picasaweb/overview.html

言語はJava、.NET、PHP、Pythonが使えるようです。今回は使ったことの無いPythonで試してみることにします。

まずはPython環境の構築です。
Getting Started with the Google Data Python Libraryを参考にしました。

はじめにPythonのインストールですが私の環境はCygwinなのでCygwinのインストーラでインストールすることができました。バージョンは2.5.2です。

次に必要な外部モジュールの確認を行います。
pythonインタプリタを実行します。
$ python

以下を入力してエラーが無ければOKです。
>> from xml.etree import ElementTree


次にPicasa ウェブ アルバム データ APIを利用するためにGoogle Data Python Libraryをインストールします。
$ wget http://gdata-python-client.googlecode.com/files/gdata.py-1.0.13.tar.gz
$ tar xf gdata.py-1.0.13.tar.gz
$ cd gdata.py-1.0.13
$ ./setup.py install


最後にモジュールのインストール確認を行います。
$ ./tests/run_data_tests.py

これでエラーが無ければOKです。

次回はPythonでGoogle APIを使ってみます。