Edoruin commited on
Commit
d8abcf2
·
1 Parent(s): b80e277

antigravity global bot changes

Browse files
Files changed (1) hide show
  1. app/main.py +97 -89
app/main.py CHANGED
@@ -48,38 +48,95 @@ class LoanManager:
48
 
49
  loan_mgr = LoanManager()
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def main(page: ft.Page):
52
  page.title = "MAKERSPACE DATABASE"
53
  page.theme_mode = ft.ThemeMode.DARK
54
  page.padding = 10
55
-
56
- # --- CONFIGURACIÓN DE VARIABLES ---
57
- TG_TOKEN = os.getenv("TELEGRAM_TOKEN")
58
- TG_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
59
- GOOGLE_PROXY_URL = "https://script.google.com/macros/s/AKfycbz7z1Jb0vsur42GmmqrL3PVXeRkN2WxSojFDIleEDoLOg6MnrmJjb_uuPcQ15CTwyzD/exec"
60
- GITLAB_URL = "https://gitlab.com"
61
- GIT_TOKEN = os.getenv("GITLAB_TOKEN")
62
- GIT_GROUP = os.getenv("GITLAB_GROUP_ID")
63
-
64
- # --- CONFIGURACIÓN DE PROXY PARA TODO EL BOT ---
65
- if TG_TOKEN and GOOGLE_PROXY_URL:
66
- # Asegurarnos de que el formato sea correcto
67
- base_url = GOOGLE_PROXY_URL.split('?')[0] # Limpiar parámetros previos
68
- telebot.apihelper.API_URL = base_url + "?path={1}&token={0}"
69
- # Google es lento; subimos el timeout del socket interno
70
- telebot.apihelper.CONNECT_TIMEOUT = 60
71
- telebot.apihelper.READ_TIMEOUT = 60
72
-
73
- # Inicializar bot
74
- bot = telebot.TeleBot(TG_TOKEN) if TG_TOKEN else None
75
-
76
- # --- AYUDANTE PARA ESCAPAR MARKDOWN (V1) ---
77
- def escape_md(text):
78
- if not text: return ""
79
- # En Markdown V1 solo necesitamos escapar estos caracteres si no son formato
80
- for char in ['_', '*', '[', '`']:
81
- text = text.replace(char, f"\\{char}")
82
- return text
83
 
84
  def mostrar_notificacion(texto, color="blue"):
85
  snack = ft.SnackBar(ft.Text(texto), bgcolor=color)
@@ -108,67 +165,18 @@ def main(page: ft.Page):
108
  return f"ERR_DNS: {error_msg[:40]}"
109
  return f"ERR_CONN: {error_msg[:100]}"
110
 
