本文转载至农民小飞侠的CSDN博客:https://blog.csdn.net/w5688414/article/details/79317534 如禁止转载请联系删除。
最近有一个项目需要调用阿里云小蜜,我就拿python调用了一下,然后在官网居然没有找到很好的sample code。就只能自己硬着头皮写一下啦
import base64
import urllib.parse
import hmac
from hashlib import sha1
import requests
import uuid
import time
import hmac,ssl
ALIYUN_ACCESS_KEY_ID="your id"
ALIYUN_ACCESS_KEY_SECRET="your secret"
# 解决 访问ssl网站证书的问题
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
D = {
'Format':'JSON',
'Version':'2017-10-11',
'SignatureMethod':'HMAC-SHA1'
}
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
D['SignatureNonce']=str(uuid.uuid1())
D['SignatureVersion']=1.0
D['AccessKeyId']=ALIYUN_ACCESS_KEY_ID
D['Timestamp']=timestamp
def percent_encode(encodeStr):
encodeStr = str(encodeStr)
res = urllib.parse.quote(encodeStr)
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
def sign(parameters):
sortedParameters = sorted(parameters.items(), key=lambda parameters: parameters[0])
print(sortedParameters)
canonicalizedQueryString = ''
for (k, v) in sortedParameters:
canonicalizedQueryString += '&' + percent_encode(k) + '=' + percent_encode(v)
stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:]) # 使用get请求方法
bs = ALIYUN_ACCESS_KEY_SECRET + '&'
bs = bytes(bs, encoding='utf8')
stringToSign = bytes(stringToSign, encoding='utf8')
h = hmac.new(bs, stringToSign, sha1)
# 进行编码
signature = base64.b64encode(h.digest()).strip()
return signature
D['Action']="Chat"
D['InstanceId']="your instance id" #你阿里云的机器人实例id
D['Utterance']="电脑黑屏了怎么办"
D['Signature'] = sign(D)
sortedParameters = sorted(D.items(), key=lambda D: D[0])
# print(D["Signature"])
# print(sortedParameters)
url = 'https://chatbot.cn-shanghai.aliyuncs.com/?' + urllib.parse.urlencode(sortedParameters)
print(url)
r = requests.get(url)
print(r.text)
运行成功了,我的输出为:
{"SessionId":"672d532e9e1e40c09563828f54ee5b05","Messages":[{"Text":{},"Type":"Knowledge","Knowledge":{"Id":"74952","Content":"亲,先确认一下是否是没有接入电源,电量过低导致的黑屏,如果不是请到IT服务台报修,IT管理员会根据检测情况处理哦。","AnswerSource":"KnowledgeBase","Title":"电脑黑屏了怎么办","Summary":"亲,先确认一下是否是没有接入电源,电量过低导致的黑屏,如果不是请到IT服务台报修,IT管理员会根据检测情况处理哦。"}}],"MessageId":"0bb0e211d48d42acaf7f6e1924f7482c","RequestId":"D241002A-FADE-4C86-8180-9CD0B857017E"}