# encoding:utf-8
import urllib, urllib2
import sys
import json
#print sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf-8')
#print sys.getdefaultencoding()
# client_id 为从UNIT的【发布上线】模块进入百度云创建应用后获取的API Key
client_id='6IyrjGqXXXXXXXXRueG2pAiw'
#client_secret 为从UNIT的【发布上线】模块进入百度云创建应用后获取的Secret Key
client_secret='xKuYf5M38XXXXXXXXQj2UySaMultIMGB'
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+client_id+'&client_secret='+client_secret
#上面的XXXXXXX 要替换成自己的API Key,YYYYYY要换成自己的Secret Key
request = urllib2.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib2.urlopen(request)
access_token = json.load(response)["access_token"]
#真实业务中要把access_token 存到redis里,不能频繁的创建access_token(频繁创建会影响性能,导致一些对话失败),access_token默认有效期为30天,要自己写定时任务在30天到期前自动更新
#print access_token
url = 'https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=' + access_token
query = "帮我定明天北京到深圳的高铁票"
#下面的log_id在真实应用中要自己生成,可是递增的数字
log_id ='7758521'
#下面的user_id在真实应用中要是自己业务中的真实用户id、设备号、ip地址等,方便在日志分析中分析定位问题
user_id='222333'
#下面要替换成自己的bot_id
bot_id='SXXXXXX'
post_data = '{\"bot_session\":\"\",\"log_id\":\"'+log_id+'\",\"request\":{\"bernard_level\":1,\"client_session\":\"{\\\"client_results\\\":\\\"\\\", \\\"candidate_options\\\":[]}\",\"query\":\"' + query + '\",\"query_info\":{\"asr_candidates\":[],\"source\":\"KEYBOARD\",\"type\":\"TEXT\"},\"updates\":\"\",\"user_id\":\"'+user_id+'\"},\"bot_id\":'+bot_id+',\"version\":\"2.0\"}'
request = urllib2.Request(url, post_data)
request.add_header('Content-Type', 'application/Json_test;charset=UTF-8')
response = urllib2.urlopen(request)
content = response.read()
#if content:
# print content
data = json.loads(content)
print '用户问: '+ query
print 'BOT答复: ' + data['result']['response']['action_list'][0]['say']
print '意图: ' + data['result']['response']['schema']['intent']
slots = data['result']['response']['schema']['slots']
#print '词槽: ' + slot[0]['name'] + " = " +slot[0]['original_word']
for slot in slots:
print '词槽: ' + slot['name'] + " = " +slot['original_word']
收藏
点赞
0
个赞
请登录后评论
TOP
切换版块
能问你个这个问题吗,我也遇到了
你好
已解决,我将bot_id值误认为机器人id了
在网页打开url显示:
{"error_code":282008,"error_msg":"The request content type is illegal."}