首页 >> 在Galileo上搭个呆萌可爱的聊天机器人
在Galileo上搭个呆萌可爱的聊天机器人
来源:  时间:2014-12-29
分享到:

在今年五六月份火遍微信的微软小冰突然间消失不见了,大家对小冰的幽默风趣印象深刻,以往颇为沉寂的微信群因为小冰的存在而活跃了许多。小冰不过是微软人工智能的一个作品,实现一定程度的智能聊天交互,当然小冰之前仍有许多类似的诸如在人人网火遍一时的小黄鸡等。

今天在这里我们将会教大家如何利用小黄鸡的api与微博api搭建一个微博聊天机器人,当然这里为了方便展示与操作就选用微博这一简单快捷的在线网络服务,后期可根据此教程做微信公共号聊天机器人、在线版聊天机器人、QQ空间聊天机器人等类似的应用。

首先在小黄鸡官网(developer.simsimi.com)注册申请一个如图所示的App Key,然后将Key如下填入代码中

def xiaohuangji(ask):

ask = ask.encode('UTF-8')

enask = urllib2.quote(ask)

baseurl = r'http://sandbox.api.simsimi.com/request.p?key=5e0051cc-bd8e-410b-a757-2ec493bab356&lc=ch&ft=1.0&text='

url = baseurl+enask

req = urllib2.Request(url)

resp = urllib2.urlopen(req)

reson = json.loads(resp.read())

  return reson['response']

将上面代码中的"key=5e0051cc-bd8e-410b-a757-2ec493bab356"替换成你申请的key即可,”xiaohuangji(ask)“函数中的”ask“即为你发送给小黄鸡的信息,当然,可以是中文。返回的结果就是小黄鸡回复你的信息。

函数写好后,在后面可以直接打印”print xiaohuangji("一加一等于几")“,运行程序后即可看到如图所示小黄鸡的回复”二!~(≧皿≦)/~“,还是很萌的样子,至此,小黄鸡端程序调试ok,下面开始微博API了。

关于微博api之前已经讲过很多,这次的大概流程就是,检测是否有@当前微博账号的微博,然后将其内容发送给刚才写好的小黄鸡程序,获取小黄鸡的回复后直接将其作为当前微博的评论发送出去。流程简单,实现容易,当然,在此基础上还能开发诸如获取当前微博账号的收到的评论然后进行回复,实现同一微博下交互盖楼的功能。

好了,直接上代码,下面的代码即while循环,不断检测是否有新的@ 微博出现,然后读取内容发送给小黄鸡,获取回复,然后评论。

while True:

this_time = autohome.get_mention().split(',')

text=this_time[4]

weibo_id= this_time[1]

  resp_xiao = xiaohuangji("%s"%text)

if this_time[1] != pre_time[1]:

print 'you have sent a new weibo'

  print resp_xiao

  autohome.send_comments(weibo_id,'%s'%resp_xiao)

else:

print "you haven't sent any new weibos"

  print text

#autohome.send_comments(weibo_id,'%s'%resp_xiao)

time.sleep(5)

  pre_time = this_time

将所有代码组合在一起如下,保存在Intel Galileo中运行即可,然后发微博调戏你的小黄鸡啦!

#!/usr/bin/env python

# coding=utf-8

import autohome,time,sys

from time import localtime,strftime

reload(sys)

sys.setdefaultencoding('utf-8')

import httplib,urllib2,sys,time

from xml.dom.minidom import parseString

import hashlib

import urllib2,json,urllib

info=autohome.get_user_info()

def xiaohuangji(ask):

ask = ask.encode('UTF-8')

  enask = urllib2.quote(ask)

baseurl = r'http://sandbox.api.simsimi.com/request.p?key=5e0051cc-bd8e-410b-a757-2ec493bab356&lc=ch&ft=1.0&text='

  url = baseurl+enask  

 req = urllib2.Request(url)  

 resp = urllib2.urlopen(req)  

 reson = json.loads(resp.read())  

 return reson['response']

#print xiaohuangji("hi")

pre_time = autohome.get_mention().split(',')

while True:

this_time = autohome.get_mention().split(',')

text=this_time[4]

weibo_id= this_time[1]

resp_xiao = xiaohuangji("%s"%text)

if this_time[1] != pre_time[1]:

  print 'you have sent a new weibo'

print resp_xiao

autohome.send_comments(weibo_id,'%s'%resp_xiao)

  else:

  print "you haven't sent any new weibos"

  print text

#autohome.send_comments(weibo_id,'%s'%resp_xiao)

  time.sleep(5)

  pre_time = this_time