我正在尝试为运动传感器制作 Alexa Skill。我需要将 Alexa.ChangeReport 事件发送到 Alexa 事件网关,但我不断收到格式错误的 JSON 错误。
我在MotionSensor Interface Documentation中使用了亚马逊为他们的ChangeReport提供的完全相同的事件格式,但他们仍然说格式错误的JSON。首先,我还没有编写代码来刷新和获取更新的令牌,而只是确保我的令牌有效。有什么想法吗?
这是我的代码:
motion_state=get_motion_state_from_iot()
acc_token = payload['state']['desired']['LWA_Access_Token']
message_id = str(uuid.uuid4())
current_time = datetime.datetime.utcnow().isoformat() + "Z"
event_data = urllib.parse.urlencode(
{
"event": {
"header": {
"namespace": "Alexa",
"name": "ChangeReport",
"messageId": message_id,
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": acc_token
},
"endpointId": endpoint_id
},
"payload": {
"change": {
"cause": {
"type": "PHYSICAL_INTERACTION"
},
"properties": [
{
"namespace": "Alexa.MotionSensor",
"name": "detectionState",
"value": motion_state,
"timeOfSample": current_time,
"uncertaintyInMilliseconds": 0
}
]
}
}
},
"context": {
"properties": [
{
"namespace": "Alexa.EndpointHealth",
"name": "connectivity",
"value": {
"value": "OK"
},
"timeOfSample": current_time,
"uncertaintyInMilliseconds": 0
}
]
}
}
).encode("utf-8")
url = "https://api.eu.amazonalexa.com/v3/events"
headers = {
'Authorization': f'Bearer {acc_token}',
'Content-Type': 'application/json'
}
posting = urllib.request.Request(url, event_data, headers, "POST")
try:
with urllib.request.urlopen(posting) as response:
lwa_tokens = json.loads(response.read().decode("utf-8"))
return ("Success!")
except HTTPError as http_error:
return(f"An error occurred: {http_error.read().decode('utf-8')}")
这是解码的错误
"An error occurred: {\"header\":{\"namespace\":\"System\",\"name\":\"Exception\",\"messageId\":\"01ca3509-734d-49ba-a89c-40cf93e2c0ae\"},\"payload\":{\"code\":\"INVALID_REQUEST_EXCEPTION\",\"description\":\"The request was malformed.\"}}"
您传递给
urllib.parse.urlencode()
的值不是有效的 Python 对象。查看此函数的文档并找出它需要什么作为输入。如果它是字符串,则需要使用 str.format() 或 f-string 语法将整个参数格式化为字符串来合并变量。