Skip to content

Commit

Permalink
Refatoração do código de localização
Browse files Browse the repository at this point in the history
* Adicionado comando para abrir o dashboard via comando de voz, dizendo "abrir dashboard" ou "abrir home assistant", customizável durante a criação da skill
  • Loading branch information
fabianosan committed Oct 15, 2024
1 parent af968b4 commit 9743d98
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 36 deletions.
51 changes: 22 additions & 29 deletions lambda/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,6 @@ def load_config():
home_assistant_dashboard = config.get("home_assistant_dashboard")
home_assistant_kioskmode = bool(config.get("home_assistant_kioskmode", False))

# Configurações da interface
echo_screen_welcome_text = None
echo_screen_click_text = None
echo_screen_button_text = None

# Configurações de respostas
alexa_speak_welcome_message = None
alexa_speak_next_message = None
alexa_speak_question = None
alexa_speak_help = None
alexa_speak_exit = None
alexa_speak_error = None
alexa_speak_timeout = None

# Função para carregar os arquivos de localização de cada idioma
def load_localization(locale):
file_name = f"locale/{locale}.lang"
Expand All @@ -82,7 +68,7 @@ def load_localization(locale):
load_localization("en-US")

# Verificação de configuração
if not home_assistant_url or not home_assistant_token or not home_assistant_agent_id or not home_assistant_language or not echo_screen_welcome_text or not echo_screen_button_text or not echo_screen_click_text or not alexa_speak_welcome_message or not alexa_speak_next_message or not alexa_speak_question or not alexa_speak_help or not alexa_speak_exit or not alexa_speak_error:
if not home_assistant_url or not home_assistant_token or not home_assistant_agent_id or not home_assistant_language:
raise ValueError("Alguma configuração não feita corretamente!")

# Variável global para armazenar o conversation_id
Expand All @@ -108,11 +94,11 @@ def handle(self, handler_input):
# Carregar o arquivo de configuração
current_date = now.strftime('%Y-%m-%d')

speak_output = alexa_speak_next_message
speak_output = globals().get("alexa_speak_next_message")

if last_interaction_date != current_date:
# Primeira execução do dia
speak_output = alexa_speak_welcome_message
speak_output = globals().get("alexa_speak_welcome_message")
last_interaction_date = current_date

# Device supported interfaces
Expand Down Expand Up @@ -141,6 +127,13 @@ def handle(self, handler_input):
query = handler_input.request_envelope.request.intent.slots["query"].value
logger.info(f"Query received: {query}")

# Se o usuário der um comando para abrir o dashboard ou o home assistant, executa a ação
keywords = globals().get("keywords_to_open_dashboard").split(";")
if any(keyword.strip().lower() in query.lower() for keyword in keywords):
logger.info("Abrindo o dashboard do Home Assistant")
open_page(handler_input)
return handler_input.response_builder.speak(globals().get("alexa_speak_open_dashboard")).response

device_id = ""
if home_assistant_room_recognition:
# Obter o deviceId do dispositivo que executou a skill
Expand All @@ -149,7 +142,7 @@ def handle(self, handler_input):
response = process_conversation(f"{query}{device_id}")

logger.info(f"Response generated: {response}")
return handler_input.response_builder.speak(response).ask(alexa_speak_question).response
return handler_input.response_builder.speak(response).ask(globals().get("alexa_speak_question")).response

def process_conversation(query):
global conversation_id
Expand Down Expand Up @@ -184,21 +177,21 @@ def process_conversation(query):
speech = response_data["response"]["speech"]["plain"]["speech"]
logger.error(f"Error code: {response_data['response']['data']['code']}")
else:
speech = alexa_speak_error
speech = globals().get("alexa_speak_error")
return improve_response(speech)
else:
error_message = response_data.get("message", "Erro desconhecido")
logger.error(f"Erro ao processar a solicitação: {error_message}")
return alexa_speak_error
return globals().get("alexa_speak_error")

