Files
Monitor-N8N/app.py

176 lines
5.2 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
from datetime import datetime
import pytz
import streamlit as st
from apscheduler.schedulers.background import BackgroundScheduler
from monitor_logic import diagnose_n8n_webhook, run_monitor_check
# Timezone configuravel via variavel de ambiente (padrao: America/Sao_Paulo)
TIMEZONE = os.getenv("TIMEZONE", "America/Sao_Paulo")
tz = pytz.timezone(TIMEZONE)
st.set_page_config(
page_title="Monitor Evolution API",
page_icon="🤖",
layout="wide",
)
def gerar_tabela_html(logs):
"""Gera tabela HTML com estilos inline para garantir funcionamento."""
if not logs:
return ""
estilo_tabela = "width: 100%; border-collapse: collapse; margin-top: 10px;"
estilo_header = (
"background-color: #f0f2f6; padding: 12px 15px; text-align: center; "
"font-weight: bold; font-size: 16px; border-bottom: 2px solid #ddd;"
)
estilo_celula = (
"padding: 10px 15px; text-align: center; font-size: 14px; "
"border-bottom: 1px solid #eee;"
)
estilo_celula_detalhes = (
"padding: 10px 15px; text-align: left; font-size: 14px; "
"border-bottom: 1px solid #eee;"
)
html = f'<table style="{estilo_tabela}">'
html += "<thead><tr>"
html += f'<th style="{estilo_header}">Hora</th>'
html += f'<th style="{estilo_header}">Status</th>'
html += f'<th style="{estilo_header}">WhatsApp</th>'
html += f'<th style="{estilo_header}">Email</th>'
html += f'<th style="{estilo_header}">Detalhes</th>'
html += "</tr></thead>"
html += "<tbody>"
for log in logs:
html += "<tr>"
html += f'<td style="{estilo_celula}">{log["Hora"]}</td>'
html += f'<td style="{estilo_celula}">{log["Status"]}</td>'
html += f'<td style="{estilo_celula}">{log["WhatsApp"]}</td>'
html += f'<td style="{estilo_celula}">{log["Email"]}</td>'
html += f'<td style="{estilo_celula_detalhes}">{log["Detalhes"]}</td>'
html += "</tr>"
html += "</tbody></table>"
return html
if "logs" not in st.session_state:
st.session_state["logs"] = []
if "last_run" not in st.session_state:
st.session_state["last_run"] = "Nunca"
def scheduled_job():
"""Executa verificacao agendada (background thread)."""
now = datetime.now(tz)
print(f"[{now}] Executando verificacao agendada...")
status, messages, whatsapp_status, email_status = run_monitor_check()
print(f"Status: {status} | WhatsApp: {whatsapp_status} | Email: {email_status}")
print("\n".join(messages))
@st.cache_resource
def init_scheduler():
scheduler = BackgroundScheduler(timezone=TIMEZONE)
scheduler.add_job(
scheduled_job,
"cron",
hour=8,
minute=0,
second=0,
id="daily_080000_check",
replace_existing=True,
)
scheduler.start()
return scheduler
scheduler = init_scheduler()
st.title("🤖 Monitor Evolution API + Webhook")
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
st.metric(label="Ultima Verificacao", value=st.session_state["last_run"])
with col2:
st.write("### Status Agendador")
st.success("✅ Ativo (diariamente as 08:00:00 | intervalo 24h)")
st.markdown("### Acoes")
if st.button("🚀 Executar Verificacao Agora", type="primary"):
with st.spinner("Verificando status dos servicos..."):
status, messages, whatsapp_status, email_status = run_monitor_check()
now = datetime.now(tz)
st.session_state["last_run"] = now.strftime("%H:%M:%S")
entry = {
"Hora": now.strftime("%H:%M:%S"),
"Status": "✅ Sucesso" if status else "❌ Erro",
"WhatsApp": whatsapp_status,
"Email": email_status,
"Detalhes": " | ".join(messages),
}
st.session_state["logs"].insert(0, entry)
if status:
st.success("✅ Todos os servicos estao operacionais!")
else:
st.error("❌ Falha detectada em um ou mais servicos. Verifique os logs.")
st.markdown("---")
st.markdown("### Historico de Execucoes (Sessao Atual)")
if st.session_state["logs"]:
tabela_html = gerar_tabela_html(st.session_state["logs"])
st.markdown(tabela_html, unsafe_allow_html=True)
else:
st.info(" Nenhuma verificacao executada nesta sessao ainda.")
st.sidebar.title(" Sobre")
st.sidebar.info(
"""
Este aplicativo monitora:
1. **Evolution API**: Verifica se a instancia esta online.
2. **N8N Webhook**: Verifica se o endpoint responde.
**Notificacoes:**
- ✅ **Sucesso**: Envia WhatsApp.
- ❌ **Erro**: Envia Email.
"""
)
st.sidebar.markdown("---")
with st.sidebar.expander("🛠️ Diagnostico N8N"):
st.write("Teste isolado do Webhook N8N")
if st.button("Testar Webhook N8N", key="btn_diag"):
with st.spinner("Enviando POST de teste..."):
success, log_data = diagnose_n8n_webhook()
if success:
st.success(f"✅ Status: {log_data['status_code']}")
else:
st.error(f"❌ Erro: {log_data.get('status_code') or log_data.get('error')}")
st.json(log_data)
st.sidebar.markdown("---")
st.sidebar.caption("Disparador automatico: diariamente as 08:00:00 (24h)")