Я создаю приложение alexa, которое должно получать данные о энергопотреблении с веб-сайта через API и ключ API. У меня есть навыки работы с консолью разработчика alexa, однако я не понимаю, нужна ли мне учетная запись AWS для лямбда-функции? очевидно, он встроен в консоль разработчика Amazon. Может ли кто-нибудь помочь с этим?
Я ожидаю, что код запустится, но, похоже, он ничего не делает. 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/electrici ... nsumption/'
`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`
Подробнее здесь: https://stackoverflow.com/questions/786 ... et-request
Создание навыка Alexa, позволяющего REST API получать запросы ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как связать Java-код в AWS Lambda и навыки Alexa в консоли Amazon Alexa?
Anonymous » » в форуме JAVA - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как пройти аутентификацию для FCM Rest API с помощью Google REST API в PHP REST API?
Anonymous » » в форуме Php - 0 Ответы
- 161 Просмотры
-
Последнее сообщение Anonymous
-