lingrのボットPython版

2007年02月02日(金) 16:24

うくくの人が作ったlingr用のPythonエコーボットをいじくって、会話から適当なサイトを推薦するボットにしました。


会話の文脈なんて知ったことじゃありません。インチキです。コードもインチキです(yahoo_searchんとこね)。


人の会話からひらがな以外をn個集めて、そのうちのm個を使ってYahooにお尋ねをします。


教えてくれたサイトから一つ、simpleapiのサムネイルとURLをボットが推薦します。


邪魔臭いです


# coding: utf-8
import urllib
from django.utils import simplejson
from BeautifulSoup import BeautifulSoup as Soup
from random import choice, randint

import re

#FIXME START
room_id = 'xxxxxx'
bot_nickname = 'xxxxxx'
yahoo_key = 'xxxxxx' #YAHOO.CO.JP Developer API application key
api_key = "xxxxxx" #LINGR API KEY
word_count = 12
word_count_for_query = 2
#FIXME END

_YAHOO_URL = 'http://api.search.yahoo.co.jp/WebSearchService/V1/webSearch?appid=%s' % yahoo_key
_SIMPLEAPI_URL = 'http://img.simpleapi.net/small/%s?.png'

_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/"


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"]
        self.word = []

    def yahoo_search(self, query):
        if not query:
            return None
        q = re.sub(u'[\u3041-\u3093 <><>:]', ' ', query).strip().encode('utf-8')
        self.word += [w for w in q.split(' ') if len(w) > 0]
        if len(self.word) < word_count:
            return None
        q = ' '.join([choice(self.word) for i in range(word_count_for_query)])
        self.word = []
        url = '%s&%s' % (_YAHOO_URL, urllib.urlencode({'query':q}))
        s = Soup(urllib.urlopen(url).read().replace('', ''))
        targets = s.findAll('result')
        if targets:
            [x.extract() for x in s.findAll('cache')]
            urls = s.findAll('url')
            if urls:
                neta = urls[randint(0, len(urls) -1)].string
                self.say(_SIMPLEAPI_URL % (neta,))
                self.say(neta)

    
    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])
        try:
            self.counter = json["counter"]
            if callback:
                messages = json["messages"]
                for m in messages:
                    type = m["type"]
                    text = m["text"]
                    if type == "user" and text:
                        callback(text)
        except KeyError:
            pass
                    
    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])
        try:
            self.counter = json["counter"]
        except KeyError:
            pass
        
    def start(self):
        import time
        while 1:
            self.observe(self.yahoo_search)
            time.sleep(1)

    

if __name__ == '__main__':
    lingr = Lingr(api_key)
    room = lingr.enter_room(room_id, nickname=bot_nickname)
    room.start()
    

自己責任で


 
ponybadge

Powered by

Feedbacks

Tweets

Tags

Calendar