111
- # --- BOT CALLBACK HANDLER ---
112
- if bot:
113
- @bot.callback_query_handler(func=lambda call: True)
114
- def handle_query(call):
115
- try:
116
- if call.data.startswith("accept_"):
117
- loan_id = call.data.replace("accept_", "")
118
- if loan_mgr.update_status(loan_id, "ACCEPTED"):
119
- bot.answer_callback_query(call.id, "Préstamo Aceptado")
120
- # Escapar el texto anterior para evitar que caracteres especiales rompan el nuevo mensaje
121
- nuevo_texto = f"✅ *ACEPTADO*\n{escape_md(call.message.text)}"
122
- bot.edit_message_text(nuevo_texto, TG_CHAT_ID, call.message.message_id, parse_mode="Markdown")
123
- mostrar_notificacion(f"Préstamo {loan_id[:8]} ACEPTADO", ft.Colors.GREEN)
124
- elif call.data.startswith("decline_"):
125
- loan_id = call.data.replace("decline_", "")
126
- if loan_mgr.update_status(loan_id, "DECLINED"):
127
- bot.answer_callback_query(call.id, "Préstamo Declinado")
128
- nuevo_texto = f"❌ *DECLINADO*\n{escape_md(call.message.text)}"
129
- bot.edit_message_text(nuevo_texto, TG_CHAT_ID, call.message.message_id, parse_mode="Markdown")
130
- mostrar_notificacion(f"Préstamo {loan_id[:8]} DECLINADO", ft.Colors.RED)
131
- page.update()
132
- except Exception as e:
133
- print(f"Callback Error: {e}")
134
-
135
- # --- BOT COMMAND HANDLER ---
136
- @bot.message_handler(commands=['aceptar', 'declinar', 'status'])
137
- def handle_text_commands(message):
138
- try:
139
- text = message.text.split()
140
- if len(text) < 2:
141
- bot.reply_to(message, "Uso: /aceptar <id> o /declinar <id>")
142
- return
143
-
144
- cmd = text[0][1:]
145
- loan_id = text[1]
146
-
147
- status = "ACCEPTED" if cmd == "aceptar" else "DECLINED"
148
- if loan_mgr.update_status(loan_id, status):
149
- emoji = "✅" if status == "ACCEPTED" else "❌"
150
- bot.reply_to(message, f"{emoji} Préstamo {loan_id} actualizado a {status}")
151
- mostrar_notificacion(f"Préstamo {loan_id[:8]} {status}", ft.Colors.GREEN if status == "ACCEPTED" else ft.Colors.RED)
152
- else:
153
- bot.reply_to(message, "ID de préstamo no encontrado.")
154
- page.update()
155
- except Exception as e:
156
- print(f"Command Error: {e}")
157
-
158
- def start_bot():
159
- if bot:
160
- while True:
161
- try:
162
- # Bajamos el timeout del 'getUpdates' para que Google no corte la conexión
163
- # pero mantenemos el 'interval' para darle respiro
164
- bot.infinity_polling(timeout=20, long_polling_timeout=10)
165
- except Exception as e:
166
- print(f"Error de red en el bot (DNS/Bloqueo?): {e}. Reintentando en 60s...")
167
- time.sleep(60)
168
-
169
- # Iniciar polling en hilo separado
170
- if bot:
171
- threading.Thread(target=start_bot, daemon=True).start()
172
 
173
  def mostrar_factura(i):
