codebydante commited on
Commit
e96b422
·
verified ·
1 Parent(s): 8e285ee

Upload 27 files

Browse files
src/plugins/__pycache__/flow.cpython-311.pyc CHANGED
Binary files a/src/plugins/__pycache__/flow.cpython-311.pyc and b/src/plugins/__pycache__/flow.cpython-311.pyc differ
 
src/plugins/flow.py CHANGED
@@ -1,469 +1,494 @@
1
- import os
2
- import asyncio
3
- from telethon import events
4
- from telethon.tl.types import (
5
- Channel,
6
- Chat,
7
- DocumentAttributeVideo,
8
- MessageService,
9
- MessageActionPinMessage,
10
- MessageActionChatJoinedByLink,
11
- MessageActionChatAddUser
12
- )
13
- from telethon.tl.functions.messages import GetForumTopicsByIDRequest
14
- from telethon.tl.functions.messages import ImportChatInviteRequest, CheckChatInviteRequest
15
- from telethon.errors import (
16
- UserAlreadyParticipantError,
17
- ChatForwardsRestrictedError
18
- )
19
- from config import TARGET_CHANNEL_LINK
20
-
21
- # Estado del modo escaneo
22
- flow_state = {
23
- "active": True,
24
- "is_processing": False
25
- }
26
-
27
- def get_media_fingerprint(message):
28
- """
29
- Genera una huella única para comparar si un video o imagen es exactamente el mismo.
30
- - Para videos: peso en bytes + duración en segundos.
31
- - Para imágenes: ID de foto de Telegram + dimensiones (ancho x alto).
32
- - Para archivos de imagen sin comprimir (documentos): peso en bytes + extensión.
33
- """
34
- if not message or not message.media:
35
- return None
36
-
37
- if message.photo:
38
- # En Telegram cada foto tiene un ID único en sus servidores
39
- photo_id = getattr(message.photo, 'id', None)
40
- # También obtener dimensiones del tamaño más grande
41
- w, h = 0, 0
42
- if hasattr(message.photo, 'sizes') and message.photo.sizes:
43
- largest = message.photo.sizes[-1]
44
- w = getattr(largest, 'w', 0)
45
- h = getattr(largest, 'h', 0)
46
- return f"photo_{photo_id}_{w}x{h}"
47
-
48
- doc = message.document
49
- if doc:
50
- size_bytes = getattr(doc, 'size', 0)
51
- # Verificar si es video
52
- for attr in (doc.attributes or []):
53
- if isinstance(attr, DocumentAttributeVideo):
54
- duration = int(getattr(attr, 'duration', 0))
55
- return f"video_{size_bytes}_{duration}"
56
-
57
- # Si es imagen enviada como documento/archivo
58
- mime = getattr(doc, 'mime_type', '') or ''
59
- if mime.startswith('image/'):
60
- return f"imgdoc_{size_bytes}_{doc.id}"
61
-
62
- return None
63
-
64
- async def get_or_join_target_channel(client, link):
65
- """
66
- Obtiene la entidad del canal destino asegurando que el userbot sea miembro.
67
- """
68
- clean_hash = link.strip().replace("https://t.me/+", "").replace("https://t.me/joinchat/", "")
69
- try:
70
- updates = await client(ImportChatInviteRequest(clean_hash))
71
- return updates.chats[0]
72
- except UserAlreadyParticipantError:
73
- check = await client(CheckChatInviteRequest(clean_hash))
74
- if hasattr(check, 'chat'):
75
- return check.chat
76
- async for dialog in client.iter_dialogs():
77
- if dialog.is_channel and clean_hash in str(dialog.entity):
78
- return dialog.entity
79
- return await client.get_entity(link)
80
- except Exception:
81
- return await client.get_entity(link)
82
-
83
- def register_flow_handlers(client):
84
- """
85
- Registra los comandos /flow_on, /flow_off y la lógica inteligente de sincronización.
86
- """
87
-
88
- @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/flow_on$"))
89
- async def flow_on_handler(event):
90
- flow_state["active"] = True
91
- msg = (
92
- "🟢 **Modo Flujo ACTIVADO**\n"
93
- "━━━━━━━━━━━━━━━━━━━━\n"
94
- "📡 **Estado:** Escaneando en Mensajes Guardados.\n"
95
- "🎯 **Canal Destino:** `" + TARGET_CHANNEL_LINK + "`\n\n"
96
- "👉 **Instrucciones:** Reenvía aquí un mensaje de cualquier **canal** que quieras sincronizar.\n"
97
- "• Si el canal prohíbe reenvíos, te avisará de inmediato.\n"
98
- "• Compara peso y duración para **no duplicar videos** ya enviados.\n"
99
- "• Si se añadieron capítulos nuevos al canal original, enviará únicamente los que falten.\n"
100
- "━━━━━━━━━━━━━━━━━━━━\n"
101
- "Para detener, usa: `/flow_off`"
102
- )
103
- await event.reply(msg)
104
-
105
- @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/flow_off$"))
106
- async def flow_off_handler(event):
107
- flow_state["active"] = False
108
- await event.reply("🔴 **Modo Flujo DESACTIVADO**.\nEl bot ya no procesará mensajes reenviados.")
109
-
110
- @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/(eliminar_fijados|elimianr_fijados)$"))
111
- async def eliminar_notificaciones_fijados_handler(event):
112
- """
113
- Escanea el canal destino y elimina todos los mensajes de servicio que genera Telegram
114
- al fijar mensajes (ej: 'FLOW fijó una foto', 'Te uniste a este canal', etc.)
115
- para que el canal quede completamente limpio.
116
- """
117
- status_msg = await event.reply("🧹 **Buscando y eliminando mensajes de 'fijó una foto' en el canal...**")
118
- try:
119
- target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
120
- service_msg_ids = []
121
- scanned = 0
122
-
123
- async for msg in client.iter_messages(target_entity, limit=2000):
124
- scanned += 1
125
- # Comprobar si es un mensaje de servicio (MessageService o acciones de fijado/unirse)
126
- is_service = isinstance(msg, MessageService)
127
- action = getattr(msg, 'action', None)
128
- if is_service or isinstance(action, (MessageActionPinMessage, MessageActionChatJoinedByLink, MessageActionChatAddUser)):
129
- service_msg_ids.append(msg.id)
130
-
131
- if not service_msg_ids:
132
- await status_msg.edit("✨ **Canal limpio:** No se encontraron mensajes de notificación de fijado.")
133
- return
134
-
135
- # Eliminar en bloques de 100
136
- deleted_count = 0
137
- for i in range(0, len(service_msg_ids), 100):
138
- chunk = service_msg_ids[i:i + 100]
139
- await client.delete_messages(target_entity, chunk)
140
- deleted_count += len(chunk)
141
- await asyncio.sleep(0.5)
142
-
143
- await status_msg.edit(
144
- f"🗑️ **Limpieza Finalizada con Éxito:**\n"
145
- f"━━━━━━━━━━━━━━━━━━━━\n"
146
- f"✅ Se eliminaron **{deleted_count}** avisos de 'fijó una foto' / avisos de servicio.\n"
147
- f"🎯 Canal: `{TARGET_CHANNEL_LINK}`"
148
- )
149
- except Exception as e:
150
- await status_msg.edit(f"❌ Error al eliminar notificaciones de fijado: `{e}`")
151
-
152
- @client.on(events.NewMessage(chats='me'))
153
- async def process_forwarded_content(event):
154
- # Ignorar comandos
155
- if event.raw_text and event.raw_text.startswith('/'):
156
- return
157
-
158
- if not flow_state["active"]:
159
- return
160
-
161
- # Verificar si el mensaje proviene de un reenvío
162
- fwd_header = event.fwd_from
163
- if not fwd_header or not fwd_header.from_id:
164
- return
165
-
166
- if flow_state["is_processing"]:
167
- await event.reply("⚠️ Ya hay un proceso de sincronización en curso. Espera a que termine.")
168
- return
169
-
170
- flow_state["is_processing"] = True
171
- status_msg = await event.reply("🔍 **Inspeccionando origen del mensaje...**")
172
-
173
- try:
174
- # 1. Obtener entidad de origen y validar que sea estrictamente un CANAL
175
- source_peer = fwd_header.from_id
176
- source_entity = await client.get_entity(source_peer)
177
-
178
- # Verificar si es un canal o grupo válido
179
- is_valid = isinstance(source_entity, (Channel, Chat))
180
- if not is_valid:
181
- await status_msg.edit("⚠️ **Solo se admiten canales y grupos.**")
182
- return
183
-
184
- # Detección de tema (Forum Topic) si proviene de un grupo con temas activados
185
- topic_id = None
186
- topic_title = None
187
-
188
- # 1. Verificar si en la cabecera de reenvío o en el mensaje original viene el tema
189
- orig_msg_id = getattr(fwd_header, 'channel_post', None) or getattr(fwd_header, 'saved_from_msg_id', None)
190
- if orig_msg_id and getattr(source_entity, 'forum', False):
191
- try:
192
- orig_msgs = await client.get_messages(source_entity, ids=[orig_msg_id])
193
- if orig_msgs and orig_msgs[0]:
194
- orig_m = orig_msgs[0]
195
- reply_header = getattr(orig_m, 'reply_to', None)
196
- if reply_header and getattr(reply_header, 'forum_topic', False):
197
- topic_id = getattr(reply_header, 'reply_to_top_id', None) or getattr(reply_header, 'reply_to_msg_id', None)
198
- except Exception as top_err:
199
- print(f"[Aviso al inspeccionar tema original]: {top_err}")
200
-
201
- # Si se detectó un tema específico dentro del grupo
202
- if topic_id:
203
- try:
204
- topics_res = await client(GetForumTopicsByIDRequest(peer=source_entity, topics=[topic_id]))
205
- if topics_res and getattr(topics_res, 'topics', None):
206
- topic_title = topics_res.topics[0].title
207
- except Exception:
208
- pass
209
-
210
- # Usar siempre el título general del grupo y su portada con el emoji 📁
211
- source_title = getattr(source_entity, 'title', 'Grupo/Canal')
212
- header_pattern = f"📁 **{source_title}**"
213
-
214
- # 2. Verificar si el origen prohíbe guardar/reenviar contenido
215
- if getattr(source_entity, 'noforwards', False):
216
- await status_msg.edit(f"⛔ **`{source_title}` prohíbe reenviar/guardar contenido.** Operación cancelada.")
217
- return
218
-
219
- # 3. Conectar con el canal destino
220
- await status_msg.edit(f"🎯 Conectando con el canal destino para sincronizar `{source_title}`...")
221
- target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
222
-
223
- # 4. Leer todos los videos e imágenes del origen (filtrando por tema si aplica)
224
- await status_msg.edit(f"📥 Leyendo contenidos de `{source_title}`...")
225
- source_items = []
226
- source_fps = set()
227
-
228
- iter_kwargs = {"reverse": True}
229
- if topic_id:
230
- iter_kwargs["reply_to"] = topic_id
231
-
232
- async for message in client.iter_messages(source_entity, **iter_kwargs):
233
- is_photo = bool(message.photo)
234
- is_video = bool(message.video)
235
- is_img_doc = False
236
-
237
- if message.document:
238
- for attr in (message.document.attributes or []):
239
- if isinstance(attr, DocumentAttributeVideo):
240
- is_video = True
241
- break
242
- mime = getattr(message.document, 'mime_type', '') or ''
243
- if mime.startswith('image/'):
244
- is_img_doc = True
245
-
246
- if is_photo or is_video or is_img_doc:
247
- fp = get_media_fingerprint(message)
248
- source_items.append((message, fp))
249
- if fp:
250
- source_fps.add(fp)
251
-
252
- total_items = len(source_items)
253
- if total_items == 0:
254
- await status_msg.edit(f"⚠️ El canal `{source_title}` no contiene videos ni imágenes.")
255
- return
256
-
257
- # 5. Analizar el canal destino: recopilar los mensajes viejos en orden cronológico (incluyendo la portada y título)
258
- await status_msg.edit(f"📊 Analizando contenidos previos de `{source_title}` en el canal destino...")
259
- target_series_msgs = []
260
- target_series_ids = set()
261
- existing_target_fps = set()
262
-
263
- clean_title = source_title.strip().lower()
264
-
265
- # Leer mensajes del canal destino
266
- all_recent_target_msgs = []
267
- async for target_msg in client.iter_messages(target_entity, limit=4000):
268
- all_recent_target_msgs.append(target_msg)
269
-
270
- # 1. Encontrar todos los mensajes multimedia que coincidan con los del canal de origen
271
- matched_indices = []
272
- for idx, target_msg in enumerate(all_recent_target_msgs):
273
- fp = get_media_fingerprint(target_msg)
274
- msg_txt = (target_msg.message or "").lower()
275
-
276
- # Coincidencia por huella multimedia
277
- is_media_match = bool(fp and fp in source_fps)
278
- # Coincidencia por texto de portada o título
279
- is_header_match = bool(clean_title in msg_txt)
280
-
281
- if is_media_match or is_header_match:
282
- if target_msg.id not in target_series_ids:
283
- target_series_msgs.append(target_msg)
284
- target_series_ids.add(target_msg.id)
285
- matched_indices.append(idx)
286
- if fp:
287
- existing_target_fps.add(fp)
288
-
289
- # 2. Si se encontraron videos pero no la portada/título por texto (ej. por caracteres especiales o emojis),
290
- # revisar los mensajes inmediatamente anteriores al video más antiguo encontrado en el destino
291
- if matched_indices:
292
- max_idx = max(matched_indices)
293
- # Revisar hasta 3 mensajes antes (los de menor id están más arriba, o sea índice más alto)
294
- for lookback in range(1, 4):
295
- if max_idx + lookback < len(all_recent_target_msgs):
296
- prev_msg = all_recent_target_msgs[max_idx + lookback]
297
- # Si es foto o texto y contiene parte del título o es la portada previa
298
- prev_txt = (prev_msg.message or "").lower()
299
- if (clean_title in prev_txt) or (prev_msg.photo and prev_txt.startswith(("📁", "🎬"))):
300
- if prev_msg.id not in target_series_ids:
301
- target_series_msgs.append(prev_msg)
302
- target_series_ids.add(prev_msg.id)
303
-
304
- # Ordenar los mensajes viejos del destino en orden cronológico (menor ID a mayor ID)
305
- target_series_msgs.sort(key=lambda m: m.id)
306
- old_msg_ids_to_delete = [m.id for m in target_series_msgs]
307
-
308
- # 6. Identificar qué contenidos del canal de origen son nuevos (faltantes)
309
- new_missing_items = [item for item in source_items if item[1] and item[1] not in existing_target_fps]
310
-
311
- # Caso A: Si NO hay ningún video/imagen nuevo y ya teníamos todo
312
- if not new_missing_items and len(existing_target_fps) >= total_items:
313
- await status_msg.edit(
314
- f"👌 **Canal al día:**\n"
315
- f"📌 **Canal:** `{source_title}`\n"
316
- f"No hay videos ni imágenes nuevas. El canal destino ya tiene todos los {total_items} contenidos."
317
- )
318
- return
319
-
320
- # Caso B: Hay contenidos nuevos o es la primera vez
321
- if old_msg_ids_to_delete:
322
- await status_msg.edit(
323
- f"🔄 **Detectados {len(new_missing_items)} contenidos nuevos:**\n"
324
- f"Reenviando la serie desde el canal destino y añadiendo los nuevos al final..."
325
- )
326
- # Reenviar los mensajes que ya estaban en el canal destino (sin etiqueta de reenvío)
327
- sent_count = 0
328
- first_sent_msg = None
329
- for old_msg in target_series_msgs:
330
- try:
331
- if old_msg.media:
332
- sent_item = await client.send_file(
333
- target_entity,
334
- file=old_msg.media,
335
- caption=old_msg.message or ""
336
- )
337
- elif old_msg.message:
338
- sent_item = await client.send_message(target_entity, old_msg.message)
339
- else:
340
- sent_item = None
341
-
342
- if first_sent_msg is None and sent_item:
343
- first_sent_msg = sent_item
344
-
345
- sent_count += 1
346
- await asyncio.sleep(0.2)
347
- except Exception as re_err:
348
- print(f"[Error reenviando existente]: {re_err}")
349
- await asyncio.sleep(1)
350
-
351
- # Agregar los nuevos faltantes que vienen del canal de origen
352
- await status_msg.edit(f"➕ Agregando los **{len(new_missing_items)}** videos/imágenes nuevos...")
353
- for msg_item, fp in new_missing_items:
354
- try:
355
- sent_item = await client.send_file(
356
- target_entity,
357
- file=msg_item.media,
358
- caption=msg_item.message or ""
359
- )
360
- if first_sent_msg is None and sent_item:
361
- first_sent_msg = sent_item
362
-
363
- sent_count += 1
364
- await asyncio.sleep(0.2)
365
- except Exception as new_err:
366
- print(f"[Error enviando nuevo]: {new_err}")
367
- await asyncio.sleep(1)
368
-
369
- # Fijar el primer mensaje enviado (portada/título de la serie)
370
- if first_sent_msg:
371
- try:
372
- await client.pin_message(target_entity, first_sent_msg, notify=False)
373
- # Limpiar notificación de servicio que genera Telegram ("FLOW fijó una foto")
374
- await asyncio.sleep(0.3)
375
- async for pin_notif in client.iter_messages(target_entity, limit=5):
376
- if isinstance(pin_notif, MessageService) or isinstance(getattr(pin_notif, 'action', None), MessageActionPinMessage):
377
- await client.delete_messages(target_entity, pin_notif.id)
378
- break
379
- except Exception as pin_err:
380
- print(f"[Error fijando mensaje en actualizacion]: {pin_err}")
381
-
382
- # Eliminar los mensajes viejos que quedaron arriba desactualizados
383
- await status_msg.edit(f"🗑️ Eliminando los {len(old_msg_ids_to_delete)} mensajes anteriores desactualizados...")
384
- try:
385
- for i in range(0, len(old_msg_ids_to_delete), 100):
386
- chunk = old_msg_ids_to_delete[i:i + 100]
387
- await client.delete_messages(target_entity, chunk)
388
- await asyncio.sleep(0.5)
389
- except Exception as del_err:
390
- print(f"[Error eliminando viejos]: {del_err}")
391
-
392
- await status_msg.edit(
393
- f"✅ **Actualización Exitosa:**\n"
394
- f"📌 **Canal:** `{source_title}`\n"
395
- f"✨ **Nuevos agregados al final:** {len(new_missing_items)}\n"
396
- f"📦 **Total serie completa al día:** {sent_count}\n"
397
- f"🗑️ **Anteriores eliminados:** {len(old_msg_ids_to_delete)}\n"
398
- f"🎯 **Destino:** `{TARGET_CHANNEL_LINK}`"
399
- )
400
- return
401
-
402
- # Caso C: Primera clonación (nunca antes se había enviado este canal)
403
- await status_msg.edit(f"🚀 **Primera clonación de:** `{source_title}` ({total_items} contenidos)...")
404
-
405
- # Portada inicial: descargar foto del canal o usar portada por defecto
406
- default_cover_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "default_cover.jpg")
407
- avatar_path = await client.download_profile_photo(source_entity, file="channel_cover.jpg")
408
-
409
- if avatar_path and os.path.exists(avatar_path):
410
- cover_to_send = avatar_path
411
- elif os.path.exists(default_cover_path):
412
- cover_to_send = default_cover_path
413
- else:
414
- cover_to_send = None
415
-
416
- # 1. Enviar primero la portada con el título
417
- first_pinned_msg = None
418
- if cover_to_send:
419
- first_pinned_msg = await client.send_file(target_entity, file=cover_to_send, caption=header_pattern)
420
- if cover_to_send == avatar_path:
421
- try:
422
- os.remove(avatar_path)
423
- except Exception:
424
- pass
425
- else:
426
- first_pinned_msg = await client.send_message(target_entity, header_pattern)
427
-
428
- # 2. FIJAR INMEDIATAMENTE la portada antes de enviar los videos
429
- if first_pinned_msg:
430
- try:
431
- await client.pin_message(target_entity, first_pinned_msg, notify=False)
432
- # Limpiar la notificación de servicio que genera Telegram al fijar ("FLOW fijó una foto")
433
- await asyncio.sleep(0.3)
434
- async for pin_notif in client.iter_messages(target_entity, limit=5):
435
- if isinstance(pin_notif, MessageService) or isinstance(getattr(pin_notif, 'action', None), MessageActionPinMessage):
436
- await client.delete_messages(target_entity, pin_notif.id)
437
- break
438
- except Exception as pin_err:
439
- print(f"[Error fijando mensaje de portada]: {pin_err}")
440
-
441
- sent_count = 0
442
- for msg_item, fp in source_items:
443
- caption = msg_item.message or ""
444
- try:
445
- await client.send_file(target_entity, file=msg_item.media, caption=caption)
446
- sent_count += 1
447
- if sent_count % 10 == 0 or sent_count == total_items:
448
- await status_msg.edit(
449
- f"⚡ **Sincronizando:** `{source_title}`\n"
450
- f"Progreso: **{sent_count}/{total_items}**"
451
- )
452
- await asyncio.sleep(0.2)
453
- except Exception as send_err:
454
- print(f"[Error enviando]: {send_err}")
455
- await asyncio.sleep(1)
456
-
457
- await status_msg.edit(
458
- f"✅ **Primera Clonación Finalizada:**\n"
459
- f"📌 **Canal:** `{source_title}`\n"
460
- f"📦 **Total de contenidos:** {sent_count}\n"
461
- f"🎯 **Destino:** `{TARGET_CHANNEL_LINK}`"
462
- )
463
-
464
- except ChatForwardsRestrictedError:
465
- await status_msg.edit("⛔ **Canal prohíbe reenvío:** Este canal tiene activada la protección contra copia.")
466
- except Exception as e:
467
- await status_msg.edit(f"❌ Error durante el flujo: `{e}`")
468
- finally:
469
- flow_state["is_processing"] = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from telethon import events
4
+ from telethon.tl.types import (
5
+ Channel,
6
+ Chat,
7
+ DocumentAttributeVideo,
8
+ MessageService,
9
+ MessageActionPinMessage,
10
+ MessageActionChatJoinedByLink,
11
+ MessageActionChatAddUser
12
+ )
13
+ from telethon.tl.functions.messages import GetForumTopicsByIDRequest
14
+ from telethon.tl.functions.messages import ImportChatInviteRequest, CheckChatInviteRequest
15
+ from telethon.errors import (
16
+ UserAlreadyParticipantError,
17
+ ChatForwardsRestrictedError
18
+ )
19
+ from config import TARGET_CHANNEL_LINK
20
+
21
+ # Estado del modo escaneo
22
+ flow_state = {
23
+ "active": True,
24
+ "is_processing": False
25
+ }
26
+
27
+ def get_media_fingerprint(message):
28
+ """
29
+ Genera una huella única para comparar si un video o imagen es exactamente el mismo.
30
+ - Para videos: peso en bytes + duración en segundos.
31
+ - Para imágenes: ID de foto de Telegram + dimensiones (ancho x alto).
32
+ - Para archivos de imagen sin comprimir (documentos): peso en bytes + extensión.
33
+ """
34
+ if not message or not message.media:
35
+ return None
36
+
37
+ if message.photo:
38
+ # En Telegram cada foto tiene un ID único en sus servidores
39
+ photo_id = getattr(message.photo, 'id', None)
40
+ # También obtener dimensiones del tamaño más grande
41
+ w, h = 0, 0
42
+ if hasattr(message.photo, 'sizes') and message.photo.sizes:
43
+ largest = message.photo.sizes[-1]
44
+ w = getattr(largest, 'w', 0)
45
+ h = getattr(largest, 'h', 0)
46
+ return f"photo_{photo_id}_{w}x{h}"
47
+
48
+ doc = message.document
49
+ if doc:
50
+ size_bytes = getattr(doc, 'size', 0)
51
+ # Verificar si es video
52
+ for attr in (doc.attributes or []):
53
+ if isinstance(attr, DocumentAttributeVideo):
54
+ duration = int(getattr(attr, 'duration', 0))
55
+ return f"video_{size_bytes}_{duration}"
56
+
57
+ # Si es imagen enviada como documento/archivo
58
+ mime = getattr(doc, 'mime_type', '') or ''
59
+ if mime.startswith('image/'):
60
+ return f"imgdoc_{size_bytes}_{doc.id}"
61
+
62
+ return None
63
+
64
+ async def get_or_join_target_channel(client, link):
65
+ """
66
+ Obtiene la entidad del canal destino asegurando que el userbot sea miembro.
67
+ """
68
+ clean_hash = link.strip().replace("https://t.me/+", "").replace("https://t.me/joinchat/", "")
69
+ try:
70
+ updates = await client(ImportChatInviteRequest(clean_hash))
71
+ return updates.chats[0]
72
+ except UserAlreadyParticipantError:
73
+ check = await client(CheckChatInviteRequest(clean_hash))
74
+ if hasattr(check, 'chat'):
75
+ return check.chat
76
+ async for dialog in client.iter_dialogs():
77
+ if dialog.is_channel and clean_hash in str(dialog.entity):
78
+ return dialog.entity
79
+ return await client.get_entity(link)
80
+ except Exception:
81
+ return await client.get_entity(link)
82
+
83
+ def register_flow_handlers(client):
84
+ """
85
+ Registra los comandos /flow_on, /flow_off y la lógica inteligente de sincronización.
86
+ """
87
+
88
+ @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/flow_on$"))
89
+ async def flow_on_handler(event):
90
+ flow_state["active"] = True
91
+ msg = (
92
+ "🟢 **Modo Flujo ACTIVADO**\n"
93
+ "━━━━━━━━━━━━━━━━━━━━\n"
94
+ "📡 **Estado:** Escaneando en Mensajes Guardados.\n"
95
+ "🎯 **Canal Destino:** `" + TARGET_CHANNEL_LINK + "`\n\n"
96
+ "👉 **Instrucciones:** Reenvía aquí un mensaje de cualquier **canal** que quieras sincronizar.\n"
97
+ "• Si el canal prohíbe reenvíos, te avisará de inmediato.\n"
98
+ "• Compara peso y duración para **no duplicar videos** ya enviados.\n"
99
+ "• Si se añadieron capítulos nuevos al canal original, enviará únicamente los que falten.\n"
100
+ "━━━━━━━━━━━━━━━━━━━━\n"
101
+ "Para detener, usa: `/flow_off`"
102
+ )
103
+ await event.reply(msg)
104
+
105
+ @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/flow_off$"))
106
+ async def flow_off_handler(event):
107
+ flow_state["active"] = False
108
+ await event.reply("🔴 **Modo Flujo DESACTIVADO**.\nEl bot ya no procesará mensajes reenviados.")
109
+
110
+ @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/(eliminar_fijados|elimianr_fijados)$"))
111
+ async def eliminar_notificaciones_fijados_handler(event):
112
+ """
113
+ Escanea el canal destino y elimina todos los mensajes de servicio que genera Telegram
114
+ al fijar mensajes (ej: 'FLOW fijó una foto', 'Te uniste a este canal', etc.)
115
+ para que el canal quede completamente limpio.
116
+ """
117
+ status_msg = await event.reply("🧹 **Buscando y eliminando mensajes de 'fijó una foto' en el canal...**")
118
+ try:
119
+ target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
120
+ service_msg_ids = []
121
+ scanned = 0
122
+
123
+ async for msg in client.iter_messages(target_entity, limit=2000):
124
+ scanned += 1
125
+ # Comprobar si es un mensaje de servicio (MessageService o acciones de fijado/unirse)
126
+ is_service = isinstance(msg, MessageService)
127
+ action = getattr(msg, 'action', None)
128
+ if is_service or isinstance(action, (MessageActionPinMessage, MessageActionChatJoinedByLink, MessageActionChatAddUser)):
129
+ service_msg_ids.append(msg.id)
130
+
131
+ if not service_msg_ids:
132
+ await status_msg.edit("✨ **Canal limpio:** No se encontraron mensajes de notificación de fijado.")
133
+ return
134
+
135
+ # Eliminar en bloques de 100
136
+ deleted_count = 0
137
+ for i in range(0, len(service_msg_ids), 100):
138
+ chunk = service_msg_ids[i:i + 100]
139
+ await client.delete_messages(target_entity, chunk)
140
+ deleted_count += len(chunk)
141
+ await asyncio.sleep(0.5)
142
+
143
+ await status_msg.edit(
144
+ f"🗑️ **Limpieza Finalizada con Éxito:**\n"
145
+ f"━━━━━━━━━━━━━━━━━━━━\n"
146
+ f"✅ Se eliminaron **{deleted_count}** avisos de 'fijó una foto' / avisos de servicio.\n"
147
+ f"🎯 Canal: `{TARGET_CHANNEL_LINK}`"
148
+ )
149
+ except Exception as e:
150
+ await status_msg.edit(f"❌ Error al eliminar notificaciones de fijado: `{e}`")
151
+
152
+ @client.on(events.NewMessage(chats='me'))
153
+ async def process_forwarded_content(event):
154
+ # Ignorar comandos
155
+ if event.raw_text and event.raw_text.startswith('/'):
156
+ return
157
+
158
+ if not flow_state["active"]:
159
+ return
160
+
161
+ # Verificar si el mensaje proviene de un reenvío
162
+ fwd_header = event.fwd_from
163
+ if not fwd_header or (not getattr(fwd_header, 'from_id', None) and not getattr(fwd_header, 'saved_from_peer', None)):
164
+ return
165
+
166
+ if flow_state["is_processing"]:
167
+ await event.reply("⚠️ Ya hay un proceso de sincronización en curso. Espera a que termine.")
168
+ return
169
+
170
+ flow_state["is_processing"] = True
171
+ status_msg = await event.reply("🔍 **Inspeccionando origen del mensaje...**")
172
+
173
+ try:
174
+ # 1. Obtener entidad de origen (Canal de donde se reenvió el mensaje)
175
+ # En Telegram, si el mensaje dentro del canal ya era un reenvío de otro canal externo:
176
+ # - `saved_from_peer`: es el canal real donde estás y desde donde reenviate a Guardados.
177
+ # - `from_id`: apunta al canal creador original remoto (que puede estar eliminado o ser privado).
178
+ # Por tanto, priorizamos `saved_from_peer` para sincronizar el canal donde el usuario está.
179
+ candidates_to_try = []
180
+ if getattr(fwd_header, 'saved_from_peer', None):
181
+ candidates_to_try.append(fwd_header.saved_from_peer)
182
+ if getattr(fwd_header, 'from_id', None):
183
+ candidates_to_try.append(fwd_header.from_id)
184
+
185
+ source_entity = None
186
+ source_peer = None
187
+ for p in candidates_to_try:
188
+ try:
189
+ ent = await client.get_entity(p)
190
+ if isinstance(ent, (Channel, Chat)):
191
+ source_entity = ent
192
+ source_peer = p
193
+ break
194
+ except Exception as ent_err:
195
+ print(f"[Aviso al resolver entidad {p}]: {ent_err}")
196
+
197
+ # Verificar si se pudo resolver un canal o grupo válido
198
+ if not source_entity:
199
+ await status_msg.edit(
200
+ "❌ **No se pudo acceder al canal de origen.**\n"
201
+ "El canal original es privado, fue eliminado o tu cuenta no tiene acceso a él."
202
+ )
203
+ return
204
+
205
+ # Detección de tema (Forum Topic) si proviene de un grupo con temas activados
206
+ topic_id = None
207
+ topic_title = None
208
+
209
+ # 1. Verificar si en la cabecera de reenvío o en el mensaje original viene el tema
210
+ if source_peer == getattr(fwd_header, 'saved_from_peer', None):
211
+ orig_msg_id = getattr(fwd_header, 'saved_from_msg_id', None) or getattr(fwd_header, 'channel_post', None)
212
+ else:
213
+ orig_msg_id = getattr(fwd_header, 'channel_post', None) or getattr(fwd_header, 'saved_from_msg_id', None)
214
+
215
+ if orig_msg_id and getattr(source_entity, 'forum', False):
216
+ try:
217
+ orig_msgs = await client.get_messages(source_entity, ids=[orig_msg_id])
218
+ if orig_msgs and orig_msgs[0]:
219
+ orig_m = orig_msgs[0]
220
+ reply_header = getattr(orig_m, 'reply_to', None)
221
+ if reply_header and getattr(reply_header, 'forum_topic', False):
222
+ topic_id = getattr(reply_header, 'reply_to_top_id', None) or getattr(reply_header, 'reply_to_msg_id', None)
223
+ except Exception as top_err:
224
+ print(f"[Aviso al inspeccionar tema original]: {top_err}")
225
+
226
+ # Si se detectó un tema específico dentro del grupo
227
+ if topic_id:
228
+ try:
229
+ topics_res = await client(GetForumTopicsByIDRequest(peer=source_entity, topics=[topic_id]))
230
+ if topics_res and getattr(topics_res, 'topics', None):
231
+ topic_title = topics_res.topics[0].title
232
+ except Exception:
233
+ pass
234
+
235
+ # Usar siempre el título general del grupo y su portada con el emoji 📁
236
+ source_title = getattr(source_entity, 'title', 'Grupo/Canal')
237
+ header_pattern = f"📁 **{source_title}**"
238
+
239
+ # 2. Verificar si el origen prohíbe guardar/reenviar contenido
240
+ if getattr(source_entity, 'noforwards', False):
241
+ await status_msg.edit(f"⛔ **`{source_title}` prohíbe reenviar/guardar contenido.** Operación cancelada.")
242
+ return
243
+
244
+ # 3. Conectar con el canal destino
245
+ await status_msg.edit(f"🎯 Conectando con el canal destino para sincronizar `{source_title}`...")
246
+ target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
247
+
248
+ # 4. Leer todos los videos e imágenes del origen (filtrando por tema si aplica)
249
+ await status_msg.edit(f"📥 Leyendo contenidos de `{source_title}`...")
250
+ source_items = []
251
+ source_fps = set()
252
+
253
+ iter_kwargs = {"reverse": True}
254
+ if topic_id:
255
+ iter_kwargs["reply_to"] = topic_id
256
+
257
+ async for message in client.iter_messages(source_entity, **iter_kwargs):
258
+ is_photo = bool(message.photo)
259
+ is_video = bool(message.video)
260
+ is_img_doc = False
261
+
262
+ if message.document:
263
+ for attr in (message.document.attributes or []):
264
+ if isinstance(attr, DocumentAttributeVideo):
265
+ is_video = True
266
+ break
267
+ mime = getattr(message.document, 'mime_type', '') or ''
268
+ if mime.startswith('image/'):
269
+ is_img_doc = True
270
+
271
+ if is_photo or is_video or is_img_doc:
272
+ fp = get_media_fingerprint(message)
273
+ source_items.append((message, fp))
274
+ if fp:
275
+ source_fps.add(fp)
276
+
277
+ total_items = len(source_items)
278
+ if total_items == 0:
279
+ await status_msg.edit(f"⚠️ El canal `{source_title}` no contiene videos ni imágenes.")
280
+ return
281
+
282
+ # 5. Analizar el canal destino: recopilar los mensajes viejos en orden cronológico (incluyendo la portada y título)
283
+ await status_msg.edit(f"📊 Analizando contenidos previos de `{source_title}` en el canal destino...")
284
+ target_series_msgs = []
285
+ target_series_ids = set()
286
+ existing_target_fps = set()
287
+
288
+ clean_title = source_title.strip().lower()
289
+
290
+ # Leer mensajes del canal destino
291
+ all_recent_target_msgs = []
292
+ async for target_msg in client.iter_messages(target_entity, limit=4000):
293
+ all_recent_target_msgs.append(target_msg)
294
+
295
+ # 1. Encontrar todos los mensajes multimedia que coincidan con los del canal de origen
296
+ matched_indices = []
297
+ for idx, target_msg in enumerate(all_recent_target_msgs):
298
+ fp = get_media_fingerprint(target_msg)
299
+ msg_txt = (target_msg.message or "").lower()
300
+
301
+ # Coincidencia por huella multimedia
302
+ is_media_match = bool(fp and fp in source_fps)
303
+ # Coincidencia por texto de portada o título
304
+ is_header_match = bool(clean_title in msg_txt)
305
+
306
+ if is_media_match or is_header_match:
307
+ if target_msg.id not in target_series_ids:
308
+ target_series_msgs.append(target_msg)
309
+ target_series_ids.add(target_msg.id)
310
+ matched_indices.append(idx)
311
+ if fp:
312
+ existing_target_fps.add(fp)
313
+
314
+ # 2. Si se encontraron videos pero no la portada/título por texto (ej. por caracteres especiales o emojis),
315
+ # revisar los mensajes inmediatamente anteriores al video más antiguo encontrado en el destino
316
+ if matched_indices:
317
+ max_idx = max(matched_indices)
318
+ # Revisar hasta 3 mensajes antes (los de menor id están más arriba, o sea índice más alto)
319
+ for lookback in range(1, 4):
320
+ if max_idx + lookback < len(all_recent_target_msgs):
321
+ prev_msg = all_recent_target_msgs[max_idx + lookback]
322
+ # Si es foto o texto y contiene parte del título o es la portada previa
323
+ prev_txt = (prev_msg.message or "").lower()
324
+ if (clean_title in prev_txt) or (prev_msg.photo and prev_txt.startswith(("📁", "🎬"))):
325
+ if prev_msg.id not in target_series_ids:
326
+ target_series_msgs.append(prev_msg)
327
+ target_series_ids.add(prev_msg.id)
328
+
329
+ # Ordenar los mensajes viejos del destino en orden cronológico (menor ID a mayor ID)
330
+ target_series_msgs.sort(key=lambda m: m.id)
331
+ old_msg_ids_to_delete = [m.id for m in target_series_msgs]
332
+
333
+ # 6. Identificar qué contenidos del canal de origen son nuevos (faltantes)
334
+ new_missing_items = [item for item in source_items if item[1] and item[1] not in existing_target_fps]
335
+
336
+ # Caso A: Si NO hay ningún video/imagen nuevo y ya teníamos todo
337
+ if not new_missing_items and len(existing_target_fps) >= total_items:
338
+ await status_msg.edit(
339
+ f"👌 **Canal al día:**\n"
340
+ f"📌 **Canal:** `{source_title}`\n"
341
+ f"No hay videos ni imágenes nuevas. El canal destino ya tiene todos los {total_items} contenidos."
342
+ )
343
+ return
344
+
345
+ # Caso B: Hay contenidos nuevos o es la primera vez
346
+ if old_msg_ids_to_delete:
347
+ await status_msg.edit(
348
+ f"🔄 **Detectados {len(new_missing_items)} contenidos nuevos:**\n"
349
+ f"Reenviando la serie desde el canal destino y añadiendo los nuevos al final..."
350
+ )
351
+ # Reenviar los mensajes que ya estaban en el canal destino (sin etiqueta de reenvío)
352
+ sent_count = 0
353
+ first_sent_msg = None
354
+ for old_msg in target_series_msgs:
355
+ try:
356
+ if old_msg.media:
357
+ sent_item = await client.send_file(
358
+ target_entity,
359
+ file=old_msg.media,
360
+ caption=old_msg.message or ""
361
+ )
362
+ elif old_msg.message:
363
+ sent_item = await client.send_message(target_entity, old_msg.message)
364
+ else:
365
+ sent_item = None
366
+
367
+ if first_sent_msg is None and sent_item:
368
+ first_sent_msg = sent_item
369
+
370
+ sent_count += 1
371
+ await asyncio.sleep(0.2)
372
+ except Exception as re_err:
373
+ print(f"[Error reenviando existente]: {re_err}")
374
+ await asyncio.sleep(1)
375
+
376
+ # Agregar los nuevos faltantes que vienen del canal de origen
377
+ await status_msg.edit(f"➕ Agregando los **{len(new_missing_items)}** videos/imágenes nuevos...")
378
+ for msg_item, fp in new_missing_items:
379
+ try:
380
+ sent_item = await client.send_file(
381
+ target_entity,
382
+ file=msg_item.media,
383
+ caption=msg_item.message or ""
384
+ )
385
+ if first_sent_msg is None and sent_item:
386
+ first_sent_msg = sent_item
387
+
388
+ sent_count += 1
389
+ await asyncio.sleep(0.2)
390
+ except Exception as new_err:
391
+ print(f"[Error enviando nuevo]: {new_err}")
392
+ await asyncio.sleep(1)
393
+
394
+ # Fijar el primer mensaje enviado (portada/título de la serie)
395
+ if first_sent_msg:
396
+ try:
397
+ await client.pin_message(target_entity, first_sent_msg, notify=False)
398
+ # Limpiar notificación de servicio que genera Telegram ("FLOW fijó una foto")
399
+ await asyncio.sleep(0.3)
400
+ async for pin_notif in client.iter_messages(target_entity, limit=5):
401
+ if isinstance(pin_notif, MessageService) or isinstance(getattr(pin_notif, 'action', None), MessageActionPinMessage):
402
+ await client.delete_messages(target_entity, pin_notif.id)
403
+ break
404
+ except Exception as pin_err:
405
+ print(f"[Error fijando mensaje en actualizacion]: {pin_err}")
406
+
407
+ # Eliminar los mensajes viejos que quedaron arriba desactualizados
408
+ await status_msg.edit(f"🗑️ Eliminando los {len(old_msg_ids_to_delete)} mensajes anteriores desactualizados...")
409
+ try:
410
+ for i in range(0, len(old_msg_ids_to_delete), 100):
411
+ chunk = old_msg_ids_to_delete[i:i + 100]
412
+ await client.delete_messages(target_entity, chunk)
413
+ await asyncio.sleep(0.5)
414
+ except Exception as del_err:
415
+ print(f"[Error eliminando viejos]: {del_err}")
416
+
417
+ await status_msg.edit(
418
+ f"✅ **Actualización Exitosa:**\n"
419
+ f"📌 **Canal:** `{source_title}`\n"
420
+ f"✨ **Nuevos agregados al final:** {len(new_missing_items)}\n"
421
+ f"📦 **Total serie completa al día:** {sent_count}\n"
422
+ f"🗑️ **Anteriores eliminados:** {len(old_msg_ids_to_delete)}\n"
423
+ f"🎯 **Destino:** `{TARGET_CHANNEL_LINK}`"
424
+ )
425
+ return
426
+
427
+ # Caso C: Primera clonación (nunca antes se había enviado este canal)
428
+ await status_msg.edit(f"🚀 **Primera clonación de:** `{source_title}` ({total_items} contenidos)...")
429
+
430
+ # Portada inicial: descargar foto del canal o usar portada por defecto
431
+ default_cover_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "default_cover.jpg")
432
+ avatar_path = await client.download_profile_photo(source_entity, file="channel_cover.jpg")
433
+
434
+ if avatar_path and os.path.exists(avatar_path):
435
+ cover_to_send = avatar_path
436
+ elif os.path.exists(default_cover_path):
437
+ cover_to_send = default_cover_path
438
+ else:
439
+ cover_to_send = None
440
+
441
+ # 1. Enviar primero la portada con el título
442
+ first_pinned_msg = None
443
+ if cover_to_send:
444
+ first_pinned_msg = await client.send_file(target_entity, file=cover_to_send, caption=header_pattern)
445
+ if cover_to_send == avatar_path:
446
+ try:
447
+ os.remove(avatar_path)
448
+ except Exception:
449
+ pass
450
+ else:
451
+ first_pinned_msg = await client.send_message(target_entity, header_pattern)
452
+
453
+ # 2. FIJAR INMEDIATAMENTE la portada antes de enviar los videos
454
+ if first_pinned_msg:
455
+ try:
456
+ await client.pin_message(target_entity, first_pinned_msg, notify=False)
457
+ # Limpiar la notificación de servicio que genera Telegram al fijar ("FLOW fijó una foto")
458
+ await asyncio.sleep(0.3)
459
+ async for pin_notif in client.iter_messages(target_entity, limit=5):
460
+ if isinstance(pin_notif, MessageService) or isinstance(getattr(pin_notif, 'action', None), MessageActionPinMessage):
461
+ await client.delete_messages(target_entity, pin_notif.id)
462
+ break
463
+ except Exception as pin_err:
464
+ print(f"[Error fijando mensaje de portada]: {pin_err}")
465
+
466
+ sent_count = 0
467
+ for msg_item, fp in source_items:
468
+ caption = msg_item.message or ""
469
+ try:
470
+ await client.send_file(target_entity, file=msg_item.media, caption=caption)
471
+ sent_count += 1
472
+ if sent_count % 10 == 0 or sent_count == total_items:
473
+ await status_msg.edit(
474
+ f"⚡ **Sincronizando:** `{source_title}`\n"
475
+ f"Progreso: **{sent_count}/{total_items}**"
476
+ )
477
+ await asyncio.sleep(0.2)
478
+ except Exception as send_err:
479
+ print(f"[Error enviando]: {send_err}")
480
+ await asyncio.sleep(1)
481
+
482
+ await status_msg.edit(
483
+ f"✅ **Primera Clonación Finalizada:**\n"
484
+ f"📌 **Canal:** `{source_title}`\n"
485
+ f"📦 **Total de contenidos:** {sent_count}\n"
486
+ f"🎯 **Destino:** `{TARGET_CHANNEL_LINK}`"
487
+ )
488
+
489
+ except ChatForwardsRestrictedError:
490
+ await status_msg.edit("⛔ **Canal prohíbe reenvío:** Este canal tiene activada la protección contra copia.")
491
+ except Exception as e:
492
+ await status_msg.edit(f"❌ Error durante el flujo: `{e}`")
493
+ finally:
494
+ flow_state["is_processing"] = False
src/plugins/general.py CHANGED
@@ -1,34 +1,34 @@
1
- from telethon import events
2
- from config import PORT
3
-
4
- def register_general_handlers(client):
5
- """
6
- Registra comandos utilitarios generales del UserBot.
7
- """
8
- @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/lista$"))
9
- async def lista_me(event):
10
- mensaje = (
11
- "📂 **Control y Canales**\n"
12
- "• `/crear_canal [nombre]` : Crea un canal privado y genera su enlace de invitación.\n\n"
13
- "📂 **Flujo y Clonación**\n"
14
- "• `/flow_on` : Activa el modo escaneo de canales/grupos.\n"
15
- "• `/flow_off` : Desactiva el modo escaneo.\n"
16
- "• `/eliminar_fijados` : Elimina los avisos de notificación ('fijó una foto') del canal sin desfijar nada."
17
- )
18
- await event.reply(mensaje)
19
-
20
- @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/ping$"))
21
- async def ping_me(event):
22
- await event.reply("🏓 **¡Pong!** El UserBot está activo y respondiendo.")
23
-
24
- @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/alive$"))
25
- async def alive_me(event):
26
- msg = (
27
- "🎬 **UserBot Películas ACTIVO**\n"
28
- "━━━━━━━━━━━━━━━━━━━━\n"
29
- "✅ **Servidor:** Online (HF Space / Flask)\n"
30
- "🌐 **Puerto:** " + str(PORT) + "\n"
31
- "🤖 **Telethon:** v1.36+\n"
32
- "━━━━━━━━━━━━━━━━━━━━"
33
- )
34
- await event.reply(msg)
 
