20-sep: [fix] Bot Telegram control PC - confirmacion + watchdog apagado/encendido + doc autologon

This commit is contained in:
juanminsanz
2026-09-20 22:19:20 +02:00
parent 8412d3f657
commit ac876f59c6
5 changed files with 383 additions and 17 deletions

View File

@@ -0,0 +1,130 @@
# Correcciones Bot Telegram Control PC (20-sep-2026)
## Problemas reportados por el usuario
1. ✅ **Apagado forzoso sin confirmación** → El bot apagaba directamente sin esperar confirmación del asistente
2. ✅ **No comprobaba estado tras apagar** → No verificaba automáticamente si el PC se apagó correctamente
3. ✅ **Encendido no respondía** → Enviaba WoL pero no verificaba si el PC arrancó
4. ✅ **Login crea usuario nuevo** → Problema de configuración de autologon (documentado en `FIX_PROBLEMA_AUTOLOGON_USUARIO_NUEVO.md`)
## Cambios implementados
### 1. Apagado con confirmación obligatoria
**ANTES:**
```python
# Apagaba directamente al pulsar el botón
await apagar_pc() → requests.post(HA_WEBHOOK_APAGAR)
```
**AHORA:**
```python
# Pide confirmación con botones SÍ/NO
await apagar_pc() → muestra mensaje de confirmación
await apagar_pc_confirmar() → ejecuta apagado SOLO tras confirmar
```
**Flujo:**
1. Usuario pulsa "🔴 Apagar PC"
2. Bot muestra mensaje: "⚠️ ¿Seguro que quieres apagar?"
3. Botones: "✅ SÍ, apagar" | "❌ Cancelar"
4. Solo si confirma → ejecuta webhook
### 2. Watchdog de estado tras apagar
**ANTES:**
```python
# Enviaba comando y mostraba mensaje genérico
response = requests.post(HA_WEBHOOK_APAGAR)
await msg.edit_text("✅ PC apagado correctamente") # ASUME que funcionó
```
**AHORA:**
```python
# Espera 30s y VERIFICA con ping
response = requests.post(HA_WEBHOOK_APAGAR)
await asyncio.sleep(30) # Espera a que se apague
# Ping de verificación
result = subprocess.run(["powershell", "-Command", f"Test-Connection -ComputerName {PC_IP} -Count 1 -Quiet"])
online = "True" in result.stdout
if online:
await msg.edit_text("⚠️ APAGADO FALLIDO - PC sigue online")
else:
await msg.edit_text("✅ PC APAGADO CONFIRMADO - IP sin respuesta")
```
### 3. Watchdog de encendido con reintentos
**ANTES:**
```python
# Enviaba WoL y mostraba mensaje genérico
response = requests.post(HA_WEBHOOK_ENCENDER)
await msg.edit_text("✅ Proceso iniciado. Usa /estado para verificar.") # Usuario tenía que comprobar manualmente
```
**AHORA:**
```python
# Espera 90s y verifica con 3 reintentos
response = requests.post(HA_WEBHOOK_ENCENDER)
await asyncio.sleep(90) # Espera inicial
# 3 intentos de ping con 15s entre cada uno
intentos = 0
max_intentos = 3
online = False
while intentos < max_intentos and not online:
result = subprocess.run([...ping...])
online = "True" in result.stdout
if not online:
intentos += 1
await asyncio.sleep(15)
if online:
await msg.edit_text("✅ PC ENCENDIDO CORRECTAMENTE - Responde en {tiempo}s")
else:
await msg.edit_text("❌ ENCENDIDO FALLIDO - Verifica regleta/WoL/BIOS")
```
### 4. Botón de cancelar
Añadido callback `cancelar` que vuelve al menú principal si el usuario cancela el apagado.
## Tiempos de espera
| Operación | Tiempo espera | Verificaciones |
|-----------|---------------|----------------|
| **Apagado** | 30 segundos | 1 ping |
| **Encendido** | 90 + (hasta 45s) | 3 intentos de ping con 15s entre cada uno |
## Archivos modificados
- `INFRAESTRUCTURA/scripts/telegram_bot_pc.py` — Bot corregido
- `INFRAESTRUCTURA/docs/FIX_PROBLEMA_AUTOLOGON_USUARIO_NUEVO.md` — Solución al problema de usuario nuevo
- `INFRAESTRUCTURA/docs/TELEGRAM_BOT_PC_FIXES.md` — Este documento
## Cómo usar el bot corregido
```powershell
# Detener el bot anterior si está corriendo
Get-Process python | Where-Object { $_.CommandLine -match "telegram_bot_pc" } | Stop-Process
# Arrancar bot corregido
python C:\Users\juanm\Documents\Github\INFRAESTRUCTURA\scripts\telegram_bot_pc.py
```
En Telegram:
1. `/start` o `/menu` → Menú principal
2. "🔴 Apagar PC" → **AHORA pide confirmación**
3. "✅ SÍ, apagar" → Ejecuta y **verifica automáticamente en 30s**
4. "🟢 Encender PC" → Ejecuta y **verifica automáticamente en ~90-135s**
5. "📊 Estado PC" → Ping manual (sin cambios)
## Pendientes
- [ ] Crear tarea programada para arrancar el bot al iniciar Windows
- [ ] Añadir logging a archivo (`telegram_bot_pc.log`)
- [ ] Decidir sobre autologon (ver `FIX_PROBLEMA_AUTOLOGON_USUARIO_NUEVO.md`)
- [ ] Script de verificación de configuración: `check_autologon_status.ps1`