Madras1 commited on
Commit
151af0a
·
verified ·
1 Parent(s): 2f524a3

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +51 -17
main.py CHANGED
@@ -4,16 +4,28 @@ import asyncio
4
  from datetime import datetime
5
  from telegram import Update
6
  from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
 
7
 
8
- # Import Agent and ReminderManager
9
  try:
10
- from .core import TelegramJadeAgent
11
- from .tools import ReminderManager
12
  except ImportError:
 
 
 
 
 
 
 
 
 
 
 
13
  from core import TelegramJadeAgent
14
  from tools import ReminderManager
15
 
16
- # Logging
17
  logging.basicConfig(
18
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
19
  level=logging.INFO
@@ -21,18 +33,21 @@ logging.basicConfig(
21
  logger = logging.getLogger(__name__)
22
 
23
  # Global instances
 
24
  reminder_manager = ReminderManager()
25
  agent = TelegramJadeAgent(reminder_manager=reminder_manager)
26
 
27
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
28
- await context.bot.send_message(chat_id=update.effective_chat.id, text="Hi! I'm Jade, your 24h assistant. How can I help you?")
29
 
30
  async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
31
  chat_id = update.effective_chat.id
32
  user_text = update.message.text
33
 
34
- # 1. Get response from Agent
35
- # agent.chat is blocking (sync), so we wrap it.
 
 
36
  response = await asyncio.to_thread(agent.chat, chat_id, user_text)
37
 
38
  await context.bot.send_message(chat_id=chat_id, text=response)
@@ -46,7 +61,14 @@ async def send_reminder_job(context: ContextTypes.DEFAULT_TYPE):
46
 
47
  # Check if reminder is still valid (not deleted)
48
  current_reminders = reminder_manager.get_due_reminders()
49
- if not any(r["id"] == reminder_id for r in current_reminders):
 
 
 
 
 
 
 
50
  logger.info(f"Reminder {reminder_id} skipped (deleted or sent).")
51
  return
52
 
@@ -65,7 +87,10 @@ async def check_reminders_loop(context: ContextTypes.DEFAULT_TYPE):
65
  Background task running every X seconds to check for new reminders in DB
66
  and schedule them in the JobQueue.
67
  """
68
- pending = reminder_manager.get_due_reminders()
 
 
 
69
  job_queue = context.job_queue
70
 
71
  # Get current scheduled jobs by name
@@ -73,32 +98,39 @@ async def check_reminders_loop(context: ContextTypes.DEFAULT_TYPE):
73
 
74
  for r in pending:
75
  job_name = f"reminder_{r['id']}"
 
76
  if job_name not in current_jobs:
77
  try:
78
  run_date = datetime.strptime(r["time"], "%Y-%m-%d %H:%M:%S")
79
 
80
- # If time is in past, schedule for immediate execution
81
  if run_date < datetime.now():
82
  run_date = datetime.now()
83
-
84
- logger.info(f"Scheduling {job_name} for {run_date}")
85
-
86
  job_queue.run_once(
87
  send_reminder_job,
88
  when=run_date,
89
  data=r,
90
  name=job_name
91
  )
 
92
  except Exception as e:
93
  logger.error(f"Failed to schedule {job_name}: {e}")
94
 
95
  if __name__ == '__main__':
 
96
  token = os.getenv("TELEGRAM_BOT_TOKEN")
97
  if not token:
98
- print("Error: TELEGRAM_BOT_TOKEN not found.")
99
  exit(1)
100
 
101
- application = ApplicationBuilder().token(token).build()
 
 
 
 
102
 
103
  start_handler = CommandHandler('start', start)
104
  msg_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message)
@@ -106,9 +138,11 @@ if __name__ == '__main__':
106
  application.add_handler(start_handler)
107
  application.add_handler(msg_handler)
108
 
109
- # Add a repeating job to sync reminders (e.g. every 10 seconds)
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()
 
 
 
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 # Importante para consertar o erro de rede
8
 
9
+ # Tenta carregar variáveis locais (útil se você testar no PC)
10
  try:
11
+ from dotenv import load_dotenv
12
+ load_dotenv()
13
  except ImportError:
14
+ pass
15
+
16
+ # --- IMPORTS CORRIGIDOS (SEM PONTO) ---
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
26
  from tools import ReminderManager
27
 
28
+ # Logging setup
29
  logging.basicConfig(
30
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
31
  level=logging.INFO
 
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
 
40
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
41
+ await context.bot.send_message(chat_id=update.effective_chat.id, text="Oi! Eu sou a Jade. Como posso ajudar você hoje?")
42
 
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)
 
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: # Recarrega para ter certeza
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
 
 
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
 
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
+ # 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 in environment variables.")
127
  exit(1)
128
 
129
+ # --- CONFIGURAÇÃO DE REDE BLINDADA PARA HUGGING FACE ---
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
  start_handler = CommandHandler('start', start)
136
  msg_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message)
 
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)