构建执行 REST API 获取请求的 Alexa 技能

问题描述 投票:0回答:1

我正在构建一个 Alexa 应用程序,该应用程序应该通过 API 和 API 密钥从网站获取能耗数据,我已经在 Alexa 开发人员控制台上构建了一项技能,但是我很困惑是否需要 AWS 帐户来使用 lambda 函数?显然它是在亚马逊开发者控制台中构建的。有人可以帮忙吗?

我期待代码运行,但它似乎没有做任何事情。 Alexa 返回错误,提示“您的 Alexa 技能响应有错误”

这是我的代码,有人能发现错误吗?显然,由于显而易见的原因,api 密钥和 api 已更改:)

`



import logging
import ask_sdk_core.utils as ask_utils
import json
import requests
import pandas as pd
from dateutil import parser
from datetime import datetime, timedelta


API_KEY = "BLABLABLABLA"
BASE_URL = f'https://api.octopus.energy/v1/electricity-meter-points/09090909/meters/2139898/consumption/'


`class GetElectricityConsumptionIntentHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        return ask_utils.is_intent_name("GetElectricityConsumptionIntent")(handler_input)

    def handle(self, handler_input):
        # Initial setup
        page_number = 1
        page_size = 15000
        more_data = True
        total_data = pd.DataFrame()

        # Define date range
        end_date = datetime.utcnow()
        start_date = end_date - timedelta(days=7)

        # Format dates for the API request
        end_date_str = end_date.strftime('%Y-%m-%dT%H:%M:%SZ')
        start_date_str = start_date.strftime('%Y-%m-%dT%H:%M:%SZ')

        while more_data:
            # Construct the URL with proper query parameter separation
            url = f"{BASE_URL}?page={page_number}&page_size={page_size}&period_from={start_date_str}&period_to={end_date_str}&order_by=period"
            
            # Get the response from the API
            response = requests.get(url, auth=(API_KEY, ''))
            
            # Check if the response is successful
            if response.status_code != 200:
                raise Exception("Failed to fetch data from the API")
            
            # Read and process the JSON data
            re = response.json()
            results = re['results']
            
            # If no results are found, break the loop
            if not results:
                more_data = False
                break
            
            # Convert to DataFrame and append to the total data
            data = pd.DataFrame(results)
            data['date'] = pd.to_datetime(data['interval_start'])
            total_data = pd.concat([total_data, data])
            
            # Move to the next page
            page_number += 1
        
        # Group by day and sum the consumption for each day
        total_data['date'] = total_data['date'].dt.date
        daily_data = total_data.groupby('date')['consumption'].sum().reset_index()
        
        # Find the highest daily consumption
        highest_daily_consumption = daily_data['consumption'].max()
        highest_daily_date = daily_data.loc[daily_data['consumption'].idxmax(), 'date']

        # Prepare the response
        speak_output = f"The highest daily electricity consumption in the last 7 days was {highest_daily_consumption} kWh on {highest_daily_date}."
        return (
            handler_input.response_builder
                .speak(speak_output)
                .response
        )`
`

# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.


lambda_handler = sb.la`
python aws-lambda alexa-skills-kit
1个回答
0
投票

编写 Alexa 应用程序是一种令人沮丧的经历,我开始意识到你在这里得不到什么帮助。大约一半的 Alexa 相关问题都没有得到解答。

就我个人而言,我发现最好执行以下操作:

  • 在本地运行 python 代码并确保其正常运行,然后再将其部署到 AWS
  • 确保将所有外部包要求添加到您的requirements.txt 文件中(这些要求将记录在 CloudWatch 日志中)
  • 检查 CloudWatch 日志(在控制台中,转到“代码”,然后转到“CloudWatch 日志” - 这通常会告诉您问题所在。这是您调试的最佳朋友。
  • 在代码中包含大量日志记录和异常处理,以便可以轻松地在 CloudWatch 日志中识别问题

祝你好运。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.