GoogleAppEngineのcronを使って

携帯百景に投稿した写真をはてダに投稿するスクリプトを書いた。
以前までは、XREAの有料サービスを使用して、cronで動かしてた。それはperlでHTMLのスクレイピングをして、shellのmailコマンドで投稿するものだった。
今回設置したのは以下のソース。

#!/usr/bin/env python
# -*- encoding:utf-8 -*-

import cgi
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api.mail import send_mail

from xml.etree import ElementTree
import StringIO
import time
import calendar
import datetime
import re

class MovapicItem(db.Model):
  title = db.StringProperty(multiline=True)
  link = db.StringProperty()
  desc = db.StringProperty(multiline=True)
  date = db.IntegerProperty()
  thumb = db.StringProperty()
    
class MainPage(webapp.RequestHandler):
  def get(self):
    feed_url = 'http://movapic.com/feed/user/fn7'
    out = "self.response.out.write"
    # get RSS
    r = urlfetch.fetch(feed_url)
    if(r.status_code != 200):
      self.response.out.write('<html><body>Error:<pre>%s</pre></body></html>' % r.content)
      return
    # データベースクリア
    #for i in db.GqlQuery('select * from MovapicItem'): i.delete()

    # 以前処理したものより新しいのだけ処理する
    src = StringIO.StringIO(r.content)
    xml = ElementTree.parse(src)
    lastItem = None
    for item in db.GqlQuery('select * from MovapicItem order by date desc limit 1'):
      lastItem = item
      break
    if (not lastItem):
      lastItem = MovapicItem()
      # 2009年 11月25日 水曜日 06時52分29秒 JST
      lastItem.date = 1259099520 
    for item in xml.findall('//item'):
      date = calendar.timegm(time.strptime(item.findtext('./pubDate'),"%a, %d %b %Y %H:%M:%S +0900"))
      if(lastItem.date < date):
        model = MovapicItem()
        model.date = date
        model.title = re.sub(r'\s+$','',item.findtext('./title'))
        model.link = item.findtext('./link')
        model.desc = item.findtext('./description')
        model.thumb = item.findall('.//{http://search.yahoo.com/mrss/}thumbnail')[0].get('url')
        model.put()        

        # メール送信
        body = (u"[%s:image]\n%s\n" % (model.thumb,model.link)).encode('utf-8')
        subject = (u"[携帯百景]%s" % model.title).encode('utf-8')
        send_mail(sender='[% 自分のgmailアドレス %]',to='[% はてダの投稿アドレス %]',subject=subject,body=body)
        
    self.response.out.write("<html><body>OK</body></html>")

def main():
  application = webapp.WSGIApplication([
    ('/movapic', MainPage)],
  debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()

cronの設定はこれ。

cron:
- description: movapic 2 hateda
  url: /movapic
  schedule: every 5 minutes

今後は、RSSの処理やメールの投稿処理等を交換可能に改造していきたいな。

[追記] はてダの投稿メルアドを公開しちゃっていたので、急ぎ投稿用メルアドを変更した。
[追記2] メールの送信が上手くいっていなかったので修正([参考] http://d.hatena.ne.jp/hiratara/20080712/1215854052)