Google App Engineで Web hook → twitter
実はWeb Hookが出た週の週末に作成。まあHello Worldの次に作ったものなんで出来がいいとは言えませんが・・・
このスクリプト
という事をしております。使い方としてはサーバーにデプロイして後はWeb Hookの設定でサーバーのアドレスを入れるだけです。
Pythonを使ってみての感想
- インデントめんどくせー
- 文字列の扱いがくせ者
- urllib2めんどくせー
めんどくさいのはなれればいいか
ちとURLフェッチを調べてみるかー
#!/usr/bin/env python import wsgiref.handlers,urllib,urllib2,logging from google.appengine.ext import webapp from django.utils import simplejson #twitter twitterurl = 'http://twitter.com/statuses/update.xml' id_str = 'ID' pass_str = 'パス' #bit.ly bitly_api = 'http://api.bit.ly/shorten?' bitly_id = 'ID' bitly_pw = 'パス' #hatena hatena_key = 'キー' class MainHandler(webapp.RequestHandler): def post(self): #Get MessageBody title = self.request.get('title') url = self.request.get('url').encode('utf_8') key = self.request.get('key') status = self.request.get('status') #bit.ly Web API apiARG = {'version':'2.0.1','longUrl':url,'login':bitly_id,'apiKey':bitly_pw} shorteningAPIurl = bitly_api + urllib.urlencode(apiARG) f_json = urllib2.urlopen(shorteningAPIurl) #parse JSON if ( f_json.code == 200): url = simplejson.load( f_json )['results'][url]['shortUrl'] f_json.close() #Twitter msgdata = '[B]' + title + ' ' + url #Basic Auth auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password('Twitter API', 'http://twitter.com/',id_str,pass_str) #URL Open msgdata = urllib.urlencode({'status':msgdata.encode('utf_8')}) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) f = urllib2.urlopen(twitterurl,msgdata) output = "%d , %s" % (f.code,f.msg) f.close() #Response self.response.out.write(output) def main(): application = webapp.WSGIApplication([('/', MainHandler)],debug=False) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
追記:
Google Apps Engine Oilとurlフェッチを使った例が見つかりました。urlエンコード用にどうしてもurllibはやっぱり必要か〜
Google Apps Engine から Twitterを更新してみた。 - ito.tetsunosuke/notebook