1
+ from telethon import events
2
+ from config import PORT
3
+
4
+ def register_general_handlers(client):
5
+ """
6
+ Registra comandos utilitarios generales del UserBot.
7
+ """
8
+ @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/lista$"))
9
+ async def lista_me(event):
10
+ mensaje = (
11
+ "📂 **Control y Canales**\n"
12
+ "• `/crear_canal [nombre]` : Crea un canal privado y genera su enlace de invitación.\n\n"
13
+ "📂 **Flujo y Clonación**\n"
14
+ "• `/flow_on` : Activa el modo escaneo de canales/grupos.\n"
15
+ "• `/flow_off` : Desactiva el modo escaneo.\n"
16
+ "• `/eliminar_fijados` : Elimina los avisos de notificación ('fijó una foto') del canal sin desfijar nada."
17
+ )
18
+ await event.reply(mensaje)
19
+
20
+ @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/ping$"))
21
+ async def ping_me(event):
22
+ await event.reply("🏓 **¡Pong!** El UserBot está activo y respondiendo.")
23
+
24
+ @client.on(events.NewMessage(chats='me', pattern=r"(?i)^/alive$"))
25
+ async def alive_me(event):
26
+ msg = (
27
+ "🎬 **UserBot Películas ACTIVO**\n"
28
+ "━━━━━━━━━━━━━━━━━━━━\n"
29
+ "✅ **Servidor:** Online (HF Space / Flask)\n"
30
+ "🌐 **Puerto:** " + str(PORT) + "\n"
31
+ "🤖 **Telethon:** v1.36+\n"
32
+ "━━━━━━━━━━━━━━━━━━━━"
33
+ )
34
+ await event.reply(msg)