智能问答——小i机器人的pythonAPI调用

首先,登陆http://open.xiaoi.com,左侧开发者中心,客服API,得到KeySecret

调用示例:
仅返回字符:

1
print(cjhGetResponse("你好","0"))

返回xml:

1
print(cjhGetResponse("你好","1"))

函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import urllib
import random
import hashlib

import requests

import re, json

#两个函数:
def getNonce():
strs = ''
for i in range(18):
strs += (str(random.randint(0, 15)))
return strs

def cjhGetResponse(question,t):
appKey = '你的Key'
appSecret = '你的Secret'
HA1 = hashlib.sha1(
':'.join([appKey, "xiaoi.com", appSecret]).encode("utf8")).hexdigest()
HA2 = hashlib.sha1(u"GET:/ask.do".encode("utf8")).hexdigest()
nonce = getNonce() # ':'.join([HA1, nonce, HA2]).encode("utf8")
sig = hashlib.sha1(
':'.join([HA1, nonce, HA2]).encode("utf8")).hexdigest()

headers = {
"X-Auth": "app_key=\"{0}\",nonce=\"{1}\",signature=\"{2}\"".format(
appKey, nonce, sig)
}
post_data = {
"question": question,
"userId": 'someone',
"type": t,
"platform": "web"
}
post_data = urllib.parse.urlencode(post_data)
url = "http://robot.open.xiaoi.com/ask.do?"+post_data
request = urllib.request.Request(url, None, headers)
request.add_header('Content-Type', 'text/html; charset=UTF-8')
response = urllib.request.urlopen(request)
return str(response.read(), 'utf8')

(您还可以在归档页搜索文章标题)