except requests.exceptions.Timeout as te:
# Tratamento para timeout
logger.error(f"Timeout ao se comunicar com o Home Assistant: \n {str(te)}", exc_info=True)
return alexa_speak_timeout
return globals().get("alexa_speak_timeout")

except Exception as e:
logger.error(f"Erro ao gerar resposta: {str(e)}", exc_info=True)
return alexa_speak_error
return globals().get("alexa_speak_error")

def replace_words(query):
query = query.replace('4.º','quarto')
Expand Down Expand Up @@ -228,10 +221,10 @@ def load_template(filepath):

if filepath == 'apl_openha.json':
# Substituindo os valores dinâmicos do APL
template['mainTemplate']['items'][0]['items'][2]['text'] = echo_screen_welcome_text
template['mainTemplate']['items'][0]['items'][3]['text'] = echo_screen_click_text
template['mainTemplate']['items'][0]['items'][2]['text'] = globals().get("echo_screen_welcome_text")
template['mainTemplate']['items'][0]['items'][3]['text'] = globals().get("echo_screen_click_text")
template['mainTemplate']['items'][0]['items'][4]['onPress']['source'] = get_hadash_url()
template['mainTemplate']['items'][0]['items'][4]['item']['text'] = echo_screen_button_text
template['mainTemplate']['items'][0]['items'][4]['item']['text'] = globals().get("echo_screen_button_text")

return template

Expand Down Expand Up @@ -275,7 +268,7 @@ def can_handle(self, handler_input):
return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)

def handle(self, handler_input):
speak_output = alexa_speak_help
speak_output = globals().get("alexa_speak_help")
return handler_input.response_builder.speak(speak_output).ask(speak_output).response

class CancelOrStopIntentHandler(AbstractRequestHandler):
Expand All @@ -284,8 +277,8 @@ def can_handle(self, handler_input):

def handle(self, handler_input):
open_page(handler_input)
speak_output = random.choice(alexa_speak_exit)
return handler_input.response_builder.speak(speak_output).response
speak_output = random.choice(globals().get("alexa_speak_exit").split(";"))
return handler_input.response_builder.speak(globals().get("speak_output")).response

class SessionEndedRequestHandler(AbstractRequestHandler):
def can_handle(self, handler_input):
Expand All @@ -301,7 +294,7 @@ def can_handle(self, handler_input, exception):

def handle(self, handler_input, exception):
logger.error(exception, exc_info=True)
speak_output = alexa_speak_error
speak_output = globals().get("alexa_speak_error")
return handler_input.response_builder.speak(speak_output).ask(speak_output).response

sb = SkillBuilder()
Expand Down
5 changes: 4 additions & 1 deletion lambda/locale/en-GB.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=Anything else?
alexa_speak_help=How can I help you?
alexa_speak_exit=See you later!;Bye;If you need me, I'm here;Ok, I'm off;Cheers;It's all good;Thanks, see ya.;I'm off, thanks.
alexa_speak_error=Sorry, I couldn't process your request.
alexa_speak_timeout=Home Assistant took too long to respond. Simplify the command and try again!
alexa_speak_timeout=Home Assistant took too long to respond. Simplify the command and try again!
alexa_speak_open_dashboard=Opening Home Assistant

keywords_to_open_dashboard=open dashboard; open home assistant
5 changes: 4 additions & 1 deletion lambda/locale/en-US.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=Anything else?
alexa_speak_help=How can I assist you?
alexa_speak_exit=Goodbye!;See you later;I'm here if you need me;Alright, I'm out;Take care;Later;Take it easy;I'm off, see ya.
alexa_speak_error=Sorry, I couldn't process your request.
alexa_speak_timeout=The Home Assistant took too long to respond. Please simplify the command and try again!
alexa_speak_timeout=The Home Assistant took too long to respond. Please simplify the command and try again!
alexa_speak_open_dashboard=Opening Home Assistant

