Python调用小黄鸡simsimi

直接从人人网小黄鸡代码里面提取一下了。https://github.com/insun/xiaohuangji
 
懒得申请SIMSIMI_KEY的话伪造User-Agent和Referer也能获取到json串
 
#!/usr/bin/env python
#-*-coding:utf-8-*-
 
# 从simsimi读数据
 
import requests
import cookielib
import socket
import random
import sys
sys.path.append('..')
reload(sys)
sys.setdefaultencoding('utf-8')
 
try:
    from settings import SIMSIMI_KEY
except:
    SIMSIMI_KEY = ''
 
class SimSimi:
 
    def __init__(self):
 
        self.session = requests.Session()
 
        self.chat_url = 'http://www.simsimi.com/func/req?lc=ch&msg=%s'
        self.api_url = 'http://api.simsimi.com/request.p?key=%s&lc=ch&ft=1.0&text=%s'
 
        if not SIMSIMI_KEY:
            self.initSimSimiCookie()
 
    def initSimSimiCookie(self):
        self.session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:18.0) Gecko/20100101 Firefox/18.0'})
        self.session.get('http://www.simsimi.com/talk.htm')
        self.session.headers.update({'Referer': 'http://www.simsimi.com/talk.htm'})
        self.session.get('http://www.simsimi.com/talk.htm?lc=ch')
        self.session.headers.update({'Referer': 'http://www.simsimi.com/talk.htm?lc=ch'})
 
    def getSimSimiResult(self, message, method='normal'):
        if method == 'normal':
            r = self.session.get(self.chat_url % message)
        else:
            url = self.api_url % (SIMSIMI_KEY, message)
            r = requests.get(url)
        return r
 
    def chat(self, message=''):
        if message:
            r = self.getSimSimiResult(message, 'normal' if not SIMSIMI_KEY else 'api')
            try:
                answer = r.json()['response']
                return answer.encode('utf-8')
            except:
                return random.choice(['呵呵', '。。。', '= =', '=。='])
        else:
            return '叫我干嘛'
 
simsimi = SimSimi()
 
def handle(data, bot):
    return simsimi.chat(data['message'])
 
if __name__ == '__main__':
    print handle({'message': '最后一个问题'}, None)
    print handle({'message': '还有一个问题'}, None)
    print handle({'message': '其实我有三个问题'}, None)
Python调用小黄鸡simsimi_第1张图片
 
 
 
 
 参考:
python模拟simsimi聊天室来调用simsimi的api:http://lidongbest5.com/blog/12/
 
github xiaohuangji: https://github.com/hupili/xiaohuangji

你可能感兴趣的:(Python调用小黄鸡simsimi)