Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,25 +1,36 @@
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
import asyncio
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
from telegram import Update
|
| 6 |
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
|
| 7 |
-
from telegram.request import HTTPXRequest
|
| 8 |
|
| 9 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
try:
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
load_dotenv()
|
| 13 |
except ImportError:
|
| 14 |
pass
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
# Se ainda der erro no core.py, lembre de remover o ponto lá também!
|
| 18 |
try:
|
| 19 |
from core import TelegramJadeAgent
|
| 20 |
from tools import ReminderManager
|
| 21 |
except ImportError:
|
| 22 |
-
# Fallback caso a estrutura de pastas mude
|
| 23 |
import sys
|
| 24 |
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 25 |
from core import TelegramJadeAgent
|
|
@@ -32,8 +43,6 @@ logging.basicConfig(
|
|
| 32 |
)
|
| 33 |
logger = logging.getLogger(__name__)
|
| 34 |
|
| 35 |
-
# Global instances
|
| 36 |
-
# Inicializa o gerenciador de lembretes e o agente
|
| 37 |
reminder_manager = ReminderManager()
|
| 38 |
agent = TelegramJadeAgent(reminder_manager=reminder_manager)
|
| 39 |
|
|
@@ -43,106 +52,63 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 43 |
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 44 |
chat_id = update.effective_chat.id
|
| 45 |
user_text = update.message.text
|
| 46 |
-
|
| 47 |
-
# Envia "Digitando..." para o usuário saber que estamos processando
|
| 48 |
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
| 49 |
-
|
| 50 |
-
# Chama o agente em uma thread separada para não travar o bot
|
| 51 |
response = await asyncio.to_thread(agent.chat, chat_id, user_text)
|
| 52 |
-
|
| 53 |
await context.bot.send_message(chat_id=chat_id, text=response)
|
| 54 |
|
| 55 |
async def send_reminder_job(context: ContextTypes.DEFAULT_TYPE):
|
| 56 |
-
"""Callback function for the scheduled job."""
|
| 57 |
job_data = context.job.data
|
| 58 |
chat_id = job_data["chat_id"]
|
| 59 |
reminder_message = job_data["message"]
|
| 60 |
reminder_id = job_data["id"]
|
| 61 |
|
| 62 |
-
# Check if reminder is still valid (not deleted)
|
| 63 |
current_reminders = reminder_manager.get_due_reminders()
|
| 64 |
-
# Verifica se o ID ainda existe na lista de pendentes
|
| 65 |
exists = False
|
| 66 |
-
for r in current_reminders:
|
| 67 |
if r["id"] == reminder_id:
|
| 68 |
exists = True
|
| 69 |
break
|
| 70 |
|
| 71 |
if not exists:
|
| 72 |
-
logger.info(f"Reminder {reminder_id} skipped (deleted or sent).")
|
| 73 |
return
|
| 74 |
|
| 75 |
-
logger.info(f"Triggering reminder {reminder_id} for chat {chat_id}")
|
| 76 |
-
|
| 77 |
-
# Generate message via Agent
|
| 78 |
text = await asyncio.to_thread(agent.generate_reminder_message, chat_id, reminder_message)
|
| 79 |
-
|
| 80 |
await context.bot.send_message(chat_id=chat_id, text=text)
|
| 81 |
-
|
| 82 |
-
# Mark as sent
|
| 83 |
reminder_manager.mark_as_sent(reminder_id)
|
| 84 |
|
| 85 |
async def check_reminders_loop(context: ContextTypes.DEFAULT_TYPE):
|
| 86 |
-
"""
|
| 87 |
-
Background task running every X seconds to check for new reminders in DB
|
| 88 |
-
and schedule them in the JobQueue.
|
| 89 |
-
"""
|
| 90 |
-
# Recarrega lembretes do arquivo
|
| 91 |
reminder_manager._load_reminders()
|
| 92 |
pending = [r for r in reminder_manager.reminders if r["status"] == "pending"]
|
| 93 |
-
|
| 94 |
job_queue = context.job_queue
|
| 95 |
-
|
| 96 |
-
# Get current scheduled jobs by name
|
| 97 |
current_jobs = [j.name for j in job_queue.jobs()]
|
| 98 |
|
| 99 |
for r in pending:
|
| 100 |
job_name = f"reminder_{r['id']}"
|
| 101 |
-
# Se o job ainda não está na fila, agende
|
| 102 |
if job_name not in current_jobs:
|
| 103 |
try:
|
| 104 |
run_date = datetime.strptime(r["time"], "%Y-%m-%d %H:%M:%S")
|
| 105 |
-
|
| 106 |
-
# Se for passado, agenda para agora
|
| 107 |
if run_date < datetime.now():
|
| 108 |
run_date = datetime.now()
|
| 109 |
-
|
| 110 |
-
# Só agenda se não for muito no passado (opcional, mas evita spam de velhos)
|
| 111 |
-
# Aqui agendamos apenas uma vez
|
| 112 |
-
job_queue.run_once(
|
| 113 |
-
send_reminder_job,
|
| 114 |
-
when=run_date,
|
| 115 |
-
data=r,
|
| 116 |
-
name=job_name
|
| 117 |
-
)
|
| 118 |
-
logger.info(f"Scheduled {job_name} for {run_date}")
|
| 119 |
except Exception as e:
|
| 120 |
logger.error(f"Failed to schedule {job_name}: {e}")
|
| 121 |
|
| 122 |
if __name__ == '__main__':
|
| 123 |
-
# Verifica o Token
|
| 124 |
token = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 125 |
if not token:
|
| 126 |
-
logger.error("Error: TELEGRAM_BOT_TOKEN not found
|
| 127 |
exit(1)
|
| 128 |
|
| 129 |
-
#
|
| 130 |
-
# Força HTTP/1.1 e aumenta timeouts para evitar desconexões
|
| 131 |
req = HTTPXRequest(connection_pool_size=8, http_version="1.1", read_timeout=20, write_timeout=20)
|
| 132 |
|
| 133 |
application = ApplicationBuilder().token(token).request(req).build()
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
application.add_handler(start_handler)
|
| 139 |
-
application.add_handler(msg_handler)
|
| 140 |
|
| 141 |
-
# Verifica lembretes a cada 10 segundos
|
| 142 |
if application.job_queue:
|
| 143 |
application.job_queue.run_repeating(check_reminders_loop, interval=10, first=1)
|
| 144 |
|
| 145 |
print("Jade Telegram Bot is running...")
|
| 146 |
-
|
| 147 |
-
# drop_pending_updates=True limpa mensagens velhas ao reiniciar para não travar
|
| 148 |
application.run_polling(drop_pending_updates=True)
|
|
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
import asyncio
|
| 4 |
+
import socket # <--- Importante para a correção
|
| 5 |
from datetime import datetime
|
| 6 |
from telegram import Update
|
| 7 |
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
|
| 8 |
+
from telegram.request import HTTPXRequest
|
| 9 |
|
| 10 |
+
# --- CORREÇÃO DE REDE DA BERTA (MONKEY PATCH) ---
|
| 11 |
+
# Isso obriga o Python a usar apenas IPv4 (o endereço antigo da internet).
|
| 12 |
+
# Resolve o erro [Errno -5] no Hugging Face.
|
| 13 |
+
original_getaddrinfo = socket.getaddrinfo
|
| 14 |
+
|
| 15 |
+
def ipv4_only_getaddrinfo(*args, **kwargs):
|
| 16 |
+
responses = original_getaddrinfo(*args, **kwargs)
|
| 17 |
+
return [res for res in responses if res[0] == socket.AF_INET]
|
| 18 |
+
|
| 19 |
+
socket.getaddrinfo = ipv4_only_getaddrinfo
|
| 20 |
+
# ------------------------------------------------
|
| 21 |
+
|
| 22 |
+
# Tenta carregar variáveis locais
|
| 23 |
try:
|
| 24 |
from dotenv import load_dotenv
|
| 25 |
load_dotenv()
|
| 26 |
except ImportError:
|
| 27 |
pass
|
| 28 |
|
| 29 |
+
# Imports com fallback
|
|
|
|
| 30 |
try:
|
| 31 |
from core import TelegramJadeAgent
|
| 32 |
from tools import ReminderManager
|
| 33 |
except ImportError:
|
|
|
|
| 34 |
import sys
|
| 35 |
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 36 |
from core import TelegramJadeAgent
|
|
|
|
| 43 |
)
|
| 44 |
logger = logging.getLogger(__name__)
|
| 45 |
|
|
|
|
|
|
|
| 46 |
reminder_manager = ReminderManager()
|
| 47 |
agent = TelegramJadeAgent(reminder_manager=reminder_manager)
|
| 48 |
|
|
|
|
| 52 |
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 53 |
chat_id = update.effective_chat.id
|
| 54 |
user_text = update.message.text
|
|
|
|
|
|
|
| 55 |
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
|
|
|
|
|
|
|
| 56 |
response = await asyncio.to_thread(agent.chat, chat_id, user_text)
|
|
|
|
| 57 |
await context.bot.send_message(chat_id=chat_id, text=response)
|
| 58 |
|
| 59 |
async def send_reminder_job(context: ContextTypes.DEFAULT_TYPE):
|
|
|
|
| 60 |
job_data = context.job.data
|
| 61 |
chat_id = job_data["chat_id"]
|
| 62 |
reminder_message = job_data["message"]
|
| 63 |
reminder_id = job_data["id"]
|
| 64 |
|
|
|
|
| 65 |
current_reminders = reminder_manager.get_due_reminders()
|
|
|
|
| 66 |
exists = False
|
| 67 |
+
for r in current_reminders:
|
| 68 |
if r["id"] == reminder_id:
|
| 69 |
exists = True
|
| 70 |
break
|
| 71 |
|
| 72 |
if not exists:
|
|
|
|
| 73 |
return
|
| 74 |
|
|
|
|
|
|
|
|
|
|
| 75 |
text = await asyncio.to_thread(agent.generate_reminder_message, chat_id, reminder_message)
|
|
|
|
| 76 |
await context.bot.send_message(chat_id=chat_id, text=text)
|
|
|
|
|
|
|
| 77 |
reminder_manager.mark_as_sent(reminder_id)
|
| 78 |
|
| 79 |
async def check_reminders_loop(context: ContextTypes.DEFAULT_TYPE):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
reminder_manager._load_reminders()
|
| 81 |
pending = [r for r in reminder_manager.reminders if r["status"] == "pending"]
|
|
|
|
| 82 |
job_queue = context.job_queue
|
|
|
|
|
|
|
| 83 |
current_jobs = [j.name for j in job_queue.jobs()]
|
| 84 |
|
| 85 |
for r in pending:
|
| 86 |
job_name = f"reminder_{r['id']}"
|
|
|
|
| 87 |
if job_name not in current_jobs:
|
| 88 |
try:
|
| 89 |
run_date = datetime.strptime(r["time"], "%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
|
| 90 |
if run_date < datetime.now():
|
| 91 |
run_date = datetime.now()
|
| 92 |
+
job_queue.run_once(send_reminder_job, when=run_date, data=r, name=job_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
logger.error(f"Failed to schedule {job_name}: {e}")
|
| 95 |
|
| 96 |
if __name__ == '__main__':
|
|
|
|
| 97 |
token = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 98 |
if not token:
|
| 99 |
+
logger.error("Error: TELEGRAM_BOT_TOKEN not found.")
|
| 100 |
exit(1)
|
| 101 |
|
| 102 |
+
# Mantemos a requisição robusta HTTP/1.1 junto com o patch IPv4
|
|
|
|
| 103 |
req = HTTPXRequest(connection_pool_size=8, http_version="1.1", read_timeout=20, write_timeout=20)
|
| 104 |
|
| 105 |
application = ApplicationBuilder().token(token).request(req).build()
|
| 106 |
|
| 107 |
+
application.add_handler(CommandHandler('start', start))
|
| 108 |
+
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))
|
|
|
|
|
|
|
|
|
|
| 109 |
|
|
|
|
| 110 |
if application.job_queue:
|
| 111 |
application.job_queue.run_repeating(check_reminders_loop, interval=10, first=1)
|
| 112 |
|
| 113 |
print("Jade Telegram Bot is running...")
|
|
|
|
|
|
|
| 114 |
application.run_polling(drop_pending_updates=True)
|