自動ニコニコ動画紹介記事生成スクリプト Python版

id:aprkさんの自動ニコニコ動画紹介記事生成スクリプト AutoNicoDiary 0.1 Python版です。Cookieをファイルに保存するようにしたので、多少はサーバに優しくなっていると思います。

使い方

$ auto-nico-diary.py -h
使い方: auto-nico-diary.py [オプション]

Options:
  -h, --help  このヘルプを表示して終了
  -k KEYWORD  ニコニコ動画の検索キーワード
  -t          ちょっとした更新

$ auto-nico-diary.py -t 
'ひぐらしのなく頃に打[IMG]'を登録しました.

$ auto-nico-diary.py -k 初音ミク -t
'【初音ミク】あなたとクリスマス【オリジナル】'を登録しました.

スクリプト

#!python
# vim:fileencoding=shift_jis

import mechanize, random, sys
from optparse import OptionParser

nico_mail = "nicoMail"
nico_pass = "nicoPass"
hatena_id = "hatenaID"
hatena_pass = "hatenaPass"

# Cookieをファイルに保存しない場合はコメントアウト
cookie_file = sys.argv[0] + ".cookie"

client_encoding = "shift-jis"

nico_url = "http://www.nicovideo.jp/"
hatena_url = ("https://www.hatena.ne.jp/login?location="
              "http%3A%2F%2Fd.hatena.ne.jp%2F" + hatena_id + "%2Fedit")


# コマンドラインオプション
# 先頭に"Usage: "が自動的に追加されるので"\r"で消す
usage = u"\r使い方: %prog [オプション]"
parser = OptionParser(usage=usage, conflict_handler="resolve")
parser.add_option("-h", "--help",
        action="help", help=u"このヘルプを表示して終了")
parser.add_option("-k", dest="keyword",
        help=u"ニコニコ動画の検索キーワード")
parser.add_option("-t",action="store_true", dest="trivial",
        default=False, help=u"ちょっとした更新")
(options, args) = parser.parse_args()


br = mechanize.Browser()
# デフォルトで使用されるCookieJarクラスにはCookieをファイルに
# 保存する機能はないので、FileCookieJarクラスのサブクラスを使う
cj = mechanize.LWPCookieJar()
br.set_cookiejar(cj)
try: # Cookieファイルがあれば読み込む
    cj.load(cookie_file)
except:
    pass


# ニコニコ動画に移動
br.open(nico_url)
br.select_form(nr=0)
if br.form.name == "login":
    br["mail"] = nico_mail
    br["password"] = nico_pass
    br.submit()
    try:
        br.select_form(nr=0)
    except:
        sys.exit("ニコニコ動画 - ログインエラー.")

# キーワードがあれば検索
keyword = ""
if options.keyword:
    keyword = options.keyword.decode(client_encoding)
    br["s"] = keyword.encode('utf-8')
    br.submit()

# トップページまたは検索結果ページから動画ページへのリンクを
# ランダムに一つ選択
links = []
for link in br.links():
    if link.url.find("watch/sm") >= 0:
        links.append(link)
if not links: sys.exit("動画が見つかりませんでした.")
link = random.choice(links)


# はてなダイアリーに登録するテキストを作成
text = u"*[ニコニコ動画]今日の"
if keyword:
    text += keyword
else:
    text += u"人気動画"
# ニコニコ動画を表示するためのガジェット
video_id = link.url[6:]
text += ('\n<script src="http://gmodules.com/ig/ifr?url='
         'http://ja2yka.homeip.net/~mitsu/gadget/nicovideo.xml&'
         'amp;up_video_id=' + video_id + '&amp;up_dummy=&amp;synd='
         'open&amp;w=312&amp;h=176&amp;title=%E3%83%8B%E3%82%B3%E3%'
         '83%8B%E3%82%B3%E5%8B%95%E7%94%BB&amp;border=%23ffffff%7C3px'
         '%2C1px+solid+%23999999&amp;output=js"></script>')


# はてなダイアリーの編集ページに移動し、テキストを登録
br.open(hatena_url)
br.select_form(nr=0)
if br.form.name != "edit":
    br["name"] = hatena_id
    br["password"] = hatena_pass
    br.submit()
    try:
        br.select_form(name="edit")
    except:
        sys.exit("はてなダイアリー - ログインエラー.")
br["body"] += "\n" + text.encode("euc-jp")
if options.trivial: br["trivial"] = ["1"]
br.submit(name='edit')


# Cookieをファイルに保存
try:
    cj.save(cookie_file)
except:
    pass

video_name = link.text.decode("utf-8", "replace")
video_name = video_name.encode(client_encoding, "replace")
sys.exit("'%s'を登録しました." % video_name)