python3:调用阿里云小蜜代码示例

最近有一个项目需要调用阿里云小蜜,我就拿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"}

 参考文献

[1].会话.https://help.aliyun.com/document_detail/60463.html?spm=a2c4g.11186623.6.555.rdcox6

[2].python3 获取阿里云ECS 实例及监控的方法.https://www.cnblogs.com/IPYQ/p/5996868.html

[3].签名机制.https://help.aliyun.com/document_detail/60762.html?spm=a2c4g.11186623.6.553.lFcX1e


评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值