ブログ アーカイブ

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の場合は省略可能です)

0 件のコメント: