tetsunosukeのnotebook

tetsunosukeのメモです

AppEngineのInBoundMailを使ってTwitterを更新した。

更新のAPIにはTweepyを使ってみた。
InBoundMailのサンプルについては、CookBookの例を見てもらうとして、本文の日本語の文字コードからみがうまくいっていなかった。なんだかわかっていなかったけど、Bエンコードの文字列になっていたので、要はMIME関連ですね、と。

というわけで、email.Headerと、unicode関連のメソッドを用いて下記のように。これでtwitter側への投稿に成功した。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from email.Header import decode_header

import tweepy

class MailHandler(InboundMailHandler):
    def receive(self, message):
        basic_auth = tweepy.BasicAuthHandler("username", "password")
        api = tweepy.API(basic_auth)
        bodies = message.bodies(content_type='text/plain')
        body_line = ""
        for body in bodies:
            h = decode_header(body[1].decode())
            body_line = body_line + unicode(h[0][0], "iso-2022-jp")

        api.update_status(body_line.encode("utf-8"))


application = webapp.WSGIApplication([MailHandler.mapping()], debug=True) 

def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()