20-sep: [fix] Sistema completo apagado/encendido remoto - shutdown listener + HA actualizado
This commit is contained in:
52
scripts/shutdown_listener.py
Normal file
52
scripts/shutdown_listener.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
Listener HTTP local que ejecuta shutdown cuando recibe POST /shutdown
|
||||
Home Assistant puede llamar a http://192.168.1.239:5555/shutdown para apagar el PC
|
||||
|
||||
Uso:
|
||||
python shutdown_listener.py
|
||||
|
||||
Debe correr como servicio/tarea programada al iniciar Windows.
|
||||
"""
|
||||
import os
|
||||
from flask import Flask, request, jsonify
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Cargar .env
|
||||
dotenv_path = r"C:\Users\juanm\Documents\GitHub\biblioteca_negocio_prolongo\.env"
|
||||
load_dotenv(dotenv_path)
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Token de seguridad para autorizar shutdowns
|
||||
SHUTDOWN_TOKEN = os.getenv("SHUTDOWN_TOKEN", "cambiar-este-token")
|
||||
|
||||
@app.route('/shutdown', methods=['POST'])
|
||||
def shutdown():
|
||||
"""Ejecuta shutdown del PC si el token es correcto"""
|
||||
# Verificar token
|
||||
token = request.headers.get('Authorization', '').replace('Bearer ', '')
|
||||
if token != SHUTDOWN_TOKEN:
|
||||
print(f"[ACCESO DENEGADO] Token incorrecto: {token[:10]}...")
|
||||
return jsonify({"error": "Unauthorized"}), 401
|
||||
|
||||
print("[SHUTDOWN] Apagando PC en 10 segundos...")
|
||||
|
||||
# Ejecutar shutdown
|
||||
os.system("shutdown /s /t 10")
|
||||
|
||||
return jsonify({"status": "ok", "message": "Shutdown iniciado (10s)"}), 200
|
||||
|
||||
@app.route('/health', methods=['GET'])
|
||||
def health():
|
||||
"""Health check"""
|
||||
return jsonify({"status": "ok", "service": "shutdown-listener"}), 200
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("=" * 60)
|
||||
print("Shutdown Listener - Esperando comandos en puerto 5555")
|
||||
print(f"Token configurado: {SHUTDOWN_TOKEN[:10]}..." if SHUTDOWN_TOKEN != "cambiar-este-token" else "Token: [NO CONFIGURADO]")
|
||||
print("Endpoint: POST http://192.168.1.239:5555/shutdown")
|
||||
print("=" * 60)
|
||||
|
||||
# Escuchar en todas las interfaces (0.0.0.0) para que Home Assistant pueda acceder
|
||||
app.run(host='0.0.0.0', port=5555, debug=False)
|
||||
0
scripts/telegram_bot_pc.log
Normal file
0
scripts/telegram_bot_pc.log
Normal file
@@ -30,12 +30,30 @@ HA_WEBHOOK_APAGAR = "http://185.187.169.109:8123/api/webhook/apagar-pc-juanjo"
|
||||
HA_WEBHOOK_ENCENDER = "http://185.187.169.109:8123/api/webhook/encender-pc-juanjo"
|
||||
PC_IP = "192.168.1.239" # IP del PC sobremesa
|
||||
|
||||
def user_autorizado(update: Update) -> bool:
|
||||
"""Verifica si el usuario está autorizado"""
|
||||
user_id = str(update.effective_user.id) if update.effective_user else None
|
||||
autorizado = user_id == TELEGRAM_USER_ID
|
||||
if not autorizado:
|
||||
print(f"[ACCESO DENEGADO] Usuario no autorizado: {user_id} (esperado: {TELEGRAM_USER_ID})")
|
||||
return autorizado
|
||||
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Comando /start"""
|
||||
if not user_autorizado(update):
|
||||
await update.message.reply_text("❌ Acceso denegado. Bot de uso personal.")
|
||||
return
|
||||
print(f"[START] Usuario {update.effective_user.id} autenticado correctamente")
|
||||
await menu(update, context)
|
||||
|
||||
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Muestra el menú principal"""
|
||||
if not user_autorizado(update):
|
||||
if update.callback_query:
|
||||
await update.callback_query.answer("❌ Acceso denegado")
|
||||
return
|
||||
|
||||
print(f"[MENU] Mostrando menú a usuario {update.effective_user.id}")
|
||||
keyboard = [
|
||||
[
|
||||
InlineKeyboardButton("🔴 Apagar PC", callback_data='apagar'),
|
||||
@@ -67,6 +85,10 @@ async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
|
||||
async def apagar_pc(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Apaga el PC con confirmación"""
|
||||
if not user_autorizado(update):
|
||||
return
|
||||
|
||||
print(f"[APAGAR] Solicitando confirmación")
|
||||
query = update.callback_query if update.callback_query else None
|
||||
|
||||
# CONFIRMAR antes de apagar
|
||||
@@ -155,6 +177,10 @@ async def apagar_pc_confirmar(update: Update, context: ContextTypes.DEFAULT_TYPE
|
||||
|
||||
async def encender_pc(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Enciende el PC y verifica que arrancó"""
|
||||
if not user_autorizado(update):
|
||||
return
|
||||
|
||||
print(f"[ENCENDER] Iniciando proceso de encendido")
|
||||
query = update.callback_query if update.callback_query else None
|
||||
|
||||
if query:
|
||||
@@ -228,6 +254,10 @@ async def encender_pc(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
|
||||
async def estado_pc(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Verifica si el PC está encendido"""
|
||||
if not user_autorizado(update):
|
||||
return
|
||||
|
||||
print(f"[ESTADO] Verificando estado del PC")
|
||||
query = update.callback_query if update.callback_query else None
|
||||
|
||||
if query:
|
||||
@@ -300,7 +330,15 @@ def main():
|
||||
print("ERROR: Falta TELEGRAM_BOT_PC_TOKEN en .env")
|
||||
return
|
||||
|
||||
print("Iniciando bot de Telegram para control de PC...")
|
||||
if not TELEGRAM_USER_ID:
|
||||
print("ERROR: Falta TELEGRAM_USER_ID en .env")
|
||||
return
|
||||
|
||||
print("=" * 50)
|
||||
print("Iniciando bot de Telegram para control de PC")
|
||||
print(f"Usuario autorizado: {TELEGRAM_USER_ID}")
|
||||
print(f"IP del PC: {PC_IP}")
|
||||
print("=" * 50)
|
||||
|
||||
app = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
|
||||
|
||||
|
||||
0
scripts/telegram_bot_pc_error.log
Normal file
0
scripts/telegram_bot_pc_error.log
Normal file
Reference in New Issue
Block a user