Doge log

Abby CTO 雑賀 力王のオフィシャルサイトです

API client for Python

何かと話題のLingrですが、pythonでもサンプルを書いてみました。
ウノウさんがやってたのを見ておもしろいなと思ったので同じように高速に反応するechoサービスを作ってみました。

import urllib
import simplejson

_CREATE_URL = "http://www.lingr.com/api/session/create/"
_ENTER_URL = "http://www.lingr.com/api/room/enter"
_SAY_URL = "http://www.lingr.com/api/room/say"
_OBSERVE_URL = "http://www.lingr.com/api/room/observe/"
_GET_MESSAGES_URL = "http://www.lingr.com/api/room/get_messages/"

api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

class Lingr(object):
        
    def __init__(self, api_key):
        self.api_key = api_key
        data = dict(api_key=api_key,format="json", client_type="human")
        r = urllib.urlopen(_CREATE_URL, urllib.urlencode(data))
        json =  r.readlines()
        json = simplejson.loads(json[0])
        self.session = json["session"]

    def enter_room(self, id, nickname="anonymous"):
        room = LingrRoom(self.session, id, nickname)
        return room        

class LingrRoom(object):

    def __init__(self, session, id, nickname):
        self.session = session
        self.id = id
        self.nickname = nickname
        data = dict(session=session,id=id,nickname=nickname,format="json")
        r = urllib.urlopen(_ENTER_URL, urllib.urlencode(data))
        json =  r.readlines()
        json =  simplejson.loads(json[0])
        self.ticket = json["ticket"]
        self.counter = json["room"]["counter"]
        
    def observe(self, callback=None):
        data = dict(session=self.session,ticket=self.ticket,counter=self.counter,format="json")
        url = _OBSERVE_URL+"?"+urllib.urlencode(data)
        r = urllib.urlopen(url)
        json =  r.readlines()
        json =  simplejson.loads(json[0])
        self.counter = json["counter"]
        if callback:
            messages = json["messages"]
            for m in messages:
                type = m["type"]
                text = m["text"]
                print text
                if type == "user" and text:
                    callback(text)
                    
    def say(self, message):
        message = message.encode('utf-8')
        data = dict(session=self.session,ticket=self.ticket,message=message,format="json")
        r = urllib.urlopen(_SAY_URL, urllib.urlencode(data))
        json = r.readlines()
        json = simplejson.loads(json[0])
        self.counter = json["counter"]
        
    def start(self, callback=None):
        import time
        while 1:
            self.observe(callback)
            time.sleep(1)
            
if __name__ == '__main__':
    lingr = Lingr(api_key)
    room = lingr.enter_room("django-ja", nickname="")
    room.start(room.say)
  

非常に汚いw適当だしwwww
誰かが入力したメッセージを即返します。即ってところがいいです。
追記
ウンコだったので直しました。
うくく。