174
  status_color = {
 
48
 
49
  loan_mgr = LoanManager()
50
 
51
+ # --- CONFIGURACIÓN DE VARIABLES GLOBALES ---
52
+ TG_TOKEN = os.getenv("TELEGRAM_TOKEN")
53
+ TG_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
54
+ GOOGLE_PROXY_URL = "https://script.google.com/macros/s/AKfycbz7z1Jb0vsur42GmmqrL3PVXeRkN2WxSojFDIleEDoLOg6MnrmJjb_uuPcQ15CTwyzD/exec"
55
+
56
+ # --- CONFIGURACIÓN DE PROXY PARA TODO EL BOT ---
57
+ if TG_TOKEN and GOOGLE_PROXY_URL:
58
+ base_url = GOOGLE_PROXY_URL.split('?')[0]
59
+ telebot.apihelper.API_URL = base_url + "?path={1}&token={0}"
60
+ telebot.apihelper.CONNECT_TIMEOUT = 60
61
+ telebot.apihelper.READ_TIMEOUT = 60
62
+
63
+ # Inicializar bot (GLOBAL)
64
+ bot = telebot.TeleBot(TG_TOKEN) if TG_TOKEN else None
65
+
66
+ # --- AYUDANTE PARA ESCAPAR MARKDOWN (GLOBAL) ---
67
+ def escape_md(text):
68
+ if not text: return ""
69
+ for char in ['_', '*', '[', '`']:
70
+ text = text.replace(char, f"\\{char}")
71
+ return text
72
+
73
+ # --- BOT HANDLERS (GLOBALS) ---
74
+ if bot:
75
+ @bot.callback_query_handler(func=lambda call: True)
76
+ def handle_query(call):
77
+ try:
78
+ if call.data.startswith("accept_"):
79
+ loan_id = call.data.replace("accept_", "")
80
+ if loan_mgr.update_status(loan_id, "ACCEPTED"):
81
+ bot.answer_callback_query(call.id, "Préstamo Aceptado")
82
+ nuevo_texto = f"✅ *ACEPTADO*\n{escape_md(call.message.text)}"
83
+ bot.edit_message_text(nuevo_texto, TG_CHAT_ID, call.message.message_id, parse_mode="Markdown")
84
+ # Notificar a todas las sesiones activas vía PubSub
85
+ bot_broadcast({"text": f"Préstamo {loan_id[:8]} ACEPTADO", "color": ft.Colors.GREEN})
86
+ elif call.data.startswith("decline_"):
87
+ loan_id = call.data.replace("decline_", "")
88
+ if loan_mgr.update_status(loan_id, "DECLINED"):
89
+ bot.answer_callback_query(call.id, "Préstamo Declinado")
90
+ nuevo_texto = f"❌ *DECLINADO*\n{escape_md(call.message.text)}"
91
+ bot.edit_message_text(nuevo_texto, TG_CHAT_ID, call.message.message_id, parse_mode="Markdown")
92
+ bot_broadcast({"text": f"Préstamo {loan_id[:8]} DECLINADO", "color": "red"})
93
+ except Exception as e:
94
+ print(f"Callback Error: {e}")
95
+
96
+ @bot.message_handler(commands=['aceptar', 'declinar', 'status'])
97
+ def handle_text_commands(message):
98
+ try:
99
+ text = message.text.split()
100
+ if len(text) < 2:
101
+ bot.reply_to(message, "Uso: /aceptar <id> o /declinar <id>")
102
+ return
103
+ cmd = text[0][1:]; loan_id = text[1]
104
+ status = "ACCEPTED" if cmd == "aceptar" else "DECLINED"
105
+ if loan_mgr.update_status(loan_id, status):
106
+ emoji = "✅" if status == "ACCEPTED" else "❌"
107
+ bot.reply_to(message, f"{emoji} Préstamo {loan_id} actualizado a {status}")
108
+ bot_broadcast({"text": f"Préstamo {loan_id[:8]} {status}", "color": "green" if status == "ACCEPTED" else "red"})
109
+ else:
110
+ bot.reply_to(message, "ID de préstamo no encontrado.")
111
+ except Exception as e:
112
+ print(f"Command Error: {e}")
113
+
114
+ # --- BROADCAST PARA NOTIFICACIONES (GLOBAL) ---
115
+ registered_pages = []
116
+ def bot_broadcast(msg):
117
+ for p in registered_pages:
118
+ try:
119
+ p.pubsub.send_all(msg)
120
+ except: pass
121
+
122
+ def start_bot_thread():
123
+ if bot:
124
+ try: bot.delete_webhook()
125
+ except: pass
126
+ while True:
127
+ try:
128
+ bot.infinity_polling(timeout=20, long_polling_timeout=10)
129
+ except Exception as e:
130
+ print(f"Error DNS/Red: {e}. Reintento en 60s...")
131
+ time.sleep(60)
132
+
133
+ if bot:
134
+ threading.Thread(target=start_bot_thread, daemon=True).start()
135
+
136
  def main(page: ft.Page):
137
  page.title = "MAKERSPACE DATABASE"
138
  page.theme_mode = ft.ThemeMode.DARK
139
  page.padding = 10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  def mostrar_notificacion(texto, color="blue"):
142
  snack = ft.SnackBar(ft.Text(texto), bgcolor=color)
 
165
  return f"ERR_DNS: {error_msg[:40]}"
166
  return f"ERR_CONN: {error_msg[:100]}"
167
 
168
+ # Registrar esta página para recibir notificaciones del bot
169
+ registered_pages.append(page)
170
+ def on_broadcast(msg):
171
+ mostrar_notificacion(msg["text"], msg["color"])
172
+ # Si estamos en /prestamos, forzar refresco (esto es un poco complejo sin una ref global)
173
+ # Por ahora solo la notificación
174
+ page.pubsub.subscribe(on_broadcast)
175
+
176
+ # --- CONFIGURACIÓN DE VARIABLES LOCALES ---
177
+ GITLAB_URL = "https://gitlab.com"
178
+ GIT_TOKEN = os.getenv("GITLAB_TOKEN")
179
+ GIT_GROUP = os.getenv("GITLAB_GROUP_ID")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  def mostrar_factura(i):
182
  status_color = {