keywords_to_open_dashboard=open dashboard; open home assistant
5 changes: 4 additions & 1 deletion lambda/locale/es-ES.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=¿Algo más?
alexa_speak_help=¿Cómo puedo ayudarte?
alexa_speak_exit=¡Hasta luego!;Adiós;Si necesitas algo, aquí estoy;Vale, me voy;Nos vemos;Gracias, adiós;Me voy, gracias.
alexa_speak_error=Lo siento, no pude procesar tu solicitud.
alexa_speak_timeout=Home Assistant ha tardado demasiado en responder. Simplifica el comando e inténtalo de nuevo.
alexa_speak_timeout=Home Assistant ha tardado demasiado en responder. Simplifica el comando e inténtalo de nuevo.
alexa_speak_open_dashboard=A abrir el Home Assistant

keywords_to_open_dashboard=abrir dashboard; abrir home assistant
5 changes: 4 additions & 1 deletion lambda/locale/fr-FR.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=Encore quelque chose ?
alexa_speak_help=Comment puis-je vous aider ?
alexa_speak_exit=À bientôt !;Au revoir;Si vous avez besoin de moi, je suis là;D'accord, je m'en vais;À plus tard;Merci, au revoir;Je m'en vais, merci.
alexa_speak_error=Désolé, je n'ai pas pu traiter votre demande.
alexa_speak_timeout=Home Assistant a mis trop de temps à répondre. Simplifiez la commande et réessayez !
alexa_speak_timeout=Home Assistant a mis trop de temps à répondre. Simplifiez la commande et réessayez !
alexa_speak_open_dashboard=Ouvrir le Home Assistant

keywords_to_open_dashboard=ouvrir dashboard; ouvrir home assistant
5 changes: 4 additions & 1 deletion lambda/locale/it-IT.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=Qualcos'altro?
alexa_speak_help=Come posso aiutarti?
alexa_speak_exit=Arrivederci!;Ciao;Se hai bisogno sono qui;Ok, sto andando via;Ci vediamo;Grazie, arrivederci;Vado, grazie.
alexa_speak_error=Scusa, non sono riuscito a processare la tua richiesta.
alexa_speak_timeout=Home Assistant ha impiegato troppo tempo a rispondere. Semplifica il comando e riprova!
alexa_speak_timeout=Home Assistant ha impiegato troppo tempo a rispondere. Semplifica il comando e riprova!
alexa_speak_open_dashboard=A aprire il Home Assistant

keywords_to_open_dashboard=aprire dashboard; aprire home assistant
5 changes: 4 additions & 1 deletion lambda/locale/pt-BR.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=Mais alguma coisa?
alexa_speak_help=Como posso te ajudar?
alexa_speak_exit=Ate logo!;Tchau;Se precisar estou por aqui;Ok, tô indo nessa;Valeu;É nóis;Valeu. falou.;Fui, valeu.
alexa_speak_error=Desculpe, não consegui processar sua solicitação.
alexa_speak_timeout=O Home Assistant demorou muito para responder. Simplifique o comando e tente novamente!
alexa_speak_timeout=O Home Assistant demorou muito para responder. Simplifique o comando e tente novamente!
alexa_speak_open_dashboard=Abrindo o Home Assistant

keywords_to_open_dashboard=abrir dashboard; abrir home assistant
5 changes: 4 additions & 1 deletion lambda/locale/pt-PT.lang
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ alexa_speak_question=Mais alguma coisa?
alexa_speak_help=Como posso ajudá-lo?
alexa_speak_exit=Até logo!;Tchau;Se precisar, estou por aqui;Ok, estou a ir nessa;Valeu;É nós;Valeu, falou.;Fui, valeu.
alexa_speak_error=Desculpe, não consegui processar a sua solicitação.
alexa_speak_timeout=O Home Assistant demorou muito a responder. Simplifique o comando e tente novamente!
alexa_speak_timeout=O Home Assistant demorou muito a responder. Simplifique o comando e tente novamente!
alexa_speak_open_dashboard=A abrir o Home Assistant

keywords_to_open_dashboard=abrir dashboard; abrir home assistant

0 comments on commit 9743d98

Please sign in to comment.