首页 > 代码库 > Python聊天机器人

Python聊天机器人

技术分享
#!/usr/bin/python # coding=utf-8 import json import urllib import datetime from urllib import urlencode # ---------------------------------- # { # "reason":"成功的返回", # "result": /*根据code值的不同,返回的字段有所不同*/ # { # "code":100000, /*返回的数据类型,请根据code的值去数据类型API查询*/ # "text":"你好啊" # }, # "error_code":0 # } # ---------------------------------- def main(): print tm() appkey = "****************************" # appKey print ‘Your name: ‘ user = raw_input(‘‘) print ‘Where are you: ‘ loc = raw_input() print ‘----> OK, You can ask me question <----‘ while 1: print tm(), ‘ ‘, user, ‘: \n\t‘, Q = raw_input() if Q == ‘exit‘: break # 1.问答 res = request1(user, loc, Q, appkey, "GET") print tm(), ‘Robot: \n\t‘, result(res) def result(res): if res: error_code = res["error_code"] if error_code == 0: # 成功请求 return res["result"][‘text‘] else: return "%s:%s" % (res["error_code"], res["reason"]) else: return "request api error" def tm(): now = datetime.datetime.now() return now.strftime(‘%m-%d %H:%M:%S‘) # 问答 def request1(user, loc, que, appkey, m="GET"): url = "http://op.juhe.cn/robot/index" params = { "key": appkey, # APPKEY "info": que, # 要发送给机器人的内容,不要超过30个字符 "dtype": "", # 返回的数据的格式,json或xml,默认为json "loc": loc, # 地点,如北京中关村 "lon": "", # 经度,东经116.234632(小数点后保留6位),需要写为116234632 "lat": "", # 纬度,北纬40.234632(小数点后保留6位),需要写为40234632 "userid": user, # 1~32位,此userid针对您自己的每一个用户,用于上下文的关联 } params = urlencode(params) if m == "GET": f = urllib.urlopen("%s?%s" % (url, params)) else: f = urllib.urlopen(url, params) content = f.read() res = json.loads(content) return res # 数据类型 def request2(appkey, m="GET"): url = "http://op.juhe.cn/robot/code" params = { "dtype": "", # 返回的数据格式,json或xml,默认json "key": appkey, # 您申请本接口的APPKEY,请在应用详细页查询 } params = urlencode(params) if m == "GET": f = urllib.urlopen("%s?%s" % (url, params)) else: f = urllib.urlopen(url, params) content = f.read() res = json.loads(content) if res: error_code = res["error_code"] if error_code == 0: # 成功请求 print res["result"] else: print "%s:%s" % (res["error_code"], res["reason"]) else: print "request api error" if __name__ == ‘__main__‘: main()

 

Python聊天机器人