python3:呼叫阿里雲小蜜程式碼示例
阿新 • • 發佈:2018-12-30
最近有一個專案需要呼叫阿里雲小蜜,我就拿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