本文作者: 峡州仙士
原文链接: https://cjh0613.github.io/blog/20200521xiaoiAPI.html
声明: 如文章有更新,将首先在本网站(峡州仙士之页)发布!(可百度搜到)| 本网站(峡州仙士之页)所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
首先,登陆http://open.xiaoi.com,左侧开发者中心,客服API,得到Key
和Secret
调用示例:
仅返回字符:
print(cjhGetResponse("你好","0"))
返回xml:
print(cjhGetResponse("你好","1"))
函数:
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')