Bloggerをプログラムによって投稿できないものかと画策しており、いろいろ調べた結果、Blogger用のAPIが使えそうだったので、PythonでBlogger APIを使う方法を私自身の備忘録としても記載しておきます。
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools,file
import argparse
import httplib2
import os
import sys
def main(argv):
# flowオブジェクトの生成
client_id = '{自身のClient ID}'
client_secret = '{自身のClient Secret}'
scope = 'https://www.googleapis.com/auth/blogger'
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(client_id=client_id,
client_secret=client_secret,
scope=scope,
redirect_uri=redirect_uri)
# strageオブジェクトの生成、読み込み
storage = file.Storage(__file__ + '.dat') # 認証資格情報の保存ファイル名
credentials = storage.get() # 認証資格情報の読み込み
# 認証資格情報の取得(保存済みの資格情報がない場合)
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage)
http = credentials.authorize(http = httplib2.Http())
service = build('blogger', 'v3', http=http)
posts = service.posts()
body = {
"kind": "blogger#post",
"id": "{自身のブログID}",
"title": "posted via python",
"content":"<div>hello world test</div>"
}
insert = posts.insert(blogId='{自身のブログID}', body=body)
posts_doc = insert.execute()
print posts_doc
if __name__ == '__main__':
main(sys.argv)
コメントを投稿