Files
BotVPS/bridge_telegram.py

189 lines
7.9 KiB
Python

import os
import logging
import httpx
import asyncio
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, CommandHandler, filters
from dotenv import load_dotenv
# Carrega as variáveis do arquivo .env
load_dotenv()
# Configurações obtidas do .env
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ALLOWED_USER_ID = os.getenv("TELEGRAM_CHAT_ID")
# Sincroniza com a PORTA definida no .env (Dica: .env diz 8000)
API_PORT = os.getenv("PORT", "8001")
API_BASE_URL = f"http://localhost:{API_PORT}"
# Timeout aumentado para 300s para permitir que o Agente execute múltiplas ferramentas
GLOBAL_TIMEOUT = 300.0
# O ID permitido deve ser comparado como string ou int, padronizando aqui
if ALLOWED_USER_ID:
ALLOWED_USER_ID = int(ALLOWED_USER_ID)
# Configuração de Logs
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
import uuid
# Dicionário global para manter o histórico (Em um sistema de produção, usar Redis ou DB)
chat_histories = {}
async def clear_history(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Limpa o histórico do usuário."""
chat_id = update.effective_chat.id
if chat_id in chat_histories:
chat_histories[chat_id] = []
await update.message.reply_text("🧹 Histórico de conversa limpo! Como posso ajudar agora?")
async def call_antigravity_api(endpoint: str, payload: dict) -> str:
"""Faz a chamada para a API interna do BotVPS com retry automático."""
max_retries = 3
for attempt in range(max_retries):
try:
async with httpx.AsyncClient(timeout=GLOBAL_TIMEOUT) as client:
logger.info(f"Enviando payload para {endpoint} (Tentativa {attempt+1})")
response = await client.post(f"{API_BASE_URL}{endpoint}", json=payload)
response.raise_for_status()
data = response.json()
return data.get("reply") or data.get("message") or str(data)
except (httpx.ConnectError, httpx.HTTPStatusError) as e:
logger.error(f"Erro de conexão na API (Tentativa {attempt+1}): {e}")
if attempt < max_retries - 1:
await asyncio.sleep(2) # Espera 2s antes de tentar novamente
else:
return "❌ *Erro de Conexão:* A API do BotVPS parece estar offline ou reiniciando. Tente novamente em instantes."
except Exception as e:
logger.error(f"Erro inesperado na chamada API: {str(e)}")
return f"❌ *Erro Interno:* {str(e)}"
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Manipulador central de mensagens com blindagem contra crashes."""
try:
if not update.message or not update.message.text:
return
chat_id = update.effective_chat.id
user_id = update.effective_user.id
# Filtro de Segurança
if ALLOWED_USER_ID and user_id != ALLOWED_USER_ID:
logger.warning(f"Acesso negado para o ID: {user_id}")
return
text = update.message.text
logger.info(f"Mensagem recebida: {text[:50]}...")
# Lógica de reset por texto
cmd_limpar = text.lower().strip()
if cmd_limpar in ["reset", "limpar histórico", "limpar"]:
chat_histories[chat_id] = []
await update.message.reply_text("🧹 Memória limpa. O que deseja fazer?")
return
# Inicializa histórico
if chat_id not in chat_histories:
chat_histories[chat_id] = []
# Processamento
if text.startswith(('/bash', '/vps', '/cmd')):
task = text.replace('/bash', '').replace('/vps', '').replace('/cmd', '').strip()
if not task:
await update.message.reply_text("❓ Envie o comando após o prefixo.")
return
await update.message.reply_text("⚙️ *Processando tarefa...*", parse_mode='Markdown')
reply = await call_antigravity_api("/api/orchestrate", {"task": task})
else:
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
payload = {"text": text, "history": chat_histories[chat_id][-10:]}
reply = await call_antigravity_api("/api/chat", payload)
# Atualiza histórico se for chat natural
chat_histories[chat_id].append({"user": text, "bot": reply})
if len(chat_histories[chat_id]) > 15: chat_histories[chat_id].pop(0)
# Envia resposta
if len(reply) > 4000: reply = reply[:3900] + "... [Truncado]"
try:
await update.message.reply_text(reply, parse_mode='Markdown')
except Exception:
await update.message.reply_text(reply)
except Exception as e:
logger.error(f"FALHA NO HANDLE_MESSAGE: {e}")
try:
await update.message.reply_text("⚠️ Ocorreu um erro ao processar sua mensagem. O sistema foi notificado.")
except: pass
async def handle_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Manipula mensagens de voz com blindagem contra crashes."""
try:
if not update.message or not update.message.voice:
return
chat_id = update.effective_chat.id
user_id = update.effective_user.id
if ALLOWED_USER_ID and user_id != ALLOWED_USER_ID: return
await context.bot.send_chat_action(chat_id=chat_id, action="record_voice")
voice_file = await update.message.voice.get_file()
temp_path = f"/tmp/tg_voice_{uuid.uuid4().hex}.ogg"
await voice_file.download_to_drive(temp_path)
async with httpx.AsyncClient(timeout=GLOBAL_TIMEOUT) as client:
with open(temp_path, "rb") as f:
files = {"audio": (os.path.basename(temp_path), f, "audio/ogg")}
response = await client.post(f"{API_BASE_URL}/api/chat-audio", files=files)
response.raise_for_status()
data = response.json()
user_text = data.get("text", "[Voz não transcrita]")
bot_reply = data.get("reply", "Erro no processamento.")
audio_url = data.get("audio_url")
await update.message.reply_text(f"🎤 *Sua mensagem:* {user_text}")
try:
await update.message.reply_text(bot_reply, parse_mode='Markdown')
except:
await update.message.reply_text(bot_reply)
if audio_url:
filename = audio_url.split("/")[-1]
audio_path = os.path.join("/tmp", filename)
if os.path.exists(audio_path):
with open(audio_path, "rb") as audio_file:
await context.bot.send_voice(chat_id=chat_id, voice=audio_file)
if chat_id not in chat_histories: chat_histories[chat_id] = []
chat_histories[chat_id].append({"user": user_text, "bot": bot_reply})
except Exception as e:
logger.error(f"FALHA NO HANDLE_VOICE: {e}")
await update.message.reply_text("⚠️ Erro ao processar áudio.")
finally:
if 'temp_path' in locals() and os.path.exists(temp_path): os.remove(temp_path)
if __name__ == '__main__':
if not TOKEN:
logger.error("ERRO: TOKEN ausente!")
exit(1)
# Inicializa o Bot (python-telegram-bot v20+)
application = ApplicationBuilder().token(TOKEN).build()
# Adiciona handlers
application.add_handler(CommandHandler("limpar", clear_history))
application.add_handler(CommandHandler("clear", clear_history))
application.add_handler(MessageHandler(filters.TEXT | filters.COMMAND, handle_message))
application.add_handler(MessageHandler(filters.VOICE, handle_voice))
logger.info("Ponte Iniciada. Modo: Resiliente.")
application.run_polling(drop_pending_updates=True)