Madras1 commited on
Commit
0ebf510
·
verified ·
1 Parent(s): 9d6ceb7

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +31 -26
main.py CHANGED
@@ -1,32 +1,40 @@
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
@@ -47,14 +55,19 @@ reminder_manager = ReminderManager()
47
  agent = TelegramJadeAgent(reminder_manager=reminder_manager)
48
 
49
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
50
- await context.bot.send_message(chat_id=update.effective_chat.id, text="Oi! Eu sou a Jade. Como posso ajudar você hoje?")
51
 
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
@@ -63,13 +76,7 @@ async def send_reminder_job(context: ContextTypes.DEFAULT_TYPE):
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)
@@ -99,10 +106,8 @@ if __name__ == '__main__':
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))
 
1
  import os
2
  import logging
3
  import asyncio
4
+ import socket
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
+ # --- A GAMBIARRA SUPREMA DA BERTA (HARDCODED DNS) ---
11
+ # Se o DNS do Hugging Face não funciona, nós somos o DNS.
12
+ # Este é o IP oficial da API do Telegram.
13
  original_getaddrinfo = socket.getaddrinfo
14
 
15
+ def fixed_ip_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
16
+ # Se for o Telegram, retornamos o IP direto (149.154.167.220)
17
+ if host == 'api.telegram.org':
18
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('149.154.167.220', port))]
19
+
20
+ # Para todo o resto (Google, DuckDuckGo), tentamos usar o sistema normal
21
+ try:
22
+ return original_getaddrinfo(host, port, family, type, proto, flags)
23
+ except socket.gaierror:
24
+ # Se falhar no DuckDuckGo, paciência, mas o bot liga.
25
+ return original_getaddrinfo(host, port, family, type, proto, flags)
26
 
27
+ socket.getaddrinfo = fixed_ip_getaddrinfo
28
+ # ----------------------------------------------------
29
 
30
+ # Carrega variáveis
31
  try:
32
  from dotenv import load_dotenv
33
  load_dotenv()
34
  except ImportError:
35
  pass
36
 
37
+ # Imports seguros
38
  try:
39
  from core import TelegramJadeAgent
40
  from tools import ReminderManager
 
55
  agent = TelegramJadeAgent(reminder_manager=reminder_manager)
56
 
57
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
58
+ await context.bot.send_message(chat_id=update.effective_chat.id, text="Oi! Eu sou a Jade. Estou viva graças à Berta!")
59
 
60
  async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
61
  chat_id = update.effective_chat.id
62
  user_text = update.message.text
63
+
64
+ try:
65
+ await context.bot.send_chat_action(chat_id=chat_id, action="typing")
66
+ response = await asyncio.to_thread(agent.chat, chat_id, user_text)
67
+ await context.bot.send_message(chat_id=chat_id, text=response)
68
+ except Exception as e:
69
+ logger.error(f"Erro ao processar mensagem: {e}")
70
+ await context.bot.send_message(chat_id=chat_id, text="Tive um erro interno, desculpe.")
71
 
72
  async def send_reminder_job(context: ContextTypes.DEFAULT_TYPE):
73
  job_data = context.job.data
 
76
  reminder_id = job_data["id"]
77
 
78
  current_reminders = reminder_manager.get_due_reminders()
79
+ if not any(r["id"] == reminder_id for r in current_reminders):
 
 
 
 
 
 
80
  return
81
 
82
  text = await asyncio.to_thread(agent.generate_reminder_message, chat_id, reminder_message)
 
106
  logger.error("Error: TELEGRAM_BOT_TOKEN not found.")
107
  exit(1)
108
 
109
+ # Removemos configurações complexas de HTTPXRequest para usar o padrão (que agora usa nosso IP fixo)
110
+ application = ApplicationBuilder().token(token).build()
 
 
111
 
112
  application.add_handler(CommandHandler('start', start))
113
  application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))