codebydante commited on
Commit
dfd2587
·
verified ·
1 Parent(s): 45e24e8

Upload 45 files

Browse files
.env ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ TELEGRAM_BOT_TOKEN=8691200988:AAGBo-sUFwj4-k1r5QVEijy0cRxfmUJuvMY
2
+ TELEGRAM_API_ID=33226415
3
+ TELEGRAM_API_HASH=01999dae3e5348c7ab0dbcc6f7f4edc5
4
+ TELEGRAM_CHANNEL_ID=-1003846066066
5
+ IMGBB_API_KEY=e94fe450ad62364662c62d09b589d06e
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ __pycache__/bot.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Usa una imagen oficial de Python ligera
2
+ FROM python:3.11-slim
3
+
4
+ # Evita que Python escriba archivos .pyc y fuerza salida de consola en tiempo real
5
+ ENV PYTHONDONTWRITEBYTECODE=1
6
+ ENV PYTHONUNBUFFERED=1
7
+
8
+ # Crea un usuario no root (Requisito estricto de Hugging Face Spaces)
9
+ RUN useradd -m -u 1000 user
10
+
11
+ # Cambia al usuario 'user'
12
+ USER user
13
+ ENV PATH="/home/user/.local/bin:$PATH"
14
+
15
+ # Directorio de trabajo
16
+ WORKDIR /app
17
+
18
+ # Copia los archivos del bot asegurando que el propietario sea 'user'
19
+ COPY --chown=user . /app
20
+
21
+ # Instala las dependencias necesarias
22
+ RUN pip install --no-cache-dir -r requirements.txt
23
+
24
+ # Expone el puerto 7860 para la página fantasma de Hugging Face
25
+ EXPOSE 7860
26
+
27
+ # Ejecuta el bot de Telegram
28
+ CMD ["python", "main.py"]
TwistedStreamingBrodybot.session ADDED
Binary file (28.7 kB). View file
 
TwistedStreamingBrodybot.session-journal ADDED
Binary file (4.62 kB). View file
 
__pycache__/bot.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b61ee2ff1eb8d4b499c02ff5362b6117b74e759305f69091f632fc3b66c70cf2
3
+ size 117172
__pycache__/bot_buscador.cpython-311.pyc ADDED
Binary file (32.3 kB). View file
 
__pycache__/bot_editor.cpython-311.pyc ADDED
Binary file (58.8 kB). View file
 
__pycache__/bot_subidor.cpython-311.pyc ADDED
Binary file (43.2 kB). View file
 
__pycache__/core.cpython-311.pyc ADDED
Binary file (13.9 kB). View file
 
__pycache__/main.cpython-311.pyc ADDED
Binary file (8.86 kB). View file
 
add_editor.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ if "editor_mode_active = {}" not in code:
9
+ old_start = """active_tasks = {}
10
+
11
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
12
+ async def start_subir_handler(event):
13
+ chat_id = event.chat_id"""
14
+
15
+ new_start = """active_tasks = {}
16
+ editor_mode_active = {}
17
+
18
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
19
+ async def start_subir_handler(event):
20
+ chat_id = event.chat_id
21
+ if editor_mode_active.get(chat_id, False):
22
+ await event.respond("🛠️ **Estás en Modo Editor.**\\nPor favor, usa `/desactivar_modo_editor` para salir del editor y usar los comandos normales.")
23
+ return"""
24
+ code = code.replace(old_start, new_start)
25
+
26
+ editor_logic = """
27
+ # --- MODO EDITOR ---
28
+ @client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
29
+ async def enable_editor(event):
30
+ chat_id = event.chat_id
31
+ editor_mode_active[chat_id] = True
32
+ await handle_editor_mode(event)
33
+
34
+ @client.on(events.NewMessage(pattern='/(desactivar_modo_editor)$'))
35
+ async def disable_editor(event):
36
+ chat_id = event.chat_id
37
+ editor_mode_active[chat_id] = False
38
+ await event.respond("✅ **Modo editor desactivado.** Ya puedes usar los comandos normales.")
39
+
40
+ async def handle_editor_mode(event):
41
+ chat_id = event.chat_id
42
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
43
+ try:
44
+ while editor_mode_active.get(chat_id, False):
45
+ msg = await conv.send_message(
46
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
47
+ buttons=[
48
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
49
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
50
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
51
+ ]
52
+ )
53
+
54
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
55
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
56
+ break
57
+
58
+ if isinstance(resp, events.CallbackQuery.Event):
59
+ await resp.answer()
60
+ await msg.edit(buttons=None)
61
+
62
+ if resp.data == b"ed_exit":
63
+ editor_mode_active[chat_id] = False
64
+ await conv.send_message("✅ **Modo editor desactivado.**")
65
+ break
66
+ elif resp.data == b"ed_mov":
67
+ await handle_editor_movie_search(conv)
68
+ elif resp.data == b"ed_ser":
69
+ await handle_editor_series_search(conv)
70
+ except Exception as e:
71
+ print("Editor error:", e)
72
+
73
+ async def handle_editor_movie_search(conv):
74
+ uid_back = str(uuid.uuid4()).encode()
75
+ msg = await conv.send_message("🔍 Escribe el nombre de la **película** que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
76
+
77
+ resp = await wait_for_message_or_callback(conv, timeout=300)
78
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
79
+ await resp.answer("Cancelado")
80
+ await msg.edit("Búsqueda cancelada.", buttons=None)
81
+ return
82
+
83
+ query = resp.raw_text.strip()
84
+ await msg.delete()
85
+
86
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
87
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower()]
88
+
89
+ if not results:
90
+ await conv.send_message("❌ No se encontraron películas con ese nombre.")
91
+ return
92
+
93
+ results = results[:10]
94
+ buttons = []
95
+ for r in results:
96
+ data = r.to_dict()
97
+ buttons.append([Button.inline(f"🎬 {data.get('title')[:30]}", f"ed_m_{r.id}".encode('utf-8'))])
98
+
99
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
100
+
101
+ msg_res = await conv.send_message("📌 **Resultados (Películas):**", buttons=buttons)
102
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
103
+
104
+ if isinstance(resp_res, events.CallbackQuery.Event):
105
+ await resp_res.answer()
106
+ await msg_res.edit(buttons=None)
107
+ if resp_res.data == b"ed_back": return
108
+
109
+ movie_id = resp_res.data.decode().replace('ed_m_', '')
110
+ await handle_editor_movie_action(conv, movie_id)
111
+
112
+ async def handle_editor_movie_action(conv, movie_id):
113
+ doc = db.collection('videos').document(movie_id).get()
114
+ if not doc.exists: return
115
+ data = doc.to_dict()
116
+
117
+ msg = await conv.send_message(
118
+ f"🎬 **Editando Película:**\\n`{data.get('title')}`",
119
+ buttons=[
120
+ [Button.inline("✏️ Renombrar Título", b"renombrar")],
121
+ [Button.inline("🗑️ Eliminar Película", b"eliminar")],
122
+ [Button.inline("⬅️ Volver", b"volver")]
123
+ ]
124
+ )
125
+ resp = await wait_for_message_or_callback(conv, timeout=300)
126
+ if isinstance(resp, events.CallbackQuery.Event):
127
+ await resp.answer()
128
+ await msg.edit(buttons=None)
129
+ if resp.data == b"volver": return
130
+ elif resp.data == b"renombrar":
131
+ await conv.send_message("Escribe el **nuevo título** para la película:")
132
+ new_title = await conv.get_response()
133
+ db.collection('videos').document(movie_id).update({"title": new_title.raw_text})
134
+ await conv.send_message(f"✅ Título actualizado a: **{new_title.raw_text}**")
135
+ elif resp.data == b"eliminar":
136
+ db.collection('videos').document(movie_id).delete()
137
+ await conv.send_message("✅ Película eliminada.")
138
+
139
+ async def handle_editor_series_search(conv):
140
+ uid_back = str(uuid.uuid4()).encode()
141
+ msg = await conv.send_message("🔍 Escribe el nombre de la **serie** que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
142
+
143
+ resp = await wait_for_message_or_callback(conv, timeout=300)
144
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
145
+ await resp.answer()
146
+ await msg.edit("Búsqueda cancelada.", buttons=None)
147
+ return
148
+
149
+ query = resp.raw_text.strip()
150
+ await msg.delete()
151
+
152
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
153
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower()]
154
+
155
+ if not results:
156
+ await conv.send_message("❌ No se encontraron series con ese nombre.")
157
+ return
158
+
159
+ results = results[:10]
160
+ buttons = []
161
+ for r in results:
162
+ buttons.append([Button.inline(f"📺 {r.to_dict().get('title')[:30]}", f"ed_s_{r.id}".encode('utf-8'))])
163
+
164
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
165
+
166
+ msg_res = await conv.send_message("📌 **Resultados (Series):**", buttons=buttons)
167
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
168
+
169
+ if isinstance(resp_res, events.CallbackQuery.Event):
170
+ await resp_res.answer()
171
+ await msg_res.edit(buttons=None)
172
+ if resp_res.data == b"ed_back": return
173
+
174
+ series_id = resp_res.data.decode().replace('ed_s_', '')
175
+ await handle_editor_series_action(conv, series_id)
176
+
177
+ async def handle_editor_series_action(conv, series_id):
178
+ while editor_mode_active.get(conv.chat_id, False):
179
+ doc = db.collection('videos').document(series_id).get()
180
+ if not doc.exists: return
181
+ data = doc.to_dict()
182
+ title = data.get('title')
183
+
184
+ msg = await conv.send_message(
185
+ f"📺 **Editando Serie:**\\n`{title}`",
186
+ buttons=[
187
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
188
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
189
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
190
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
191
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
192
+ ]
193
+ )
194
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
195
+ if getattr(resp, 'raw_text', '').startswith('/'): return
196
+
197
+ if isinstance(resp, events.CallbackQuery.Event):
198
+ await resp.answer()
199
+ await msg.edit(buttons=None)
200
+
201
+ if resp.data == b"volver": return
202
+ elif resp.data == b"renombrar":
203
+ await conv.send_message("Escribe el **nuevo título general** para la serie:")
204
+ new_title = await conv.get_response()
205
+ db.collection('videos').document(series_id).update({"title": new_title.raw_text})
206
+ await conv.send_message(f"✅ Título general actualizado a: **{new_title.raw_text}**")
207
+ elif resp.data == b"eliminar":
208
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
209
+ for c in caps: db.collection('videos').document(c.id).delete()
210
+ db.collection('videos').document(series_id).delete()
211
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados.")
212
+ return
213
+ elif resp.data == b"ver_caps":
214
+ await handle_editor_series_chapters(conv, series_id, title)
215
+ elif resp.data == b"add_caps":
216
+ await handle_editor_add_chapters(conv, series_id, title)
217
+
218
+ async def handle_editor_series_chapters(conv, series_id, series_title):
219
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
220
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
221
+ if not caps:
222
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
223
+ return
224
+
225
+ buttons = []
226
+ for c in caps[:90]:
227
+ c_data = c.to_dict()
228
+ buttons.append([Button.inline(f"Cap {c_data.get('episode', 0)}: {c_data.get('title')[:20]}", f"ed_c_{c.id}".encode('utf-8'))])
229
+
230
+ buttons.append([Button.inline("⬅️ Volver", b"volver_caps")])
231
+
232
+ msg = await conv.send_message(f"📑 **Capítulos de {series_title}**\\nSelecciona uno para editar:", buttons=buttons)
233
+ resp = await wait_for_message_or_callback(conv, timeout=300)
234
+
235
+ if isinstance(resp, events.CallbackQuery.Event):
236
+ await resp.answer()
237
+ await msg.edit(buttons=None)
238
+ if resp.data == b"volver_caps": return
239
+ cap_id = resp.data.decode().replace('ed_c_', '')
240
+ await handle_editor_single_chapter(conv, cap_id)
241
+
242
+ async def handle_editor_single_chapter(conv, cap_id):
243
+ doc = db.collection('videos').document(cap_id).get()
244
+ if not doc.exists: return
245
+ data = doc.to_dict()
246
+
247
+ msg = await conv.send_message(
248
+ f"🎞️ **Editando Capítulo:**\\n`{data.get('title')}`",
249
+ buttons=[
250
+ [Button.inline("✏️ Renombrar", b"renombrar")],
251
+ [Button.inline("🗑️ Eliminar", b"eliminar")],
252
+ [Button.inline("⬅️ Volver", b"volver")]
253
+ ]
254
+ )
255
+ resp = await wait_for_message_or_callback(conv, timeout=300)
256
+ if isinstance(resp, events.CallbackQuery.Event):
257
+ await resp.answer()
258
+ await msg.edit(buttons=None)
259
+ if resp.data == b"volver": return
260
+ if resp.data == b"renombrar":
261
+ await conv.send_message("Escribe el **nuevo nombre** del capítulo:")
262
+ new_title = await conv.get_response()
263
+ db.collection('videos').document(cap_id).update({"title": new_title.raw_text})
264
+ await conv.send_message(f"✅ Capítulo renombrado a: **{new_title.raw_text}**")
265
+ if resp.data == b"eliminar":
266
+ db.collection('videos').document(cap_id).delete()
267
+ await conv.send_message("✅ Capítulo eliminado.")
268
+
269
+ async def handle_editor_add_chapters(conv, series_id, series_title):
270
+ uid_done = str(uuid.uuid4()).encode()
271
+ videos = []
272
+
273
+ msg_v = await conv.send_message(
274
+ f"➕ **Añadiendo capítulos a: {series_title}**\\n\\nEnvía los videos. Cuando termines presiona el botón.",
275
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
276
+ )
277
+
278
+ debounce_task = None
279
+ async def update_button():
280
+ await asyncio.sleep(0.8)
281
+ nonlocal msg_v
282
+ try: await msg_v.delete()
283
+ except: pass
284
+ msg_v = await conv.send_message(
285
+ f"➕ **Añadiendo capítulos a: {series_title}**\\n\\n({len(videos)} recibidos). Envía más o termina.",
286
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
287
+ )
288
+
289
+ async def video_receiver(e):
290
+ is_video = False
291
+ if getattr(e, 'media', None):
292
+ if getattr(e, 'video', None):
293
+ is_video = True
294
+ elif getattr(e, 'document', None):
295
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
296
+ if mime.startswith('video/'):
297
+ is_video = True
298
+ else:
299
+ for attr in e.document.attributes:
300
+ if hasattr(attr, 'file_name'):
301
+ import os
302
+ ext = os.path.splitext(attr.file_name)[1].lower()
303
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
304
+ is_video = True
305
+ break
306
+ if is_video:
307
+ videos.append(e)
308
+ nonlocal debounce_task
309
+ if debounce_task: debounce_task.cancel()
310
+ debounce_task = asyncio.create_task(update_button())
311
+
312
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
313
+ try:
314
+ while True:
315
+ event = await wait_for_message_or_callback(conv, timeout=3600)
316
+ if isinstance(event, events.CallbackQuery.Event):
317
+ if event.data == uid_done:
318
+ if not videos:
319
+ await event.answer("No has enviado videos.", alert=True)
320
+ return
321
+ await event.answer("Guardando...")
322
+ if debounce_task: debounce_task.cancel()
323
+ await msg_v.edit(f"✅ Se recibieron {len(videos)} capítulos.", buttons=None)
324
+ break
325
+ finally:
326
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
327
+
328
+ if not videos: return
329
+
330
+ uid_title = str(uuid.uuid4()).encode()
331
+ uid_file = str(uuid.uuid4()).encode()
332
+ msg_n = await conv.send_message(
333
+ "📁 ¿Cómo nombrar estos capítulos extra?",
334
+ buttons=[
335
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
336
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
337
+ ]
338
+ )
339
+
340
+ naming_strategy = "title"
341
+ while True:
342
+ event = await wait_for_message_or_callback(conv, timeout=300)
343
+ if isinstance(event, events.CallbackQuery.Event):
344
+ if event.data == uid_title:
345
+ naming_strategy = "title"
346
+ await msg_n.edit("Formato: Serie - Capítulo X", buttons=None)
347
+ break
348
+ elif event.data == uid_file:
349
+ naming_strategy = "file"
350
+ await msg_n.edit("Formato: Archivo original", buttons=None)
351
+ break
352
+ else:
353
+ naming_strategy = "manual"
354
+ manual_prefix = event.raw_text
355
+ await msg_n.edit(f"Formato: {manual_prefix}...", buttons=None)
356
+ break
357
+
358
+ status_msg = await conv.send_message("📁 **Procesando capítulos extra...**")
359
+
360
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
361
+ max_ep = 0
362
+ for c in caps:
363
+ ep = c.to_dict().get('episode', 0)
364
+ if ep > max_ep: max_ep = ep
365
+
366
+ for i, video_msg in enumerate(videos):
367
+ max_ep += 1
368
+
369
+ if naming_strategy == "title":
370
+ ep_title = f"{series_title} - Capítulo {max_ep}"
371
+ elif naming_strategy == "manual":
372
+ ep_title = f"{manual_prefix} - Capítulo {max_ep}"
373
+ else:
374
+ doc_name = "Episodio"
375
+ if hasattr(video_msg.media, 'document'):
376
+ for attr in video_msg.media.document.attributes:
377
+ if hasattr(attr, 'file_name'):
378
+ import os
379
+ doc_name = os.path.splitext(attr.file_name)[0]
380
+ break
381
+ ep_title = doc_name
382
+
383
+ await status_msg.edit(f"📁 Subiendo extra: **{ep_title}** ({i+1}/{len(videos)})")
384
+ caption = f"**Twisted Streaming Brody Data**\\n\\n📁 **Serie:** {series_title}\\n📁 **Episodio:** {ep_title}"
385
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
386
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
387
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
388
+
389
+ db.collection('videos').add({
390
+ "title": ep_title,
391
+ "section": "series",
392
+ "is_folder": False,
393
+ "folder_id": series_id,
394
+ "episode": max_ep,
395
+ "season": 1,
396
+ "video_url": file_url,
397
+ "telegram_file_id": str(sent_to_channel.id),
398
+ "description": "",
399
+ "thumbnail_url": "",
400
+ "cover_url": "",
401
+ "views": 0,
402
+ "rating": 0,
403
+ "status": "active",
404
+ "is_public": True,
405
+ "categories": [],
406
+ "servers": [file_url],
407
+ "created_at": firestore.SERVER_TIMESTAMP,
408
+ "updated_at": firestore.SERVER_TIMESTAMP
409
+ })
410
+ await status_msg.edit(f"✅ **¡{len(videos)} capítulos extra añadidos con éxito!**")
411
+
412
+ if __name__ == '__main__':
413
+ """
414
+ code = code.replace("if __name__ == '__main__':", editor_logic)
415
+
416
+ old_cmds = """ BotCommand(command="app", description="Abrir la Mini App de Catálogo"),
417
+ BotCommand(command="setting", description="Configurar envío de videos"),
418
+ BotCommand(command="cancelar", description="Cancelar proceso de subida")"""
419
+ new_cmds = """ BotCommand(command="app", description="Abrir la Mini App de Catálogo"),
420
+ BotCommand(command="setting", description="Configurar envío de videos"),
421
+ BotCommand(command="cancelar", description="Cancelar proceso de subida"),
422
+ BotCommand(command="activar_modo_editor", description="Activar Modo Editor"),
423
+ BotCommand(command="desactivar_modo_editor", description="Desactivar Modo Editor")"""
424
+ code = code.replace(old_cmds, new_cmds)
425
+
426
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
427
+ f.write(code)
428
+
429
+ print("Patch applied successfully.")
bot.py ADDED
@@ -0,0 +1,1897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import logging
4
+ import asyncio
5
+ import requests
6
+ import base64
7
+ from dotenv import load_dotenv
8
+ from telethon import TelegramClient, events, Button
9
+ import firebase_admin
10
+ from firebase_admin import credentials, firestore
11
+ from google.cloud.firestore_v1.base_query import FieldFilter
12
+
13
+ # Cargar variables de entorno
14
+ load_dotenv()
15
+
16
+ # --- SERVIDOR WEB FANTASMA (Para Hugging Face) ---
17
+ from threading import Thread
18
+ from http.server import HTTPServer, BaseHTTPRequestHandler
19
+
20
+ class DummyHandler(BaseHTTPRequestHandler):
21
+ def do_GET(self):
22
+ self.send_response(200)
23
+ self.send_header("Content-type", "text/html")
24
+ self.end_headers()
25
+ html_content = b"""<!DOCTYPE html>
26
+ <html lang="es">
27
+ <head>
28
+ <meta charset="UTF-8">
29
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
30
+ <title>Twisted Streaming Brody</title>
31
+ <style>
32
+ body { margin: 0; padding: 0; background-color: #0a0a0a; display: flex; justify-content: center; align-items: center; height: 100vh; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
33
+ .btn { background-color: #2481cc; color: white; padding: 15px 35px; border-radius: 30px; text-decoration: none; font-size: 20px; font-weight: bold; box-shadow: 0 5px 15px rgba(36,129,204,0.4); transition: 0.3s; }
34
+ .btn:hover { transform: translateY(-3px); background-color: #1a629c; box-shadow: 0 8px 20px rgba(36,129,204,0.6); }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <a href="https://t.me/TwistedStreamingBrodybot" target="_blank" class="btn">\xF0\x9F\x9A\x80 Abrir Twisted Streaming Brody</a>
39
+ </body>
40
+ </html>"""
41
+ self.wfile.write(html_content)
42
+ def log_message(self, format, *args):
43
+ pass # Silenciar logs del servidor
44
+
45
+ def run_server():
46
+ try:
47
+ server = HTTPServer(('0.0.0.0', 7860), DummyHandler)
48
+ server.serve_forever()
49
+ except Exception as e:
50
+ print("Error en servidor web:", e)
51
+
52
+ Thread(target=run_server, daemon=True).start()
53
+
54
+ API_ID = int(os.getenv('TELEGRAM_API_ID'))
55
+ API_HASH = os.getenv('TELEGRAM_API_HASH')
56
+ TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
57
+ CHANNEL_ID = int(os.getenv('TELEGRAM_CHANNEL_ID'))
58
+ IMGBB_KEY = os.getenv('IMGBB_API_KEY')
59
+
60
+ # Nombre del archivo de sesión
61
+ SESSION_NAME = 'TwistedStreamingBrodybot'
62
+
63
+ # --- CONFIGURACIÓN DE FIREBASE ---
64
+ try:
65
+ if not firebase_admin._apps:
66
+ cred = credentials.Certificate("firebase-credentials.json")
67
+ app = firebase_admin.initialize_app(cred)
68
+ print(f"📁 Firebase conectado correctamente. Proyecto: {app.project_id}")
69
+ db = firestore.client()
70
+ except Exception as e:
71
+ print(f"📁 Error al conectar con Firebase: {e}")
72
+
73
+ # Logs
74
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
75
+
76
+ # Inicializar Cliente de Telethon
77
+ client = TelegramClient(SESSION_NAME, API_ID, API_HASH)
78
+
79
+ # --- FUNCIONES AUXILIARES ---
80
+
81
+ async def upload_to_imgbb(photo_source):
82
+ """Sube una imagen a ImgBB y devuelve la URL"""
83
+ try:
84
+ # Descargar la foto en memoria
85
+ path = await client.download_media(photo_source, file=bytes)
86
+ image_base64 = base64.b64encode(path)
87
+
88
+ url = "https://api.imgbb.com/1/upload"
89
+ payload = {"key": IMGBB_KEY, "image": image_base64}
90
+
91
+ response = requests.post(url, payload)
92
+ res_json = response.json()
93
+ if res_json['success']:
94
+ return res_json['data']['url']
95
+ except Exception as e:
96
+ print(f"Error ImgBB: {e}")
97
+ return None
98
+
99
+ import re
100
+
101
+ def extract_categories_from_title(title):
102
+ """Extrae categorías de un título como [Accion] El Guerrero (2024)"""
103
+ found = re.findall(r'\[(.*?)\]|\((.*?)\)|\{(.*?)\}|\|(.*?)\|', title)
104
+ categories = []
105
+ for match in found:
106
+ for item in match:
107
+ if item and len(item.strip()) > 1:
108
+ categories.append(item.strip())
109
+ return list(set(categories))
110
+
111
+ def get_or_create_categories(names):
112
+ """Busca o crea categorías por nombre y devuelve sus IDs"""
113
+ ids = []
114
+ for name in names:
115
+ try:
116
+ # Buscar si ya existe
117
+ cats = db.collection('categories').where(filter=FieldFilter('name', '==', name)).get()
118
+ if cats:
119
+ ids.append(cats[0].id)
120
+ else:
121
+ # Crear si no existe
122
+ _, doc_ref = db.collection('categories').add({
123
+ "name": name,
124
+ "type": "genre"
125
+ })
126
+ ids.append(doc_ref.id)
127
+ print(f"🆕 Categoría creada: {name}")
128
+ except Exception as e:
129
+ print(f"Error gestionando categoría {name}: {e}")
130
+ return ids
131
+
132
+ def get_all_categories():
133
+ try:
134
+ cats = db.collection('categories').get()
135
+ return [{"id": c.id, "name": c.to_dict().get('name', 'Sin nombre')} for c in cats]
136
+ except Exception:
137
+ return []
138
+
139
+ import uuid
140
+
141
+ class CancelUploadException(Exception):
142
+ pass
143
+
144
+ class EditorJumpException(Exception):
145
+ def __init__(self, jump_id):
146
+ self.jump_id = jump_id
147
+
148
+ async def wait_for_message_or_callback(conv, timeout=300):
149
+ client = conv._client
150
+ chat_id = conv.chat_id
151
+ future = asyncio.Future()
152
+
153
+ async def msg_handler(e):
154
+ if not future.done():
155
+ future.set_result(e)
156
+
157
+ async def cb_handler(e):
158
+ if not future.done():
159
+ future.set_result(e)
160
+
161
+ client.add_event_handler(msg_handler, events.NewMessage(chats=chat_id, incoming=True))
162
+ client.add_event_handler(cb_handler, events.CallbackQuery(chats=chat_id))
163
+
164
+ try:
165
+ event = await asyncio.wait_for(future, timeout=timeout)
166
+ txt = getattr(event, 'raw_text', getattr(event, 'text', '')).strip()
167
+
168
+ if txt == '/cancelar':
169
+ await client.send_message(chat_id, "📁 **Proceso cancelado.**")
170
+ raise CancelUploadException()
171
+
172
+ # Global intercept for editor mode jumps
173
+ if editor_mode_active.get(chat_id, False):
174
+ if txt.startswith('/start '):
175
+ extracted = txt.replace('/start ', '').replace('folder_', '').strip()
176
+ raise EditorJumpException(extracted)
177
+ elif len(txt) == 20 and txt.isalnum() and not txt.startswith('/'):
178
+ # Heuristic for Firebase ID jump
179
+ raise EditorJumpException(txt)
180
+
181
+ return event
182
+ finally:
183
+ client.remove_event_handler(msg_handler)
184
+ client.remove_event_handler(cb_handler)
185
+
186
+ async def get_input_or_skip(conv, text, can_skip=True):
187
+ """Espera un mensaje o un botón de omitir con IDs únicos para evitar bugs"""
188
+ uid = str(uuid.uuid4()).encode()
189
+ buttons = [Button.inline("📁 Omitir", uid)] if can_skip else None
190
+ msg = await conv.send_message(text, buttons=buttons)
191
+
192
+ try:
193
+ while True:
194
+ event = await wait_for_message_or_callback(conv, timeout=300)
195
+ if isinstance(event, events.CallbackQuery.Event):
196
+ if event.data == uid:
197
+ await event.answer("Omitido")
198
+ await msg.edit(text + " (Omitido)", buttons=None)
199
+ return None
200
+ else:
201
+ await event.answer("Este botón ya no es válido", alert=True)
202
+ else:
203
+ if buttons:
204
+ await msg.edit(text, buttons=None)
205
+ return event
206
+ except asyncio.TimeoutError:
207
+ await conv.send_message("📁 Tiempo de espera agotado. Proceso cancelado.")
208
+ return None
209
+ except Exception as e:
210
+ print(f"Error en get_input_or_skip: {e}")
211
+ return None
212
+
213
+ # --- MANEJADORES ---
214
+
215
+ # --- MODO BUSCADOR ---
216
+ @client.on(events.NewMessage(pattern='^/buscador_on$'))
217
+ async def enable_search_mode(event):
218
+ chat_id = event.chat_id
219
+
220
+ # Desactivar editor y cancelar subidas
221
+ editor_mode_active[chat_id] = False
222
+ if chat_id in active_tasks:
223
+ for t in active_tasks[chat_id]:
224
+ t.cancel()
225
+ del active_tasks[chat_id]
226
+
227
+ search_mode_active[chat_id] = True
228
+ await event.respond("🔍 **Modo Buscador Activado**\n\nAhora puedes buscar enviando el título de una película, serie o capítulo. También puedes pegar enlaces directos o IDs.\n\nEnvía /buscador_off para salir.")
229
+
230
+ @client.on(events.NewMessage(pattern='^/buscador_off$'))
231
+ async def disable_search_mode(event):
232
+ chat_id = event.chat_id
233
+ search_mode_active[chat_id] = False
234
+ await event.respond("❌ **Modo Buscador Desactivado**.")
235
+
236
+ @client.on(events.NewMessage(func=lambda e: not e.text.startswith('/') and len(e.text) != 20))
237
+ async def handle_text_search(event):
238
+ chat_id = event.chat_id
239
+ if not search_mode_active.get(chat_id, False):
240
+ return
241
+ if editor_mode_active.get(chat_id, False):
242
+ return
243
+
244
+ query = event.raw_text.strip().lower()
245
+ if not query: return
246
+
247
+ msg = await event.respond("🔍 Buscando...")
248
+
249
+ # Buscar en Firestore (limitado en memoria por diseño simple de Firebase)
250
+ docs = db.collection('videos').get()
251
+
252
+ matched_docs = []
253
+ for d in docs:
254
+ data = d.to_dict()
255
+ title = data.get('title', '').lower()
256
+ if query in title:
257
+ matched_docs.append((d.id, data))
258
+
259
+ if not matched_docs:
260
+ await msg.edit("❌ No se encontraron resultados para tu búsqueda.")
261
+ return
262
+
263
+ # Buscar si hay alguna coincidencia EXACTA (para evitar que "Capítulo 1" muestre el "10", "11", etc.)
264
+ exact_matches = [m for m in matched_docs if m[1].get('title', '').lower() == query]
265
+ if len(exact_matches) == 1:
266
+ matched_docs = exact_matches
267
+
268
+ # Si hay exactamente 1 resultado, lo enviamos directamente
269
+ if len(matched_docs) == 1:
270
+ doc_id, data = matched_docs[0]
271
+ class DummyEvent:
272
+ def __init__(self, chat_id, raw_text):
273
+ self.chat_id = chat_id
274
+ self.raw_text = raw_text
275
+ async def respond(self, *args, **kwargs):
276
+ return await client.send_message(self.chat_id, *args, **kwargs)
277
+
278
+ dummy = DummyEvent(event.chat_id, doc_id)
279
+ await msg.delete()
280
+ await handle_document_id(dummy)
281
+ return
282
+
283
+ # Si hay múltiples, filtramos para dar prioridad a las Carpetas (Series) y Películas
284
+ # Esto evita mostrar una lista gigante de subcapítulos
285
+ folders_and_movies = []
286
+ chapters = []
287
+
288
+ for r_id, data in matched_docs:
289
+ if data.get('section') == 'peliculas' or data.get('is_folder'):
290
+ folders_and_movies.append((r_id, data))
291
+ else:
292
+ chapters.append((r_id, data))
293
+
294
+ # Mostrar carpetas/pelis si hay, sino mostrar capítulos sueltos
295
+ results = folders_and_movies if folders_and_movies else chapters
296
+
297
+ # Mostrar resultados en botones
298
+ results = results[:20] # Limitar a 20 resultados para no exceder limite de botones
299
+ buttons = []
300
+ for r_id, data in results:
301
+ t = data.get('title', 'Sin titulo')[:40]
302
+ icon = "🎬" if data.get('section') == 'peliculas' else ("📺" if data.get('is_folder') else "🎞️")
303
+ buttons.append([Button.inline(f"{icon} {t}", f"get_vid_{r_id}".encode('utf-8'))])
304
+
305
+ await msg.edit(f"📌 **Resultados para:** `{query}`", buttons=buttons)
306
+
307
+ @client.on(events.CallbackQuery(pattern=b'^get_vid_'))
308
+ async def handle_search_result_click(event):
309
+ if not search_mode_active.get(event.chat_id, False):
310
+ await event.answer("El modo buscador está desactivado.", alert=True)
311
+ return
312
+
313
+ doc_id = event.data.decode('utf-8').replace('get_vid_', '')
314
+ await event.answer()
315
+
316
+ # Simulamos como si el usuario hubiera enviado el ID directamente
317
+ class DummyEvent:
318
+ def __init__(self, chat_id, raw_text):
319
+ self.chat_id = chat_id
320
+ self.raw_text = raw_text
321
+ async def respond(self, *args, **kwargs):
322
+ return await client.send_message(self.chat_id, *args, **kwargs)
323
+
324
+ dummy = DummyEvent(event.chat_id, doc_id)
325
+ await handle_document_id(dummy)
326
+
327
+ # --------------------------
328
+
329
+
330
+ active_tasks = {}
331
+ editor_mode_active = {}
332
+ search_mode_active = {}
333
+
334
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
335
+ async def start_subir_handler(event):
336
+ chat_id = event.chat_id
337
+ if editor_mode_active.get(chat_id, False):
338
+ await event.respond("🛠️ **Estás en Modo Editor.**\nPor favor, usa `/desactivar_modo_editor` para salir del editor y usar los comandos normales.")
339
+ return
340
+
341
+ if chat_id not in active_tasks:
342
+ active_tasks[chat_id] = []
343
+
344
+ current_task = asyncio.current_task()
345
+ current_task.is_uploading = False
346
+
347
+ remaining_tasks = []
348
+ for old_task in active_tasks[chat_id]:
349
+ if not old_task.done():
350
+ if getattr(old_task, 'is_uploading', False):
351
+ remaining_tasks.append(old_task)
352
+ else:
353
+ old_task.cancel()
354
+ try:
355
+ await asyncio.sleep(0.1)
356
+ except: pass
357
+
358
+ active_tasks[chat_id] = remaining_tasks
359
+ active_tasks[chat_id].append(current_task)
360
+
361
+ try:
362
+ async with client.conversation(chat_id, timeout=600, exclusive=False) as conv:
363
+ try:
364
+ cmd = event.text.strip().lower()
365
+
366
+ if cmd == '/subir_pelicula':
367
+ await handle_movie_upload(conv)
368
+ return
369
+ elif cmd == '/subir_serie':
370
+ await handle_series_upload(conv)
371
+ return
372
+
373
+ msg_text = "📁 Bienvenido a **Twisted Streaming Brody**.\nElige una opción:"
374
+ botones = [
375
+ [Button.inline("📁 Subir Película", b"type_movie"), Button.inline("📁 Subir Serie", b"type_series")]
376
+ ]
377
+
378
+ if cmd == '/start':
379
+ photos = await client.get_profile_photos('me', limit=1)
380
+ if photos:
381
+ msg = await conv.send_message(msg_text, file=photos[0], buttons=botones)
382
+ else:
383
+ msg = await conv.send_message(msg_text, buttons=botones)
384
+ else:
385
+ msg = await conv.send_message(msg_text, buttons=botones)
386
+
387
+ while True:
388
+ press = await wait_for_message_or_callback(conv, timeout=3600)
389
+ if isinstance(press, events.CallbackQuery.Event):
390
+ if press.data in [b"type_movie", b"type_series"]:
391
+ await press.answer()
392
+ try:
393
+ await msg.edit(buttons=None)
394
+ except: pass
395
+
396
+ if press.data == b"type_movie":
397
+ await handle_movie_upload(conv)
398
+ elif press.data == b"type_series":
399
+ await handle_series_upload(conv)
400
+ break
401
+ else:
402
+ await press.answer("Botón expirado", alert=True)
403
+ elif getattr(press, 'text', '') in ['/start', '/subir', '/subir_pelicula', '/subir_serie']:
404
+ # El usuario envió otro comando, dejamos que el nuevo handler lo tome
405
+ break
406
+ except CancelUploadException:
407
+ pass
408
+ except asyncio.CancelledError:
409
+ pass
410
+ finally:
411
+ if current_task in active_tasks.get(chat_id, []):
412
+ active_tasks[chat_id].remove(current_task)
413
+ if not active_tasks[chat_id]:
414
+ del active_tasks[chat_id]
415
+
416
+ async def handle_movie_upload(conv):
417
+ # 1. Video
418
+ await conv.send_message("📁 **Paso 1:** Envía el **video** (o el archivo) de la película:")
419
+ msg_video = await conv.get_response()
420
+
421
+ is_video = False
422
+ if msg_video and getattr(msg_video, 'media', None):
423
+ if getattr(msg_video, 'video', None):
424
+ is_video = True
425
+ elif getattr(msg_video, 'document', None):
426
+ mime = getattr(msg_video.file, 'mime_type', '') if hasattr(msg_video, 'file') else ''
427
+ if mime.startswith('video/'):
428
+ is_video = True
429
+ else:
430
+ for attr in msg_video.document.attributes:
431
+ if hasattr(attr, 'file_name'):
432
+ import os
433
+ ext = os.path.splitext(attr.file_name)[1].lower()
434
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
435
+ is_video = True
436
+ break
437
+
438
+ if not is_video:
439
+ await conv.send_message("📁 No enviaste un video válido. Debes enviar un video normal o un archivo de video (documento). Las imágenes no son aceptadas. Abortando proceso.")
440
+ print("📁 Intento de subida fallido: No se recibió un video o documento válido.")
441
+ return
442
+
443
+ doc_name = ""
444
+ video_caption = msg_video.raw_text if getattr(msg_video, 'raw_text', None) else ""
445
+ if hasattr(msg_video.media, 'document'):
446
+ for attr in msg_video.media.document.attributes:
447
+ if hasattr(attr, 'file_name'):
448
+ import os
449
+ doc_name = os.path.splitext(attr.file_name)[0]
450
+ break
451
+
452
+ # 2. Título
453
+ uid_title = str(uuid.uuid4()).encode()
454
+ buttons_title = []
455
+ if doc_name:
456
+ buttons_title.append([Button.inline(f"📁 Usar nombre del archivo: {doc_name[:30]}", uid_title)])
457
+
458
+ msg_t = await conv.send_message("📁 **Paso 2:** Escribe el **Título** de la película:", buttons=buttons_title if buttons_title else None)
459
+ title = ""
460
+ while True:
461
+ event = await wait_for_message_or_callback(conv, timeout=300)
462
+ if isinstance(event, events.CallbackQuery.Event):
463
+ if doc_name and event.data == uid_title:
464
+ await event.answer("Título seleccionado")
465
+ title = doc_name
466
+ await msg_t.edit(f"📁 Título: **{title}**", buttons=None)
467
+ break
468
+ else:
469
+ await event.answer("Botón expirado", alert=True)
470
+ else:
471
+ title = event.raw_text
472
+ if buttons_title:
473
+ await msg_t.edit(buttons=None)
474
+ break
475
+
476
+ print(f"📁 Iniciando carga de película: {title}")
477
+
478
+ # 3. Descripción
479
+ uid_desc = str(uuid.uuid4()).encode()
480
+ uid_skip = str(uuid.uuid4()).encode()
481
+ buttons_desc = []
482
+ if video_caption:
483
+ buttons_desc.append([Button.inline("📁 Usar descripción del video", uid_desc)])
484
+ buttons_desc.append([Button.inline("📁 Omitir", uid_skip)])
485
+
486
+ msg_d = await conv.send_message("📁 **Paso 3:** Escribe la **Descripción**:", buttons=buttons_desc)
487
+ description = ""
488
+ while True:
489
+ event = await wait_for_message_or_callback(conv, timeout=300)
490
+ if isinstance(event, events.CallbackQuery.Event):
491
+ if video_caption and event.data == uid_desc:
492
+ await event.answer("Descripción seleccionada")
493
+ description = video_caption
494
+ await msg_d.edit("📁 Descripción obtenida del video.", buttons=None)
495
+ break
496
+ elif event.data == uid_skip:
497
+ await event.answer("Omitido")
498
+ description = ""
499
+ await msg_d.edit("📁 Descripción: (Omitida)", buttons=None)
500
+ break
501
+ else:
502
+ await event.answer("Botón expirado", alert=True)
503
+ else:
504
+ description = event.raw_text
505
+ await msg_d.edit(buttons=None)
506
+ break
507
+
508
+ # 4. Portada
509
+ cover_url = ""
510
+ while True:
511
+ resp_cover = await get_input_or_skip(conv, "📁 **Paso 4:** Envía la **Portada** (solo como imagen):")
512
+ if not resp_cover:
513
+ break
514
+ if resp_cover.photo:
515
+ cover_url = await upload_to_imgbb(resp_cover.photo)
516
+ break
517
+ else:
518
+ await conv.send_message("📁 Por favor, envía una IMAGEN, no un texto ni un link.")
519
+
520
+ async def progress_callback(current, total):
521
+ porcentaje = (current / total) * 100
522
+ print(f" ⬆️ Subiendo: {porcentaje:.1f}% ({current}/{total} bytes)")
523
+
524
+ print(f"📦 Video recibido. Tamaño estimado: {getattr(msg_video.file, 'size', 'desconocido')} bytes")
525
+ status_msg = await conv.send_message("📁 **Subiendo video al canal...** (Mira la consola para ver el progreso)")
526
+
527
+ try:
528
+ asyncio.current_task().is_uploading = True
529
+ # Formatear el mensaje para el canal
530
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Película:** {title}\n📁 {description}"
531
+
532
+ print(f"📤 Enviando al canal {CHANNEL_ID}...")
533
+
534
+ if resp_cover and getattr(resp_cover, 'photo', None):
535
+ try:
536
+ await client.send_file(CHANNEL_ID, resp_cover.photo, caption=f"📁 **Portada Película:** {title}")
537
+ except Exception as e:
538
+ print(f"Error enviando portada de película al canal: {e}")
539
+
540
+ sent_to_channel = await client.send_file(
541
+ CHANNEL_ID,
542
+ msg_video.media,
543
+ caption=caption,
544
+ progress_callback=progress_callback
545
+ )
546
+
547
+ print(f"📁 Enviado al canal. ID: {sent_to_channel.id}")
548
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
549
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
550
+
551
+ print("🗄️ Guardando en Firebase...")
552
+ # Guardar en Firestore con todos los campos observados en tu consola
553
+ db.collection('videos').add({
554
+ "title": title,
555
+ "description": description,
556
+ "section": "peliculas",
557
+ "is_folder": False,
558
+ "folder_id": "", # Sin nulls para evitar errores en React
559
+ "video_url": file_url,
560
+ "telegram_file_id": str(sent_to_channel.id),
561
+ "thumbnail_url": "",
562
+ "cover_url": cover_url,
563
+ "thumbnail_position": "50% center",
564
+ "episode": 0,
565
+ "views": 0,
566
+ "rating": 0,
567
+ "categories": [],
568
+ "servers": [file_url],
569
+ "status": "active",
570
+ "is_public": True,
571
+ "created_at": firestore.SERVER_TIMESTAMP,
572
+ "updated_at": firestore.SERVER_TIMESTAMP
573
+ })
574
+ print("🎉 Guardado en Firebase exitoso.")
575
+ await status_msg.edit("📁 **¡Película registrada y enviada correctamente!**")
576
+ except Exception as e:
577
+ print(f"📁 ERROR CRÍTICO: {e}")
578
+ await status_msg.edit(f"📁 **Error al procesar:** {e}")
579
+
580
+ async def handle_series_upload(conv):
581
+ series_title = ""
582
+ videos = []
583
+ naming_strategy = "title"
584
+ manual_prefix = ""
585
+ desc_strategy = "manual"
586
+ desc_text = ""
587
+ cover_url = ""
588
+ resp_cover = None
589
+
590
+ step = 1
591
+ while step <= 4:
592
+ if step == 1:
593
+ await conv.send_message("📁 **Paso 1:** Escribe el título general de la Serie (`Ej: The Last of Us, Breaking Bad, Invencible, etc.`):")
594
+ while True:
595
+ title_msg = await wait_for_message_or_callback(conv, timeout=300)
596
+ if isinstance(title_msg, events.CallbackQuery.Event):
597
+ await title_msg.answer("Por favor, escribe un texto.", alert=True)
598
+ elif getattr(title_msg, 'raw_text', getattr(title_msg, 'text', None)):
599
+ series_title = getattr(title_msg, 'raw_text', title_msg.text)
600
+ step = 2
601
+ break
602
+
603
+ elif step == 2:
604
+ uid_done = str(uuid.uuid4()).encode()
605
+ uid_back = str(uuid.uuid4()).encode()
606
+ msg_v = await conv.send_message(
607
+ f"📁 **Paso 2:** Envía los videos de los capítulos. Puedes enviar varios de una vez.\n\n"
608
+ f"Esperando a más videos... ({len(videos)} recibidos)",
609
+ buttons=[
610
+ [Button.inline("📁 Terminar y confirmar", uid_done)],
611
+ [Button.inline("⬅️ Atrás (Editar Título)", uid_back)]
612
+ ]
613
+ )
614
+
615
+ debounce_task = None
616
+ async def update_button():
617
+ await asyncio.sleep(0.8)
618
+ nonlocal msg_v
619
+ try:
620
+ await msg_v.delete()
621
+ except Exception:
622
+ pass
623
+ msg_v = await conv.send_message(
624
+ f"📁 **Paso 2:** Envía los videos de los capítulos.\n\n"
625
+ f"Esperando a más videos... ({len(videos)} recibidos)",
626
+ buttons=[
627
+ [Button.inline("📁 Terminar y confirmar", uid_done)],
628
+ [Button.inline("⬅️ Atrás (Editar Título)", uid_back)]
629
+ ]
630
+ )
631
+
632
+ async def video_receiver(e):
633
+ is_video = False
634
+ if getattr(e, 'media', None):
635
+ if getattr(e, 'video', None):
636
+ is_video = True
637
+ elif getattr(e, 'document', None):
638
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
639
+ if mime.startswith('video/'):
640
+ is_video = True
641
+ else:
642
+ for attr in e.document.attributes:
643
+ if hasattr(attr, 'file_name'):
644
+ import os
645
+ ext = os.path.splitext(attr.file_name)[1].lower()
646
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
647
+ is_video = True
648
+ break
649
+
650
+ if is_video:
651
+ videos.append(e)
652
+ nonlocal debounce_task
653
+ if debounce_task:
654
+ debounce_task.cancel()
655
+ debounce_task = asyncio.create_task(update_button())
656
+
657
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
658
+
659
+ try:
660
+ while True:
661
+ event = await wait_for_message_or_callback(conv, timeout=3600)
662
+ if isinstance(event, events.CallbackQuery.Event):
663
+ if event.data == uid_done:
664
+ if not videos:
665
+ await event.answer("No has enviado ningún video aún.", alert=True)
666
+ else:
667
+ await event.answer("Videos confirmados")
668
+ if debounce_task:
669
+ debounce_task.cancel()
670
+ await msg_v.edit(f"📁 Se registraron {len(videos)} videos en total.", buttons=None)
671
+ step = 3
672
+ break
673
+ elif event.data == uid_back:
674
+ await event.answer("Volviendo atrás")
675
+ if debounce_task:
676
+ debounce_task.cancel()
677
+ await msg_v.edit("📁 Volviendo al Paso 1...", buttons=None)
678
+ step = 1
679
+ break
680
+ finally:
681
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
682
+
683
+ elif step == 3:
684
+ uid_title = str(uuid.uuid4()).encode()
685
+ uid_file = str(uuid.uuid4()).encode()
686
+ uid_back = str(uuid.uuid4()).encode()
687
+
688
+ sample_names = ""
689
+ for v in videos[:2]:
690
+ doc_name = "Video_desconocido.mp4"
691
+ if hasattr(v.media, 'document'):
692
+ for attr in v.media.document.attributes:
693
+ if hasattr(attr, 'file_name'):
694
+ doc_name = attr.file_name
695
+ break
696
+ sample_names += f"- {doc_name}\n"
697
+
698
+ msg_n = await conv.send_message(
699
+ "📁 **Paso 3:** ¿Qué nombre llevarán los capítulos?\n\n"
700
+ "Escribe un nombre base y se enumerarán automáticamente.\n\n"
701
+ f"Por ejemplo, si escribes un nombre o usas el botón **Usar nombre del título general** (`{series_title}`), se nombrarán así:\n"
702
+ f"- {series_title} - Capítulo 1\n"
703
+ f"- {series_title} - Capítulo 2\n"
704
+ f"- {series_title} - Capítulo 3\n\n"
705
+ "Si usas el botón **Usar nombres originales de los archivos**, se usarán los nombres reales que acabas de subir:\n"
706
+ f"{sample_names}\n"
707
+ "Elige un atajo rápido o escribe tu propio nombre base:",
708
+ buttons=[
709
+ [Button.inline("📁 Usar nombre del título general", uid_title)],
710
+ [Button.inline("📁 Usar nombres originales de los archivos", uid_file)],
711
+ [Button.inline("⬅️ Atrás (Añadir más videos)", uid_back)]
712
+ ]
713
+ )
714
+
715
+ while True:
716
+ event = await wait_for_message_or_callback(conv, timeout=300)
717
+ if isinstance(event, events.CallbackQuery.Event):
718
+ if event.data == uid_title:
719
+ naming_strategy = "title"
720
+ await msg_n.edit(f"📁 Formato: **{series_title} - Capítulo X**", buttons=None)
721
+ step = 3.5
722
+ break
723
+ elif event.data == uid_file:
724
+ naming_strategy = "file"
725
+ await msg_n.edit("📁 Formato: **Nombres originales de los archivos**", buttons=None)
726
+ step = 3.5
727
+ break
728
+ elif event.data == uid_back:
729
+ await event.answer("Volviendo atrás")
730
+ await msg_n.edit("📁 Volviendo al Paso 2...", buttons=None)
731
+ step = 2
732
+ break
733
+ else:
734
+ await event.answer("Botón expirado", alert=True)
735
+ else:
736
+ naming_strategy = "manual"
737
+ manual_prefix = event.raw_text.strip()
738
+ await msg_n.edit(f"📁 Formato Manual: **{manual_prefix} - Capítulo 1, ...**", buttons=None)
739
+ step = 3.5
740
+ break
741
+
742
+ elif step == 3.5:
743
+ uid_desc_video = str(uuid.uuid4()).encode()
744
+ uid_skip = str(uuid.uuid4()).encode()
745
+ uid_back = str(uuid.uuid4()).encode()
746
+ msg_d = await conv.send_message(
747
+ "📁 **Paso 3.5:** Escribe una **Descripción** (se usará la misma para todos los capítulos).\n\n"
748
+ "Opcional: puedes extraer la descripción original de cada video, o simplemente omitir este paso.",
749
+ buttons=[
750
+ [Button.inline("📁 Usar descripción de cada video", uid_desc_video)],
751
+ [Button.inline("📁 Omitir", uid_skip)],
752
+ [Button.inline("⬅️ Atrás (Editar Nombre Capítulos)", uid_back)]
753
+ ]
754
+ )
755
+
756
+ while True:
757
+ event = await wait_for_message_or_callback(conv, timeout=300)
758
+ if isinstance(event, events.CallbackQuery.Event):
759
+ if event.data == uid_desc_video:
760
+ desc_strategy = "video"
761
+ await msg_d.edit("📁 Descripción: **Se usará la de cada video**", buttons=None)
762
+ step = 4
763
+ break
764
+ elif event.data == uid_skip:
765
+ desc_strategy = "skip"
766
+ await msg_d.edit("📁 Descripción: **(Omitida)**", buttons=None)
767
+ step = 4
768
+ break
769
+ elif event.data == uid_back:
770
+ await event.answer("Volviendo atrás")
771
+ await msg_d.edit("📁 Volviendo al Paso 3...", buttons=None)
772
+ step = 3
773
+ break
774
+ else:
775
+ await event.answer("Botón expirado", alert=True)
776
+ else:
777
+ desc_strategy = "manual"
778
+ desc_text = event.raw_text
779
+ await msg_d.edit(f"📁 Descripción: **{desc_text[:30]}...**", buttons=None)
780
+ step = 4
781
+ break
782
+
783
+ elif step == 4:
784
+ uid_skip = str(uuid.uuid4()).encode()
785
+ uid_back = str(uuid.uuid4()).encode()
786
+ msg_c = await conv.send_message(
787
+ "📁 **Paso 4:** Envía la **Portada** de la serie (solo como imagen):",
788
+ buttons=[
789
+ [Button.inline("📁 Omitir", uid_skip)],
790
+ [Button.inline("⬅️ Atrás (Editar Descripción)", uid_back)]
791
+ ]
792
+ )
793
+
794
+ while True:
795
+ event = await wait_for_message_or_callback(conv, timeout=300)
796
+ if isinstance(event, events.CallbackQuery.Event):
797
+ if event.data == uid_skip:
798
+ await event.answer("Omitido")
799
+ await msg_c.edit("📁 Portada: **(Omitida)**", buttons=None)
800
+ resp_cover = None
801
+ cover_url = ""
802
+ step = 5
803
+ break
804
+ elif event.data == uid_back:
805
+ await event.answer("Volviendo atrás")
806
+ await msg_c.edit("📁 Volviendo al Paso 3.5...", buttons=None)
807
+ step = 3.5
808
+ break
809
+ else:
810
+ await event.answer("Botón expirado", alert=True)
811
+ elif getattr(event, 'photo', None):
812
+ await msg_c.edit("📁 Subiendo portada...", buttons=None)
813
+ cover_url = await upload_to_imgbb(event.photo)
814
+ resp_cover = event
815
+ step = 5
816
+ break
817
+ else:
818
+ await conv.send_message("📁 Por favor, envía una IMAGEN, o presiona Omitir/Atrás.")
819
+
820
+ # 5. Guardado en Firebase y reenvío
821
+ status_msg = await conv.send_message("📁 **Procesando y subiendo los capítulos...**")
822
+ try:
823
+ asyncio.current_task().is_uploading = True
824
+ if resp_cover and getattr(resp_cover, 'photo', None):
825
+ try:
826
+ await client.send_file(CHANNEL_ID, resp_cover.photo, caption=f"📁 **Portada Serie:** {series_title}")
827
+ except Exception as e:
828
+ print(f"Error enviando portada de serie al canal: {e}")
829
+
830
+ # Buscar serie existente para asegurar nombre único
831
+ original_title = series_title
832
+ counter = 1
833
+
834
+ while True:
835
+ series_query = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).where(filter=FieldFilter('title', '==', series_title)).get()
836
+ if series_query:
837
+ counter += 1
838
+ series_title = f"{original_title} {counter}"
839
+ else:
840
+ break
841
+
842
+ _, doc_ref = db.collection('videos').add({
843
+ "title": series_title,
844
+ "section": "series",
845
+ "is_folder": True,
846
+ "thumbnail_url": cover_url,
847
+ "categories": [],
848
+ "created_at": firestore.SERVER_TIMESTAMP,
849
+ "updated_at": firestore.SERVER_TIMESTAMP
850
+ })
851
+ series_id = doc_ref.id
852
+
853
+ for i, video_msg in enumerate(videos):
854
+ current_num = i + 1
855
+
856
+ # Nombre
857
+ if naming_strategy == "title":
858
+ ep_title = f"{series_title} - Capítulo {i+1}"
859
+ elif naming_strategy == "manual":
860
+ ep_title = f"{manual_prefix} - Capítulo {i+1}"
861
+ else:
862
+ doc_name = "Episodio"
863
+ if hasattr(video_msg.media, 'document'):
864
+ for attr in video_msg.media.document.attributes:
865
+ if hasattr(attr, 'file_name'):
866
+ import os
867
+ doc_name = os.path.splitext(attr.file_name)[0]
868
+ break
869
+ ep_title = doc_name
870
+
871
+ # Descripción
872
+ if desc_strategy == "video":
873
+ ep_desc = video_msg.raw_text if getattr(video_msg, 'raw_text', None) else ""
874
+ elif desc_strategy == "skip":
875
+ ep_desc = ""
876
+ else:
877
+ ep_desc = desc_text
878
+
879
+ await status_msg.edit(f"📁 Subiendo: **{ep_title}** ({i+1}/{len(videos)})")
880
+
881
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Serie:** {series_title}\n📁 **Episodio:** {ep_title}"
882
+ if ep_desc:
883
+ caption += f"\n📁 {ep_desc}"
884
+
885
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
886
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
887
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
888
+
889
+ db.collection('videos').add({
890
+ "title": ep_title,
891
+ "section": "series",
892
+ "is_folder": False,
893
+ "folder_id": series_id,
894
+ "episode": current_num,
895
+ "season": 1,
896
+ "video_url": file_url,
897
+ "telegram_file_id": str(sent_to_channel.id),
898
+ "description": ep_desc,
899
+ "thumbnail_url": "",
900
+ "cover_url": "",
901
+ "views": 0,
902
+ "rating": 0,
903
+ "status": "active",
904
+ "is_public": True,
905
+ "categories": [],
906
+ "servers": [file_url],
907
+ "created_at": firestore.SERVER_TIMESTAMP,
908
+ "updated_at": firestore.SERVER_TIMESTAMP
909
+ })
910
+
911
+ await status_msg.edit(f"📁 **¡Completado! {len(videos)} capítulos de '{series_title}' se han subido con éxito.**")
912
+
913
+ except Exception as e:
914
+ print(f"📁 Error al procesar serie: {e}")
915
+ await status_msg.edit(f"📁 **Error al subir los capítulos:** {e}")
916
+
917
+
918
+
919
+ # --- CONFIGURACIÓN Y FUNCIONES DE BÚSQUEDA POR ID ---
920
+
921
+ bot_settings = {
922
+ "send_title": True,
923
+ "send_description": True,
924
+ "ask_series": True
925
+ }
926
+
927
+ try:
928
+ doc_settings = db.collection('settings').document('delivery').get()
929
+ if doc_settings.exists:
930
+ s_data = doc_settings.to_dict()
931
+ bot_settings['send_title'] = s_data.get('send_title', True)
932
+ bot_settings['send_description'] = s_data.get('send_description', True)
933
+ bot_settings['ask_series'] = s_data.get('ask_series', True)
934
+ except Exception as e:
935
+ print(f"📁 Error cargando settings: {e}")
936
+
937
+ @client.on(events.NewMessage(pattern='/(settings|setting|config)$'))
938
+ async def settings_handler(event):
939
+ await show_settings_menu(event)
940
+
941
+ async def show_settings_menu(event_or_query):
942
+ title_status = "✅ PRENDIDO" if bot_settings['send_title'] else "❌ APAGADO"
943
+ desc_status = "✅ PRENDIDO" if bot_settings['send_description'] else "❌ APAGADO"
944
+ ask_status = "✅ PRENDIDO" if bot_settings['ask_series'] else "❌ APAGADO"
945
+
946
+ botones = [
947
+ [Button.inline(f"Título: {title_status}", b"toggle_title")],
948
+ [Button.inline(f"Descripción: {desc_status}", b"toggle_desc")],
949
+ [Button.inline(f"Preguntar Temporada/Capítulo: {ask_status}", b"toggle_ask")]
950
+ ]
951
+
952
+ text = "⚙️ **Configuración de Envío de Videos**\n\nElige cómo quieres que el bot entregue los videos:"
953
+
954
+ if isinstance(event_or_query, events.CallbackQuery.Event):
955
+ await event_or_query.edit(text, buttons=botones)
956
+ else:
957
+ await event_or_query.respond(text, buttons=botones)
958
+
959
+ from telethon.tl.types import KeyboardButtonWebView
960
+
961
+ @client.on(events.NewMessage(pattern='/(twistedstreamingbrodybot|app)$'))
962
+ async def miniapp_handler(event):
963
+ # Usamos KeyboardButtonWebView para forzar a Telegram a abrirlo como Mini App
964
+ botones = [[KeyboardButtonWebView(text="🍿 Abrir Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")]]
965
+
966
+ await event.respond(
967
+ "🍿 **¡Twisted Streaming Brody!**\n\nToca el botón abajo para abrir nuestra Mini App y navegar por todas las películas y series directamente desde Telegram.",
968
+ buttons=botones
969
+ )
970
+
971
+ button_cooldowns = {}
972
+
973
+ @client.on(events.CallbackQuery(pattern=b'^toggle_(title|desc|ask)$'))
974
+ async def toggle_settings_handler(event):
975
+ chat_id = event.chat_id
976
+ now = time.time()
977
+ if now - button_cooldowns.get(chat_id, 0) < 0.5:
978
+ await event.answer()
979
+ return
980
+ button_cooldowns[chat_id] = now
981
+
982
+ action = event.pattern_match.group(1).decode()
983
+ if action == 'title':
984
+ bot_settings['send_title'] = not bot_settings['send_title']
985
+ elif action == 'desc':
986
+ bot_settings['send_description'] = not bot_settings['send_description']
987
+ elif action == 'ask':
988
+ bot_settings['ask_series'] = not bot_settings['ask_series']
989
+
990
+ try:
991
+ db.collection('settings').document('delivery').set(bot_settings)
992
+ except: pass
993
+
994
+ await event.answer()
995
+ await show_settings_menu(event)
996
+
997
+ async def send_movie(chat_id, file_id, data):
998
+ cover = data.get('cover_url') or data.get('thumbnail_url')
999
+ caption_parts = []
1000
+ if bot_settings['send_title'] and data.get('title'):
1001
+ caption_parts.append(f"📁 **{data.get('title')}**")
1002
+ if bot_settings['send_description'] and data.get('description'):
1003
+ caption_parts.append(f"{data.get('description')}")
1004
+
1005
+ custom_caption = "\n\n".join(caption_parts)
1006
+
1007
+ if cover:
1008
+ try:
1009
+ await client.send_file(chat_id, cover, caption=custom_caption)
1010
+ except Exception:
1011
+ if custom_caption: await client.send_message(chat_id, custom_caption)
1012
+ elif custom_caption:
1013
+ await client.send_message(chat_id, custom_caption)
1014
+
1015
+ try:
1016
+ msg = await client.get_messages(CHANNEL_ID, ids=int(file_id))
1017
+ if msg and getattr(msg, 'media', None):
1018
+ await client.send_file(chat_id, msg.media, caption="")
1019
+ else:
1020
+ await client.send_message(chat_id, "📁 Video no encontrado en el canal.")
1021
+ except Exception as e:
1022
+ print("Error enviando película:", e)
1023
+
1024
+ async def send_series_cover(chat_id, folder_id):
1025
+ if not folder_id: return
1026
+ try:
1027
+ s_doc = db.collection('videos').document(folder_id).get()
1028
+ if s_doc.exists:
1029
+ s_data = s_doc.to_dict()
1030
+ cover = s_data.get('thumbnail_url') or s_data.get('cover_url')
1031
+
1032
+ caption = ""
1033
+ if bot_settings['send_title'] and s_data.get('title'):
1034
+ caption = f"📁 **{s_data.get('title')}**"
1035
+
1036
+ if cover:
1037
+ try:
1038
+ await client.send_file(chat_id, cover, caption=caption)
1039
+ except Exception:
1040
+ if caption: await client.send_message(chat_id, caption)
1041
+ elif caption:
1042
+ await client.send_message(chat_id, caption)
1043
+ except Exception as e:
1044
+ print("Error al enviar portada de serie:", e)
1045
+
1046
+ async def send_episode_video(chat_id, file_id, ep_data):
1047
+ try:
1048
+ msg = await client.get_messages(CHANNEL_ID, ids=int(file_id))
1049
+ if not msg or not getattr(msg, 'media', None):
1050
+ await client.send_message(chat_id, "📁 Capítulo no encontrado en el canal.")
1051
+ return
1052
+
1053
+ caption_parts = []
1054
+ if bot_settings['send_title'] and ep_data.get('title'):
1055
+ caption_parts.append(f"📁 **{ep_data.get('title')}**")
1056
+ if bot_settings['send_description'] and ep_data.get('description'):
1057
+ caption_parts.append(f"{ep_data.get('description')}")
1058
+
1059
+ custom_caption = "\n\n".join(caption_parts)
1060
+ await client.send_file(chat_id, msg.media, caption=custom_caption)
1061
+ except Exception as e:
1062
+ print("Error enviando capítulo:", e)
1063
+
1064
+ async def send_full_season(chat_id, folder_id, status_msg=None):
1065
+ if not status_msg:
1066
+ status_msg = await client.send_message(chat_id, "📁 Preparando los capítulos...")
1067
+ else:
1068
+ try:
1069
+ await status_msg.edit("📁 Preparando los capítulos...", buttons=None)
1070
+ except Exception:
1071
+ pass
1072
+
1073
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', folder_id)).get()
1074
+ if not episodes:
1075
+ await status_msg.edit("📁 No se encontraron capítulos.")
1076
+ return
1077
+
1078
+ await send_series_cover(chat_id, folder_id)
1079
+
1080
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
1081
+ for ep in episodes_sorted:
1082
+ data = ep.to_dict()
1083
+ file_id = data.get('telegram_file_id')
1084
+ if file_id:
1085
+ await send_episode_video(chat_id, file_id, data)
1086
+ await asyncio.sleep(0.5)
1087
+ await status_msg.edit("📁 **¡Temporada enviada!**")
1088
+
1089
+ @client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
1090
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
1091
+ async def handle_document_id(event):
1092
+ if editor_mode_active.get(event.chat_id, False):
1093
+ return
1094
+
1095
+ if not search_mode_active.get(event.chat_id, False):
1096
+ return # Ignore links/IDs if search mode is OFF
1097
+
1098
+ text = event.raw_text.strip()
1099
+ is_folder_request = False
1100
+
1101
+ if text.startswith('/start '):
1102
+ payload = text.split(' ')[1]
1103
+ if payload.startswith('folder_'):
1104
+ is_folder_request = True
1105
+ doc_id = payload.replace('folder_', '', 1)
1106
+ else:
1107
+ doc_id = payload
1108
+ else:
1109
+ if text.startswith('folder/') or text.startswith('folder_'):
1110
+ is_folder_request = True
1111
+ doc_id = text.replace('folder/', '', 1).replace('folder_', '', 1)
1112
+ else:
1113
+ doc_id = text
1114
+
1115
+ try:
1116
+ doc = db.collection('videos').document(doc_id).get()
1117
+ if not doc.exists:
1118
+ return
1119
+
1120
+ data = doc.to_dict()
1121
+ section = data.get('section')
1122
+ is_folder = data.get('is_folder')
1123
+
1124
+ if section == 'peliculas':
1125
+ file_id = data.get('telegram_file_id')
1126
+ if file_id:
1127
+ await send_movie(event.chat_id, file_id, data)
1128
+ else:
1129
+ await event.respond("📁 No se encontró el archivo en Telegram para esta película.")
1130
+
1131
+ elif section == 'series':
1132
+ folder_id = doc_id if is_folder else data.get('folder_id')
1133
+
1134
+ if is_folder_request:
1135
+ await send_full_season(event.chat_id, folder_id)
1136
+ return
1137
+
1138
+ if not bot_settings.get('ask_series', True):
1139
+ if is_folder:
1140
+ await send_full_season(event.chat_id, folder_id)
1141
+ else:
1142
+ file_id = data.get('telegram_file_id')
1143
+ if file_id:
1144
+ await send_series_cover(event.chat_id, folder_id)
1145
+ await send_episode_video(event.chat_id, file_id, data)
1146
+ else:
1147
+ await event.respond("📁 Archivo no encontrado.")
1148
+ return
1149
+
1150
+ if is_folder:
1151
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', doc_id)).get()
1152
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
1153
+
1154
+ botones = []
1155
+ row = []
1156
+ for ep in episodes_sorted:
1157
+ ep_data = ep.to_dict()
1158
+ ep_num = ep_data.get('episode', '?')
1159
+ ep_id = ep.id
1160
+ row.append(Button.inline(f"Cap {ep_num}", f"this_cap_{ep_id}".encode()))
1161
+ if len(row) == 3:
1162
+ botones.append(row)
1163
+ row = []
1164
+ if row:
1165
+ botones.append(row)
1166
+
1167
+ botones.append([Button.inline("📁 Enviar Temporada Completa", f"all_caps_{doc_id}".encode())])
1168
+
1169
+ await event.respond(f"📁 **Serie:** {data.get('title')}\nSelecciona un capítulo o envía la temporada completa:", buttons=botones)
1170
+ else:
1171
+ botones = [
1172
+ [Button.inline("📁 Enviar solo este video", f"this_cap_{doc_id}".encode())],
1173
+ [Button.inline("📁 Enviar Temporada Completa", f"all_caps_{folder_id}".encode())]
1174
+ ]
1175
+ await event.respond(f"📁 **Capítulo:** {data.get('title')}\n¿Qué deseas hacer?", buttons=botones)
1176
+
1177
+ except Exception as e:
1178
+ print(f"Error buscando documento {doc_id}: {e}")
1179
+
1180
+ @client.on(events.CallbackQuery(pattern=b'^(this_cap_|all_caps_|choose_cap_)(.*)'))
1181
+ async def handle_series_delivery(event):
1182
+ chat_id = event.chat_id
1183
+ now = time.time()
1184
+ if now - button_cooldowns.get(chat_id, 0) < 1.0:
1185
+ await event.answer("Procesando...", alert=False)
1186
+ return
1187
+ button_cooldowns[chat_id] = now
1188
+
1189
+ action = event.pattern_match.group(1).decode()
1190
+ target_id = event.pattern_match.group(2).decode()
1191
+
1192
+ try:
1193
+ if action == "this_cap_":
1194
+ await event.answer("📁 Enviando capítulo...", alert=False)
1195
+ doc = db.collection('videos').document(target_id).get()
1196
+ if doc.exists:
1197
+ data = doc.to_dict()
1198
+ file_id = data.get('telegram_file_id')
1199
+ folder_id = data.get('folder_id')
1200
+ if file_id:
1201
+ await send_series_cover(event.chat_id, folder_id)
1202
+ await send_episode_video(event.chat_id, file_id, data)
1203
+ else:
1204
+ await event.respond("📁 Archivo no encontrado.")
1205
+
1206
+ elif action == "all_caps_":
1207
+ await event.answer("📁 Preparando temporada...", alert=False)
1208
+ await send_full_season(chat_id, target_id, status_msg=event)
1209
+
1210
+ elif action == "choose_cap_":
1211
+ await event.answer("📁 Cargando capítulos...", alert=False)
1212
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', target_id)).get()
1213
+ if not episodes:
1214
+ await event.answer("No se encontraron capítulos.", alert=True)
1215
+ return
1216
+
1217
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
1218
+
1219
+ botones = []
1220
+ row = []
1221
+ for ep in episodes_sorted:
1222
+ data = ep.to_dict()
1223
+ ep_num = data.get('episode', '?')
1224
+ ep_id = ep.id
1225
+ row.append(Button.inline(f"Cap {ep_num}", f"this_cap_{ep_id}".encode()))
1226
+ if len(row) == 3:
1227
+ botones.append(row)
1228
+ row = []
1229
+ if row:
1230
+ botones.append(row)
1231
+
1232
+ await event.edit("📁 **Selecciona el capítulo:**", buttons=botones)
1233
+
1234
+ except Exception as e:
1235
+ print(f"Error en delivery: {e}")
1236
+ await event.respond("📁 Hubo un error procesando la solicitud.")
1237
+
1238
+
1239
+ # --- MODO EDITOR ---
1240
+ @client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
1241
+ async def enable_editor(event):
1242
+ import asyncio
1243
+ chat_id = event.chat_id
1244
+
1245
+ # Cancel previous tasks to prevent "Botón expirado" background overlap
1246
+ if chat_id in active_tasks:
1247
+ for old_task in active_tasks[chat_id]:
1248
+ if not old_task.done():
1249
+ if not getattr(old_task, 'is_uploading', False):
1250
+ old_task.cancel()
1251
+ try: await asyncio.sleep(0.1)
1252
+ except: pass
1253
+
1254
+ current_task = asyncio.current_task()
1255
+ current_task.is_uploading = False
1256
+
1257
+ if chat_id not in active_tasks:
1258
+ active_tasks[chat_id] = []
1259
+ active_tasks[chat_id].append(current_task)
1260
+
1261
+ editor_mode_active[chat_id] = True
1262
+ try:
1263
+ await handle_editor_mode(event)
1264
+ finally:
1265
+ if current_task in active_tasks.get(chat_id, []):
1266
+ active_tasks[chat_id].remove(current_task)
1267
+ if not active_tasks[chat_id]:
1268
+ del active_tasks[chat_id]
1269
+
1270
+
1271
+ @client.on(events.NewMessage(pattern='/(desactivar_modo_editor)$'))
1272
+ async def disable_editor(event):
1273
+ chat_id = event.chat_id
1274
+ editor_mode_active[chat_id] = False
1275
+ await event.respond("✅ **Modo editor desactivado.** Ya puedes usar los comandos normales.")
1276
+
1277
+ async def process_editor_id(conv, txt):
1278
+ doc = db.collection('videos').document(txt).get()
1279
+ if doc.exists:
1280
+ data = doc.to_dict()
1281
+ if data.get('section') == 'peliculas':
1282
+ await handle_editor_movie_action(conv, txt)
1283
+ elif data.get('is_folder', False):
1284
+ await handle_editor_series_action(conv, txt)
1285
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
1286
+ await handle_editor_single_chapter(conv, txt)
1287
+ else:
1288
+ await conv.send_message("❌ Tipo de documento no reconocido.")
1289
+ else:
1290
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
1291
+
1292
+ async def handle_editor_mode(event):
1293
+ chat_id = event.chat_id
1294
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
1295
+ current_jump_id = None
1296
+ last_msg = None
1297
+
1298
+ while editor_mode_active.get(chat_id, False):
1299
+ try:
1300
+ if current_jump_id:
1301
+ jump = current_jump_id
1302
+ current_jump_id = None
1303
+ if last_msg:
1304
+ try: await last_msg.delete()
1305
+ except: pass
1306
+ await process_editor_id(conv, jump)
1307
+ continue # Go back to start of loop
1308
+
1309
+ last_msg = await conv.send_message(
1310
+ "🛠️ **Modo Editor Activado**\n\n¿Qué deseas gestionar?",
1311
+ buttons=[
1312
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
1313
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
1314
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
1315
+ ]
1316
+ )
1317
+
1318
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
1319
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
1320
+ break
1321
+
1322
+ if isinstance(resp, events.CallbackQuery.Event):
1323
+ await resp.answer()
1324
+ try: await last_msg.delete()
1325
+ except: pass
1326
+
1327
+ if resp.data == b"ed_exit":
1328
+ editor_mode_active[chat_id] = False
1329
+ await conv.send_message("✅ **Modo editor desactivado.**")
1330
+ break
1331
+ elif resp.data == b"ed_mov":
1332
+ await handle_editor_movie_search(conv)
1333
+ elif resp.data == b"ed_ser":
1334
+ await handle_editor_series_search(conv)
1335
+
1336
+ elif getattr(resp, 'raw_text', ''):
1337
+ txt = resp.raw_text.strip()
1338
+ if txt.startswith('/start '):
1339
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
1340
+
1341
+ if txt.startswith('/'):
1342
+ if txt == '/desactivar_modo_editor':
1343
+ break
1344
+ continue
1345
+
1346
+ try: await last_msg.delete()
1347
+ except: pass
1348
+
1349
+ await process_editor_id(conv, txt)
1350
+
1351
+ except EditorJumpException as e:
1352
+ # A jump occurred from anywhere (main menu or submenu)! Loop back and handle it.
1353
+ current_jump_id = e.jump_id
1354
+ except Exception as e:
1355
+ print("Editor error:", e)
1356
+ break
1357
+
1358
+ async def handle_editor_movie_search(conv):
1359
+ from telethon.tl.types import KeyboardButtonSimpleWebView
1360
+ uid_back = str(uuid.uuid4()).encode()
1361
+ btn_webapp = KeyboardButtonSimpleWebView(text="🍿 Buscar ID en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
1362
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la película que deseas buscar:", buttons=[
1363
+ [btn_webapp],
1364
+ [Button.inline("⬅️ Cancelar", uid_back)]
1365
+ ])
1366
+
1367
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1368
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
1369
+ await resp.answer("Cancelado")
1370
+ await msg.edit("Búsqueda cancelada.", buttons=None)
1371
+ return
1372
+
1373
+ query = resp.raw_text.strip()
1374
+ await msg.delete()
1375
+
1376
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
1377
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower() or query == m.id]
1378
+
1379
+ if not results:
1380
+ await conv.send_message("❌ No se encontraron películas con ese nombre.")
1381
+ return
1382
+
1383
+ results = results[:10]
1384
+ buttons = []
1385
+ for r in results:
1386
+ data = r.to_dict()
1387
+ buttons.append([Button.inline(f"🎬 {data.get('title')[:30]}", f"ed_m_{r.id}".encode('utf-8'))])
1388
+
1389
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
1390
+
1391
+ msg_res = await conv.send_message("📌 **Resultados (Películas):**", buttons=buttons)
1392
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
1393
+
1394
+ if isinstance(resp_res, events.CallbackQuery.Event):
1395
+ await resp_res.answer()
1396
+ await msg_res.edit(buttons=None)
1397
+ if resp_res.data == b"ed_back": return
1398
+
1399
+ movie_id = resp_res.data.decode().replace('ed_m_', '')
1400
+ await handle_editor_movie_action(conv, movie_id)
1401
+
1402
+ async def handle_editor_movie_action(conv, movie_id):
1403
+ doc = db.collection('videos').document(movie_id).get()
1404
+ if not doc.exists: return
1405
+ data = doc.to_dict()
1406
+
1407
+ msg = await conv.send_message(
1408
+ f"🎬 **Editando Película:**\n`{data.get('title')}`",
1409
+ buttons=[
1410
+ [Button.inline("✏️ Renombrar Título", b"renombrar")],
1411
+ [Button.inline("📝 Editar Descripción", b"edit_desc")],
1412
+ [Button.inline("🗑️ Eliminar Película", b"eliminar")],
1413
+ [Button.inline("⬅️ Volver", b"volver")]
1414
+ ]
1415
+ )
1416
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1417
+ if isinstance(resp, events.CallbackQuery.Event):
1418
+ await resp.answer()
1419
+ await msg.edit(buttons=None)
1420
+ if resp.data == b"volver": return
1421
+ elif resp.data == b"renombrar":
1422
+ await conv.send_message("Escribe el **nuevo título** para la película:")
1423
+ new_title = await conv.get_response()
1424
+ db.collection('videos').document(movie_id).update({"title": new_title.raw_text})
1425
+ await conv.send_message(f"✅ Título actualizado a: **{new_title.raw_text}**")
1426
+ elif resp.data == b"edit_desc":
1427
+ uid_del = str(uuid.uuid4()).encode()
1428
+ msg_d = await conv.send_message("Escribe la **nueva descripción** para la película:", buttons=[[Button.inline("❌ Eliminar Descripción", uid_del)]])
1429
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
1430
+ if isinstance(resp_d, events.CallbackQuery.Event):
1431
+ await resp_d.answer("Eliminando...")
1432
+ db.collection('videos').document(movie_id).update({"description": ""})
1433
+ await msg_d.edit("✅ Descripción eliminada.", buttons=None)
1434
+ else:
1435
+ db.collection('videos').document(movie_id).update({"description": resp_d.raw_text})
1436
+ await msg_d.edit("✅ Descripción actualizada.", buttons=None)
1437
+ elif resp.data == b"eliminar":
1438
+ msg_conf = await conv.send_message(
1439
+ f"⚠️ ¿Estás seguro de que deseas eliminar la película **{data.get('title')}**?\nEsta acción no se puede deshacer.",
1440
+ buttons=[
1441
+ [Button.inline("⚠️ Sí, eliminar definitivamente", b"confirm_del")],
1442
+ [Button.inline("❌ Cancelar", b"cancel_del")]
1443
+ ]
1444
+ )
1445
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
1446
+ if isinstance(resp_conf, events.CallbackQuery.Event):
1447
+ await resp_conf.answer()
1448
+ await msg_conf.edit(buttons=None)
1449
+ if resp_conf.data == b"confirm_del":
1450
+ db.collection('videos').document(movie_id).delete()
1451
+ await conv.send_message("✅ Película eliminada exitosamente.")
1452
+ else:
1453
+ await conv.send_message("✅ Eliminación cancelada.")
1454
+
1455
+ async def handle_editor_series_search(conv):
1456
+ from telethon.tl.types import KeyboardButtonSimpleWebView
1457
+ uid_back = str(uuid.uuid4()).encode()
1458
+ btn_webapp = KeyboardButtonSimpleWebView(text="🍿 Buscar ID en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
1459
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la serie que deseas buscar:", buttons=[
1460
+ [btn_webapp],
1461
+ [Button.inline("⬅️ Cancelar", uid_back)]
1462
+ ])
1463
+
1464
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1465
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
1466
+ await resp.answer()
1467
+ await msg.edit("Búsqueda cancelada.", buttons=None)
1468
+ return
1469
+
1470
+ query = resp.raw_text.strip()
1471
+ await msg.delete()
1472
+
1473
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
1474
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower() or query == s.id]
1475
+
1476
+ if not results:
1477
+ await conv.send_message("❌ No se encontraron series con ese nombre.")
1478
+ return
1479
+
1480
+ results = results[:10]
1481
+ buttons = []
1482
+ for r in results:
1483
+ buttons.append([Button.inline(f"📺 {r.to_dict().get('title')[:30]}", f"ed_s_{r.id}".encode('utf-8'))])
1484
+
1485
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
1486
+
1487
+ msg_res = await conv.send_message("📌 **Resultados (Series):**", buttons=buttons)
1488
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
1489
+
1490
+ if isinstance(resp_res, events.CallbackQuery.Event):
1491
+ await resp_res.answer()
1492
+ await msg_res.edit(buttons=None)
1493
+ if resp_res.data == b"ed_back": return
1494
+
1495
+ series_id = resp_res.data.decode().replace('ed_s_', '')
1496
+ await handle_editor_series_action(conv, series_id)
1497
+
1498
+ async def handle_editor_series_action(conv, series_id):
1499
+ while editor_mode_active.get(conv.chat_id, False):
1500
+ doc = db.collection('videos').document(series_id).get()
1501
+ if not doc.exists: return
1502
+ data = doc.to_dict()
1503
+ title = data.get('title')
1504
+
1505
+ msg = await conv.send_message(
1506
+ f"📺 **Editando Serie:**\n`{title}`",
1507
+ buttons=[
1508
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
1509
+ [Button.inline("📝 Edición Masiva de Descripciones", b"edit_desc_masiva")],
1510
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
1511
+ [Button.inline("📝 Edición Masiva de Capítulos", b"editar_lista")],
1512
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
1513
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
1514
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
1515
+ ]
1516
+ )
1517
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
1518
+ if getattr(resp, 'raw_text', '').startswith('/'): return
1519
+
1520
+ if isinstance(resp, events.CallbackQuery.Event):
1521
+ await resp.answer()
1522
+ await msg.edit(buttons=None)
1523
+
1524
+ if resp.data == b"volver": return
1525
+ elif resp.data == b"renombrar":
1526
+ await conv.send_message("Escribe el **nuevo título general** para la serie:")
1527
+ new_title = await conv.get_response()
1528
+ db.collection('videos').document(series_id).update({"title": new_title.raw_text})
1529
+ await conv.send_message(f"✅ Título general actualizado a: **{new_title.raw_text}**")
1530
+ elif resp.data == b"edit_desc_masiva":
1531
+ uid_del = str(uuid.uuid4()).encode()
1532
+ msg_d = await conv.send_message("Escribe la **nueva descripción** para aplicarla a TODOS los capítulos de esta serie:", buttons=[[Button.inline("❌ Eliminar Todas las Descripciones", uid_del)]])
1533
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
1534
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1535
+ updated_count = 0
1536
+
1537
+ if isinstance(resp_d, events.CallbackQuery.Event):
1538
+ await resp_d.answer("Eliminando...")
1539
+ for c in caps:
1540
+ db.collection('videos').document(c.id).update({"description": ""})
1541
+ updated_count += 1
1542
+ await msg_d.edit(f"✅ Descripciones eliminadas masivamente en {updated_count} capítulos.", buttons=None)
1543
+ else:
1544
+ for c in caps:
1545
+ db.collection('videos').document(c.id).update({"description": resp_d.raw_text})
1546
+ updated_count += 1
1547
+ await msg_d.edit(f"✅ Descripción aplicada masivamente a {updated_count} capítulos.", buttons=None)
1548
+ elif resp.data == b"eliminar":
1549
+ msg_conf = await conv.send_message(
1550
+ f"⚠️ ¿Estás seguro de que deseas eliminar la serie completa **{title}** y **TODOS** sus capítulos?\nEsta acción no se puede deshacer.",
1551
+ buttons=[
1552
+ [Button.inline("⚠️ Sí, eliminar serie y capítulos", b"confirm_del")],
1553
+ [Button.inline("❌ Cancelar", b"cancel_del")]
1554
+ ]
1555
+ )
1556
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
1557
+ if isinstance(resp_conf, events.CallbackQuery.Event):
1558
+ await resp_conf.answer()
1559
+ await msg_conf.edit(buttons=None)
1560
+ if resp_conf.data == b"confirm_del":
1561
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1562
+ for c in caps: db.collection('videos').document(c.id).delete()
1563
+ db.collection('videos').document(series_id).delete()
1564
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados exitosamente.")
1565
+ return
1566
+ else:
1567
+ await conv.send_message("✅ Eliminación cancelada.")
1568
+ elif resp.data == b"ver_caps":
1569
+ await handle_editor_series_chapters(conv, series_id, title)
1570
+ elif resp.data == b"editar_lista":
1571
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1572
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
1573
+ if not caps:
1574
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
1575
+ continue
1576
+
1577
+ template = f"{{TITULO_GENERAL}} {title}\n\n"
1578
+ for c in caps:
1579
+ template += f"{{{c.id}}} {c.to_dict().get('title')}\n"
1580
+
1581
+ await conv.send_message(
1582
+ "📝 **EDICIÓN MASIVA**\n\n"
1583
+ "1. Toca el siguiente mensaje para copiarlo.\n"
1584
+ "2. Pégalo en el chat y edita el nombre de la serie o de los capítulos como desees.\n"
1585
+ "3. Envíamelo.\n\n"
1586
+ "⚠️ **MUY IMPORTANTE:** ¡NO borres ni modifiques los códigos entre llaves `{ }`!"
1587
+ )
1588
+ await conv.send_message(f"```{template}```")
1589
+
1590
+ await conv.send_message("⏳ Esperando tu mensaje con la plantilla editada... (O envía `/cancelar` para abortar)")
1591
+
1592
+ resp_text = await wait_for_message_or_callback(conv, timeout=3600)
1593
+ if isinstance(resp_text, events.CallbackQuery.Event):
1594
+ await resp_text.answer("Operación cancelada")
1595
+ continue
1596
+ if resp_text.raw_text.strip().lower() == '/cancelar':
1597
+ await conv.send_message("✅ Edición masiva cancelada.")
1598
+ continue
1599
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
1600
+
1601
+ new_text = resp_text.raw_text
1602
+ import re
1603
+ matches = re.findall(r'\{(.*?)\}\s*(.*)', new_text)
1604
+
1605
+ if not matches:
1606
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
1607
+ continue
1608
+
1609
+ status_m = await conv.send_message("⚙️ Guardando cambios...")
1610
+ updated_count = 0
1611
+ for doc_id, new_title in matches:
1612
+ doc_id = doc_id.strip()
1613
+ new_title = new_title.strip()
1614
+ if new_title:
1615
+ if doc_id == "TITULO_GENERAL":
1616
+ try:
1617
+ db.collection('videos').document(series_id).update({"title": new_title})
1618
+ title = new_title # update variable
1619
+ except: pass
1620
+ else:
1621
+ try:
1622
+ db.collection('videos').document(doc_id).update({"title": new_title})
1623
+ updated_count += 1
1624
+ except: pass
1625
+
1626
+ await status_m.edit(f"✅ **¡Listo!** Se actualizó el título general y {updated_count} capítulos correctamente.")
1627
+ elif resp.data == b"add_caps":
1628
+ await handle_editor_add_chapters(conv, series_id, title)
1629
+
1630
+ async def handle_editor_series_chapters(conv, series_id, series_title):
1631
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1632
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
1633
+ if not caps:
1634
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
1635
+ return
1636
+
1637
+ buttons = []
1638
+ for c in caps[:90]:
1639
+ c_data = c.to_dict()
1640
+ buttons.append([Button.inline(f"Cap {c_data.get('episode', 0)}: {c_data.get('title')[:20]}", f"ed_c_{c.id}".encode('utf-8'))])
1641
+
1642
+ buttons.append([Button.inline("⬅️ Volver", b"volver_caps")])
1643
+
1644
+ msg = await conv.send_message(f"📑 **Capítulos de {series_title}**\nSelecciona uno para editar:", buttons=buttons)
1645
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1646
+
1647
+ if isinstance(resp, events.CallbackQuery.Event):
1648
+ await resp.answer()
1649
+ await msg.edit(buttons=None)
1650
+ if resp.data == b"volver_caps": return
1651
+ cap_id = resp.data.decode().replace('ed_c_', '')
1652
+ await handle_editor_single_chapter(conv, cap_id)
1653
+
1654
+ async def handle_editor_single_chapter(conv, cap_id):
1655
+ doc = db.collection('videos').document(cap_id).get()
1656
+ if not doc.exists: return
1657
+ data = doc.to_dict()
1658
+
1659
+ msg = await conv.send_message(
1660
+ f"🎞️ **Editando Capítulo:**\n`{data.get('title')}`",
1661
+ buttons=[
1662
+ [Button.inline("✏️ Renombrar", b"renombrar")],
1663
+ [Button.inline("📝 Editar Descripción", b"edit_desc")],
1664
+ [Button.inline("🗑️ Eliminar", b"eliminar")],
1665
+ [Button.inline("⬅️ Volver", b"volver")]
1666
+ ]
1667
+ )
1668
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1669
+ if isinstance(resp, events.CallbackQuery.Event):
1670
+ await resp.answer()
1671
+ await msg.edit(buttons=None)
1672
+ if resp.data == b"volver": return
1673
+ if resp.data == b"renombrar":
1674
+ await conv.send_message("Escribe el **nuevo nombre** del capítulo:")
1675
+ new_title = await conv.get_response()
1676
+ db.collection('videos').document(cap_id).update({"title": new_title.raw_text})
1677
+ await conv.send_message(f"✅ Capítulo renombrado a: **{new_title.raw_text}**")
1678
+ if resp.data == b"edit_desc":
1679
+ uid_del = str(uuid.uuid4()).encode()
1680
+ msg_d = await conv.send_message("Escribe la **nueva descripción** del capítulo:", buttons=[[Button.inline("❌ Eliminar Descripción", uid_del)]])
1681
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
1682
+ if isinstance(resp_d, events.CallbackQuery.Event):
1683
+ await resp_d.answer("Eliminando...")
1684
+ db.collection('videos').document(cap_id).update({"description": ""})
1685
+ await msg_d.edit("✅ Descripción eliminada.", buttons=None)
1686
+ else:
1687
+ db.collection('videos').document(cap_id).update({"description": resp_d.raw_text})
1688
+ await msg_d.edit("✅ Descripción actualizada.", buttons=None)
1689
+ if resp.data == b"eliminar":
1690
+ msg_conf = await conv.send_message(
1691
+ f"⚠️ ¿Estás seguro de que deseas eliminar el capítulo **{data.get('title')}**?\nEsta acción no se puede deshacer.",
1692
+ buttons=[
1693
+ [Button.inline("⚠️ Sí, eliminar capítulo", b"confirm_del")],
1694
+ [Button.inline("❌ Cancelar", b"cancel_del")]
1695
+ ]
1696
+ )
1697
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
1698
+ if isinstance(resp_conf, events.CallbackQuery.Event):
1699
+ await resp_conf.answer()
1700
+ await msg_conf.edit(buttons=None)
1701
+ if resp_conf.data == b"confirm_del":
1702
+ db.collection('videos').document(cap_id).delete()
1703
+ await conv.send_message("✅ Capítulo eliminado exitosamente.")
1704
+ else:
1705
+ await conv.send_message("✅ Eliminación cancelada.")
1706
+
1707
+ async def handle_editor_add_chapters(conv, series_id, series_title):
1708
+ uid_done = str(uuid.uuid4()).encode()
1709
+ videos = []
1710
+
1711
+ msg_v = await conv.send_message(
1712
+ f"➕ **Añadiendo capítulos a: {series_title}**\n\nEnvía los videos. Cuando termines presiona el botón.",
1713
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
1714
+ )
1715
+
1716
+ debounce_task = None
1717
+ async def update_button():
1718
+ await asyncio.sleep(0.8)
1719
+ nonlocal msg_v
1720
+ try: await msg_v.delete()
1721
+ except: pass
1722
+ msg_v = await conv.send_message(
1723
+ f"➕ **Añadiendo capítulos a: {series_title}**\n\n({len(videos)} recibidos). Envía más o termina.",
1724
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
1725
+ )
1726
+
1727
+ async def video_receiver(e):
1728
+ is_video = False
1729
+ if getattr(e, 'media', None):
1730
+ if getattr(e, 'video', None):
1731
+ is_video = True
1732
+ elif getattr(e, 'document', None):
1733
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
1734
+ if mime.startswith('video/'):
1735
+ is_video = True
1736
+ else:
1737
+ for attr in e.document.attributes:
1738
+ if hasattr(attr, 'file_name'):
1739
+ import os
1740
+ ext = os.path.splitext(attr.file_name)[1].lower()
1741
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
1742
+ is_video = True
1743
+ break
1744
+ if is_video:
1745
+ videos.append(e)
1746
+ nonlocal debounce_task
1747
+ if debounce_task: debounce_task.cancel()
1748
+ debounce_task = asyncio.create_task(update_button())
1749
+
1750
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
1751
+ try:
1752
+ while True:
1753
+ event = await wait_for_message_or_callback(conv, timeout=3600)
1754
+ if isinstance(event, events.CallbackQuery.Event):
1755
+ if event.data == uid_done:
1756
+ if not videos:
1757
+ await event.answer("No has enviado videos.", alert=True)
1758
+ return
1759
+ await event.answer("Guardando...")
1760
+ if debounce_task: debounce_task.cancel()
1761
+ await msg_v.edit(f"✅ Se recibieron {len(videos)} capítulos.", buttons=None)
1762
+ break
1763
+ finally:
1764
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
1765
+
1766
+ if not videos: return
1767
+
1768
+ uid_title = str(uuid.uuid4()).encode()
1769
+ uid_file = str(uuid.uuid4()).encode()
1770
+
1771
+ sample_names = ""
1772
+ for v in videos[:2]:
1773
+ doc_name = "Video_desconocido.mp4"
1774
+ if hasattr(v.media, 'document'):
1775
+ for attr in v.media.document.attributes:
1776
+ if hasattr(attr, 'file_name'):
1777
+ doc_name = attr.file_name
1778
+ break
1779
+ sample_names += f"- {doc_name}\n"
1780
+
1781
+ msg_n = await conv.send_message(
1782
+ "📁 ¿Cómo nombrar estos capítulos extra?\n\n"
1783
+ "Si usas nombres originales, se verán así:\n"
1784
+ f"{sample_names}",
1785
+ buttons=[
1786
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
1787
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
1788
+ ]
1789
+ )
1790
+
1791
+ naming_strategy = "title"
1792
+ while True:
1793
+ event = await wait_for_message_or_callback(conv, timeout=300)
1794
+ if isinstance(event, events.CallbackQuery.Event):
1795
+ if event.data == uid_title:
1796
+ naming_strategy = "title"
1797
+ await msg_n.edit("Formato: Serie - Capítulo X", buttons=None)
1798
+ break
1799
+ elif event.data == uid_file:
1800
+ naming_strategy = "file"
1801
+ await msg_n.edit("Formato: Archivo original", buttons=None)
1802
+ break
1803
+ else:
1804
+ naming_strategy = "manual"
1805
+ manual_prefix = event.raw_text
1806
+ await msg_n.edit(f"Formato: {manual_prefix}...", buttons=None)
1807
+ break
1808
+
1809
+ status_msg = await conv.send_message("📁 **Procesando capítulos extra...**")
1810
+
1811
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1812
+ max_ep = 0
1813
+ for c in caps:
1814
+ ep = c.to_dict().get('episode', 0)
1815
+ if ep > max_ep: max_ep = ep
1816
+
1817
+ for i, video_msg in enumerate(videos):
1818
+ max_ep += 1
1819
+
1820
+ if naming_strategy == "title":
1821
+ ep_title = f"{series_title} - Capítulo {max_ep}"
1822
+ elif naming_strategy == "manual":
1823
+ ep_title = f"{manual_prefix} - Capítulo {max_ep}"
1824
+ else:
1825
+ doc_name = "Episodio"
1826
+ if hasattr(video_msg.media, 'document'):
1827
+ for attr in video_msg.media.document.attributes:
1828
+ if hasattr(attr, 'file_name'):
1829
+ import os
1830
+ doc_name = os.path.splitext(attr.file_name)[0]
1831
+ break
1832
+ ep_title = doc_name
1833
+
1834
+ await status_msg.edit(f"📁 Subiendo extra: **{ep_title}** ({i+1}/{len(videos)})")
1835
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Serie:** {series_title}\n📁 **Episodio:** {ep_title}"
1836
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
1837
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
1838
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
1839
+
1840
+ db.collection('videos').add({
1841
+ "title": ep_title,
1842
+ "section": "series",
1843
+ "is_folder": False,
1844
+ "folder_id": series_id,
1845
+ "episode": max_ep,
1846
+ "season": 1,
1847
+ "video_url": file_url,
1848
+ "telegram_file_id": str(sent_to_channel.id),
1849
+ "description": "",
1850
+ "thumbnail_url": "",
1851
+ "cover_url": "",
1852
+ "views": 0,
1853
+ "rating": 0,
1854
+ "status": "active",
1855
+ "is_public": True,
1856
+ "categories": [],
1857
+ "servers": [file_url],
1858
+ "created_at": firestore.SERVER_TIMESTAMP,
1859
+ "updated_at": firestore.SERVER_TIMESTAMP
1860
+ })
1861
+ await status_msg.edit(f"✅ **¡{len(videos)} capítulos extra añadidos con éxito!**")
1862
+
1863
+ if __name__ == '__main__':
1864
+
1865
+ print("================================")
1866
+ print(f" BOT @TwistedStreamingBrodybot INICIADO")
1867
+ print("================================")
1868
+ client.start(bot_token=TOKEN)
1869
+
1870
+ # Limpiar el menú nativo de comandos de Telegram
1871
+ async def set_commands():
1872
+ from telethon.tl.functions.bots import SetBotCommandsRequest
1873
+ from telethon.tl.types import BotCommand, BotCommandScopeDefault
1874
+ try:
1875
+ await client(SetBotCommandsRequest(
1876
+ scope=BotCommandScopeDefault(),
1877
+ lang_code='',
1878
+ commands=[
1879
+ BotCommand(command="start", description="Iniciar el bot / Ver instrucciones"),
1880
+ BotCommand(command="subir", description="Men\xC3\xBA principal de subida"),
1881
+ BotCommand(command="subir_pelicula", description="Atajo: Subir Pel\xC3\xADcula"),
1882
+ BotCommand(command="subir_serie", description="Atajo: Subir Serie"),
1883
+ BotCommand(command="app", description="Abrir la Mini App de Cat\xC3\xA1logo"),
1884
+ BotCommand(command="setting", description="Configurar env\xC3\xADo de videos"),
1885
+ BotCommand(command="cancelar", description="Cancelar proceso de subida"),
1886
+ BotCommand(command="activar_modo_editor", description="Activar Modo Editor"),
1887
+ BotCommand(command="desactivar_modo_editor", description="Desactivar Modo Editor"),
1888
+ BotCommand(command="buscador_on", description="Activar Modo Buscador"),
1889
+ BotCommand(command="buscador_off", description="Desactivar Modo Buscador")
1890
+ ]
1891
+ ))
1892
+ print("📁 Menú nativo de comandos (/) actualizado.")
1893
+ except Exception as e:
1894
+ pass
1895
+
1896
+ client.loop.run_until_complete(set_commands())
1897
+ client.run_until_disconnected()
bot_backup.py ADDED
@@ -0,0 +1,1897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import logging
4
+ import asyncio
5
+ import requests
6
+ import base64
7
+ from dotenv import load_dotenv
8
+ from telethon import TelegramClient, events, Button
9
+ import firebase_admin
10
+ from firebase_admin import credentials, firestore
11
+ from google.cloud.firestore_v1.base_query import FieldFilter
12
+
13
+ # Cargar variables de entorno
14
+ load_dotenv()
15
+
16
+ # --- SERVIDOR WEB FANTASMA (Para Hugging Face) ---
17
+ from threading import Thread
18
+ from http.server import HTTPServer, BaseHTTPRequestHandler
19
+
20
+ class DummyHandler(BaseHTTPRequestHandler):
21
+ def do_GET(self):
22
+ self.send_response(200)
23
+ self.send_header("Content-type", "text/html")
24
+ self.end_headers()
25
+ html_content = b"""<!DOCTYPE html>
26
+ <html lang="es">
27
+ <head>
28
+ <meta charset="UTF-8">
29
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
30
+ <title>Twisted Streaming Brody</title>
31
+ <style>
32
+ body { margin: 0; padding: 0; background-color: #0a0a0a; display: flex; justify-content: center; align-items: center; height: 100vh; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
33
+ .btn { background-color: #2481cc; color: white; padding: 15px 35px; border-radius: 30px; text-decoration: none; font-size: 20px; font-weight: bold; box-shadow: 0 5px 15px rgba(36,129,204,0.4); transition: 0.3s; }
34
+ .btn:hover { transform: translateY(-3px); background-color: #1a629c; box-shadow: 0 8px 20px rgba(36,129,204,0.6); }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <a href="https://t.me/TwistedStreamingBrodybot" target="_blank" class="btn">\xF0\x9F\x9A\x80 Abrir Twisted Streaming Brody</a>
39
+ </body>
40
+ </html>"""
41
+ self.wfile.write(html_content)
42
+ def log_message(self, format, *args):
43
+ pass # Silenciar logs del servidor
44
+
45
+ def run_server():
46
+ try:
47
+ server = HTTPServer(('0.0.0.0', 7860), DummyHandler)
48
+ server.serve_forever()
49
+ except Exception as e:
50
+ print("Error en servidor web:", e)
51
+
52
+ Thread(target=run_server, daemon=True).start()
53
+
54
+ API_ID = int(os.getenv('TELEGRAM_API_ID'))
55
+ API_HASH = os.getenv('TELEGRAM_API_HASH')
56
+ TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
57
+ CHANNEL_ID = int(os.getenv('TELEGRAM_CHANNEL_ID'))
58
+ IMGBB_KEY = os.getenv('IMGBB_API_KEY')
59
+
60
+ # Nombre del archivo de sesión
61
+ SESSION_NAME = 'TwistedStreamingBrodybot'
62
+
63
+ # --- CONFIGURACIÓN DE FIREBASE ---
64
+ try:
65
+ if not firebase_admin._apps:
66
+ cred = credentials.Certificate("firebase-credentials.json")
67
+ app = firebase_admin.initialize_app(cred)
68
+ print(f"📁 Firebase conectado correctamente. Proyecto: {app.project_id}")
69
+ db = firestore.client()
70
+ except Exception as e:
71
+ print(f"📁 Error al conectar con Firebase: {e}")
72
+
73
+ # Logs
74
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
75
+
76
+ # Inicializar Cliente de Telethon
77
+ client = TelegramClient(SESSION_NAME, API_ID, API_HASH)
78
+
79
+ # --- FUNCIONES AUXILIARES ---
80
+
81
+ async def upload_to_imgbb(photo_source):
82
+ """Sube una imagen a ImgBB y devuelve la URL"""
83
+ try:
84
+ # Descargar la foto en memoria
85
+ path = await client.download_media(photo_source, file=bytes)
86
+ image_base64 = base64.b64encode(path)
87
+
88
+ url = "https://api.imgbb.com/1/upload"
89
+ payload = {"key": IMGBB_KEY, "image": image_base64}
90
+
91
+ response = requests.post(url, payload)
92
+ res_json = response.json()
93
+ if res_json['success']:
94
+ return res_json['data']['url']
95
+ except Exception as e:
96
+ print(f"Error ImgBB: {e}")
97
+ return None
98
+
99
+ import re
100
+
101
+ def extract_categories_from_title(title):
102
+ """Extrae categorías de un título como [Accion] El Guerrero (2024)"""
103
+ found = re.findall(r'\[(.*?)\]|\((.*?)\)|\{(.*?)\}|\|(.*?)\|', title)
104
+ categories = []
105
+ for match in found:
106
+ for item in match:
107
+ if item and len(item.strip()) > 1:
108
+ categories.append(item.strip())
109
+ return list(set(categories))
110
+
111
+ def get_or_create_categories(names):
112
+ """Busca o crea categorías por nombre y devuelve sus IDs"""
113
+ ids = []
114
+ for name in names:
115
+ try:
116
+ # Buscar si ya existe
117
+ cats = db.collection('categories').where(filter=FieldFilter('name', '==', name)).get()
118
+ if cats:
119
+ ids.append(cats[0].id)
120
+ else:
121
+ # Crear si no existe
122
+ _, doc_ref = db.collection('categories').add({
123
+ "name": name,
124
+ "type": "genre"
125
+ })
126
+ ids.append(doc_ref.id)
127
+ print(f"🆕 Categoría creada: {name}")
128
+ except Exception as e:
129
+ print(f"Error gestionando categoría {name}: {e}")
130
+ return ids
131
+
132
+ def get_all_categories():
133
+ try:
134
+ cats = db.collection('categories').get()
135
+ return [{"id": c.id, "name": c.to_dict().get('name', 'Sin nombre')} for c in cats]
136
+ except Exception:
137
+ return []
138
+
139
+ import uuid
140
+
141
+ class CancelUploadException(Exception):
142
+ pass
143
+
144
+ class EditorJumpException(Exception):
145
+ def __init__(self, jump_id):
146
+ self.jump_id = jump_id
147
+
148
+ async def wait_for_message_or_callback(conv, timeout=300):
149
+ client = conv._client
150
+ chat_id = conv.chat_id
151
+ future = asyncio.Future()
152
+
153
+ async def msg_handler(e):
154
+ if not future.done():
155
+ future.set_result(e)
156
+
157
+ async def cb_handler(e):
158
+ if not future.done():
159
+ future.set_result(e)
160
+
161
+ client.add_event_handler(msg_handler, events.NewMessage(chats=chat_id, incoming=True))
162
+ client.add_event_handler(cb_handler, events.CallbackQuery(chats=chat_id))
163
+
164
+ try:
165
+ event = await asyncio.wait_for(future, timeout=timeout)
166
+ txt = getattr(event, 'raw_text', getattr(event, 'text', '')).strip()
167
+
168
+ if txt == '/cancelar':
169
+ await client.send_message(chat_id, "📁 **Proceso cancelado.**")
170
+ raise CancelUploadException()
171
+
172
+ # Global intercept for editor mode jumps
173
+ if editor_mode_active.get(chat_id, False):
174
+ if txt.startswith('/start '):
175
+ extracted = txt.replace('/start ', '').replace('folder_', '').strip()
176
+ raise EditorJumpException(extracted)
177
+ elif len(txt) == 20 and txt.isalnum() and not txt.startswith('/'):
178
+ # Heuristic for Firebase ID jump
179
+ raise EditorJumpException(txt)
180
+
181
+ return event
182
+ finally:
183
+ client.remove_event_handler(msg_handler)
184
+ client.remove_event_handler(cb_handler)
185
+
186
+ async def get_input_or_skip(conv, text, can_skip=True):
187
+ """Espera un mensaje o un botón de omitir con IDs únicos para evitar bugs"""
188
+ uid = str(uuid.uuid4()).encode()
189
+ buttons = [Button.inline("📁 Omitir", uid)] if can_skip else None
190
+ msg = await conv.send_message(text, buttons=buttons)
191
+
192
+ try:
193
+ while True:
194
+ event = await wait_for_message_or_callback(conv, timeout=300)
195
+ if isinstance(event, events.CallbackQuery.Event):
196
+ if event.data == uid:
197
+ await event.answer("Omitido")
198
+ await msg.edit(text + " (Omitido)", buttons=None)
199
+ return None
200
+ else:
201
+ await event.answer("Este botón ya no es válido", alert=True)
202
+ else:
203
+ if buttons:
204
+ await msg.edit(text, buttons=None)
205
+ return event
206
+ except asyncio.TimeoutError:
207
+ await conv.send_message("📁 Tiempo de espera agotado. Proceso cancelado.")
208
+ return None
209
+ except Exception as e:
210
+ print(f"Error en get_input_or_skip: {e}")
211
+ return None
212
+
213
+ # --- MANEJADORES ---
214
+
215
+ # --- MODO BUSCADOR ---
216
+ @client.on(events.NewMessage(pattern='^/buscador_on$'))
217
+ async def enable_search_mode(event):
218
+ chat_id = event.chat_id
219
+
220
+ # Desactivar editor y cancelar subidas
221
+ editor_mode_active[chat_id] = False
222
+ if chat_id in active_tasks:
223
+ for t in active_tasks[chat_id]:
224
+ t.cancel()
225
+ del active_tasks[chat_id]
226
+
227
+ search_mode_active[chat_id] = True
228
+ await event.respond("🔍 **Modo Buscador Activado**\n\nAhora puedes buscar enviando el título de una película, serie o capítulo. También puedes pegar enlaces directos o IDs.\n\nEnvía /buscador_off para salir.")
229
+
230
+ @client.on(events.NewMessage(pattern='^/buscador_off$'))
231
+ async def disable_search_mode(event):
232
+ chat_id = event.chat_id
233
+ search_mode_active[chat_id] = False
234
+ await event.respond("❌ **Modo Buscador Desactivado**.")
235
+
236
+ @client.on(events.NewMessage(func=lambda e: not e.text.startswith('/') and len(e.text) != 20))
237
+ async def handle_text_search(event):
238
+ chat_id = event.chat_id
239
+ if not search_mode_active.get(chat_id, False):
240
+ return
241
+ if editor_mode_active.get(chat_id, False):
242
+ return
243
+
244
+ query = event.raw_text.strip().lower()
245
+ if not query: return
246
+
247
+ msg = await event.respond("🔍 Buscando...")
248
+
249
+ # Buscar en Firestore (limitado en memoria por diseño simple de Firebase)
250
+ docs = db.collection('videos').get()
251
+
252
+ matched_docs = []
253
+ for d in docs:
254
+ data = d.to_dict()
255
+ title = data.get('title', '').lower()
256
+ if query in title:
257
+ matched_docs.append((d.id, data))
258
+
259
+ if not matched_docs:
260
+ await msg.edit("❌ No se encontraron resultados para tu búsqueda.")
261
+ return
262
+
263
+ # Buscar si hay alguna coincidencia EXACTA (para evitar que "Capítulo 1" muestre el "10", "11", etc.)
264
+ exact_matches = [m for m in matched_docs if m[1].get('title', '').lower() == query]
265
+ if len(exact_matches) == 1:
266
+ matched_docs = exact_matches
267
+
268
+ # Si hay exactamente 1 resultado, lo enviamos directamente
269
+ if len(matched_docs) == 1:
270
+ doc_id, data = matched_docs[0]
271
+ class DummyEvent:
272
+ def __init__(self, chat_id, raw_text):
273
+ self.chat_id = chat_id
274
+ self.raw_text = raw_text
275
+ async def respond(self, *args, **kwargs):
276
+ return await client.send_message(self.chat_id, *args, **kwargs)
277
+
278
+ dummy = DummyEvent(event.chat_id, doc_id)
279
+ await msg.delete()
280
+ await handle_document_id(dummy)
281
+ return
282
+
283
+ # Si hay múltiples, filtramos para dar prioridad a las Carpetas (Series) y Películas
284
+ # Esto evita mostrar una lista gigante de subcapítulos
285
+ folders_and_movies = []
286
+ chapters = []
287
+
288
+ for r_id, data in matched_docs:
289
+ if data.get('section') == 'peliculas' or data.get('is_folder'):
290
+ folders_and_movies.append((r_id, data))
291
+ else:
292
+ chapters.append((r_id, data))
293
+
294
+ # Mostrar carpetas/pelis si hay, sino mostrar capítulos sueltos
295
+ results = folders_and_movies if folders_and_movies else chapters
296
+
297
+ # Mostrar resultados en botones
298
+ results = results[:20] # Limitar a 20 resultados para no exceder limite de botones
299
+ buttons = []
300
+ for r_id, data in results:
301
+ t = data.get('title', 'Sin titulo')[:40]
302
+ icon = "🎬" if data.get('section') == 'peliculas' else ("📺" if data.get('is_folder') else "🎞️")
303
+ buttons.append([Button.inline(f"{icon} {t}", f"get_vid_{r_id}".encode('utf-8'))])
304
+
305
+ await msg.edit(f"📌 **Resultados para:** `{query}`", buttons=buttons)
306
+
307
+ @client.on(events.CallbackQuery(pattern=b'^get_vid_'))
308
+ async def handle_search_result_click(event):
309
+ if not search_mode_active.get(event.chat_id, False):
310
+ await event.answer("El modo buscador está desactivado.", alert=True)
311
+ return
312
+
313
+ doc_id = event.data.decode('utf-8').replace('get_vid_', '')
314
+ await event.answer()
315
+
316
+ # Simulamos como si el usuario hubiera enviado el ID directamente
317
+ class DummyEvent:
318
+ def __init__(self, chat_id, raw_text):
319
+ self.chat_id = chat_id
320
+ self.raw_text = raw_text
321
+ async def respond(self, *args, **kwargs):
322
+ return await client.send_message(self.chat_id, *args, **kwargs)
323
+
324
+ dummy = DummyEvent(event.chat_id, doc_id)
325
+ await handle_document_id(dummy)
326
+
327
+ # --------------------------
328
+
329
+
330
+ active_tasks = {}
331
+ editor_mode_active = {}
332
+ search_mode_active = {}
333
+
334
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
335
+ async def start_subir_handler(event):
336
+ chat_id = event.chat_id
337
+ if editor_mode_active.get(chat_id, False):
338
+ await event.respond("🛠️ **Estás en Modo Editor.**\nPor favor, usa `/desactivar_modo_editor` para salir del editor y usar los comandos normales.")
339
+ return
340
+
341
+ if chat_id not in active_tasks:
342
+ active_tasks[chat_id] = []
343
+
344
+ current_task = asyncio.current_task()
345
+ current_task.is_uploading = False
346
+
347
+ remaining_tasks = []
348
+ for old_task in active_tasks[chat_id]:
349
+ if not old_task.done():
350
+ if getattr(old_task, 'is_uploading', False):
351
+ remaining_tasks.append(old_task)
352
+ else:
353
+ old_task.cancel()
354
+ try:
355
+ await asyncio.sleep(0.1)
356
+ except: pass
357
+
358
+ active_tasks[chat_id] = remaining_tasks
359
+ active_tasks[chat_id].append(current_task)
360
+
361
+ try:
362
+ async with client.conversation(chat_id, timeout=600, exclusive=False) as conv:
363
+ try:
364
+ cmd = event.text.strip().lower()
365
+
366
+ if cmd == '/subir_pelicula':
367
+ await handle_movie_upload(conv)
368
+ return
369
+ elif cmd == '/subir_serie':
370
+ await handle_series_upload(conv)
371
+ return
372
+
373
+ msg_text = "📁 Bienvenido a **Twisted Streaming Brody**.\nElige una opción:"
374
+ botones = [
375
+ [Button.inline("📁 Subir Película", b"type_movie"), Button.inline("📁 Subir Serie", b"type_series")]
376
+ ]
377
+
378
+ if cmd == '/start':
379
+ photos = await client.get_profile_photos('me', limit=1)
380
+ if photos:
381
+ msg = await conv.send_message(msg_text, file=photos[0], buttons=botones)
382
+ else:
383
+ msg = await conv.send_message(msg_text, buttons=botones)
384
+ else:
385
+ msg = await conv.send_message(msg_text, buttons=botones)
386
+
387
+ while True:
388
+ press = await wait_for_message_or_callback(conv, timeout=3600)
389
+ if isinstance(press, events.CallbackQuery.Event):
390
+ if press.data in [b"type_movie", b"type_series"]:
391
+ await press.answer()
392
+ try:
393
+ await msg.edit(buttons=None)
394
+ except: pass
395
+
396
+ if press.data == b"type_movie":
397
+ await handle_movie_upload(conv)
398
+ elif press.data == b"type_series":
399
+ await handle_series_upload(conv)
400
+ break
401
+ else:
402
+ await press.answer("Botón expirado", alert=True)
403
+ elif getattr(press, 'text', '') in ['/start', '/subir', '/subir_pelicula', '/subir_serie']:
404
+ # El usuario envió otro comando, dejamos que el nuevo handler lo tome
405
+ break
406
+ except CancelUploadException:
407
+ pass
408
+ except asyncio.CancelledError:
409
+ pass
410
+ finally:
411
+ if current_task in active_tasks.get(chat_id, []):
412
+ active_tasks[chat_id].remove(current_task)
413
+ if not active_tasks[chat_id]:
414
+ del active_tasks[chat_id]
415
+
416
+ async def handle_movie_upload(conv):
417
+ # 1. Video
418
+ await conv.send_message("📁 **Paso 1:** Envía el **video** (o el archivo) de la película:")
419
+ msg_video = await conv.get_response()
420
+
421
+ is_video = False
422
+ if msg_video and getattr(msg_video, 'media', None):
423
+ if getattr(msg_video, 'video', None):
424
+ is_video = True
425
+ elif getattr(msg_video, 'document', None):
426
+ mime = getattr(msg_video.file, 'mime_type', '') if hasattr(msg_video, 'file') else ''
427
+ if mime.startswith('video/'):
428
+ is_video = True
429
+ else:
430
+ for attr in msg_video.document.attributes:
431
+ if hasattr(attr, 'file_name'):
432
+ import os
433
+ ext = os.path.splitext(attr.file_name)[1].lower()
434
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
435
+ is_video = True
436
+ break
437
+
438
+ if not is_video:
439
+ await conv.send_message("📁 No enviaste un video válido. Debes enviar un video normal o un archivo de video (documento). Las imágenes no son aceptadas. Abortando proceso.")
440
+ print("📁 Intento de subida fallido: No se recibió un video o documento válido.")
441
+ return
442
+
443
+ doc_name = ""
444
+ video_caption = msg_video.raw_text if getattr(msg_video, 'raw_text', None) else ""
445
+ if hasattr(msg_video.media, 'document'):
446
+ for attr in msg_video.media.document.attributes:
447
+ if hasattr(attr, 'file_name'):
448
+ import os
449
+ doc_name = os.path.splitext(attr.file_name)[0]
450
+ break
451
+
452
+ # 2. Título
453
+ uid_title = str(uuid.uuid4()).encode()
454
+ buttons_title = []
455
+ if doc_name:
456
+ buttons_title.append([Button.inline(f"📁 Usar nombre del archivo: {doc_name[:30]}", uid_title)])
457
+
458
+ msg_t = await conv.send_message("📁 **Paso 2:** Escribe el **Título** de la película:", buttons=buttons_title if buttons_title else None)
459
+ title = ""
460
+ while True:
461
+ event = await wait_for_message_or_callback(conv, timeout=300)
462
+ if isinstance(event, events.CallbackQuery.Event):
463
+ if doc_name and event.data == uid_title:
464
+ await event.answer("Título seleccionado")
465
+ title = doc_name
466
+ await msg_t.edit(f"📁 Título: **{title}**", buttons=None)
467
+ break
468
+ else:
469
+ await event.answer("Botón expirado", alert=True)
470
+ else:
471
+ title = event.raw_text
472
+ if buttons_title:
473
+ await msg_t.edit(buttons=None)
474
+ break
475
+
476
+ print(f"📁 Iniciando carga de película: {title}")
477
+
478
+ # 3. Descripción
479
+ uid_desc = str(uuid.uuid4()).encode()
480
+ uid_skip = str(uuid.uuid4()).encode()
481
+ buttons_desc = []
482
+ if video_caption:
483
+ buttons_desc.append([Button.inline("📁 Usar descripción del video", uid_desc)])
484
+ buttons_desc.append([Button.inline("📁 Omitir", uid_skip)])
485
+
486
+ msg_d = await conv.send_message("📁 **Paso 3:** Escribe la **Descripción**:", buttons=buttons_desc)
487
+ description = ""
488
+ while True:
489
+ event = await wait_for_message_or_callback(conv, timeout=300)
490
+ if isinstance(event, events.CallbackQuery.Event):
491
+ if video_caption and event.data == uid_desc:
492
+ await event.answer("Descripción seleccionada")
493
+ description = video_caption
494
+ await msg_d.edit("📁 Descripción obtenida del video.", buttons=None)
495
+ break
496
+ elif event.data == uid_skip:
497
+ await event.answer("Omitido")
498
+ description = ""
499
+ await msg_d.edit("📁 Descripción: (Omitida)", buttons=None)
500
+ break
501
+ else:
502
+ await event.answer("Botón expirado", alert=True)
503
+ else:
504
+ description = event.raw_text
505
+ await msg_d.edit(buttons=None)
506
+ break
507
+
508
+ # 4. Portada
509
+ cover_url = ""
510
+ while True:
511
+ resp_cover = await get_input_or_skip(conv, "📁 **Paso 4:** Envía la **Portada** (solo como imagen):")
512
+ if not resp_cover:
513
+ break
514
+ if resp_cover.photo:
515
+ cover_url = await upload_to_imgbb(resp_cover.photo)
516
+ break
517
+ else:
518
+ await conv.send_message("📁 Por favor, envía una IMAGEN, no un texto ni un link.")
519
+
520
+ async def progress_callback(current, total):
521
+ porcentaje = (current / total) * 100
522
+ print(f" ⬆️ Subiendo: {porcentaje:.1f}% ({current}/{total} bytes)")
523
+
524
+ print(f"📦 Video recibido. Tamaño estimado: {getattr(msg_video.file, 'size', 'desconocido')} bytes")
525
+ status_msg = await conv.send_message("📁 **Subiendo video al canal...** (Mira la consola para ver el progreso)")
526
+
527
+ try:
528
+ asyncio.current_task().is_uploading = True
529
+ # Formatear el mensaje para el canal
530
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Película:** {title}\n📁 {description}"
531
+
532
+ print(f"📤 Enviando al canal {CHANNEL_ID}...")
533
+
534
+ if resp_cover and getattr(resp_cover, 'photo', None):
535
+ try:
536
+ await client.send_file(CHANNEL_ID, resp_cover.photo, caption=f"📁 **Portada Película:** {title}")
537
+ except Exception as e:
538
+ print(f"Error enviando portada de película al canal: {e}")
539
+
540
+ sent_to_channel = await client.send_file(
541
+ CHANNEL_ID,
542
+ msg_video.media,
543
+ caption=caption,
544
+ progress_callback=progress_callback
545
+ )
546
+
547
+ print(f"📁 Enviado al canal. ID: {sent_to_channel.id}")
548
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
549
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
550
+
551
+ print("🗄️ Guardando en Firebase...")
552
+ # Guardar en Firestore con todos los campos observados en tu consola
553
+ db.collection('videos').add({
554
+ "title": title,
555
+ "description": description,
556
+ "section": "peliculas",
557
+ "is_folder": False,
558
+ "folder_id": "", # Sin nulls para evitar errores en React
559
+ "video_url": file_url,
560
+ "telegram_file_id": str(sent_to_channel.id),
561
+ "thumbnail_url": "",
562
+ "cover_url": cover_url,
563
+ "thumbnail_position": "50% center",
564
+ "episode": 0,
565
+ "views": 0,
566
+ "rating": 0,
567
+ "categories": [],
568
+ "servers": [file_url],
569
+ "status": "active",
570
+ "is_public": True,
571
+ "created_at": firestore.SERVER_TIMESTAMP,
572
+ "updated_at": firestore.SERVER_TIMESTAMP
573
+ })
574
+ print("🎉 Guardado en Firebase exitoso.")
575
+ await status_msg.edit("📁 **¡Película registrada y enviada correctamente!**")
576
+ except Exception as e:
577
+ print(f"📁 ERROR CRÍTICO: {e}")
578
+ await status_msg.edit(f"📁 **Error al procesar:** {e}")
579
+
580
+ async def handle_series_upload(conv):
581
+ series_title = ""
582
+ videos = []
583
+ naming_strategy = "title"
584
+ manual_prefix = ""
585
+ desc_strategy = "manual"
586
+ desc_text = ""
587
+ cover_url = ""
588
+ resp_cover = None
589
+
590
+ step = 1
591
+ while step <= 4:
592
+ if step == 1:
593
+ await conv.send_message("📁 **Paso 1:** Escribe el título general de la Serie (`Ej: The Last of Us, Breaking Bad, Invencible, etc.`):")
594
+ while True:
595
+ title_msg = await wait_for_message_or_callback(conv, timeout=300)
596
+ if isinstance(title_msg, events.CallbackQuery.Event):
597
+ await title_msg.answer("Por favor, escribe un texto.", alert=True)
598
+ elif getattr(title_msg, 'raw_text', getattr(title_msg, 'text', None)):
599
+ series_title = getattr(title_msg, 'raw_text', title_msg.text)
600
+ step = 2
601
+ break
602
+
603
+ elif step == 2:
604
+ uid_done = str(uuid.uuid4()).encode()
605
+ uid_back = str(uuid.uuid4()).encode()
606
+ msg_v = await conv.send_message(
607
+ f"📁 **Paso 2:** Envía los videos de los capítulos. Puedes enviar varios de una vez.\n\n"
608
+ f"Esperando a más videos... ({len(videos)} recibidos)",
609
+ buttons=[
610
+ [Button.inline("📁 Terminar y confirmar", uid_done)],
611
+ [Button.inline("⬅️ Atrás (Editar Título)", uid_back)]
612
+ ]
613
+ )
614
+
615
+ debounce_task = None
616
+ async def update_button():
617
+ await asyncio.sleep(0.8)
618
+ nonlocal msg_v
619
+ try:
620
+ await msg_v.delete()
621
+ except Exception:
622
+ pass
623
+ msg_v = await conv.send_message(
624
+ f"📁 **Paso 2:** Envía los videos de los capítulos.\n\n"
625
+ f"Esperando a más videos... ({len(videos)} recibidos)",
626
+ buttons=[
627
+ [Button.inline("📁 Terminar y confirmar", uid_done)],
628
+ [Button.inline("⬅️ Atrás (Editar Título)", uid_back)]
629
+ ]
630
+ )
631
+
632
+ async def video_receiver(e):
633
+ is_video = False
634
+ if getattr(e, 'media', None):
635
+ if getattr(e, 'video', None):
636
+ is_video = True
637
+ elif getattr(e, 'document', None):
638
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
639
+ if mime.startswith('video/'):
640
+ is_video = True
641
+ else:
642
+ for attr in e.document.attributes:
643
+ if hasattr(attr, 'file_name'):
644
+ import os
645
+ ext = os.path.splitext(attr.file_name)[1].lower()
646
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
647
+ is_video = True
648
+ break
649
+
650
+ if is_video:
651
+ videos.append(e)
652
+ nonlocal debounce_task
653
+ if debounce_task:
654
+ debounce_task.cancel()
655
+ debounce_task = asyncio.create_task(update_button())
656
+
657
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
658
+
659
+ try:
660
+ while True:
661
+ event = await wait_for_message_or_callback(conv, timeout=3600)
662
+ if isinstance(event, events.CallbackQuery.Event):
663
+ if event.data == uid_done:
664
+ if not videos:
665
+ await event.answer("No has enviado ningún video aún.", alert=True)
666
+ else:
667
+ await event.answer("Videos confirmados")
668
+ if debounce_task:
669
+ debounce_task.cancel()
670
+ await msg_v.edit(f"📁 Se registraron {len(videos)} videos en total.", buttons=None)
671
+ step = 3
672
+ break
673
+ elif event.data == uid_back:
674
+ await event.answer("Volviendo atrás")
675
+ if debounce_task:
676
+ debounce_task.cancel()
677
+ await msg_v.edit("📁 Volviendo al Paso 1...", buttons=None)
678
+ step = 1
679
+ break
680
+ finally:
681
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
682
+
683
+ elif step == 3:
684
+ uid_title = str(uuid.uuid4()).encode()
685
+ uid_file = str(uuid.uuid4()).encode()
686
+ uid_back = str(uuid.uuid4()).encode()
687
+
688
+ sample_names = ""
689
+ for v in videos[:2]:
690
+ doc_name = "Video_desconocido.mp4"
691
+ if hasattr(v.media, 'document'):
692
+ for attr in v.media.document.attributes:
693
+ if hasattr(attr, 'file_name'):
694
+ doc_name = attr.file_name
695
+ break
696
+ sample_names += f"- {doc_name}\n"
697
+
698
+ msg_n = await conv.send_message(
699
+ "📁 **Paso 3:** ¿Qué nombre llevarán los capítulos?\n\n"
700
+ "Escribe un nombre base y se enumerarán automáticamente.\n\n"
701
+ f"Por ejemplo, si escribes un nombre o usas el botón **Usar nombre del título general** (`{series_title}`), se nombrarán así:\n"
702
+ f"- {series_title} - Capítulo 1\n"
703
+ f"- {series_title} - Capítulo 2\n"
704
+ f"- {series_title} - Capítulo 3\n\n"
705
+ "Si usas el botón **Usar nombres originales de los archivos**, se usarán los nombres reales que acabas de subir:\n"
706
+ f"{sample_names}\n"
707
+ "Elige un atajo rápido o escribe tu propio nombre base:",
708
+ buttons=[
709
+ [Button.inline("📁 Usar nombre del título general", uid_title)],
710
+ [Button.inline("📁 Usar nombres originales de los archivos", uid_file)],
711
+ [Button.inline("⬅️ Atrás (Añadir más videos)", uid_back)]
712
+ ]
713
+ )
714
+
715
+ while True:
716
+ event = await wait_for_message_or_callback(conv, timeout=300)
717
+ if isinstance(event, events.CallbackQuery.Event):
718
+ if event.data == uid_title:
719
+ naming_strategy = "title"
720
+ await msg_n.edit(f"📁 Formato: **{series_title} - Capítulo X**", buttons=None)
721
+ step = 3.5
722
+ break
723
+ elif event.data == uid_file:
724
+ naming_strategy = "file"
725
+ await msg_n.edit("📁 Formato: **Nombres originales de los archivos**", buttons=None)
726
+ step = 3.5
727
+ break
728
+ elif event.data == uid_back:
729
+ await event.answer("Volviendo atrás")
730
+ await msg_n.edit("📁 Volviendo al Paso 2...", buttons=None)
731
+ step = 2
732
+ break
733
+ else:
734
+ await event.answer("Botón expirado", alert=True)
735
+ else:
736
+ naming_strategy = "manual"
737
+ manual_prefix = event.raw_text.strip()
738
+ await msg_n.edit(f"📁 Formato Manual: **{manual_prefix} - Capítulo 1, ...**", buttons=None)
739
+ step = 3.5
740
+ break
741
+
742
+ elif step == 3.5:
743
+ uid_desc_video = str(uuid.uuid4()).encode()
744
+ uid_skip = str(uuid.uuid4()).encode()
745
+ uid_back = str(uuid.uuid4()).encode()
746
+ msg_d = await conv.send_message(
747
+ "📁 **Paso 3.5:** Escribe una **Descripción** (se usará la misma para todos los capítulos).\n\n"
748
+ "Opcional: puedes extraer la descripción original de cada video, o simplemente omitir este paso.",
749
+ buttons=[
750
+ [Button.inline("📁 Usar descripción de cada video", uid_desc_video)],
751
+ [Button.inline("📁 Omitir", uid_skip)],
752
+ [Button.inline("⬅️ Atrás (Editar Nombre Capítulos)", uid_back)]
753
+ ]
754
+ )
755
+
756
+ while True:
757
+ event = await wait_for_message_or_callback(conv, timeout=300)
758
+ if isinstance(event, events.CallbackQuery.Event):
759
+ if event.data == uid_desc_video:
760
+ desc_strategy = "video"
761
+ await msg_d.edit("📁 Descripción: **Se usará la de cada video**", buttons=None)
762
+ step = 4
763
+ break
764
+ elif event.data == uid_skip:
765
+ desc_strategy = "skip"
766
+ await msg_d.edit("📁 Descripción: **(Omitida)**", buttons=None)
767
+ step = 4
768
+ break
769
+ elif event.data == uid_back:
770
+ await event.answer("Volviendo atrás")
771
+ await msg_d.edit("📁 Volviendo al Paso 3...", buttons=None)
772
+ step = 3
773
+ break
774
+ else:
775
+ await event.answer("Botón expirado", alert=True)
776
+ else:
777
+ desc_strategy = "manual"
778
+ desc_text = event.raw_text
779
+ await msg_d.edit(f"📁 Descripción: **{desc_text[:30]}...**", buttons=None)
780
+ step = 4
781
+ break
782
+
783
+ elif step == 4:
784
+ uid_skip = str(uuid.uuid4()).encode()
785
+ uid_back = str(uuid.uuid4()).encode()
786
+ msg_c = await conv.send_message(
787
+ "📁 **Paso 4:** Envía la **Portada** de la serie (solo como imagen):",
788
+ buttons=[
789
+ [Button.inline("📁 Omitir", uid_skip)],
790
+ [Button.inline("⬅️ Atrás (Editar Descripción)", uid_back)]
791
+ ]
792
+ )
793
+
794
+ while True:
795
+ event = await wait_for_message_or_callback(conv, timeout=300)
796
+ if isinstance(event, events.CallbackQuery.Event):
797
+ if event.data == uid_skip:
798
+ await event.answer("Omitido")
799
+ await msg_c.edit("📁 Portada: **(Omitida)**", buttons=None)
800
+ resp_cover = None
801
+ cover_url = ""
802
+ step = 5
803
+ break
804
+ elif event.data == uid_back:
805
+ await event.answer("Volviendo atrás")
806
+ await msg_c.edit("📁 Volviendo al Paso 3.5...", buttons=None)
807
+ step = 3.5
808
+ break
809
+ else:
810
+ await event.answer("Botón expirado", alert=True)
811
+ elif getattr(event, 'photo', None):
812
+ await msg_c.edit("📁 Subiendo portada...", buttons=None)
813
+ cover_url = await upload_to_imgbb(event.photo)
814
+ resp_cover = event
815
+ step = 5
816
+ break
817
+ else:
818
+ await conv.send_message("📁 Por favor, envía una IMAGEN, o presiona Omitir/Atrás.")
819
+
820
+ # 5. Guardado en Firebase y reenvío
821
+ status_msg = await conv.send_message("📁 **Procesando y subiendo los capítulos...**")
822
+ try:
823
+ asyncio.current_task().is_uploading = True
824
+ if resp_cover and getattr(resp_cover, 'photo', None):
825
+ try:
826
+ await client.send_file(CHANNEL_ID, resp_cover.photo, caption=f"📁 **Portada Serie:** {series_title}")
827
+ except Exception as e:
828
+ print(f"Error enviando portada de serie al canal: {e}")
829
+
830
+ # Buscar serie existente para asegurar nombre único
831
+ original_title = series_title
832
+ counter = 1
833
+
834
+ while True:
835
+ series_query = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).where(filter=FieldFilter('title', '==', series_title)).get()
836
+ if series_query:
837
+ counter += 1
838
+ series_title = f"{original_title} {counter}"
839
+ else:
840
+ break
841
+
842
+ _, doc_ref = db.collection('videos').add({
843
+ "title": series_title,
844
+ "section": "series",
845
+ "is_folder": True,
846
+ "thumbnail_url": cover_url,
847
+ "categories": [],
848
+ "created_at": firestore.SERVER_TIMESTAMP,
849
+ "updated_at": firestore.SERVER_TIMESTAMP
850
+ })
851
+ series_id = doc_ref.id
852
+
853
+ for i, video_msg in enumerate(videos):
854
+ current_num = i + 1
855
+
856
+ # Nombre
857
+ if naming_strategy == "title":
858
+ ep_title = f"{series_title} - Capítulo {i+1}"
859
+ elif naming_strategy == "manual":
860
+ ep_title = f"{manual_prefix} - Capítulo {i+1}"
861
+ else:
862
+ doc_name = "Episodio"
863
+ if hasattr(video_msg.media, 'document'):
864
+ for attr in video_msg.media.document.attributes:
865
+ if hasattr(attr, 'file_name'):
866
+ import os
867
+ doc_name = os.path.splitext(attr.file_name)[0]
868
+ break
869
+ ep_title = doc_name
870
+
871
+ # Descripción
872
+ if desc_strategy == "video":
873
+ ep_desc = video_msg.raw_text if getattr(video_msg, 'raw_text', None) else ""
874
+ elif desc_strategy == "skip":
875
+ ep_desc = ""
876
+ else:
877
+ ep_desc = desc_text
878
+
879
+ await status_msg.edit(f"📁 Subiendo: **{ep_title}** ({i+1}/{len(videos)})")
880
+
881
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Serie:** {series_title}\n📁 **Episodio:** {ep_title}"
882
+ if ep_desc:
883
+ caption += f"\n📁 {ep_desc}"
884
+
885
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
886
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
887
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
888
+
889
+ db.collection('videos').add({
890
+ "title": ep_title,
891
+ "section": "series",
892
+ "is_folder": False,
893
+ "folder_id": series_id,
894
+ "episode": current_num,
895
+ "season": 1,
896
+ "video_url": file_url,
897
+ "telegram_file_id": str(sent_to_channel.id),
898
+ "description": ep_desc,
899
+ "thumbnail_url": "",
900
+ "cover_url": "",
901
+ "views": 0,
902
+ "rating": 0,
903
+ "status": "active",
904
+ "is_public": True,
905
+ "categories": [],
906
+ "servers": [file_url],
907
+ "created_at": firestore.SERVER_TIMESTAMP,
908
+ "updated_at": firestore.SERVER_TIMESTAMP
909
+ })
910
+
911
+ await status_msg.edit(f"📁 **¡Completado! {len(videos)} capítulos de '{series_title}' se han subido con éxito.**")
912
+
913
+ except Exception as e:
914
+ print(f"📁 Error al procesar serie: {e}")
915
+ await status_msg.edit(f"📁 **Error al subir los capítulos:** {e}")
916
+
917
+
918
+
919
+ # --- CONFIGURACIÓN Y FUNCIONES DE BÚSQUEDA POR ID ---
920
+
921
+ bot_settings = {
922
+ "send_title": True,
923
+ "send_description": True,
924
+ "ask_series": True
925
+ }
926
+
927
+ try:
928
+ doc_settings = db.collection('settings').document('delivery').get()
929
+ if doc_settings.exists:
930
+ s_data = doc_settings.to_dict()
931
+ bot_settings['send_title'] = s_data.get('send_title', True)
932
+ bot_settings['send_description'] = s_data.get('send_description', True)
933
+ bot_settings['ask_series'] = s_data.get('ask_series', True)
934
+ except Exception as e:
935
+ print(f"📁 Error cargando settings: {e}")
936
+
937
+ @client.on(events.NewMessage(pattern='/(settings|setting|config)$'))
938
+ async def settings_handler(event):
939
+ await show_settings_menu(event)
940
+
941
+ async def show_settings_menu(event_or_query):
942
+ title_status = "✅ PRENDIDO" if bot_settings['send_title'] else "❌ APAGADO"
943
+ desc_status = "✅ PRENDIDO" if bot_settings['send_description'] else "❌ APAGADO"
944
+ ask_status = "✅ PRENDIDO" if bot_settings['ask_series'] else "❌ APAGADO"
945
+
946
+ botones = [
947
+ [Button.inline(f"Título: {title_status}", b"toggle_title")],
948
+ [Button.inline(f"Descripción: {desc_status}", b"toggle_desc")],
949
+ [Button.inline(f"Preguntar Temporada/Capítulo: {ask_status}", b"toggle_ask")]
950
+ ]
951
+
952
+ text = "⚙️ **Configuración de Envío de Videos**\n\nElige cómo quieres que el bot entregue los videos:"
953
+
954
+ if isinstance(event_or_query, events.CallbackQuery.Event):
955
+ await event_or_query.edit(text, buttons=botones)
956
+ else:
957
+ await event_or_query.respond(text, buttons=botones)
958
+
959
+ from telethon.tl.types import KeyboardButtonWebView
960
+
961
+ @client.on(events.NewMessage(pattern='/(twistedstreamingbrodybot|app)$'))
962
+ async def miniapp_handler(event):
963
+ # Usamos KeyboardButtonWebView para forzar a Telegram a abrirlo como Mini App
964
+ botones = [[KeyboardButtonWebView(text="🍿 Abrir Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")]]
965
+
966
+ await event.respond(
967
+ "🍿 **¡Twisted Streaming Brody!**\n\nToca el botón abajo para abrir nuestra Mini App y navegar por todas las películas y series directamente desde Telegram.",
968
+ buttons=botones
969
+ )
970
+
971
+ button_cooldowns = {}
972
+
973
+ @client.on(events.CallbackQuery(pattern=b'^toggle_(title|desc|ask)$'))
974
+ async def toggle_settings_handler(event):
975
+ chat_id = event.chat_id
976
+ now = time.time()
977
+ if now - button_cooldowns.get(chat_id, 0) < 0.5:
978
+ await event.answer()
979
+ return
980
+ button_cooldowns[chat_id] = now
981
+
982
+ action = event.pattern_match.group(1).decode()
983
+ if action == 'title':
984
+ bot_settings['send_title'] = not bot_settings['send_title']
985
+ elif action == 'desc':
986
+ bot_settings['send_description'] = not bot_settings['send_description']
987
+ elif action == 'ask':
988
+ bot_settings['ask_series'] = not bot_settings['ask_series']
989
+
990
+ try:
991
+ db.collection('settings').document('delivery').set(bot_settings)
992
+ except: pass
993
+
994
+ await event.answer()
995
+ await show_settings_menu(event)
996
+
997
+ async def send_movie(chat_id, file_id, data):
998
+ cover = data.get('cover_url') or data.get('thumbnail_url')
999
+ caption_parts = []
1000
+ if bot_settings['send_title'] and data.get('title'):
1001
+ caption_parts.append(f"📁 **{data.get('title')}**")
1002
+ if bot_settings['send_description'] and data.get('description'):
1003
+ caption_parts.append(f"{data.get('description')}")
1004
+
1005
+ custom_caption = "\n\n".join(caption_parts)
1006
+
1007
+ if cover:
1008
+ try:
1009
+ await client.send_file(chat_id, cover, caption=custom_caption)
1010
+ except Exception:
1011
+ if custom_caption: await client.send_message(chat_id, custom_caption)
1012
+ elif custom_caption:
1013
+ await client.send_message(chat_id, custom_caption)
1014
+
1015
+ try:
1016
+ msg = await client.get_messages(CHANNEL_ID, ids=int(file_id))
1017
+ if msg and getattr(msg, 'media', None):
1018
+ await client.send_file(chat_id, msg.media, caption="")
1019
+ else:
1020
+ await client.send_message(chat_id, "📁 Video no encontrado en el canal.")
1021
+ except Exception as e:
1022
+ print("Error enviando película:", e)
1023
+
1024
+ async def send_series_cover(chat_id, folder_id):
1025
+ if not folder_id: return
1026
+ try:
1027
+ s_doc = db.collection('videos').document(folder_id).get()
1028
+ if s_doc.exists:
1029
+ s_data = s_doc.to_dict()
1030
+ cover = s_data.get('thumbnail_url') or s_data.get('cover_url')
1031
+
1032
+ caption = ""
1033
+ if bot_settings['send_title'] and s_data.get('title'):
1034
+ caption = f"📁 **{s_data.get('title')}**"
1035
+
1036
+ if cover:
1037
+ try:
1038
+ await client.send_file(chat_id, cover, caption=caption)
1039
+ except Exception:
1040
+ if caption: await client.send_message(chat_id, caption)
1041
+ elif caption:
1042
+ await client.send_message(chat_id, caption)
1043
+ except Exception as e:
1044
+ print("Error al enviar portada de serie:", e)
1045
+
1046
+ async def send_episode_video(chat_id, file_id, ep_data):
1047
+ try:
1048
+ msg = await client.get_messages(CHANNEL_ID, ids=int(file_id))
1049
+ if not msg or not getattr(msg, 'media', None):
1050
+ await client.send_message(chat_id, "📁 Capítulo no encontrado en el canal.")
1051
+ return
1052
+
1053
+ caption_parts = []
1054
+ if bot_settings['send_title'] and ep_data.get('title'):
1055
+ caption_parts.append(f"📁 **{ep_data.get('title')}**")
1056
+ if bot_settings['send_description'] and ep_data.get('description'):
1057
+ caption_parts.append(f"{ep_data.get('description')}")
1058
+
1059
+ custom_caption = "\n\n".join(caption_parts)
1060
+ await client.send_file(chat_id, msg.media, caption=custom_caption)
1061
+ except Exception as e:
1062
+ print("Error enviando capítulo:", e)
1063
+
1064
+ async def send_full_season(chat_id, folder_id, status_msg=None):
1065
+ if not status_msg:
1066
+ status_msg = await client.send_message(chat_id, "📁 Preparando los capítulos...")
1067
+ else:
1068
+ try:
1069
+ await status_msg.edit("📁 Preparando los capítulos...", buttons=None)
1070
+ except Exception:
1071
+ pass
1072
+
1073
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', folder_id)).get()
1074
+ if not episodes:
1075
+ await status_msg.edit("📁 No se encontraron capítulos.")
1076
+ return
1077
+
1078
+ await send_series_cover(chat_id, folder_id)
1079
+
1080
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
1081
+ for ep in episodes_sorted:
1082
+ data = ep.to_dict()
1083
+ file_id = data.get('telegram_file_id')
1084
+ if file_id:
1085
+ await send_episode_video(chat_id, file_id, data)
1086
+ await asyncio.sleep(0.5)
1087
+ await status_msg.edit("📁 **¡Temporada enviada!**")
1088
+
1089
+ @client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
1090
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
1091
+ async def handle_document_id(event):
1092
+ if editor_mode_active.get(event.chat_id, False):
1093
+ return
1094
+
1095
+ if not search_mode_active.get(event.chat_id, False):
1096
+ return # Ignore links/IDs if search mode is OFF
1097
+
1098
+ text = event.raw_text.strip()
1099
+ is_folder_request = False
1100
+
1101
+ if text.startswith('/start '):
1102
+ payload = text.split(' ')[1]
1103
+ if payload.startswith('folder_'):
1104
+ is_folder_request = True
1105
+ doc_id = payload.replace('folder_', '', 1)
1106
+ else:
1107
+ doc_id = payload
1108
+ else:
1109
+ if text.startswith('folder/') or text.startswith('folder_'):
1110
+ is_folder_request = True
1111
+ doc_id = text.replace('folder/', '', 1).replace('folder_', '', 1)
1112
+ else:
1113
+ doc_id = text
1114
+
1115
+ try:
1116
+ doc = db.collection('videos').document(doc_id).get()
1117
+ if not doc.exists:
1118
+ return
1119
+
1120
+ data = doc.to_dict()
1121
+ section = data.get('section')
1122
+ is_folder = data.get('is_folder')
1123
+
1124
+ if section == 'peliculas':
1125
+ file_id = data.get('telegram_file_id')
1126
+ if file_id:
1127
+ await send_movie(event.chat_id, file_id, data)
1128
+ else:
1129
+ await event.respond("📁 No se encontró el archivo en Telegram para esta película.")
1130
+
1131
+ elif section == 'series':
1132
+ folder_id = doc_id if is_folder else data.get('folder_id')
1133
+
1134
+ if is_folder_request:
1135
+ await send_full_season(event.chat_id, folder_id)
1136
+ return
1137
+
1138
+ if not bot_settings.get('ask_series', True):
1139
+ if is_folder:
1140
+ await send_full_season(event.chat_id, folder_id)
1141
+ else:
1142
+ file_id = data.get('telegram_file_id')
1143
+ if file_id:
1144
+ await send_series_cover(event.chat_id, folder_id)
1145
+ await send_episode_video(event.chat_id, file_id, data)
1146
+ else:
1147
+ await event.respond("📁 Archivo no encontrado.")
1148
+ return
1149
+
1150
+ if is_folder:
1151
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', doc_id)).get()
1152
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
1153
+
1154
+ botones = []
1155
+ row = []
1156
+ for ep in episodes_sorted:
1157
+ ep_data = ep.to_dict()
1158
+ ep_num = ep_data.get('episode', '?')
1159
+ ep_id = ep.id
1160
+ row.append(Button.inline(f"Cap {ep_num}", f"this_cap_{ep_id}".encode()))
1161
+ if len(row) == 3:
1162
+ botones.append(row)
1163
+ row = []
1164
+ if row:
1165
+ botones.append(row)
1166
+
1167
+ botones.append([Button.inline("📁 Enviar Temporada Completa", f"all_caps_{doc_id}".encode())])
1168
+
1169
+ await event.respond(f"📁 **Serie:** {data.get('title')}\nSelecciona un capítulo o envía la temporada completa:", buttons=botones)
1170
+ else:
1171
+ botones = [
1172
+ [Button.inline("📁 Enviar solo este video", f"this_cap_{doc_id}".encode())],
1173
+ [Button.inline("📁 Enviar Temporada Completa", f"all_caps_{folder_id}".encode())]
1174
+ ]
1175
+ await event.respond(f"📁 **Capítulo:** {data.get('title')}\n¿Qué deseas hacer?", buttons=botones)
1176
+
1177
+ except Exception as e:
1178
+ print(f"Error buscando documento {doc_id}: {e}")
1179
+
1180
+ @client.on(events.CallbackQuery(pattern=b'^(this_cap_|all_caps_|choose_cap_)(.*)'))
1181
+ async def handle_series_delivery(event):
1182
+ chat_id = event.chat_id
1183
+ now = time.time()
1184
+ if now - button_cooldowns.get(chat_id, 0) < 1.0:
1185
+ await event.answer("Procesando...", alert=False)
1186
+ return
1187
+ button_cooldowns[chat_id] = now
1188
+
1189
+ action = event.pattern_match.group(1).decode()
1190
+ target_id = event.pattern_match.group(2).decode()
1191
+
1192
+ try:
1193
+ if action == "this_cap_":
1194
+ await event.answer("📁 Enviando capítulo...", alert=False)
1195
+ doc = db.collection('videos').document(target_id).get()
1196
+ if doc.exists:
1197
+ data = doc.to_dict()
1198
+ file_id = data.get('telegram_file_id')
1199
+ folder_id = data.get('folder_id')
1200
+ if file_id:
1201
+ await send_series_cover(event.chat_id, folder_id)
1202
+ await send_episode_video(event.chat_id, file_id, data)
1203
+ else:
1204
+ await event.respond("📁 Archivo no encontrado.")
1205
+
1206
+ elif action == "all_caps_":
1207
+ await event.answer("📁 Preparando temporada...", alert=False)
1208
+ await send_full_season(chat_id, target_id, status_msg=event)
1209
+
1210
+ elif action == "choose_cap_":
1211
+ await event.answer("📁 Cargando capítulos...", alert=False)
1212
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', target_id)).get()
1213
+ if not episodes:
1214
+ await event.answer("No se encontraron capítulos.", alert=True)
1215
+ return
1216
+
1217
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
1218
+
1219
+ botones = []
1220
+ row = []
1221
+ for ep in episodes_sorted:
1222
+ data = ep.to_dict()
1223
+ ep_num = data.get('episode', '?')
1224
+ ep_id = ep.id
1225
+ row.append(Button.inline(f"Cap {ep_num}", f"this_cap_{ep_id}".encode()))
1226
+ if len(row) == 3:
1227
+ botones.append(row)
1228
+ row = []
1229
+ if row:
1230
+ botones.append(row)
1231
+
1232
+ await event.edit("📁 **Selecciona el capítulo:**", buttons=botones)
1233
+
1234
+ except Exception as e:
1235
+ print(f"Error en delivery: {e}")
1236
+ await event.respond("📁 Hubo un error procesando la solicitud.")
1237
+
1238
+
1239
+ # --- MODO EDITOR ---
1240
+ @client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
1241
+ async def enable_editor(event):
1242
+ import asyncio
1243
+ chat_id = event.chat_id
1244
+
1245
+ # Cancel previous tasks to prevent "Botón expirado" background overlap
1246
+ if chat_id in active_tasks:
1247
+ for old_task in active_tasks[chat_id]:
1248
+ if not old_task.done():
1249
+ if not getattr(old_task, 'is_uploading', False):
1250
+ old_task.cancel()
1251
+ try: await asyncio.sleep(0.1)
1252
+ except: pass
1253
+
1254
+ current_task = asyncio.current_task()
1255
+ current_task.is_uploading = False
1256
+
1257
+ if chat_id not in active_tasks:
1258
+ active_tasks[chat_id] = []
1259
+ active_tasks[chat_id].append(current_task)
1260
+
1261
+ editor_mode_active[chat_id] = True
1262
+ try:
1263
+ await handle_editor_mode(event)
1264
+ finally:
1265
+ if current_task in active_tasks.get(chat_id, []):
1266
+ active_tasks[chat_id].remove(current_task)
1267
+ if not active_tasks[chat_id]:
1268
+ del active_tasks[chat_id]
1269
+
1270
+
1271
+ @client.on(events.NewMessage(pattern='/(desactivar_modo_editor)$'))
1272
+ async def disable_editor(event):
1273
+ chat_id = event.chat_id
1274
+ editor_mode_active[chat_id] = False
1275
+ await event.respond("✅ **Modo editor desactivado.** Ya puedes usar los comandos normales.")
1276
+
1277
+ async def process_editor_id(conv, txt):
1278
+ doc = db.collection('videos').document(txt).get()
1279
+ if doc.exists:
1280
+ data = doc.to_dict()
1281
+ if data.get('section') == 'peliculas':
1282
+ await handle_editor_movie_action(conv, txt)
1283
+ elif data.get('is_folder', False):
1284
+ await handle_editor_series_action(conv, txt)
1285
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
1286
+ await handle_editor_single_chapter(conv, txt)
1287
+ else:
1288
+ await conv.send_message("❌ Tipo de documento no reconocido.")
1289
+ else:
1290
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
1291
+
1292
+ async def handle_editor_mode(event):
1293
+ chat_id = event.chat_id
1294
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
1295
+ current_jump_id = None
1296
+ last_msg = None
1297
+
1298
+ while editor_mode_active.get(chat_id, False):
1299
+ try:
1300
+ if current_jump_id:
1301
+ jump = current_jump_id
1302
+ current_jump_id = None
1303
+ if last_msg:
1304
+ try: await last_msg.delete()
1305
+ except: pass
1306
+ await process_editor_id(conv, jump)
1307
+ continue # Go back to start of loop
1308
+
1309
+ last_msg = await conv.send_message(
1310
+ "🛠️ **Modo Editor Activado**\n\n¿Qué deseas gestionar?",
1311
+ buttons=[
1312
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
1313
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
1314
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
1315
+ ]
1316
+ )
1317
+
1318
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
1319
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
1320
+ break
1321
+
1322
+ if isinstance(resp, events.CallbackQuery.Event):
1323
+ await resp.answer()
1324
+ try: await last_msg.delete()
1325
+ except: pass
1326
+
1327
+ if resp.data == b"ed_exit":
1328
+ editor_mode_active[chat_id] = False
1329
+ await conv.send_message("✅ **Modo editor desactivado.**")
1330
+ break
1331
+ elif resp.data == b"ed_mov":
1332
+ await handle_editor_movie_search(conv)
1333
+ elif resp.data == b"ed_ser":
1334
+ await handle_editor_series_search(conv)
1335
+
1336
+ elif getattr(resp, 'raw_text', ''):
1337
+ txt = resp.raw_text.strip()
1338
+ if txt.startswith('/start '):
1339
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
1340
+
1341
+ if txt.startswith('/'):
1342
+ if txt == '/desactivar_modo_editor':
1343
+ break
1344
+ continue
1345
+
1346
+ try: await last_msg.delete()
1347
+ except: pass
1348
+
1349
+ await process_editor_id(conv, txt)
1350
+
1351
+ except EditorJumpException as e:
1352
+ # A jump occurred from anywhere (main menu or submenu)! Loop back and handle it.
1353
+ current_jump_id = e.jump_id
1354
+ except Exception as e:
1355
+ print("Editor error:", e)
1356
+ break
1357
+
1358
+ async def handle_editor_movie_search(conv):
1359
+ from telethon.tl.types import KeyboardButtonSimpleWebView
1360
+ uid_back = str(uuid.uuid4()).encode()
1361
+ btn_webapp = KeyboardButtonSimpleWebView(text="🍿 Buscar ID en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
1362
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la película que deseas buscar:", buttons=[
1363
+ [btn_webapp],
1364
+ [Button.inline("⬅️ Cancelar", uid_back)]
1365
+ ])
1366
+
1367
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1368
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
1369
+ await resp.answer("Cancelado")
1370
+ await msg.edit("Búsqueda cancelada.", buttons=None)
1371
+ return
1372
+
1373
+ query = resp.raw_text.strip()
1374
+ await msg.delete()
1375
+
1376
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
1377
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower() or query == m.id]
1378
+
1379
+ if not results:
1380
+ await conv.send_message("❌ No se encontraron películas con ese nombre.")
1381
+ return
1382
+
1383
+ results = results[:10]
1384
+ buttons = []
1385
+ for r in results:
1386
+ data = r.to_dict()
1387
+ buttons.append([Button.inline(f"🎬 {data.get('title')[:30]}", f"ed_m_{r.id}".encode('utf-8'))])
1388
+
1389
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
1390
+
1391
+ msg_res = await conv.send_message("📌 **Resultados (Películas):**", buttons=buttons)
1392
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
1393
+
1394
+ if isinstance(resp_res, events.CallbackQuery.Event):
1395
+ await resp_res.answer()
1396
+ await msg_res.edit(buttons=None)
1397
+ if resp_res.data == b"ed_back": return
1398
+
1399
+ movie_id = resp_res.data.decode().replace('ed_m_', '')
1400
+ await handle_editor_movie_action(conv, movie_id)
1401
+
1402
+ async def handle_editor_movie_action(conv, movie_id):
1403
+ doc = db.collection('videos').document(movie_id).get()
1404
+ if not doc.exists: return
1405
+ data = doc.to_dict()
1406
+
1407
+ msg = await conv.send_message(
1408
+ f"🎬 **Editando Película:**\n`{data.get('title')}`",
1409
+ buttons=[
1410
+ [Button.inline("✏️ Renombrar Título", b"renombrar")],
1411
+ [Button.inline("📝 Editar Descripción", b"edit_desc")],
1412
+ [Button.inline("🗑️ Eliminar Película", b"eliminar")],
1413
+ [Button.inline("⬅️ Volver", b"volver")]
1414
+ ]
1415
+ )
1416
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1417
+ if isinstance(resp, events.CallbackQuery.Event):
1418
+ await resp.answer()
1419
+ await msg.edit(buttons=None)
1420
+ if resp.data == b"volver": return
1421
+ elif resp.data == b"renombrar":
1422
+ await conv.send_message("Escribe el **nuevo título** para la película:")
1423
+ new_title = await conv.get_response()
1424
+ db.collection('videos').document(movie_id).update({"title": new_title.raw_text})
1425
+ await conv.send_message(f"✅ Título actualizado a: **{new_title.raw_text}**")
1426
+ elif resp.data == b"edit_desc":
1427
+ uid_del = str(uuid.uuid4()).encode()
1428
+ msg_d = await conv.send_message("Escribe la **nueva descripción** para la película:", buttons=[[Button.inline("❌ Eliminar Descripción", uid_del)]])
1429
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
1430
+ if isinstance(resp_d, events.CallbackQuery.Event):
1431
+ await resp_d.answer("Eliminando...")
1432
+ db.collection('videos').document(movie_id).update({"description": ""})
1433
+ await msg_d.edit("✅ Descripción eliminada.", buttons=None)
1434
+ else:
1435
+ db.collection('videos').document(movie_id).update({"description": resp_d.raw_text})
1436
+ await msg_d.edit("✅ Descripción actualizada.", buttons=None)
1437
+ elif resp.data == b"eliminar":
1438
+ msg_conf = await conv.send_message(
1439
+ f"⚠️ ¿Estás seguro de que deseas eliminar la película **{data.get('title')}**?\nEsta acción no se puede deshacer.",
1440
+ buttons=[
1441
+ [Button.inline("⚠️ Sí, eliminar definitivamente", b"confirm_del")],
1442
+ [Button.inline("❌ Cancelar", b"cancel_del")]
1443
+ ]
1444
+ )
1445
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
1446
+ if isinstance(resp_conf, events.CallbackQuery.Event):
1447
+ await resp_conf.answer()
1448
+ await msg_conf.edit(buttons=None)
1449
+ if resp_conf.data == b"confirm_del":
1450
+ db.collection('videos').document(movie_id).delete()
1451
+ await conv.send_message("✅ Película eliminada exitosamente.")
1452
+ else:
1453
+ await conv.send_message("✅ Eliminación cancelada.")
1454
+
1455
+ async def handle_editor_series_search(conv):
1456
+ from telethon.tl.types import KeyboardButtonSimpleWebView
1457
+ uid_back = str(uuid.uuid4()).encode()
1458
+ btn_webapp = KeyboardButtonSimpleWebView(text="🍿 Buscar ID en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
1459
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la serie que deseas buscar:", buttons=[
1460
+ [btn_webapp],
1461
+ [Button.inline("⬅️ Cancelar", uid_back)]
1462
+ ])
1463
+
1464
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1465
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
1466
+ await resp.answer()
1467
+ await msg.edit("Búsqueda cancelada.", buttons=None)
1468
+ return
1469
+
1470
+ query = resp.raw_text.strip()
1471
+ await msg.delete()
1472
+
1473
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
1474
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower() or query == s.id]
1475
+
1476
+ if not results:
1477
+ await conv.send_message("❌ No se encontraron series con ese nombre.")
1478
+ return
1479
+
1480
+ results = results[:10]
1481
+ buttons = []
1482
+ for r in results:
1483
+ buttons.append([Button.inline(f"📺 {r.to_dict().get('title')[:30]}", f"ed_s_{r.id}".encode('utf-8'))])
1484
+
1485
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
1486
+
1487
+ msg_res = await conv.send_message("📌 **Resultados (Series):**", buttons=buttons)
1488
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
1489
+
1490
+ if isinstance(resp_res, events.CallbackQuery.Event):
1491
+ await resp_res.answer()
1492
+ await msg_res.edit(buttons=None)
1493
+ if resp_res.data == b"ed_back": return
1494
+
1495
+ series_id = resp_res.data.decode().replace('ed_s_', '')
1496
+ await handle_editor_series_action(conv, series_id)
1497
+
1498
+ async def handle_editor_series_action(conv, series_id):
1499
+ while editor_mode_active.get(conv.chat_id, False):
1500
+ doc = db.collection('videos').document(series_id).get()
1501
+ if not doc.exists: return
1502
+ data = doc.to_dict()
1503
+ title = data.get('title')
1504
+
1505
+ msg = await conv.send_message(
1506
+ f"📺 **Editando Serie:**\n`{title}`",
1507
+ buttons=[
1508
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
1509
+ [Button.inline("📝 Edición Masiva de Descripciones", b"edit_desc_masiva")],
1510
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
1511
+ [Button.inline("📝 Edición Masiva de Capítulos", b"editar_lista")],
1512
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
1513
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
1514
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
1515
+ ]
1516
+ )
1517
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
1518
+ if getattr(resp, 'raw_text', '').startswith('/'): return
1519
+
1520
+ if isinstance(resp, events.CallbackQuery.Event):
1521
+ await resp.answer()
1522
+ await msg.edit(buttons=None)
1523
+
1524
+ if resp.data == b"volver": return
1525
+ elif resp.data == b"renombrar":
1526
+ await conv.send_message("Escribe el **nuevo título general** para la serie:")
1527
+ new_title = await conv.get_response()
1528
+ db.collection('videos').document(series_id).update({"title": new_title.raw_text})
1529
+ await conv.send_message(f"✅ Título general actualizado a: **{new_title.raw_text}**")
1530
+ elif resp.data == b"edit_desc_masiva":
1531
+ uid_del = str(uuid.uuid4()).encode()
1532
+ msg_d = await conv.send_message("Escribe la **nueva descripción** para aplicarla a TODOS los capítulos de esta serie:", buttons=[[Button.inline("❌ Eliminar Todas las Descripciones", uid_del)]])
1533
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
1534
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1535
+ updated_count = 0
1536
+
1537
+ if isinstance(resp_d, events.CallbackQuery.Event):
1538
+ await resp_d.answer("Eliminando...")
1539
+ for c in caps:
1540
+ db.collection('videos').document(c.id).update({"description": ""})
1541
+ updated_count += 1
1542
+ await msg_d.edit(f"✅ Descripciones eliminadas masivamente en {updated_count} capítulos.", buttons=None)
1543
+ else:
1544
+ for c in caps:
1545
+ db.collection('videos').document(c.id).update({"description": resp_d.raw_text})
1546
+ updated_count += 1
1547
+ await msg_d.edit(f"✅ Descripción aplicada masivamente a {updated_count} capítulos.", buttons=None)
1548
+ elif resp.data == b"eliminar":
1549
+ msg_conf = await conv.send_message(
1550
+ f"⚠️ ¿Estás seguro de que deseas eliminar la serie completa **{title}** y **TODOS** sus capítulos?\nEsta acción no se puede deshacer.",
1551
+ buttons=[
1552
+ [Button.inline("⚠️ Sí, eliminar serie y capítulos", b"confirm_del")],
1553
+ [Button.inline("❌ Cancelar", b"cancel_del")]
1554
+ ]
1555
+ )
1556
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
1557
+ if isinstance(resp_conf, events.CallbackQuery.Event):
1558
+ await resp_conf.answer()
1559
+ await msg_conf.edit(buttons=None)
1560
+ if resp_conf.data == b"confirm_del":
1561
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1562
+ for c in caps: db.collection('videos').document(c.id).delete()
1563
+ db.collection('videos').document(series_id).delete()
1564
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados exitosamente.")
1565
+ return
1566
+ else:
1567
+ await conv.send_message("✅ Eliminación cancelada.")
1568
+ elif resp.data == b"ver_caps":
1569
+ await handle_editor_series_chapters(conv, series_id, title)
1570
+ elif resp.data == b"editar_lista":
1571
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1572
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
1573
+ if not caps:
1574
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
1575
+ continue
1576
+
1577
+ template = f"{{TITULO_GENERAL}} {title}\n\n"
1578
+ for c in caps:
1579
+ template += f"{{{c.id}}} {c.to_dict().get('title')}\n"
1580
+
1581
+ await conv.send_message(
1582
+ "📝 **EDICIÓN MASIVA**\n\n"
1583
+ "1. Toca el siguiente mensaje para copiarlo.\n"
1584
+ "2. Pégalo en el chat y edita el nombre de la serie o de los capítulos como desees.\n"
1585
+ "3. Envíamelo.\n\n"
1586
+ "⚠️ **MUY IMPORTANTE:** ¡NO borres ni modifiques los códigos entre llaves `{ }`!"
1587
+ )
1588
+ await conv.send_message(f"```{template}```")
1589
+
1590
+ await conv.send_message("⏳ Esperando tu mensaje con la plantilla editada... (O envía `/cancelar` para abortar)")
1591
+
1592
+ resp_text = await wait_for_message_or_callback(conv, timeout=3600)
1593
+ if isinstance(resp_text, events.CallbackQuery.Event):
1594
+ await resp_text.answer("Operación cancelada")
1595
+ continue
1596
+ if resp_text.raw_text.strip().lower() == '/cancelar':
1597
+ await conv.send_message("✅ Edición masiva cancelada.")
1598
+ continue
1599
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
1600
+
1601
+ new_text = resp_text.raw_text
1602
+ import re
1603
+ matches = re.findall(r'\{(.*?)\}\s*(.*)', new_text)
1604
+
1605
+ if not matches:
1606
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
1607
+ continue
1608
+
1609
+ status_m = await conv.send_message("⚙️ Guardando cambios...")
1610
+ updated_count = 0
1611
+ for doc_id, new_title in matches:
1612
+ doc_id = doc_id.strip()
1613
+ new_title = new_title.strip()
1614
+ if new_title:
1615
+ if doc_id == "TITULO_GENERAL":
1616
+ try:
1617
+ db.collection('videos').document(series_id).update({"title": new_title})
1618
+ title = new_title # update variable
1619
+ except: pass
1620
+ else:
1621
+ try:
1622
+ db.collection('videos').document(doc_id).update({"title": new_title})
1623
+ updated_count += 1
1624
+ except: pass
1625
+
1626
+ await status_m.edit(f"✅ **¡Listo!** Se actualizó el título general y {updated_count} capítulos correctamente.")
1627
+ elif resp.data == b"add_caps":
1628
+ await handle_editor_add_chapters(conv, series_id, title)
1629
+
1630
+ async def handle_editor_series_chapters(conv, series_id, series_title):
1631
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1632
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
1633
+ if not caps:
1634
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
1635
+ return
1636
+
1637
+ buttons = []
1638
+ for c in caps[:90]:
1639
+ c_data = c.to_dict()
1640
+ buttons.append([Button.inline(f"Cap {c_data.get('episode', 0)}: {c_data.get('title')[:20]}", f"ed_c_{c.id}".encode('utf-8'))])
1641
+
1642
+ buttons.append([Button.inline("⬅️ Volver", b"volver_caps")])
1643
+
1644
+ msg = await conv.send_message(f"📑 **Capítulos de {series_title}**\nSelecciona uno para editar:", buttons=buttons)
1645
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1646
+
1647
+ if isinstance(resp, events.CallbackQuery.Event):
1648
+ await resp.answer()
1649
+ await msg.edit(buttons=None)
1650
+ if resp.data == b"volver_caps": return
1651
+ cap_id = resp.data.decode().replace('ed_c_', '')
1652
+ await handle_editor_single_chapter(conv, cap_id)
1653
+
1654
+ async def handle_editor_single_chapter(conv, cap_id):
1655
+ doc = db.collection('videos').document(cap_id).get()
1656
+ if not doc.exists: return
1657
+ data = doc.to_dict()
1658
+
1659
+ msg = await conv.send_message(
1660
+ f"🎞️ **Editando Capítulo:**\n`{data.get('title')}`",
1661
+ buttons=[
1662
+ [Button.inline("✏️ Renombrar", b"renombrar")],
1663
+ [Button.inline("📝 Editar Descripción", b"edit_desc")],
1664
+ [Button.inline("🗑️ Eliminar", b"eliminar")],
1665
+ [Button.inline("⬅️ Volver", b"volver")]
1666
+ ]
1667
+ )
1668
+ resp = await wait_for_message_or_callback(conv, timeout=300)
1669
+ if isinstance(resp, events.CallbackQuery.Event):
1670
+ await resp.answer()
1671
+ await msg.edit(buttons=None)
1672
+ if resp.data == b"volver": return
1673
+ if resp.data == b"renombrar":
1674
+ await conv.send_message("Escribe el **nuevo nombre** del capítulo:")
1675
+ new_title = await conv.get_response()
1676
+ db.collection('videos').document(cap_id).update({"title": new_title.raw_text})
1677
+ await conv.send_message(f"✅ Capítulo renombrado a: **{new_title.raw_text}**")
1678
+ if resp.data == b"edit_desc":
1679
+ uid_del = str(uuid.uuid4()).encode()
1680
+ msg_d = await conv.send_message("Escribe la **nueva descripción** del capítulo:", buttons=[[Button.inline("❌ Eliminar Descripción", uid_del)]])
1681
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
1682
+ if isinstance(resp_d, events.CallbackQuery.Event):
1683
+ await resp_d.answer("Eliminando...")
1684
+ db.collection('videos').document(cap_id).update({"description": ""})
1685
+ await msg_d.edit("✅ Descripción eliminada.", buttons=None)
1686
+ else:
1687
+ db.collection('videos').document(cap_id).update({"description": resp_d.raw_text})
1688
+ await msg_d.edit("✅ Descripción actualizada.", buttons=None)
1689
+ if resp.data == b"eliminar":
1690
+ msg_conf = await conv.send_message(
1691
+ f"⚠️ ¿Estás seguro de que deseas eliminar el capítulo **{data.get('title')}**?\nEsta acción no se puede deshacer.",
1692
+ buttons=[
1693
+ [Button.inline("⚠️ Sí, eliminar capítulo", b"confirm_del")],
1694
+ [Button.inline("❌ Cancelar", b"cancel_del")]
1695
+ ]
1696
+ )
1697
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
1698
+ if isinstance(resp_conf, events.CallbackQuery.Event):
1699
+ await resp_conf.answer()
1700
+ await msg_conf.edit(buttons=None)
1701
+ if resp_conf.data == b"confirm_del":
1702
+ db.collection('videos').document(cap_id).delete()
1703
+ await conv.send_message("✅ Capítulo eliminado exitosamente.")
1704
+ else:
1705
+ await conv.send_message("✅ Eliminación cancelada.")
1706
+
1707
+ async def handle_editor_add_chapters(conv, series_id, series_title):
1708
+ uid_done = str(uuid.uuid4()).encode()
1709
+ videos = []
1710
+
1711
+ msg_v = await conv.send_message(
1712
+ f"➕ **Añadiendo capítulos a: {series_title}**\n\nEnvía los videos. Cuando termines presiona el botón.",
1713
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
1714
+ )
1715
+
1716
+ debounce_task = None
1717
+ async def update_button():
1718
+ await asyncio.sleep(0.8)
1719
+ nonlocal msg_v
1720
+ try: await msg_v.delete()
1721
+ except: pass
1722
+ msg_v = await conv.send_message(
1723
+ f"➕ **Añadiendo capítulos a: {series_title}**\n\n({len(videos)} recibidos). Envía más o termina.",
1724
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
1725
+ )
1726
+
1727
+ async def video_receiver(e):
1728
+ is_video = False
1729
+ if getattr(e, 'media', None):
1730
+ if getattr(e, 'video', None):
1731
+ is_video = True
1732
+ elif getattr(e, 'document', None):
1733
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
1734
+ if mime.startswith('video/'):
1735
+ is_video = True
1736
+ else:
1737
+ for attr in e.document.attributes:
1738
+ if hasattr(attr, 'file_name'):
1739
+ import os
1740
+ ext = os.path.splitext(attr.file_name)[1].lower()
1741
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
1742
+ is_video = True
1743
+ break
1744
+ if is_video:
1745
+ videos.append(e)
1746
+ nonlocal debounce_task
1747
+ if debounce_task: debounce_task.cancel()
1748
+ debounce_task = asyncio.create_task(update_button())
1749
+
1750
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
1751
+ try:
1752
+ while True:
1753
+ event = await wait_for_message_or_callback(conv, timeout=3600)
1754
+ if isinstance(event, events.CallbackQuery.Event):
1755
+ if event.data == uid_done:
1756
+ if not videos:
1757
+ await event.answer("No has enviado videos.", alert=True)
1758
+ return
1759
+ await event.answer("Guardando...")
1760
+ if debounce_task: debounce_task.cancel()
1761
+ await msg_v.edit(f"✅ Se recibieron {len(videos)} capítulos.", buttons=None)
1762
+ break
1763
+ finally:
1764
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
1765
+
1766
+ if not videos: return
1767
+
1768
+ uid_title = str(uuid.uuid4()).encode()
1769
+ uid_file = str(uuid.uuid4()).encode()
1770
+
1771
+ sample_names = ""
1772
+ for v in videos[:2]:
1773
+ doc_name = "Video_desconocido.mp4"
1774
+ if hasattr(v.media, 'document'):
1775
+ for attr in v.media.document.attributes:
1776
+ if hasattr(attr, 'file_name'):
1777
+ doc_name = attr.file_name
1778
+ break
1779
+ sample_names += f"- {doc_name}\n"
1780
+
1781
+ msg_n = await conv.send_message(
1782
+ "📁 ¿Cómo nombrar estos capítulos extra?\n\n"
1783
+ "Si usas nombres originales, se verán así:\n"
1784
+ f"{sample_names}",
1785
+ buttons=[
1786
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
1787
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
1788
+ ]
1789
+ )
1790
+
1791
+ naming_strategy = "title"
1792
+ while True:
1793
+ event = await wait_for_message_or_callback(conv, timeout=300)
1794
+ if isinstance(event, events.CallbackQuery.Event):
1795
+ if event.data == uid_title:
1796
+ naming_strategy = "title"
1797
+ await msg_n.edit("Formato: Serie - Capítulo X", buttons=None)
1798
+ break
1799
+ elif event.data == uid_file:
1800
+ naming_strategy = "file"
1801
+ await msg_n.edit("Formato: Archivo original", buttons=None)
1802
+ break
1803
+ else:
1804
+ naming_strategy = "manual"
1805
+ manual_prefix = event.raw_text
1806
+ await msg_n.edit(f"Formato: {manual_prefix}...", buttons=None)
1807
+ break
1808
+
1809
+ status_msg = await conv.send_message("📁 **Procesando capítulos extra...**")
1810
+
1811
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
1812
+ max_ep = 0
1813
+ for c in caps:
1814
+ ep = c.to_dict().get('episode', 0)
1815
+ if ep > max_ep: max_ep = ep
1816
+
1817
+ for i, video_msg in enumerate(videos):
1818
+ max_ep += 1
1819
+
1820
+ if naming_strategy == "title":
1821
+ ep_title = f"{series_title} - Capítulo {max_ep}"
1822
+ elif naming_strategy == "manual":
1823
+ ep_title = f"{manual_prefix} - Capítulo {max_ep}"
1824
+ else:
1825
+ doc_name = "Episodio"
1826
+ if hasattr(video_msg.media, 'document'):
1827
+ for attr in video_msg.media.document.attributes:
1828
+ if hasattr(attr, 'file_name'):
1829
+ import os
1830
+ doc_name = os.path.splitext(attr.file_name)[0]
1831
+ break
1832
+ ep_title = doc_name
1833
+
1834
+ await status_msg.edit(f"📁 Subiendo extra: **{ep_title}** ({i+1}/{len(videos)})")
1835
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Serie:** {series_title}\n📁 **Episodio:** {ep_title}"
1836
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
1837
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
1838
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
1839
+
1840
+ db.collection('videos').add({
1841
+ "title": ep_title,
1842
+ "section": "series",
1843
+ "is_folder": False,
1844
+ "folder_id": series_id,
1845
+ "episode": max_ep,
1846
+ "season": 1,
1847
+ "video_url": file_url,
1848
+ "telegram_file_id": str(sent_to_channel.id),
1849
+ "description": "",
1850
+ "thumbnail_url": "",
1851
+ "cover_url": "",
1852
+ "views": 0,
1853
+ "rating": 0,
1854
+ "status": "active",
1855
+ "is_public": True,
1856
+ "categories": [],
1857
+ "servers": [file_url],
1858
+ "created_at": firestore.SERVER_TIMESTAMP,
1859
+ "updated_at": firestore.SERVER_TIMESTAMP
1860
+ })
1861
+ await status_msg.edit(f"✅ **¡{len(videos)} capítulos extra añadidos con éxito!**")
1862
+
1863
+ if __name__ == '__main__':
1864
+
1865
+ print("================================")
1866
+ print(f" BOT @TwistedStreamingBrodybot INICIADO")
1867
+ print("================================")
1868
+ client.start(bot_token=TOKEN)
1869
+
1870
+ # Limpiar el menú nativo de comandos de Telegram
1871
+ async def set_commands():
1872
+ from telethon.tl.functions.bots import SetBotCommandsRequest
1873
+ from telethon.tl.types import BotCommand, BotCommandScopeDefault
1874
+ try:
1875
+ await client(SetBotCommandsRequest(
1876
+ scope=BotCommandScopeDefault(),
1877
+ lang_code='',
1878
+ commands=[
1879
+ BotCommand(command="start", description="Iniciar el bot / Ver instrucciones"),
1880
+ BotCommand(command="subir", description="Men\xC3\xBA principal de subida"),
1881
+ BotCommand(command="subir_pelicula", description="Atajo: Subir Pel\xC3\xADcula"),
1882
+ BotCommand(command="subir_serie", description="Atajo: Subir Serie"),
1883
+ BotCommand(command="app", description="Abrir la Mini App de Cat\xC3\xA1logo"),
1884
+ BotCommand(command="setting", description="Configurar env\xC3\xADo de videos"),
1885
+ BotCommand(command="cancelar", description="Cancelar proceso de subida"),
1886
+ BotCommand(command="activar_modo_editor", description="Activar Modo Editor"),
1887
+ BotCommand(command="desactivar_modo_editor", description="Desactivar Modo Editor"),
1888
+ BotCommand(command="buscador_on", description="Activar Modo Buscador"),
1889
+ BotCommand(command="buscador_off", description="Desactivar Modo Buscador")
1890
+ ]
1891
+ ))
1892
+ print("📁 Menú nativo de comandos (/) actualizado.")
1893
+ except Exception as e:
1894
+ pass
1895
+
1896
+ client.loop.run_until_complete(set_commands())
1897
+ client.run_until_disconnected()
bot_buscador.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import uuid
3
+ import time
4
+ from telethon import events, Button
5
+ from telethon.tl.types import KeyboardButtonSimpleWebView, KeyboardButtonWebView
6
+ from google.cloud.firestore_v1.base_query import FieldFilter
7
+ from core import *
8
+
9
+ # --- MODO BUSCADOR ---
10
+ @client.on(events.NewMessage(pattern='^/buscador_on$'))
11
+ async def enable_search_mode(event):
12
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
13
+ if user_modes.get(chat_id) != 'buscador': return
14
+ chat_id = event.chat_id
15
+
16
+ # Desactivar editor y cancelar subidas
17
+ editor_mode_active[chat_id] = False
18
+ if chat_id in active_tasks:
19
+ for t in active_tasks[chat_id]:
20
+ t.cancel()
21
+ del active_tasks[chat_id]
22
+
23
+ search_mode_active[chat_id] = True
24
+ await event.respond("🔍 **Modo Buscador Activado**\n\nAhora puedes buscar enviando el título de una película, serie o capítulo. También puedes pegar enlaces directos o IDs.\n\nEnvía /buscador_off para salir.")
25
+
26
+ @client.on(events.NewMessage(pattern='^/buscador_off$'))
27
+ async def disable_search_mode(event):
28
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
29
+ if user_modes.get(chat_id) != 'buscador': return
30
+ chat_id = event.chat_id
31
+ search_mode_active[chat_id] = False
32
+ await event.respond("❌ **Modo Buscador Desactivado**.")
33
+
34
+ @client.on(events.NewMessage(func=lambda e: not e.text.startswith('/') and len(e.text) != 20))
35
+ async def handle_text_search(event):
36
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
37
+ if user_modes.get(chat_id) != 'buscador': return
38
+ chat_id = event.chat_id
39
+ if not True:
40
+ return
41
+ if editor_mode_active.get(chat_id, False):
42
+ return
43
+
44
+ query = event.raw_text.strip().lower()
45
+ if not query: return
46
+
47
+ msg = await event.respond("🔍 Buscando...")
48
+
49
+ # Buscar en Firestore (limitado en memoria por diseño simple de Firebase)
50
+ docs = db.collection('videos').get()
51
+
52
+ matched_docs = []
53
+ for d in docs:
54
+ data = d.to_dict()
55
+ title = data.get('title', '').lower()
56
+ if query in title:
57
+ matched_docs.append((d.id, data))
58
+
59
+ if not matched_docs:
60
+ await msg.edit("❌ No se encontraron resultados para tu búsqueda.")
61
+ return
62
+
63
+ # Buscar si hay alguna coincidencia EXACTA (para evitar que "Capítulo 1" muestre el "10", "11", etc.)
64
+ exact_matches = [m for m in matched_docs if m[1].get('title', '').lower() == query]
65
+ if len(exact_matches) == 1:
66
+ matched_docs = exact_matches
67
+
68
+ # Si hay exactamente 1 resultado, lo enviamos directamente
69
+ if len(matched_docs) == 1:
70
+ doc_id, data = matched_docs[0]
71
+ class DummyEvent:
72
+ def __init__(self, chat_id, raw_text):
73
+ self.chat_id = chat_id
74
+ self.raw_text = raw_text
75
+ async def respond(self, *args, **kwargs):
76
+ return await client.send_message(self.chat_id, *args, **kwargs)
77
+
78
+ dummy = DummyEvent(event.chat_id, doc_id)
79
+ await msg.delete()
80
+ await handle_document_id(dummy)
81
+ return
82
+
83
+ # Si hay múltiples, filtramos para dar prioridad a las Carpetas (Series) y Películas
84
+ # Esto evita mostrar una lista gigante de subcapítulos
85
+ folders_and_movies = []
86
+ chapters = []
87
+
88
+ for r_id, data in matched_docs:
89
+ if data.get('section') == 'peliculas' or data.get('is_folder'):
90
+ folders_and_movies.append((r_id, data))
91
+ else:
92
+ chapters.append((r_id, data))
93
+
94
+ # Mostrar carpetas/pelis si hay, sino mostrar capítulos sueltos
95
+ results = folders_and_movies if folders_and_movies else chapters
96
+
97
+ # Ordenar los resultados alfabéticamente por el título
98
+ results.sort(key=lambda x: x[1].get('title', '').lower())
99
+
100
+ # Mostrar resultados en botones
101
+ results = results[:20] # Limitar a 20 resultados para no exceder limite de botones
102
+ buttons = []
103
+ for r_id, data in results:
104
+ t = data.get('title', 'Sin titulo')[:40]
105
+ icon = "🎬" if data.get('section') == 'peliculas' else ("📺" if data.get('is_folder') else "🎞️")
106
+ buttons.append([Button.inline(f"{icon} {t}", f"get_vid_{r_id}".encode('utf-8'))])
107
+
108
+ await msg.edit(f"📌 **Resultados para:** `{query}`", buttons=buttons)
109
+
110
+ @client.on(events.CallbackQuery(pattern=b'^get_vid_'))
111
+ async def handle_search_result_click(event):
112
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
113
+ if user_modes.get(chat_id) != 'buscador': return
114
+ if not True:
115
+ await event.answer("El modo buscador está desactivado.", alert=True)
116
+ return
117
+
118
+ doc_id = event.data.decode('utf-8').replace('get_vid_', '')
119
+ await event.answer()
120
+
121
+ # Simulamos como si el usuario hubiera enviado el ID directamente
122
+ class DummyEvent:
123
+ def __init__(self, chat_id, raw_text):
124
+ self.chat_id = chat_id
125
+ self.raw_text = raw_text
126
+ async def respond(self, *args, **kwargs):
127
+ return await client.send_message(self.chat_id, *args, **kwargs)
128
+
129
+ dummy = DummyEvent(event.chat_id, doc_id)
130
+ await handle_document_id(dummy)
131
+
132
+ # --------------------------
133
+
134
+
135
+ # --- CONFIGURACIÓN Y FUNCIONES DE BÚSQUEDA POR ID ---
136
+
137
+ bot_settings = {
138
+ "send_title": True,
139
+ "send_description": True,
140
+ "ask_series": True
141
+ }
142
+
143
+ try:
144
+ doc_settings = db.collection('settings').document('delivery').get()
145
+ if doc_settings.exists:
146
+ s_data = doc_settings.to_dict()
147
+ bot_settings['send_title'] = s_data.get('send_title', True)
148
+ bot_settings['send_description'] = s_data.get('send_description', True)
149
+ bot_settings['ask_series'] = s_data.get('ask_series', True)
150
+ except Exception as e:
151
+ print(f"📁 Error cargando settings: {e}")
152
+
153
+ @client.on(events.NewMessage(pattern='/(settings|setting|config)$'))
154
+ async def settings_handler(event):
155
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
156
+ if user_modes.get(chat_id) != 'buscador': return
157
+ await show_settings_menu(event)
158
+
159
+ async def show_settings_menu(event_or_query):
160
+ title_status = "✅ PRENDIDO" if bot_settings['send_title'] else "❌ APAGADO"
161
+ desc_status = "✅ PRENDIDO" if bot_settings['send_description'] else "❌ APAGADO"
162
+ ask_status = "✅ PRENDIDO" if bot_settings['ask_series'] else "❌ APAGADO"
163
+
164
+ botones = [
165
+ [Button.inline(f"Título: {title_status}", b"toggle_title")],
166
+ [Button.inline(f"Descripción: {desc_status}", b"toggle_desc")],
167
+ [Button.inline(f"Preguntar Temporada/Capítulo: {ask_status}", b"toggle_ask")]
168
+ ]
169
+
170
+ text = "⚙️ **Configuración de Envío de Videos**\n\nElige cómo quieres que el bot entregue los videos:"
171
+
172
+ if isinstance(event_or_query, events.CallbackQuery.Event):
173
+ await event_or_query.edit(text, buttons=botones)
174
+ else:
175
+ await event_or_query.respond(text, buttons=botones)
176
+
177
+ from telethon.tl.types import KeyboardButtonWebView
178
+
179
+ @client.on(events.NewMessage(pattern='/(twistedstreamingbrodybot|app)$'))
180
+ async def miniapp_handler(event):
181
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
182
+ if user_modes.get(chat_id) != 'buscador': return
183
+ # Usamos KeyboardButtonWebView para forzar a Telegram a abrirlo como Mini App
184
+ botones = [[KeyboardButtonWebView(text="🍿 Abrir Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")]]
185
+
186
+ await event.respond(
187
+ "🍿 **¡Twisted Streaming Brody!**\n\nToca el botón abajo para abrir nuestra Mini App y navegar por todas las películas y series directamente desde Telegram.",
188
+ buttons=botones
189
+ )
190
+
191
+ button_cooldowns = {}
192
+
193
+ @client.on(events.CallbackQuery(pattern=b'^toggle_(title|desc|ask)$'))
194
+ async def toggle_settings_handler(event):
195
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
196
+ if user_modes.get(chat_id) != 'buscador': return
197
+ chat_id = event.chat_id
198
+ now = time.time()
199
+ if now - button_cooldowns.get(chat_id, 0) < 0.5:
200
+ await event.answer()
201
+ return
202
+ button_cooldowns[chat_id] = now
203
+
204
+ action = event.pattern_match.group(1).decode()
205
+ if action == 'title':
206
+ bot_settings['send_title'] = not bot_settings['send_title']
207
+ elif action == 'desc':
208
+ bot_settings['send_description'] = not bot_settings['send_description']
209
+ elif action == 'ask':
210
+ bot_settings['ask_series'] = not bot_settings['ask_series']
211
+
212
+ try:
213
+ db.collection('settings').document('delivery').set(bot_settings)
214
+ except: pass
215
+
216
+ await event.answer()
217
+ await show_settings_menu(event)
218
+
219
+ async def send_movie(chat_id, file_id, data):
220
+ cover = data.get('cover_url') or data.get('thumbnail_url')
221
+ caption_parts = []
222
+ if bot_settings['send_title'] and data.get('title'):
223
+ caption_parts.append(f"📁 **{data.get('title')}**")
224
+ if bot_settings['send_description'] and data.get('description'):
225
+ caption_parts.append(f"{data.get('description')}")
226
+
227
+ custom_caption = "\n\n".join(caption_parts)
228
+
229
+ if cover:
230
+ try:
231
+ await client.send_file(chat_id, cover, caption=custom_caption)
232
+ except Exception:
233
+ if custom_caption: await client.send_message(chat_id, custom_caption)
234
+ elif custom_caption:
235
+ await client.send_message(chat_id, custom_caption)
236
+
237
+ try:
238
+ msg = await client.get_messages(CHANNEL_ID, ids=int(file_id))
239
+ if msg and getattr(msg, 'media', None):
240
+ await client.send_file(chat_id, msg.media, caption="")
241
+ else:
242
+ await client.send_message(chat_id, "📁 Video no encontrado en el canal.")
243
+ except Exception as e:
244
+ print("Error enviando película:", e)
245
+
246
+ async def send_series_cover(chat_id, folder_id):
247
+ if not folder_id: return
248
+ try:
249
+ s_doc = db.collection('videos').document(folder_id).get()
250
+ if s_doc.exists:
251
+ s_data = s_doc.to_dict()
252
+ cover = s_data.get('thumbnail_url') or s_data.get('cover_url')
253
+
254
+ caption = ""
255
+ if bot_settings['send_title'] and s_data.get('title'):
256
+ caption = f"📁 **{s_data.get('title')}**"
257
+
258
+ if cover:
259
+ try:
260
+ await client.send_file(chat_id, cover, caption=caption)
261
+ except Exception:
262
+ if caption: await client.send_message(chat_id, caption)
263
+ elif caption:
264
+ await client.send_message(chat_id, caption)
265
+ except Exception as e:
266
+ print("Error al enviar portada de serie:", e)
267
+
268
+ async def send_episode_video(chat_id, file_id, ep_data):
269
+ try:
270
+ msg = await client.get_messages(CHANNEL_ID, ids=int(file_id))
271
+ if not msg or not getattr(msg, 'media', None):
272
+ await client.send_message(chat_id, "📁 Capítulo no encontrado en el canal.")
273
+ return
274
+
275
+ caption_parts = []
276
+ if bot_settings['send_title'] and ep_data.get('title'):
277
+ caption_parts.append(f"📁 **{ep_data.get('title')}**")
278
+ if bot_settings['send_description'] and ep_data.get('description'):
279
+ caption_parts.append(f"{ep_data.get('description')}")
280
+
281
+ custom_caption = "\n\n".join(caption_parts)
282
+ await client.send_file(chat_id, msg.media, caption=custom_caption)
283
+ except Exception as e:
284
+ print("Error enviando capítulo:", e)
285
+
286
+ async def send_full_season(chat_id, folder_id, status_msg=None):
287
+ if not status_msg:
288
+ status_msg = await client.send_message(chat_id, "📁 Preparando los capítulos...")
289
+ else:
290
+ try:
291
+ await status_msg.edit("📁 Preparando los capítulos...", buttons=None)
292
+ except Exception:
293
+ pass
294
+
295
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', folder_id)).get()
296
+ if not episodes:
297
+ await status_msg.edit("📁 No se encontraron capítulos.")
298
+ return
299
+
300
+ await send_series_cover(chat_id, folder_id)
301
+
302
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
303
+ for ep in episodes_sorted:
304
+ data = ep.to_dict()
305
+ file_id = data.get('telegram_file_id')
306
+ if file_id:
307
+ await send_episode_video(chat_id, file_id, data)
308
+ await asyncio.sleep(0.5)
309
+ await status_msg.edit("📁 **¡Temporada enviada!**")
310
+
311
+ @client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
312
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
313
+ async def handle_document_id(event):
314
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
315
+ if user_modes.get(chat_id) != 'buscador': return
316
+
317
+ if editor_mode_active.get(event.chat_id, False):
318
+ return
319
+
320
+ text = event.raw_text.strip()
321
+ is_folder_request = False
322
+
323
+ if text.startswith('/start '):
324
+ payload = text.split(' ')[1]
325
+ if payload.startswith('folder_'):
326
+ is_folder_request = True
327
+ doc_id = payload.replace('folder_', '', 1)
328
+ else:
329
+ doc_id = payload
330
+ else:
331
+ if text.startswith('folder/') or text.startswith('folder_'):
332
+ is_folder_request = True
333
+ doc_id = text.replace('folder/', '', 1).replace('folder_', '', 1)
334
+ else:
335
+ doc_id = text
336
+
337
+ try:
338
+ doc = db.collection('videos').document(doc_id).get()
339
+ if not doc.exists:
340
+ return
341
+
342
+ data = doc.to_dict()
343
+ section = data.get('section')
344
+ is_folder = data.get('is_folder')
345
+
346
+ if section == 'peliculas':
347
+ file_id = data.get('telegram_file_id')
348
+ if file_id:
349
+ await send_movie(event.chat_id, file_id, data)
350
+ else:
351
+ await event.respond("📁 No se encontró el archivo en Telegram para esta película.")
352
+
353
+ elif section == 'series':
354
+ folder_id = doc_id if is_folder else data.get('folder_id')
355
+
356
+ if is_folder_request:
357
+ await send_full_season(event.chat_id, folder_id)
358
+ return
359
+
360
+ if not bot_settings.get('ask_series', True):
361
+ if is_folder:
362
+ await send_full_season(event.chat_id, folder_id)
363
+ else:
364
+ file_id = data.get('telegram_file_id')
365
+ if file_id:
366
+ await send_series_cover(event.chat_id, folder_id)
367
+ await send_episode_video(event.chat_id, file_id, data)
368
+ else:
369
+ await event.respond("📁 Archivo no encontrado.")
370
+ return
371
+
372
+ if is_folder:
373
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', doc_id)).get()
374
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
375
+
376
+ botones = []
377
+ row = []
378
+ for ep in episodes_sorted:
379
+ ep_data = ep.to_dict()
380
+ ep_num = ep_data.get('episode', '?')
381
+ ep_id = ep.id
382
+ row.append(Button.inline(f"Cap {ep_num}", f"this_cap_{ep_id}".encode()))
383
+ if len(row) == 3:
384
+ botones.append(row)
385
+ row = []
386
+ if row:
387
+ botones.append(row)
388
+
389
+ botones.append([Button.inline("📁 Enviar Temporada Completa", f"all_caps_{doc_id}".encode())])
390
+
391
+ await event.respond(f"📁 **Serie:** {data.get('title')}\nSelecciona un capítulo o envía la temporada completa:", buttons=botones)
392
+ else:
393
+ botones = [
394
+ [Button.inline("📁 Enviar solo este video", f"this_cap_{doc_id}".encode())],
395
+ [Button.inline("📁 Enviar Temporada Completa", f"all_caps_{folder_id}".encode())]
396
+ ]
397
+ await event.respond(f"📁 **Capítulo:** {data.get('title')}\n¿Qué deseas hacer?", buttons=botones)
398
+
399
+ except Exception as e:
400
+ print(f"Error buscando documento {doc_id}: {e}")
401
+
402
+ @client.on(events.CallbackQuery(pattern=b'^(this_cap_|all_caps_|choose_cap_)(.*)'))
403
+ async def handle_series_delivery(event):
404
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
405
+ if user_modes.get(chat_id) != 'buscador': return
406
+ chat_id = event.chat_id
407
+ now = time.time()
408
+ if now - button_cooldowns.get(chat_id, 0) < 1.0:
409
+ await event.answer("Procesando...", alert=False)
410
+ return
411
+ button_cooldowns[chat_id] = now
412
+
413
+ action = event.pattern_match.group(1).decode()
414
+ target_id = event.pattern_match.group(2).decode()
415
+
416
+ try:
417
+ if action == "this_cap_":
418
+ await event.answer("📁 Enviando capítulo...", alert=False)
419
+ doc = db.collection('videos').document(target_id).get()
420
+ if doc.exists:
421
+ data = doc.to_dict()
422
+ file_id = data.get('telegram_file_id')
423
+ folder_id = data.get('folder_id')
424
+ if file_id:
425
+ await send_series_cover(event.chat_id, folder_id)
426
+ await send_episode_video(event.chat_id, file_id, data)
427
+ else:
428
+ await event.respond("📁 Archivo no encontrado.")
429
+
430
+ elif action == "all_caps_":
431
+ await event.answer("📁 Preparando temporada...", alert=False)
432
+ await send_full_season(chat_id, target_id, status_msg=event)
433
+
434
+ elif action == "choose_cap_":
435
+ await event.answer("📁 Cargando capítulos...", alert=False)
436
+ episodes = db.collection('videos').where(filter=FieldFilter('folder_id', '==', target_id)).get()
437
+ if not episodes:
438
+ await event.answer("No se encontraron capítulos.", alert=True)
439
+ return
440
+
441
+ episodes_sorted = sorted(episodes, key=lambda x: x.to_dict().get('episode', 0))
442
+
443
+ botones = []
444
+ row = []
445
+ for ep in episodes_sorted:
446
+ data = ep.to_dict()
447
+ ep_num = data.get('episode', '?')
448
+ ep_id = ep.id
449
+ row.append(Button.inline(f"Cap {ep_num}", f"this_cap_{ep_id}".encode()))
450
+ if len(row) == 3:
451
+ botones.append(row)
452
+ row = []
453
+ if row:
454
+ botones.append(row)
455
+
456
+ await event.edit("📁 **Selecciona el capítulo:**", buttons=botones)
457
+
458
+ except Exception as e:
459
+ print(f"Error en delivery: {e}")
460
+ await event.respond("📁 Hubo un error procesando la solicitud.")
461
+
462
+
bot_editor.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import uuid
3
+ import time
4
+ from telethon import events, Button
5
+ from telethon.tl.types import KeyboardButtonSimpleWebView, KeyboardButtonWebView
6
+ from google.cloud.firestore_v1.base_query import FieldFilter
7
+ from core import *
8
+
9
+ # --- MODO EDITOR ---
10
+ @client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
11
+ async def enable_editor(event):
12
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
13
+ if user_modes.get(chat_id) != 'editor': return
14
+ import asyncio
15
+ chat_id = event.chat_id
16
+
17
+ # Cancel previous tasks to prevent "Botón expirado" background overlap
18
+ if chat_id in active_tasks:
19
+ for old_task in active_tasks[chat_id]:
20
+ if not old_task.done():
21
+ if not getattr(old_task, 'is_uploading', False):
22
+ old_task.cancel()
23
+ try: await asyncio.sleep(0.1)
24
+ except: pass
25
+
26
+ current_task = asyncio.current_task()
27
+ current_task.is_uploading = False
28
+
29
+ if chat_id not in active_tasks:
30
+ active_tasks[chat_id] = []
31
+ active_tasks[chat_id].append(current_task)
32
+
33
+ editor_mode_active[chat_id] = True
34
+ try:
35
+ await handle_editor_mode(event)
36
+ finally:
37
+ if current_task in active_tasks.get(chat_id, []):
38
+ active_tasks[chat_id].remove(current_task)
39
+ if not active_tasks[chat_id]:
40
+ del active_tasks[chat_id]
41
+
42
+
43
+ @client.on(events.NewMessage(pattern='/(desactivar_modo_editor)$'))
44
+ async def disable_editor(event):
45
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
46
+ if user_modes.get(chat_id) != 'editor': return
47
+ chat_id = event.chat_id
48
+ editor_mode_active[chat_id] = False
49
+ await event.respond("✅ **Modo editor desactivado.** Ya puedes usar los comandos normales.")
50
+
51
+ async def process_editor_id(conv, txt):
52
+ doc = db.collection('videos').document(txt).get()
53
+ if doc.exists:
54
+ data = doc.to_dict()
55
+ if data.get('section') == 'peliculas':
56
+ await handle_editor_movie_action(conv, txt)
57
+ elif data.get('is_folder', False):
58
+ await handle_editor_series_action(conv, txt)
59
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
60
+ await handle_editor_single_chapter(conv, txt)
61
+ else:
62
+ await conv.send_message("❌ Tipo de documento no reconocido.")
63
+ else:
64
+ # Búsqueda por texto si no es un ID exacto
65
+ all_videos = db.collection('videos').get()
66
+ results = [v for v in all_videos if txt.lower() in v.to_dict().get('title', '').lower()]
67
+
68
+ if not results:
69
+ from telethon.tl.types import KeyboardButtonWebView
70
+ btn_webapp = KeyboardButtonWebView(text="🍿 Buscar en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
71
+ await conv.send_message(
72
+ f"❌ No se encontró ningún contenido con el nombre o ID: `{txt}`\n\n🔍 **Sugerencia:** Puedes buscar el nombre o ID exacto directamente en la Mini App:",
73
+ buttons=[[btn_webapp]]
74
+ )
75
+ return
76
+
77
+ results = results[:10]
78
+ buttons = []
79
+ for r in results:
80
+ data = r.to_dict()
81
+ icon = "🎬" if data.get('section') == 'peliculas' else "📺" if data.get('is_folder', False) else "🎞️"
82
+ title = data.get('title', 'Sin título')[:30]
83
+ buttons.append([Button.inline(f"{icon} {title}", f"ed_jump_{r.id}".encode('utf-8'))])
84
+
85
+ buttons.append([Button.inline("❌ Cancelar", b"ed_cancel")])
86
+
87
+ msg_res = await conv.send_message("📌 **Resultados de Búsqueda:**", buttons=buttons)
88
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
89
+
90
+ if isinstance(resp_res, events.CallbackQuery.Event):
91
+ await resp_res.answer()
92
+ try: await msg_res.edit(buttons=None)
93
+ except: pass
94
+
95
+ if resp_res.data == b"ed_cancel": return
96
+
97
+ selected_id = resp_res.data.decode().replace('ed_jump_', '')
98
+ await process_editor_id(conv, selected_id)
99
+
100
+ async def handle_editor_mode(event, initial_txt=None):
101
+ chat_id = event.chat_id
102
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
103
+ current_jump_id = initial_txt
104
+
105
+ while True:
106
+ try:
107
+ if current_jump_id:
108
+ jump = current_jump_id
109
+ current_jump_id = None
110
+ await process_editor_id(conv, jump)
111
+
112
+ from telethon.tl.types import KeyboardButtonWebView
113
+ btn_webapp = KeyboardButtonWebView(text="🍿 Twisted Streaming Brody", url="https://codebybrody-twistedstreamingbrody.hf.space")
114
+ await conv.send_message("🛠️ **Modo Editor**\nEnvíame otro ID para editar, o busca en la Mini App:", buttons=[[btn_webapp]])
115
+ continue
116
+
117
+ if not initial_txt and not current_jump_id:
118
+ msg_main = await conv.send_message(
119
+ "🛠️ **Modo Editor Activado**\n\n"
120
+ "Envíame el **ID** del contenido que deseas editar..."
121
+ )
122
+
123
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
124
+
125
+ if isinstance(resp, events.CallbackQuery.Event):
126
+ await resp.answer("Botón expirado o inválido.", alert=True)
127
+ continue
128
+
129
+ if getattr(resp, 'raw_text', ''):
130
+ txt = resp.raw_text.strip()
131
+ if txt.startswith('/start '):
132
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
133
+
134
+ if txt.startswith('/'):
135
+ if txt == '/desactivar_modo_editor':
136
+ break
137
+ continue
138
+
139
+ await process_editor_id(conv, txt)
140
+
141
+ # Prompt user again after finishing an edit
142
+ from telethon.tl.types import KeyboardButtonWebView
143
+ btn_webapp = KeyboardButtonWebView(text="🍿 Twisted Streaming Brody", url="https://codebybrody-twistedstreamingbrody.hf.space")
144
+ await conv.send_message("🛠️ **Modo Editor**\nEnvíame otro ID para editar, o busca en la Mini App:", buttons=[[btn_webapp]])
145
+
146
+ except EditorJumpException as e:
147
+ current_jump_id = e.jump_id
148
+ except CancelUploadException:
149
+ break
150
+ except asyncio.CancelledError:
151
+ break
152
+ except Exception as e:
153
+ print("Editor error:", e)
154
+ break
155
+
156
+ async def handle_editor_movie_search(conv):
157
+ from telethon.tl.types import KeyboardButtonWebView
158
+ try:
159
+ tmp = await conv.send_message("🔄 Actualizando...", buttons=Button.clear())
160
+ await tmp.delete()
161
+ except: pass
162
+ uid_back = str(uuid.uuid4()).encode()
163
+ btn_webapp = KeyboardButtonWebView(text="🍿 Buscar ID en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
164
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la película que deseas buscar:", buttons=[
165
+ [btn_webapp],
166
+ [Button.inline("⬅️ Cancelar", uid_back)]
167
+ ])
168
+
169
+ resp = await wait_for_message_or_callback(conv, timeout=300)
170
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
171
+ await resp.answer("Cancelado")
172
+ await msg.edit("Búsqueda cancelada.", buttons=None)
173
+ return
174
+
175
+ query = resp.raw_text.strip()
176
+ await msg.delete()
177
+
178
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
179
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower() or query == m.id]
180
+
181
+ if not results:
182
+ await conv.send_message("❌ No se encontraron películas con ese nombre.")
183
+ return
184
+
185
+ results = results[:10]
186
+ buttons = []
187
+ for r in results:
188
+ data = r.to_dict()
189
+ buttons.append([Button.inline(f"🎬 {data.get('title')[:30]}", f"ed_m_{r.id}".encode('utf-8'))])
190
+
191
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
192
+
193
+ msg_res = await conv.send_message("📌 **Resultados (Películas):**", buttons=buttons)
194
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
195
+
196
+ if isinstance(resp_res, events.CallbackQuery.Event):
197
+ await resp_res.answer()
198
+ await msg_res.edit(buttons=None)
199
+ if resp_res.data == b"ed_back": return
200
+
201
+ movie_id = resp_res.data.decode().replace('ed_m_', '')
202
+ await handle_editor_movie_action(conv, movie_id)
203
+
204
+ async def handle_editor_movie_action(conv, movie_id):
205
+ doc = db.collection('videos').document(movie_id).get()
206
+ if not doc.exists: return
207
+ data = doc.to_dict()
208
+
209
+ msg = await conv.send_message(
210
+ f"🎬 **Editando Película:**\n`{data.get('title')}`",
211
+ buttons=[
212
+ [Button.inline("✏️ Renombrar Título", b"renombrar")],
213
+ [Button.inline("📝 Editar Descripción", b"edit_desc")],
214
+ [Button.inline("🖼️ Editar Portada", b"edit_cover")],
215
+ [Button.inline("🗑️ Eliminar Película", b"eliminar")],
216
+ [Button.inline("⬅️ Volver", b"volver")]
217
+ ]
218
+ )
219
+ resp = await wait_for_message_or_callback(conv, timeout=300)
220
+ if isinstance(resp, events.CallbackQuery.Event):
221
+ await resp.answer()
222
+ await msg.edit(buttons=None)
223
+ if resp.data == b"volver": return
224
+ elif resp.data == b"renombrar":
225
+ await conv.send_message("Escribe el **nuevo título** para la película:")
226
+ new_title = await conv.get_response()
227
+ db.collection('videos').document(movie_id).update({"title": new_title.raw_text})
228
+ await conv.send_message(f"✅ Título actualizado a: **{new_title.raw_text}**")
229
+ elif resp.data == b"edit_desc":
230
+ uid_del = str(uuid.uuid4()).encode()
231
+ msg_d = await conv.send_message("Escribe la **nueva descripción** para la película:", buttons=[[Button.inline("❌ Eliminar Descripción", uid_del)]])
232
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
233
+ if isinstance(resp_d, events.CallbackQuery.Event):
234
+ await resp_d.answer("Eliminando...")
235
+ db.collection('videos').document(movie_id).update({"description": ""})
236
+ await msg_d.edit("✅ Descripción eliminada.", buttons=None)
237
+ else:
238
+ db.collection('videos').document(movie_id).update({"description": resp_d.raw_text})
239
+ await msg_d.edit("✅ Descripción actualizada.", buttons=None)
240
+ elif resp.data == b"edit_cover":
241
+ msg_cover = await conv.send_message("🖼️ Envía la nueva portada como imagen (no archivo):")
242
+ resp_cover = await wait_for_message_or_callback(conv, timeout=300)
243
+ if getattr(resp_cover, 'photo', None):
244
+ await msg_cover.edit("🖼️ Subiendo portada...", buttons=None)
245
+ cover_url = await upload_to_imgbb(resp_cover.photo)
246
+ if cover_url:
247
+ db.collection('videos').document(movie_id).update({"cover_url": cover_url, "thumbnail_url": cover_url})
248
+ await conv.send_message("✅ Portada actualizada con éxito.")
249
+ else:
250
+ await conv.send_message("❌ Hubo un error al subir la portada.")
251
+ else:
252
+ if isinstance(resp_cover, events.CallbackQuery.Event):
253
+ await resp_cover.answer("Cancelado")
254
+ else:
255
+ await conv.send_message("❌ No se recibió una imagen válida.")
256
+ elif resp.data == b"eliminar":
257
+ msg_conf = await conv.send_message(
258
+ f"⚠️ ¿Estás seguro de que deseas eliminar la película **{data.get('title')}**?\nEsta acción no se puede deshacer.",
259
+ buttons=[
260
+ [Button.inline("⚠️ Sí, eliminar definitivamente", b"confirm_del")],
261
+ [Button.inline("❌ Cancelar", b"cancel_del")]
262
+ ]
263
+ )
264
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
265
+ if isinstance(resp_conf, events.CallbackQuery.Event):
266
+ await resp_conf.answer()
267
+ await msg_conf.edit(buttons=None)
268
+ if resp_conf.data == b"confirm_del":
269
+ db.collection('videos').document(movie_id).delete()
270
+ await conv.send_message("✅ Película eliminada exitosamente.")
271
+ else:
272
+ await conv.send_message("✅ Eliminación cancelada.")
273
+
274
+ async def handle_editor_series_search(conv):
275
+ from telethon.tl.types import KeyboardButtonWebView
276
+ try:
277
+ tmp = await conv.send_message("🔄 Actualizando...", buttons=Button.clear())
278
+ await tmp.delete()
279
+ except: pass
280
+ uid_back = str(uuid.uuid4()).encode()
281
+ btn_webapp = KeyboardButtonWebView(text="🍿 Buscar ID en Catálogo", url="https://codebybrody-twistedstreamingbrody.hf.space")
282
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la serie que deseas buscar:", buttons=[
283
+ [btn_webapp],
284
+ [Button.inline("⬅️ Cancelar", uid_back)]
285
+ ])
286
+
287
+ resp = await wait_for_message_or_callback(conv, timeout=300)
288
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
289
+ await resp.answer()
290
+ await msg.edit("Búsqueda cancelada.", buttons=None)
291
+ return
292
+
293
+ query = resp.raw_text.strip()
294
+ await msg.delete()
295
+
296
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
297
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower() or query == s.id]
298
+
299
+ if not results:
300
+ await conv.send_message("❌ No se encontraron series con ese nombre.")
301
+ return
302
+
303
+ results = results[:10]
304
+ buttons = []
305
+ for r in results:
306
+ buttons.append([Button.inline(f"📺 {r.to_dict().get('title')[:30]}", f"ed_s_{r.id}".encode('utf-8'))])
307
+
308
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
309
+
310
+ msg_res = await conv.send_message("📌 **Resultados (Series):**", buttons=buttons)
311
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
312
+
313
+ if isinstance(resp_res, events.CallbackQuery.Event):
314
+ await resp_res.answer()
315
+ await msg_res.edit(buttons=None)
316
+ if resp_res.data == b"ed_back": return
317
+
318
+ series_id = resp_res.data.decode().replace('ed_s_', '')
319
+ await handle_editor_series_action(conv, series_id)
320
+
321
+ async def handle_editor_series_action(conv, series_id):
322
+ while True:
323
+ doc = db.collection('videos').document(series_id).get()
324
+ if not doc.exists: return
325
+ data = doc.to_dict()
326
+ title = data.get('title')
327
+
328
+ msg = await conv.send_message(
329
+ f"📺 **Editando Serie:**\n`{title}`",
330
+ buttons=[
331
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
332
+ [Button.inline("🖼️ Editar Portada General", b"edit_cover")],
333
+ [Button.inline("📝 Edición Masiva de Descripciones", b"edit_desc_masiva")],
334
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
335
+ [Button.inline("📝 Edición Masiva de Capítulos", b"editar_lista")],
336
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
337
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
338
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
339
+ ]
340
+ )
341
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
342
+ if getattr(resp, 'raw_text', '').startswith('/'): return
343
+
344
+ if isinstance(resp, events.CallbackQuery.Event):
345
+ await resp.answer()
346
+ await msg.edit(buttons=None)
347
+
348
+ if resp.data == b"volver": return
349
+ elif resp.data == b"renombrar":
350
+ await conv.send_message("Escribe el **nuevo título general** para la serie:")
351
+ new_title = await conv.get_response()
352
+ db.collection('videos').document(series_id).update({"title": new_title.raw_text})
353
+ await conv.send_message(f"✅ Título general actualizado a: **{new_title.raw_text}**")
354
+ elif resp.data == b"edit_cover":
355
+ msg_cover = await conv.send_message("🖼️ Envía la nueva portada general de la serie como imagen (no archivo):")
356
+ resp_cover = await wait_for_message_or_callback(conv, timeout=300)
357
+ if getattr(resp_cover, 'photo', None):
358
+ await msg_cover.edit("🖼️ Subiendo portada...", buttons=None)
359
+ cover_url = await upload_to_imgbb(resp_cover.photo)
360
+ if cover_url:
361
+ db.collection('videos').document(series_id).update({"thumbnail_url": cover_url, "cover_url": cover_url})
362
+ await conv.send_message("✅ Portada de la serie actualizada con éxito.")
363
+ else:
364
+ await conv.send_message("❌ Hubo un error al subir la portada.")
365
+ else:
366
+ if isinstance(resp_cover, events.CallbackQuery.Event):
367
+ await resp_cover.answer("Cancelado")
368
+ else:
369
+ await conv.send_message("❌ No se recibió una imagen válida.")
370
+ elif resp.data == b"edit_desc_masiva":
371
+ uid_del = str(uuid.uuid4()).encode()
372
+ msg_d = await conv.send_message("Escribe la **nueva descripción** para aplicarla a TODOS los capítulos de esta serie:", buttons=[[Button.inline("❌ Eliminar Todas las Descripciones", uid_del)]])
373
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
374
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
375
+ updated_count = 0
376
+
377
+ if isinstance(resp_d, events.CallbackQuery.Event):
378
+ await resp_d.answer("Eliminando...")
379
+ for c in caps:
380
+ db.collection('videos').document(c.id).update({"description": ""})
381
+ updated_count += 1
382
+ await msg_d.edit(f"✅ Descripciones eliminadas masivamente en {updated_count} capítulos.", buttons=None)
383
+ else:
384
+ for c in caps:
385
+ db.collection('videos').document(c.id).update({"description": resp_d.raw_text})
386
+ updated_count += 1
387
+ await msg_d.edit(f"✅ Descripción aplicada masivamente a {updated_count} capítulos.", buttons=None)
388
+ elif resp.data == b"eliminar":
389
+ msg_conf = await conv.send_message(
390
+ f"⚠️ ¿Estás seguro de que deseas eliminar la serie completa **{title}** y **TODOS** sus capítulos?\nEsta acción no se puede deshacer.",
391
+ buttons=[
392
+ [Button.inline("⚠️ Sí, eliminar serie y capítulos", b"confirm_del")],
393
+ [Button.inline("❌ Cancelar", b"cancel_del")]
394
+ ]
395
+ )
396
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
397
+ if isinstance(resp_conf, events.CallbackQuery.Event):
398
+ await resp_conf.answer()
399
+ await msg_conf.edit(buttons=None)
400
+ if resp_conf.data == b"confirm_del":
401
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
402
+ for c in caps: db.collection('videos').document(c.id).delete()
403
+ db.collection('videos').document(series_id).delete()
404
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados exitosamente.")
405
+ return
406
+ else:
407
+ await conv.send_message("✅ Eliminación cancelada.")
408
+ elif resp.data == b"ver_caps":
409
+ await handle_editor_series_chapters(conv, series_id, title)
410
+ elif resp.data == b"editar_lista":
411
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
412
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
413
+ if not caps:
414
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
415
+ continue
416
+
417
+ template = f"{{TITULO_GENERAL}} {title}\n\n"
418
+ for c in caps:
419
+ template += f"{{{c.id}}} {c.to_dict().get('title')}\n"
420
+
421
+ await conv.send_message(
422
+ "📝 **EDICIÓN MASIVA**\n\n"
423
+ "1. Toca el siguiente mensaje para copiarlo.\n"
424
+ "2. Pégalo en el chat y edita el nombre de la serie o de los capítulos como desees.\n"
425
+ "3. Envíamelo.\n\n"
426
+ "⚠️ **MUY IMPORTANTE:** ¡NO borres ni modifiques los códigos entre llaves `{ }`!"
427
+ )
428
+ await conv.send_message(f"```{template}```")
429
+
430
+ await conv.send_message("⏳ Esperando tu mensaje con la plantilla editada... (O envía `/cancelar` para abortar)")
431
+
432
+ resp_text = await wait_for_message_or_callback(conv, timeout=3600)
433
+ if isinstance(resp_text, events.CallbackQuery.Event):
434
+ await resp_text.answer("Operación cancelada")
435
+ continue
436
+ if resp_text.raw_text.strip().lower() == '/cancelar':
437
+ await conv.send_message("✅ Edición masiva cancelada.")
438
+ continue
439
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
440
+
441
+ new_text = resp_text.raw_text
442
+ import re
443
+ matches = re.findall(r'\{(.*?)\}\s*(.*)', new_text)
444
+
445
+ if not matches:
446
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
447
+ continue
448
+
449
+ status_m = await conv.send_message("⚙️ Guardando cambios...")
450
+ updated_count = 0
451
+ for doc_id, new_title in matches:
452
+ doc_id = doc_id.strip()
453
+ new_title = new_title.strip()
454
+ if new_title:
455
+ if doc_id == "TITULO_GENERAL":
456
+ try:
457
+ db.collection('videos').document(series_id).update({"title": new_title})
458
+ title = new_title # update variable
459
+ except: pass
460
+ else:
461
+ try:
462
+ db.collection('videos').document(doc_id).update({"title": new_title})
463
+ updated_count += 1
464
+ except: pass
465
+
466
+ await status_m.edit(f"✅ **¡Listo!** Se actualizó el título general y {updated_count} capítulos correctamente.")
467
+ elif resp.data == b"add_caps":
468
+ await handle_editor_add_chapters(conv, series_id, title)
469
+
470
+ async def handle_editor_series_chapters(conv, series_id, series_title):
471
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
472
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
473
+ if not caps:
474
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
475
+ return
476
+
477
+ buttons = []
478
+ for c in caps[:90]:
479
+ c_data = c.to_dict()
480
+ buttons.append([Button.inline(f"Cap {c_data.get('episode', 0)}: {c_data.get('title')[:20]}", f"ed_c_{c.id}".encode('utf-8'))])
481
+
482
+ buttons.append([Button.inline("⬅️ Volver", b"volver_caps")])
483
+
484
+ msg = await conv.send_message(f"📑 **Capítulos de {series_title}**\nSelecciona uno para editar:", buttons=buttons)
485
+ resp = await wait_for_message_or_callback(conv, timeout=300)
486
+
487
+ if isinstance(resp, events.CallbackQuery.Event):
488
+ await resp.answer()
489
+ await msg.edit(buttons=None)
490
+ if resp.data == b"volver_caps": return
491
+ cap_id = resp.data.decode().replace('ed_c_', '')
492
+ await handle_editor_single_chapter(conv, cap_id)
493
+
494
+ async def handle_editor_single_chapter(conv, cap_id):
495
+ doc = db.collection('videos').document(cap_id).get()
496
+ if not doc.exists: return
497
+ data = doc.to_dict()
498
+
499
+ msg = await conv.send_message(
500
+ f"🎞️ **Editando Capítulo:**\n`{data.get('title')}`",
501
+ buttons=[
502
+ [Button.inline("✏️ Renombrar", b"renombrar")],
503
+ [Button.inline("📝 Editar Descripción", b"edit_desc")],
504
+ [Button.inline("🗑️ Eliminar Capítulo", b"eliminar")],
505
+ [Button.inline("🚨 Eliminar Serie Completa", b"elim_serie")],
506
+ [Button.inline("⬅️ Volver", b"volver")]
507
+ ]
508
+ )
509
+ resp = await wait_for_message_or_callback(conv, timeout=300)
510
+ if isinstance(resp, events.CallbackQuery.Event):
511
+ await resp.answer()
512
+ await msg.edit(buttons=None)
513
+ if resp.data == b"volver": return
514
+ if resp.data == b"renombrar":
515
+ await conv.send_message("Escribe el **nuevo nombre** del capítulo:")
516
+ new_title = await conv.get_response()
517
+ db.collection('videos').document(cap_id).update({"title": new_title.raw_text})
518
+ await conv.send_message(f"✅ Capítulo renombrado a: **{new_title.raw_text}**")
519
+ if resp.data == b"edit_desc":
520
+ uid_del = str(uuid.uuid4()).encode()
521
+ msg_d = await conv.send_message("Escribe la **nueva descripción** del capítulo:", buttons=[[Button.inline("❌ Eliminar Descripción", uid_del)]])
522
+ resp_d = await wait_for_message_or_callback(conv, timeout=300)
523
+ if isinstance(resp_d, events.CallbackQuery.Event):
524
+ await resp_d.answer("Eliminando...")
525
+ db.collection('videos').document(cap_id).update({"description": ""})
526
+ await msg_d.edit("✅ Descripción eliminada.", buttons=None)
527
+ else:
528
+ db.collection('videos').document(cap_id).update({"description": resp_d.raw_text})
529
+ await msg_d.edit("✅ Descripción actualizada.", buttons=None)
530
+ if resp.data == b"eliminar":
531
+ msg_conf = await conv.send_message(
532
+ f"⚠️ ¿Estás seguro de que deseas eliminar el capítulo **{data.get('title')}**?\nEsta acción no se puede deshacer.",
533
+ buttons=[
534
+ [Button.inline("⚠️ Sí, eliminar capítulo", b"confirm_del")],
535
+ [Button.inline("❌ Cancelar", b"cancel_del")]
536
+ ]
537
+ )
538
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
539
+ if isinstance(resp_conf, events.CallbackQuery.Event):
540
+ await resp_conf.answer()
541
+ await msg_conf.edit(buttons=None)
542
+ if resp_conf.data == b"confirm_del":
543
+ db.collection('videos').document(cap_id).delete()
544
+ await conv.send_message("✅ Capítulo eliminado exitosamente.")
545
+ else:
546
+ await conv.send_message("✅ Eliminación cancelada.")
547
+ if resp.data == b"elim_serie":
548
+ series_id = data.get('folder_id')
549
+ if not series_id:
550
+ await conv.send_message("❌ Error: Este capítulo no pertenece a una serie.")
551
+ return
552
+
553
+ series_doc = db.collection('videos').document(series_id).get()
554
+ series_title = series_doc.to_dict().get('title') if series_doc.exists else "Desconocida"
555
+
556
+ msg_conf = await conv.send_message(
557
+ f"🚨 **¡PELIGRO!**\n¿Estás seguro de que deseas eliminar la serie completa **{series_title}** y **TODOS** sus capítulos?\nEsta acción te dejará sin nada y no se puede deshacer.",
558
+ buttons=[
559
+ [Button.inline("🚨 Sí, eliminar serie y capítulos", b"confirm_del_serie")],
560
+ [Button.inline("❌ Cancelar", b"cancel_del")]
561
+ ]
562
+ )
563
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
564
+ if isinstance(resp_conf, events.CallbackQuery.Event):
565
+ await resp_conf.answer()
566
+ await msg_conf.edit(buttons=None)
567
+ if resp_conf.data == b"confirm_del_serie":
568
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
569
+ for c in caps: db.collection('videos').document(c.id).delete()
570
+ if series_doc.exists:
571
+ db.collection('videos').document(series_id).delete()
572
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados exitosamente.")
573
+ raise CancelUploadException() # Fuerza salida limpia al menú principal
574
+ else:
575
+ await conv.send_message("✅ Eliminación cancelada.")
576
+
577
+
578
+ async def handle_editor_add_chapters(conv, series_id, series_title):
579
+ uid_done = str(uuid.uuid4()).encode()
580
+ videos = []
581
+
582
+ msg_v = await conv.send_message(
583
+ f"➕ **Añadiendo capítulos a: {series_title}**\n\nEnvía los videos. Cuando termines presiona el botón.",
584
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
585
+ )
586
+
587
+ debounce_task = None
588
+ async def update_button():
589
+ await asyncio.sleep(0.8)
590
+ nonlocal msg_v
591
+ try: await msg_v.delete()
592
+ except: pass
593
+ msg_v = await conv.send_message(
594
+ f"➕ **Añadiendo capítulos a: {series_title}**\n\n({len(videos)} recibidos). Envía más o termina.",
595
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
596
+ )
597
+
598
+ async def video_receiver(e):
599
+ is_video = False
600
+ if getattr(e, 'media', None):
601
+ if getattr(e, 'video', None):
602
+ is_video = True
603
+ elif getattr(e, 'document', None):
604
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
605
+ if mime.startswith('video/'):
606
+ is_video = True
607
+ else:
608
+ for attr in e.document.attributes:
609
+ if hasattr(attr, 'file_name'):
610
+ import os
611
+ ext = os.path.splitext(attr.file_name)[1].lower()
612
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
613
+ is_video = True
614
+ break
615
+ if is_video:
616
+ videos.append(e)
617
+ nonlocal debounce_task
618
+ if debounce_task: debounce_task.cancel()
619
+ debounce_task = asyncio.create_task(update_button())
620
+
621
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
622
+ try:
623
+ while True:
624
+ event = await wait_for_message_or_callback(conv, timeout=3600)
625
+ if isinstance(event, events.CallbackQuery.Event):
626
+ if event.data == uid_done:
627
+ if not videos:
628
+ await event.answer("No has enviado videos.", alert=True)
629
+ return
630
+ await event.answer("Guardando...")
631
+ if debounce_task: debounce_task.cancel()
632
+ await msg_v.edit(f"✅ Se recibieron {len(videos)} capítulos.", buttons=None)
633
+ break
634
+ finally:
635
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
636
+
637
+ if not videos: return
638
+
639
+ uid_title = str(uuid.uuid4()).encode()
640
+ uid_file = str(uuid.uuid4()).encode()
641
+
642
+ sample_names = ""
643
+ for v in videos[:2]:
644
+ doc_name = "Video_desconocido.mp4"
645
+ if hasattr(v.media, 'document'):
646
+ for attr in v.media.document.attributes:
647
+ if hasattr(attr, 'file_name'):
648
+ doc_name = attr.file_name
649
+ break
650
+ sample_names += f"- {doc_name}\n"
651
+
652
+ msg_n = await conv.send_message(
653
+ "📁 ¿Cómo nombrar estos capítulos extra?\n\n"
654
+ "Si usas nombres originales, se verán así:\n"
655
+ f"{sample_names}",
656
+ buttons=[
657
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
658
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
659
+ ]
660
+ )
661
+
662
+ naming_strategy = "title"
663
+ while True:
664
+ event = await wait_for_message_or_callback(conv, timeout=300)
665
+ if isinstance(event, events.CallbackQuery.Event):
666
+ if event.data == uid_title:
667
+ naming_strategy = "title"
668
+ await msg_n.edit("Formato: Serie - Capítulo X", buttons=None)
669
+ break
670
+ elif event.data == uid_file:
671
+ naming_strategy = "file"
672
+ await msg_n.edit("Formato: Archivo original", buttons=None)
673
+ break
674
+ else:
675
+ naming_strategy = "manual"
676
+ manual_prefix = event.raw_text
677
+ await msg_n.edit(f"Formato: {manual_prefix}...", buttons=None)
678
+ break
679
+
680
+ status_msg = await conv.send_message("📁 **Procesando capítulos extra...**")
681
+
682
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
683
+ max_ep = 0
684
+ for c in caps:
685
+ ep = c.to_dict().get('episode', 0)
686
+ if ep > max_ep: max_ep = ep
687
+
688
+ for i, video_msg in enumerate(videos):
689
+ max_ep += 1
690
+
691
+ if naming_strategy == "title":
692
+ ep_title = f"{series_title} - Capítulo {max_ep}"
693
+ elif naming_strategy == "manual":
694
+ ep_title = f"{manual_prefix} - Capítulo {max_ep}"
695
+ else:
696
+ doc_name = "Episodio"
697
+ if hasattr(video_msg.media, 'document'):
698
+ for attr in video_msg.media.document.attributes:
699
+ if hasattr(attr, 'file_name'):
700
+ import os
701
+ doc_name = os.path.splitext(attr.file_name)[0]
702
+ break
703
+ ep_title = doc_name
704
+
705
+ await status_msg.edit(f"📁 Subiendo extra: **{ep_title}** ({i+1}/{len(videos)})")
706
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Serie:** {series_title}\n📁 **Episodio:** {ep_title}"
707
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
708
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
709
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
710
+
711
+ db.collection('videos').add({
712
+ "title": ep_title,
713
+ "section": "series",
714
+ "is_folder": False,
715
+ "folder_id": series_id,
716
+ "episode": max_ep,
717
+ "season": 1,
718
+ "video_url": file_url,
719
+ "telegram_file_id": str(sent_to_channel.id),
720
+ "description": "",
721
+ "thumbnail_url": "",
722
+ "cover_url": "",
723
+ "views": 0,
724
+ "rating": 0,
725
+ "status": "active",
726
+ "is_public": True,
727
+ "categories": [],
728
+ "servers": [file_url],
729
+ "created_at": firestore.SERVER_TIMESTAMP,
730
+ "updated_at": firestore.SERVER_TIMESTAMP
731
+ })
732
+ await status_msg.edit(f"✅ **¡{len(videos)} capítulos extra añadidos con éxito!**")
733
+
734
+ @client.on(events.NewMessage())
735
+ async def global_editor_listener(event):
736
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
737
+ if user_modes.get(chat_id) != 'editor': return
738
+
739
+ # Si ya hay tareas activas en este chat, la conversación interceptará el mensaje sola
740
+ if chat_id in active_tasks and active_tasks[chat_id]:
741
+ return
742
+
743
+ txt = getattr(event, 'raw_text', '').strip()
744
+ if txt.startswith('/start '):
745
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
746
+
747
+ if txt.startswith('/'):
748
+ return
749
+
750
+ # Iniciar ciclo del editor inyectando el ID directamente
751
+ import asyncio
752
+ current_task = asyncio.current_task()
753
+ if chat_id not in active_tasks:
754
+ active_tasks[chat_id] = []
755
+ active_tasks[chat_id].append(current_task)
756
+ try:
757
+ await handle_editor_mode(event, initial_txt=txt)
758
+ finally:
759
+ if current_task in active_tasks.get(chat_id, []):
760
+ active_tasks[chat_id].remove(current_task)
bot_subidor.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import uuid
3
+ import time
4
+ from telethon import events, Button
5
+ from telethon.tl.types import KeyboardButtonSimpleWebView, KeyboardButtonWebView
6
+ from google.cloud.firestore_v1.base_query import FieldFilter
7
+ from core import *
8
+
9
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
10
+ async def start_subir_handler(event):
11
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
12
+ if user_modes.get(chat_id) != 'subidor': return
13
+ chat_id = event.chat_id
14
+ if False:
15
+ await event.respond("🛠️ **Estás en Modo Editor.**\nPor favor, usa `/desactivar_modo_editor` para salir del editor y usar los comandos normales.")
16
+ return
17
+
18
+ if chat_id not in active_tasks:
19
+ active_tasks[chat_id] = []
20
+
21
+ current_task = asyncio.current_task()
22
+ current_task.is_uploading = False
23
+
24
+ remaining_tasks = []
25
+ for old_task in active_tasks[chat_id]:
26
+ if not old_task.done():
27
+ if getattr(old_task, 'is_uploading', False):
28
+ remaining_tasks.append(old_task)
29
+ else:
30
+ old_task.cancel()
31
+ try:
32
+ await asyncio.sleep(0.1)
33
+ except: pass
34
+
35
+ active_tasks[chat_id] = remaining_tasks
36
+ active_tasks[chat_id].append(current_task)
37
+
38
+ try:
39
+ async with client.conversation(chat_id, timeout=600, exclusive=False) as conv:
40
+ cmd = event.text.strip().lower()
41
+ while True:
42
+ try:
43
+ if cmd == '/subir_pelicula':
44
+ await handle_movie_upload(conv)
45
+ break
46
+ elif cmd == '/subir_serie':
47
+ await handle_series_upload(conv)
48
+ break
49
+
50
+ msg_text = "📁 Bienvenido a **Twisted Streaming Brody**.\nElige una opción:"
51
+ botones = [
52
+ [Button.inline("📁 Subir Película", b"type_movie"), Button.inline("📁 Subir Serie", b"type_series")]
53
+ ]
54
+
55
+ if cmd == '/start':
56
+ photos = await client.get_profile_photos('me', limit=1)
57
+ if photos:
58
+ msg = await conv.send_message(msg_text, file=photos[0], buttons=botones)
59
+ else:
60
+ msg = await conv.send_message(msg_text, buttons=botones)
61
+ else:
62
+ msg = await conv.send_message(msg_text, buttons=botones)
63
+
64
+ cmd = "" # Reset cmd
65
+
66
+ while True:
67
+ press = await wait_for_message_or_callback(conv, timeout=3600)
68
+ if isinstance(press, events.CallbackQuery.Event):
69
+ if press.data in [b"type_movie", b"type_series"]:
70
+ await press.answer()
71
+ try:
72
+ await msg.edit(buttons=None)
73
+ except: pass
74
+
75
+ if press.data == b"type_movie":
76
+ await handle_movie_upload(conv)
77
+ elif press.data == b"type_series":
78
+ await handle_series_upload(conv)
79
+ break
80
+ else:
81
+ await press.answer("Botón expirado", alert=True)
82
+ elif getattr(press, 'text', '') in ['/start', '/subir', '/subir_pelicula', '/subir_serie']:
83
+ cmd = press.text
84
+ break
85
+ break
86
+ except CancelUploadException:
87
+ cmd = "/subir"
88
+ continue
89
+ except asyncio.CancelledError:
90
+ break
91
+ finally:
92
+ if current_task in active_tasks.get(chat_id, []):
93
+ active_tasks[chat_id].remove(current_task)
94
+ if not active_tasks[chat_id]:
95
+ del active_tasks[chat_id]
96
+
97
+ async def handle_movie_upload(conv):
98
+ # 1. Video
99
+ await conv.send_message("📁 **Paso 1:** Envía el **video** (o el archivo) de la película:")
100
+ msg_video = await conv.get_response()
101
+
102
+ is_video = False
103
+ if msg_video and getattr(msg_video, 'media', None):
104
+ if getattr(msg_video, 'video', None):
105
+ is_video = True
106
+ elif getattr(msg_video, 'document', None):
107
+ mime = getattr(msg_video.file, 'mime_type', '') if hasattr(msg_video, 'file') else ''
108
+ if mime.startswith('video/'):
109
+ is_video = True
110
+ else:
111
+ for attr in msg_video.document.attributes:
112
+ if hasattr(attr, 'file_name'):
113
+ import os
114
+ ext = os.path.splitext(attr.file_name)[1].lower()
115
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
116
+ is_video = True
117
+ break
118
+
119
+ if not is_video:
120
+ await conv.send_message("📁 No enviaste un video válido. Debes enviar un video normal o un archivo de video (documento). Las imágenes no son aceptadas. Abortando proceso.")
121
+ print("📁 Intento de subida fallido: No se recibió un video o documento válido.")
122
+ return
123
+
124
+ doc_name = ""
125
+ video_caption = msg_video.raw_text if getattr(msg_video, 'raw_text', None) else ""
126
+ if getattr(msg_video, 'file', None) and getattr(msg_video.file, 'name', None):
127
+ import os
128
+ doc_name = os.path.splitext(msg_video.file.name)[0]
129
+ elif hasattr(msg_video.media, 'document'):
130
+ for attr in msg_video.media.document.attributes:
131
+ if hasattr(attr, 'file_name'):
132
+ import os
133
+ doc_name = os.path.splitext(attr.file_name)[0]
134
+ break
135
+
136
+ # 2. Título
137
+ uid_title = str(uuid.uuid4()).encode()
138
+ buttons_title = []
139
+ if doc_name:
140
+ buttons_title.append([Button.inline(f"📁 Usar nombre del archivo: {doc_name[:30]}", uid_title)])
141
+
142
+ msg_t = await conv.send_message("📁 **Paso 2:** Escribe el **Título** de la película:", buttons=buttons_title if buttons_title else None)
143
+ title = ""
144
+ while True:
145
+ event = await wait_for_message_or_callback(conv, timeout=300)
146
+ if isinstance(event, events.CallbackQuery.Event):
147
+ if doc_name and event.data == uid_title:
148
+ await event.answer("Título seleccionado")
149
+ title = doc_name
150
+ await msg_t.edit(f"📁 Título: **{title}**", buttons=None)
151
+ break
152
+ else:
153
+ await event.answer("Botón expirado", alert=True)
154
+ else:
155
+ title = event.raw_text
156
+ if buttons_title:
157
+ await msg_t.edit(buttons=None)
158
+ break
159
+
160
+ print(f"📁 Iniciando carga de película: {title}")
161
+
162
+ # 3. Descripción
163
+ uid_desc = str(uuid.uuid4()).encode()
164
+ uid_skip = str(uuid.uuid4()).encode()
165
+ buttons_desc = []
166
+ if video_caption:
167
+ buttons_desc.append([Button.inline("📁 Usar descripción del video", uid_desc)])
168
+ buttons_desc.append([Button.inline("📁 Omitir", uid_skip)])
169
+
170
+ msg_d = await conv.send_message("📁 **Paso 3:** Escribe la **Descripción**:", buttons=buttons_desc)
171
+ description = ""
172
+ while True:
173
+ event = await wait_for_message_or_callback(conv, timeout=300)
174
+ if isinstance(event, events.CallbackQuery.Event):
175
+ if video_caption and event.data == uid_desc:
176
+ await event.answer("Descripción seleccionada")
177
+ description = video_caption
178
+ await msg_d.edit("📁 Descripción obtenida del video.", buttons=None)
179
+ break
180
+ elif event.data == uid_skip:
181
+ await event.answer("Omitido")
182
+ description = ""
183
+ await msg_d.edit("📁 Descripción: (Omitida)", buttons=None)
184
+ break
185
+ else:
186
+ await event.answer("Botón expirado", alert=True)
187
+ else:
188
+ description = event.raw_text
189
+ await msg_d.edit(buttons=None)
190
+ break
191
+
192
+ # 4. Portada
193
+ cover_url = ""
194
+ uid_skip = str(uuid.uuid4()).encode()
195
+ uid_cancel = str(uuid.uuid4()).encode()
196
+
197
+ msg_c = await conv.send_message("📁 **Paso 4:** Envía la **Portada** (solo como imagen):", buttons=[
198
+ [Button.inline("📁 Omitir", uid_skip)],
199
+ [Button.inline("❌ Cancelar Subida", uid_cancel)]
200
+ ])
201
+
202
+ resp_cover = None
203
+ while True:
204
+ event = await wait_for_message_or_callback(conv, timeout=300)
205
+ if isinstance(event, events.CallbackQuery.Event):
206
+ if event.data == uid_skip:
207
+ await event.answer("Omitido")
208
+ await msg_c.edit("📁 Portada: (Omitida)", buttons=None)
209
+ break
210
+ elif event.data == uid_cancel:
211
+ await event.answer("Cancelado")
212
+ await msg_c.edit("📁 **Subida cancelada.**", buttons=None)
213
+ raise CancelUploadException()
214
+ else:
215
+ await event.answer("Botón expirado", alert=True)
216
+ else:
217
+ if getattr(event, 'photo', None):
218
+ await msg_c.edit("📁 Subiendo portada...", buttons=None)
219
+ cover_url = await upload_to_imgbb(event.photo)
220
+ resp_cover = event
221
+ break
222
+ else:
223
+ await conv.send_message("📁 Por favor, envía una IMAGEN, o presiona Omitir/Cancelar.")
224
+
225
+ async def progress_callback(current, total):
226
+ porcentaje = (current / total) * 100
227
+ print(f" ⬆️ Subiendo: {porcentaje:.1f}% ({current}/{total} bytes)")
228
+
229
+ print(f"📦 Video recibido. Tamaño estimado: {getattr(msg_video.file, 'size', 'desconocido')} bytes")
230
+ status_msg = await conv.send_message("📁 **Subiendo video al canal...** (Mira la consola para ver el progreso)")
231
+
232
+ try:
233
+ asyncio.current_task().is_uploading = True
234
+ # Formatear el mensaje para el canal
235
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Película:** {title}\n📁 {description}"
236
+
237
+ print(f"📤 Enviando al canal {CHANNEL_ID}...")
238
+
239
+ if resp_cover and getattr(resp_cover, 'photo', None):
240
+ try:
241
+ await client.send_file(CHANNEL_ID, resp_cover.photo, caption=f"📁 **Portada Película:** {title}")
242
+ except Exception as e:
243
+ print(f"Error enviando portada de película al canal: {e}")
244
+
245
+ sent_to_channel = await client.send_file(
246
+ CHANNEL_ID,
247
+ msg_video.media,
248
+ caption=caption,
249
+ progress_callback=progress_callback
250
+ )
251
+
252
+ print(f"📁 Enviado al canal. ID: {sent_to_channel.id}")
253
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
254
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
255
+
256
+ print("🗄️ Guardando en Firebase...")
257
+ # Guardar en Firestore con todos los campos observados en tu consola
258
+ db.collection('videos').add({
259
+ "title": title,
260
+ "description": description,
261
+ "section": "peliculas",
262
+ "is_folder": False,
263
+ "folder_id": "", # Sin nulls para evitar errores en React
264
+ "video_url": file_url,
265
+ "telegram_file_id": str(sent_to_channel.id),
266
+ "thumbnail_url": "",
267
+ "cover_url": cover_url,
268
+ "thumbnail_position": "50% center",
269
+ "episode": 0,
270
+ "views": 0,
271
+ "rating": 0,
272
+ "categories": [],
273
+ "servers": [file_url],
274
+ "status": "active",
275
+ "is_public": True,
276
+ "created_at": firestore.SERVER_TIMESTAMP,
277
+ "updated_at": firestore.SERVER_TIMESTAMP
278
+ })
279
+ print("🎉 Guardado en Firebase exitoso.")
280
+ await status_msg.edit("📁 **¡Película registrada y enviada correctamente!**")
281
+ except Exception as e:
282
+ print(f"📁 ERROR CRÍTICO: {e}")
283
+ await status_msg.edit(f"📁 **Error al procesar:** {e}")
284
+
285
+ async def handle_series_upload(conv):
286
+ series_title = ""
287
+ videos = []
288
+ naming_strategy = "title"
289
+ manual_prefix = ""
290
+ ep_titles = []
291
+ desc_strategy = "manual"
292
+ desc_text = ""
293
+ cover_url = ""
294
+ resp_cover = None
295
+
296
+ step = 1
297
+ while step <= 4:
298
+ if step == 1:
299
+ await conv.send_message("📁 **Paso 1:** Escribe el título general de la Serie (`Ej: The Last of Us, Breaking Bad, Invencible, etc.`):")
300
+ while True:
301
+ title_msg = await wait_for_message_or_callback(conv, timeout=300)
302
+ if isinstance(title_msg, events.CallbackQuery.Event):
303
+ await title_msg.answer("Por favor, escribe un texto.", alert=True)
304
+ elif getattr(title_msg, 'raw_text', getattr(title_msg, 'text', None)):
305
+ series_title = getattr(title_msg, 'raw_text', title_msg.text)
306
+ step = 2
307
+ break
308
+
309
+ elif step == 2:
310
+ uid_done = str(uuid.uuid4()).encode()
311
+ uid_back = str(uuid.uuid4()).encode()
312
+ msg_v = await conv.send_message(
313
+ f"📁 **Paso 2:** Envía los videos de los capítulos. Puedes enviar varios de una vez.\n\n"
314
+ f"Esperando a más videos... ({len(videos)} recibidos)",
315
+ buttons=[
316
+ [Button.inline("📁 Terminar y confirmar", uid_done)],
317
+ [Button.inline("⬅️ Atrás (Editar Título)", uid_back)]
318
+ ]
319
+ )
320
+
321
+ debounce_task = None
322
+ async def update_button():
323
+ await asyncio.sleep(0.8)
324
+ nonlocal msg_v
325
+ try:
326
+ await msg_v.delete()
327
+ except Exception:
328
+ pass
329
+ msg_v = await conv.send_message(
330
+ f"📁 **Paso 2:** Envía los videos de los capítulos.\n\n"
331
+ f"Esperando a más videos... ({len(videos)} recibidos)",
332
+ buttons=[
333
+ [Button.inline("📁 Terminar y confirmar", uid_done)],
334
+ [Button.inline("⬅️ Atrás (Editar Título)", uid_back)]
335
+ ]
336
+ )
337
+
338
+ async def video_receiver(e):
339
+ is_video = False
340
+ if getattr(e, 'media', None):
341
+ if getattr(e, 'video', None):
342
+ is_video = True
343
+ elif getattr(e, 'document', None):
344
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
345
+ if mime.startswith('video/'):
346
+ is_video = True
347
+ else:
348
+ for attr in e.document.attributes:
349
+ if hasattr(attr, 'file_name'):
350
+ import os
351
+ ext = os.path.splitext(attr.file_name)[1].lower()
352
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
353
+ is_video = True
354
+ break
355
+
356
+ if is_video:
357
+ videos.append(e)
358
+ nonlocal debounce_task
359
+ if debounce_task:
360
+ debounce_task.cancel()
361
+ debounce_task = asyncio.create_task(update_button())
362
+
363
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
364
+
365
+ try:
366
+ while True:
367
+ event = await wait_for_message_or_callback(conv, timeout=3600)
368
+ if isinstance(event, events.CallbackQuery.Event):
369
+ if event.data == uid_done:
370
+ if not videos:
371
+ await event.answer("No has enviado ningún video aún.", alert=True)
372
+ else:
373
+ await event.answer("Videos confirmados")
374
+ if debounce_task:
375
+ debounce_task.cancel()
376
+ await msg_v.edit(f"📁 Se registraron {len(videos)} videos en total.", buttons=None)
377
+ step = 3
378
+ break
379
+ elif event.data == uid_back:
380
+ await event.answer("Volviendo atrás")
381
+ if debounce_task:
382
+ debounce_task.cancel()
383
+ await msg_v.edit("📁 Volviendo al Paso 1...", buttons=None)
384
+ step = 1
385
+ break
386
+ finally:
387
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
388
+
389
+ elif step == 3:
390
+ uid_title = str(uuid.uuid4()).encode()
391
+ uid_auto = str(uuid.uuid4()).encode()
392
+ uid_file = str(uuid.uuid4()).encode()
393
+ uid_unique = str(uuid.uuid4()).encode()
394
+ uid_manual = str(uuid.uuid4()).encode()
395
+ uid_back = str(uuid.uuid4()).encode()
396
+
397
+ buttons = [
398
+ [Button.inline("📁 Título General + Capítulo X", uid_title)],
399
+ [Button.inline("📁 Personalización Automática", uid_auto)],
400
+ [Button.inline("📁 Nombres Originales de Archivos", uid_file)],
401
+ [Button.inline("📁 Nombramiento Manual Masivo", uid_manual)]
402
+ ]
403
+ if len(videos) == 1:
404
+ buttons.append([Button.inline("📁 Personalizado Único (1 cap)", uid_unique)])
405
+ buttons.append([Button.inline("⬅️ Atrás (Añadir más videos)", uid_back)])
406
+
407
+ msg_n = await conv.send_message(
408
+ "📁 **Paso 3:** ¿Qué nombre llevarán los capítulos? Elige una opción:\n\n"
409
+ "🔹 **Título General + Capítulo X:**\n"
410
+ f"Usa el título de la serie y lo enumera. `Ej: {series_title} - Capítulo 1`\n\n"
411
+ "🔹 **Personalización Automática:**\n"
412
+ "Te pedirá un nombre base y lo enumerará. `Ej: Tu Texto - Capítulo 1`\n\n"
413
+ "🔹 **Nombres Originales:**\n"
414
+ "Mantiene el nombre exacto de cada archivo. `Ej: video_2026.mp4`\n\n"
415
+ "🔹 **Nombramiento Manual Masivo:**\n"
416
+ "Te enviará una plantilla vacía para que nombres todos a la vez.\n\n"
417
+ "💡 Si enviaste 1 solo video, aparecerá la opción `Personalizado Único` para usar un nombre exacto sin números.\n",
418
+ buttons=buttons
419
+ )
420
+
421
+ strategy = None
422
+ while True:
423
+ event = await wait_for_message_or_callback(conv, timeout=300)
424
+ if isinstance(event, events.CallbackQuery.Event):
425
+ if event.data == uid_title:
426
+ strategy = "title"
427
+ await msg_n.edit(f"📁 Título General + Capítulo X", buttons=None)
428
+ break
429
+ elif event.data == uid_auto:
430
+ strategy = "auto"
431
+ await msg_n.edit("📁 Personalización Automática", buttons=None)
432
+ break
433
+ elif event.data == uid_file:
434
+ strategy = "file"
435
+ await msg_n.edit("📁 Nombres Originales de Archivos", buttons=None)
436
+ break
437
+ elif event.data == uid_manual:
438
+ strategy = "manual_mass"
439
+ await msg_n.edit("📁 Nombramiento Manual Masivo", buttons=None)
440
+ break
441
+ elif event.data == uid_unique and len(videos) == 1:
442
+ strategy = "unique"
443
+ await msg_n.edit("📁 Personalizado Único", buttons=None)
444
+ break
445
+ elif event.data == uid_back:
446
+ strategy = "back"
447
+ await event.answer("Volviendo atrás")
448
+ await msg_n.edit("📁 Volviendo al Paso 2...", buttons=None)
449
+ break
450
+ else:
451
+ await event.answer("Botón expirado", alert=True)
452
+ else:
453
+ await msg_n.delete()
454
+ msg_n = await conv.send_message("📁 Por favor, usa los botones:", buttons=buttons)
455
+
456
+ if strategy == "back":
457
+ step = 2
458
+ continue
459
+
460
+ manual_prefix = ""
461
+ if strategy == "auto":
462
+ await conv.send_message("Escribe el nombre base para los capítulos (se enumerarán solos):")
463
+ while True:
464
+ resp = await wait_for_message_or_callback(conv, timeout=300)
465
+ if not isinstance(resp, events.CallbackQuery.Event):
466
+ manual_prefix = resp.raw_text.strip()
467
+ break
468
+ elif strategy == "unique":
469
+ await conv.send_message("Escribe el nombre exacto que tendrá este capítulo (SIN números automáticos):")
470
+ while True:
471
+ resp = await wait_for_message_or_callback(conv, timeout=300)
472
+ if not isinstance(resp, events.CallbackQuery.Event):
473
+ manual_prefix = resp.raw_text.strip()
474
+ break
475
+
476
+ ep_titles = []
477
+ for i, video_msg in enumerate(videos):
478
+ if strategy == "title":
479
+ ep_titles.append(f"{series_title} - Capítulo {i+1}")
480
+ elif strategy == "auto":
481
+ ep_titles.append(f"{manual_prefix} - Capítulo {i+1}")
482
+ elif strategy == "unique":
483
+ ep_titles.append(manual_prefix)
484
+ elif strategy == "manual_mass":
485
+ ep_titles.append("")
486
+ elif strategy == "file":
487
+ doc_name = "Episodio"
488
+ if getattr(video_msg, 'file', None) and getattr(video_msg.file, 'name', None):
489
+ import os
490
+ doc_name = os.path.splitext(video_msg.file.name)[0]
491
+ elif hasattr(video_msg.media, 'document'):
492
+ for attr in video_msg.media.document.attributes:
493
+ if hasattr(attr, 'file_name'):
494
+ import os
495
+ doc_name = os.path.splitext(attr.file_name)[0]
496
+ break
497
+ ep_titles.append(doc_name)
498
+
499
+ if strategy == "manual_mass":
500
+ step = 3.3
501
+ else:
502
+ step = 3.2
503
+
504
+ elif step == 3.2:
505
+ uid_confirm = str(uuid.uuid4()).encode()
506
+ uid_edit = str(uuid.uuid4()).encode()
507
+ uid_back = str(uuid.uuid4()).encode()
508
+
509
+ preview = ""
510
+ for i, title in enumerate(ep_titles[:20]):
511
+ preview += f"({i+1}) {title}\n"
512
+ if len(ep_titles) > 20:
513
+ preview += f"... y {len(ep_titles) - 20} más.\n"
514
+
515
+ msg_p = await conv.send_message(
516
+ f"📝 **Vista Previa de los Nombres:**\n\n{preview}\n¿Qué deseas hacer?",
517
+ buttons=[
518
+ [Button.inline("✅ Confirmar Nombres", uid_confirm)],
519
+ [Button.inline("✏️ Editar Nombres (Plantilla)", uid_edit)],
520
+ [Button.inline("⬅️ Atrás (Elegir otro formato)", uid_back)]
521
+ ]
522
+ )
523
+
524
+ while True:
525
+ event = await wait_for_message_or_callback(conv, timeout=300)
526
+ if isinstance(event, events.CallbackQuery.Event):
527
+ if event.data == uid_confirm:
528
+ await msg_p.edit("✅ Nombres confirmados.", buttons=None)
529
+ step = 3.5
530
+ break
531
+ elif event.data == uid_edit:
532
+ await msg_p.edit("✏️ Modo edición...", buttons=None)
533
+ step = 3.3
534
+ break
535
+ elif event.data == uid_back:
536
+ await msg_p.edit("📁 Volviendo a formatos...", buttons=None)
537
+ step = 3
538
+ break
539
+ else:
540
+ await event.answer("Botón expirado", alert=True)
541
+ else:
542
+ await msg_p.delete()
543
+ msg_p = await conv.send_message("📁 Por favor, usa los botones:", buttons=[
544
+ [Button.inline("✅ Confirmar Nombres", uid_confirm)],
545
+ [Button.inline("✏️ Editar Nombres (Plantilla)", uid_edit)],
546
+ [Button.inline("⬅️ Atrás (Elegir otro formato)", uid_back)]
547
+ ])
548
+
549
+ elif step == 3.3:
550
+ template = ""
551
+ for i, title in enumerate(ep_titles):
552
+ template += f"{{{i+1}}} {title}\n"
553
+
554
+ await conv.send_message(
555
+ "📝 **EDICIÓN MANUAL**\n\n"
556
+ "1. Copia el siguiente mensaje.\n"
557
+ "2. Pégalo en el chat y edita los nombres como desees.\n"
558
+ "3. Envíamelo.\n\n"
559
+ "⚠️ **NO borres los números entre llaves `{ }`**"
560
+ )
561
+ await conv.send_message(f"```{template}```")
562
+
563
+ while True:
564
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
565
+ if isinstance(resp, events.CallbackQuery.Event):
566
+ await resp.answer("Botón inválido.", alert=True)
567
+ continue
568
+
569
+ new_text = resp.raw_text
570
+ import re
571
+ matches = re.findall(r'\{(\d+)\}\s*(.*)', new_text)
572
+
573
+ if not matches:
574
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
575
+ continue
576
+
577
+ for idx_str, new_title in matches:
578
+ try:
579
+ idx = int(idx_str) - 1
580
+ if 0 <= idx < len(ep_titles):
581
+ if new_title.strip():
582
+ ep_titles[idx] = new_title.strip()
583
+ except:
584
+ pass
585
+
586
+ await conv.send_message("✅ Nombres actualizados.")
587
+ step = 3.2
588
+ break
589
+
590
+ elif step == 3.5:
591
+ uid_desc_video = str(uuid.uuid4()).encode()
592
+ uid_skip = str(uuid.uuid4()).encode()
593
+ uid_back = str(uuid.uuid4()).encode()
594
+ msg_d = await conv.send_message(
595
+ "📁 **Paso 3.5:** Escribe una **Descripción** (se usará la misma para todos los capítulos).\n\n"
596
+ "Opcional: puedes extraer la descripción original de cada video, o simplemente omitir este paso.",
597
+ buttons=[
598
+ [Button.inline("📁 Usar descripción de cada video", uid_desc_video)],
599
+ [Button.inline("📁 Omitir", uid_skip)],
600
+ [Button.inline("⬅️ Atrás (Editar Nombre Capítulos)", uid_back)]
601
+ ]
602
+ )
603
+
604
+ while True:
605
+ event = await wait_for_message_or_callback(conv, timeout=300)
606
+ if isinstance(event, events.CallbackQuery.Event):
607
+ if event.data == uid_desc_video:
608
+ desc_strategy = "video"
609
+ await msg_d.edit("📁 Descripción: **Se usará la de cada video**", buttons=None)
610
+ step = 4
611
+ break
612
+ elif event.data == uid_skip:
613
+ desc_strategy = "skip"
614
+ await msg_d.edit("📁 Descripción: **(Omitida)**", buttons=None)
615
+ step = 4
616
+ break
617
+ elif event.data == uid_back:
618
+ await event.answer("Volviendo atrás")
619
+ await msg_d.edit("📁 Volviendo al Paso 3...", buttons=None)
620
+ step = 3
621
+ break
622
+ else:
623
+ await event.answer("Botón expirado", alert=True)
624
+ else:
625
+ desc_strategy = "manual"
626
+ desc_text = event.raw_text
627
+ await msg_d.edit(f"📁 Descripción: **{desc_text[:30]}...**", buttons=None)
628
+ step = 4
629
+ break
630
+
631
+ elif step == 4:
632
+ uid_skip = str(uuid.uuid4()).encode()
633
+ uid_back = str(uuid.uuid4()).encode()
634
+ uid_cancel = str(uuid.uuid4()).encode()
635
+
636
+ msg_c = await conv.send_message(
637
+ "📁 **Paso 4:** Envía la **Portada** de la serie (solo como imagen):",
638
+ buttons=[
639
+ [Button.inline("📁 Omitir", uid_skip)],
640
+ [Button.inline("⬅️ Atrás (Editar Descripción)", uid_back)],
641
+ [Button.inline("❌ Cancelar Subida", uid_cancel)]
642
+ ]
643
+ )
644
+
645
+ while True:
646
+ event = await wait_for_message_or_callback(conv, timeout=300)
647
+ if isinstance(event, events.CallbackQuery.Event):
648
+ if event.data == uid_skip:
649
+ await event.answer("Omitido")
650
+ await msg_c.edit("📁 Portada: **(Omitida)**", buttons=None)
651
+ resp_cover = None
652
+ cover_url = ""
653
+ step = 5
654
+ break
655
+ elif event.data == uid_back:
656
+ await event.answer("Volviendo atrás")
657
+ await msg_c.edit("📁 Volviendo al Paso 3.5...", buttons=None)
658
+ step = 3.5
659
+ break
660
+ elif event.data == uid_cancel:
661
+ await event.answer("Cancelado")
662
+ await msg_c.edit("📁 **Subida cancelada.**", buttons=None)
663
+ raise CancelUploadException()
664
+ else:
665
+ await event.answer("Botón expirado", alert=True)
666
+ elif getattr(event, 'photo', None):
667
+ await msg_c.edit("📁 Subiendo portada...", buttons=None)
668
+ cover_url = await upload_to_imgbb(event.photo)
669
+ resp_cover = event
670
+ step = 5
671
+ break
672
+ else:
673
+ await conv.send_message("📁 Por favor, envía una IMAGEN, o usa los botones.")
674
+
675
+ # 5. Guardado en Firebase y reenvío
676
+ status_msg = await conv.send_message("📁 **Procesando y subiendo los capítulos...**")
677
+ try:
678
+ asyncio.current_task().is_uploading = True
679
+ if resp_cover and getattr(resp_cover, 'photo', None):
680
+ try:
681
+ await client.send_file(CHANNEL_ID, resp_cover.photo, caption=f"📁 **Portada Serie:** {series_title}")
682
+ except Exception as e:
683
+ print(f"Error enviando portada de serie al canal: {e}")
684
+
685
+ # Buscar serie existente para asegurar nombre único
686
+ original_title = series_title
687
+ counter = 1
688
+
689
+ while True:
690
+ series_query = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).where(filter=FieldFilter('title', '==', series_title)).get()
691
+ if series_query:
692
+ counter += 1
693
+ series_title = f"{original_title} v{counter}"
694
+ else:
695
+ break
696
+
697
+ _, doc_ref = db.collection('videos').add({
698
+ "title": series_title,
699
+ "section": "series",
700
+ "is_folder": True,
701
+ "thumbnail_url": cover_url,
702
+ "categories": [],
703
+ "created_at": firestore.SERVER_TIMESTAMP,
704
+ "updated_at": firestore.SERVER_TIMESTAMP
705
+ })
706
+ series_id = doc_ref.id
707
+
708
+ for i, video_msg in enumerate(videos):
709
+ current_num = i + 1
710
+
711
+ # Nombre
712
+ ep_title = ep_titles[i] if i < len(ep_titles) else f"Capítulo {current_num}"
713
+
714
+ # Descripción
715
+ if desc_strategy == "video":
716
+ ep_desc = video_msg.raw_text if getattr(video_msg, 'raw_text', None) else ""
717
+ elif desc_strategy == "skip":
718
+ ep_desc = ""
719
+ else:
720
+ ep_desc = desc_text
721
+
722
+ await status_msg.edit(f"📁 Subiendo: **{ep_title}** ({i+1}/{len(videos)})")
723
+
724
+ caption = f"**Twisted Streaming Brody Data**\n\n📁 **Serie:** {series_title}\n📁 **Episodio:** {ep_title}"
725
+ if ep_desc:
726
+ caption += f"\n📁 {ep_desc}"
727
+
728
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
729
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
730
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
731
+
732
+ db.collection('videos').add({
733
+ "title": ep_title,
734
+ "section": "series",
735
+ "is_folder": False,
736
+ "folder_id": series_id,
737
+ "episode": current_num,
738
+ "season": 1,
739
+ "video_url": file_url,
740
+ "telegram_file_id": str(sent_to_channel.id),
741
+ "description": ep_desc,
742
+ "thumbnail_url": "",
743
+ "cover_url": "",
744
+ "views": 0,
745
+ "rating": 0,
746
+ "status": "active",
747
+ "is_public": True,
748
+ "categories": [],
749
+ "servers": [file_url],
750
+ "created_at": firestore.SERVER_TIMESTAMP,
751
+ "updated_at": firestore.SERVER_TIMESTAMP
752
+ })
753
+
754
+ await status_msg.edit(f"📁 **¡Completado! {len(videos)} capítulos de '{series_title}' se han subido con éxito.**")
755
+
756
+ except Exception as e:
757
+ print(f"📁 Error al procesar serie: {e}")
758
+ await status_msg.edit(f"📁 **Error al subir los capítulos:** {e}")
759
+
760
+
761
+
core.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import logging
4
+ import asyncio
5
+ import requests
6
+ import base64
7
+ from dotenv import load_dotenv
8
+ from telethon import TelegramClient, events, Button
9
+ import firebase_admin
10
+ from firebase_admin import credentials, firestore
11
+ from google.cloud.firestore_v1.base_query import FieldFilter
12
+
13
+ # Cargar variables de entorno
14
+ load_dotenv()
15
+
16
+ # --- SERVIDOR WEB FANTASMA (Para Hugging Face) ---
17
+ from threading import Thread
18
+ from http.server import HTTPServer, BaseHTTPRequestHandler
19
+
20
+ class DummyHandler(BaseHTTPRequestHandler):
21
+ def do_GET(self):
22
+ self.send_response(200)
23
+ self.send_header("Content-type", "text/html")
24
+ self.end_headers()
25
+ html_content = b"""<!DOCTYPE html>
26
+ <html lang="es">
27
+ <head>
28
+ <meta charset="UTF-8">
29
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
30
+ <title>Twisted Streaming Brody</title>
31
+ <style>
32
+ body { margin: 0; padding: 0; background-color: #0a0a0a; display: flex; justify-content: center; align-items: center; height: 100vh; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
33
+ .btn { background-color: #2481cc; color: white; padding: 15px 35px; border-radius: 30px; text-decoration: none; font-size: 20px; font-weight: bold; box-shadow: 0 5px 15px rgba(36,129,204,0.4); transition: 0.3s; }
34
+ .btn:hover { transform: translateY(-3px); background-color: #1a629c; box-shadow: 0 8px 20px rgba(36,129,204,0.6); }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <a href="https://t.me/TwistedStreamingBrodybot" target="_blank" class="btn">\xF0\x9F\x9A\x80 Abrir Twisted Streaming Brody</a>
39
+ </body>
40
+ </html>"""
41
+ self.wfile.write(html_content)
42
+ def log_message(self, format, *args):
43
+ pass # Silenciar logs del servidor
44
+
45
+ def run_server():
46
+ try:
47
+ server = HTTPServer(('0.0.0.0', 7860), DummyHandler)
48
+ server.serve_forever()
49
+ except Exception as e:
50
+ print("Error en servidor web:", e)
51
+
52
+ Thread(target=run_server, daemon=True).start()
53
+
54
+ API_ID = int(os.getenv('TELEGRAM_API_ID'))
55
+ API_HASH = os.getenv('TELEGRAM_API_HASH')
56
+ TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
57
+ CHANNEL_ID = int(os.getenv('TELEGRAM_CHANNEL_ID'))
58
+ IMGBB_KEY = os.getenv('IMGBB_API_KEY')
59
+
60
+ # Nombre del archivo de sesión
61
+ SESSION_NAME = 'TwistedStreamingBrodybot'
62
+
63
+ # --- CONFIGURACIÓN DE FIREBASE ---
64
+ try:
65
+ if not firebase_admin._apps:
66
+ cred = credentials.Certificate("firebase-credentials.json")
67
+ app = firebase_admin.initialize_app(cred)
68
+ print(f"📁 Firebase conectado correctamente. Proyecto: {app.project_id}")
69
+ db = firestore.client()
70
+ except Exception as e:
71
+ print(f"📁 Error al conectar con Firebase: {e}")
72
+
73
+ # Logs
74
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
75
+
76
+ # Inicializar Cliente de Telethon
77
+ client = TelegramClient(SESSION_NAME, API_ID, API_HASH)
78
+
79
+ # --- FUNCIONES AUXILIARES ---
80
+
81
+ async def upload_to_imgbb(photo_source):
82
+ """Sube una imagen a ImgBB y devuelve la URL"""
83
+ try:
84
+ # Descargar la foto en memoria
85
+ path = await client.download_media(photo_source, file=bytes)
86
+ image_base64 = base64.b64encode(path)
87
+
88
+ url = "https://api.imgbb.com/1/upload"
89
+ payload = {"key": IMGBB_KEY, "image": image_base64}
90
+
91
+ response = requests.post(url, payload)
92
+ res_json = response.json()
93
+ if res_json['success']:
94
+ return res_json['data']['url']
95
+ except Exception as e:
96
+ print(f"Error ImgBB: {e}")
97
+ return None
98
+
99
+ import re
100
+
101
+ def extract_categories_from_title(title):
102
+ """Extrae categorías de un título como [Accion] El Guerrero (2024)"""
103
+ found = re.findall(r'\[(.*?)\]|\((.*?)\)|\{(.*?)\}|\|(.*?)\|', title)
104
+ categories = []
105
+ for match in found:
106
+ for item in match:
107
+ if item and len(item.strip()) > 1:
108
+ categories.append(item.strip())
109
+ return list(set(categories))
110
+
111
+ def get_or_create_categories(names):
112
+ """Busca o crea categorías por nombre y devuelve sus IDs"""
113
+ ids = []
114
+ for name in names:
115
+ try:
116
+ # Buscar si ya existe
117
+ cats = db.collection('categories').where(filter=FieldFilter('name', '==', name)).get()
118
+ if cats:
119
+ ids.append(cats[0].id)
120
+ else:
121
+ # Crear si no existe
122
+ _, doc_ref = db.collection('categories').add({
123
+ "name": name,
124
+ "type": "genre"
125
+ })
126
+ ids.append(doc_ref.id)
127
+ print(f"🆕 Categoría creada: {name}")
128
+ except Exception as e:
129
+ print(f"Error gestionando categoría {name}: {e}")
130
+ return ids
131
+
132
+ def get_all_categories():
133
+ try:
134
+ cats = db.collection('categories').get()
135
+ return [{"id": c.id, "name": c.to_dict().get('name', 'Sin nombre')} for c in cats]
136
+ except Exception:
137
+ return []
138
+
139
+ import uuid
140
+
141
+ class CancelUploadException(Exception):
142
+ pass
143
+
144
+ class EditorJumpException(Exception):
145
+ def __init__(self, jump_id):
146
+ self.jump_id = jump_id
147
+
148
+ async def wait_for_message_or_callback(conv, timeout=300):
149
+ client = conv._client
150
+ chat_id = conv.chat_id
151
+ future = asyncio.Future()
152
+
153
+ async def msg_handler(e):
154
+ if not future.done():
155
+ future.set_result(e)
156
+
157
+ async def cb_handler(e):
158
+ if not future.done():
159
+ future.set_result(e)
160
+
161
+ client.add_event_handler(msg_handler, events.NewMessage(chats=chat_id, incoming=True))
162
+ client.add_event_handler(cb_handler, events.CallbackQuery(chats=chat_id))
163
+
164
+ try:
165
+ event = await asyncio.wait_for(future, timeout=timeout)
166
+ txt = getattr(event, 'raw_text', getattr(event, 'text', '')).strip()
167
+
168
+ if txt == '/cancelar':
169
+ await client.send_message(chat_id, "📁 **Proceso cancelado.**\nEscribe /start para volver al menú principal.")
170
+ raise CancelUploadException()
171
+
172
+ # Global intercept for editor mode jumps
173
+ if user_modes.get(chat_id) == 'editor':
174
+ if txt.startswith('/start '):
175
+ extracted = txt.replace('/start ', '').replace('folder_', '').strip()
176
+ raise EditorJumpException(extracted)
177
+ elif len(txt) == 20 and txt.isalnum() and not txt.startswith('/'):
178
+ # Heuristic for Firebase ID jump
179
+ raise EditorJumpException(txt)
180
+
181
+ return event
182
+ finally:
183
+ client.remove_event_handler(msg_handler)
184
+ client.remove_event_handler(cb_handler)
185
+
186
+ async def get_input_or_skip(conv, text, can_skip=True):
187
+ """Espera un mensaje o un botón de omitir con IDs únicos para evitar bugs"""
188
+ uid = str(uuid.uuid4()).encode()
189
+ buttons = [Button.inline("📁 Omitir", uid)] if can_skip else None
190
+ msg = await conv.send_message(text, buttons=buttons)
191
+
192
+ try:
193
+ while True:
194
+ event = await wait_for_message_or_callback(conv, timeout=300)
195
+ if isinstance(event, events.CallbackQuery.Event):
196
+ if event.data == uid:
197
+ await event.answer("Omitido")
198
+ await msg.edit(text + " (Omitido)", buttons=None)
199
+ return None
200
+ else:
201
+ await event.answer("Este botón ya no es válido", alert=True)
202
+ else:
203
+ if buttons:
204
+ await msg.edit(text, buttons=None)
205
+ return event
206
+ except asyncio.TimeoutError:
207
+ await conv.send_message("📁 Tiempo de espera agotado. Proceso cancelado.")
208
+ return None
209
+ except Exception as e:
210
+ print(f"Error en get_input_or_skip: {e}")
211
+ return None
212
+
213
+ # --- MANEJADORES ---
214
+
215
+
216
+ user_modes = {}
217
+ active_tasks = {}
218
+ button_cooldowns = {}
219
+ bot_settings = {'send_title': True, 'send_description': True, 'ask_series': True}
220
+ editor_mode_active = {}
221
+ search_mode_active = {}
firebase-credentials.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "twisted-streaming-brody",
4
+ "private_key_id": "753fe4f2238bef069bd4e3b3de87143b7bd85673",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC/yxONOccbe0p5\nhmqUzJrLU0x6pyLzVE3ZEO1r/v1cXUnwpTTEKpQtdUNlu3VFg2sfAOhjvgvXYEw6\nq4jaBIqLSM+twP2BtQkk3vDiVvXCo8+c1j28xizItKipLb6qM2WNnM4FzN5X13ph\n/2HtGEfuErMeKdWdSefEmwcoXE/vzH6idZIArnOfAcAfcUWsGFf8D6UIuTO3emNJ\nfQkHU/BQrmoh54mLV81P6GVn3XelKr7FHUvtg3ijvcOh4F12uQCU5HqTVtBlFA8s\nVZ7A1Z7DSHLkmqsJznvjd3qHxQFXdlZR7U2Dx3V6GHuL95sGZxwbWsI60NvAbTcn\nIZ4/sxgBAgMBAAECggEAF2O8Usvl6aaxpIwlVZf1tT/neupE34SrmUIgmDvwuUnJ\ntYKqQpWYPEp5kY+oy7VNFCr7zEUuI8ITTdDjR8ZHwJh8tkmLyPyTXMcg/JNjFY19\naVixzwKijcgFbRtebhqGQxzJPckYIQGO4+JdlojwZbrrU+2BZvUPQilvWCdY2ssg\n/faeuArUdrvmzcFok0y9BtDIs2s0wEmzJdcw+HHtwwO3+u5Fbn0gkjJhi+TimxvE\nUdOg9TEBDrrQmuevJjDw9XGiLSCF/P2ob5UFl7hsazi7Xwg+bsFBi/hPMJsxAqht\n6+pRHgC0u6Y7ED2/fhXn3qAsLfp9pXUkNLl8ToL6qQKBgQDvXF9l2pZKZV4pqyTA\n7V7Ds7sqd/ZzKaEIjKPiRtfIIQhRhBzQkJhTTJvvZHpFewL8bebuhonGcLSS+g5C\nrdXF8IhJNUy+Slx2jQTjGXfqHZSVsS/uTGZSu7tbN3VNYJG3G4ELUv/9TJXhn+71\nmpEzK8c51DmazDfiPFj7rTQzOQKBgQDNIDLsCdufhhuzc/Ga9J0+62EkbtHC0w+C\nE/C+cKsLBSgtIpkyHl42yE3RiSEPmI59ydCz7jOUTKPwV9z+RwyJH9/5f2y9tyle\n97qez37qttN6rrgCDterXTTYIfBeTr8o4HQMh3ererNt0iSkMYHa7//Vks66As8c\n8Ke7DkCjCQKBgAQjV67eGY0NtZQI1mjTcbj2aXzxd/xDsvn/3HF0AhT+pTMrkof0\nh/2grG12EjsTRljw2XY0MzuQBT8pPYffk3uJjgGd/0am6HRQOc5nSVBt1HzGBGsd\nPQOfJT0Nd2SwD7TXr+JvO+e4JDszVaE/W9VDo30Xcyt+7lRl8K/hLa7ZAoGAfMly\n0Q9qMVDHd1M4jvjy1D0jWqOkLi5yB8MTuPcXxtt7RoH+ynOZAyC13pvapf876CAn\nO97UOAqrzOHWykX0xVLD0aeIQp2zqFdyi3xVjHpuivrRbEcVQuWv6TA0Z1rmhfqN\n/rVGwuYhU9T8f3qysbtBWu81nglpcASjNXOFNOkCgYAB7V6CDcYK2FlJgEm3uJpb\n1FO2kveNdLDOLuX25LMgaUXx4hH60z5RPOzFlIyIuHxb1tc0tTYvnOU3gPHKnJp+\nhUniXY15e1KpCSSWyFzCOr2fFNyLU5EE626GLHyhJkScYOK9i28keXSKR1EG334r\nvUMRYX60bBEybDt2fV4DjQ==\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "firebase-adminsdk-fbsvc@twisted-streaming-brody.iam.gserviceaccount.com",
7
+ "client_id": "114809841591755230406",
8
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
9
+ "token_uri": "https://oauth2.googleapis.com/token",
10
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40twisted-streaming-brody.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
iniciar_bot.bat ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ @echo off
2
+ echo Iniciando el bot...
3
+ python main.py
4
+ pause
instalar_requerimientos.bat ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo Instalando requerimientos...
3
+ pip install -r requirements.txt
4
+ echo.
5
+ echo Instalacion completada.
6
+ pause
main.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from telethon import events
4
+ from core import client, user_modes, active_tasks
5
+
6
+ import bot_subidor
7
+ import bot_editor
8
+ import bot_buscador
9
+
10
+ @client.on(events.NewMessage(pattern='^/start$'))
11
+ async def handle_start(event):
12
+ mode = user_modes.get(event.chat_id)
13
+ if not mode:
14
+ await event.respond("👋 **Bienvenido a Twisted Streaming Brody**\n\nPor favor elige el bot que deseas usar:\n- /bot_subidor : Para subir películas y series.\n- /bot_editor : Para editar la base de datos.\n- /bot_buscador : Para buscar y entregar videos.")
15
+ elif mode == 'buscador':
16
+ await send_buscador_welcome(event)
17
+ elif mode == 'editor':
18
+ await set_editor(event)
19
+
20
+ async def send_buscador_welcome(event):
21
+ from telethon.tl.types import KeyboardButtonWebView
22
+ from telethon import Button
23
+ chat_id = getattr(event, 'chat_id', getattr(getattr(event, 'message', None), 'chat_id', None))
24
+
25
+ # Eliminar cualquier teclado de respuesta previo que haya quedado atascado
26
+ try:
27
+ tmp = await client.send_message(chat_id, "🔄 Actualizando teclado...", buttons=Button.clear())
28
+ await tmp.delete()
29
+ except: pass
30
+
31
+ photos = await client.get_profile_photos('me', limit=1)
32
+ msg = "🔍 **Modo Buscador Activado**\n\nBienvenido al Bot Buscador. Escribe el nombre de la película o serie que buscas, o abre la Mini App debajo."
33
+
34
+ btn_webapp = KeyboardButtonWebView(text="🍿 Twisted Streaming Brody", url="https://codebybrody-twistedstreamingbrody.hf.space")
35
+
36
+ if photos:
37
+ await client.send_file(chat_id, photos[0], caption=msg, buttons=[[btn_webapp]])
38
+ else:
39
+ await client.send_message(chat_id, msg, buttons=[[btn_webapp]])
40
+
41
+ @client.on(events.NewMessage(pattern='^/bot_subidor$'))
42
+ async def set_subidor(event):
43
+ chat_id = event.chat_id
44
+ user_modes[chat_id] = 'subidor'
45
+ if chat_id in active_tasks:
46
+ for t in active_tasks[chat_id]:
47
+ t.cancel()
48
+ del active_tasks[chat_id]
49
+
50
+ photos = await client.get_profile_photos('me', limit=1)
51
+ msg = "📁 **Modo Subidor Activado**\n\nBienvenido al Bot Subidor. Aquí podrás registrar tus películas y series. Usa /start para ver las opciones."
52
+ if photos:
53
+ await client.send_file(chat_id, photos[0], caption=msg)
54
+ else:
55
+ await event.respond(msg)
56
+
57
+ @client.on(events.NewMessage(pattern='^/bot_editor$'))
58
+ async def set_editor(event):
59
+ chat_id = event.chat_id
60
+ user_modes[chat_id] = 'editor'
61
+ if chat_id in active_tasks:
62
+ for t in active_tasks[chat_id]:
63
+ t.cancel()
64
+ del active_tasks[chat_id]
65
+
66
+ from telethon.tl.types import KeyboardButtonWebView
67
+ from telethon import Button
68
+ photos = await client.get_profile_photos('me', limit=1)
69
+ msg = "🛠️ **Modo Editor Activado**\n\nBienvenido al Bot Editor. Envíame el ID del contenido que deseas editar o usa las opciones que aparecen debajo."
70
+
71
+ # Limpiar cualquier teclado previo por si acaso
72
+ try:
73
+ tmp = await client.send_message(chat_id, "🔄 Actualizando teclado...", buttons=Button.clear())
74
+ await tmp.delete()
75
+ except: pass
76
+
77
+ btn_webapp = KeyboardButtonWebView(text="🍿 Twisted Streaming Brody", url="https://codebybrody-twistedstreamingbrody.hf.space")
78
+
79
+ if photos:
80
+ await client.send_file(chat_id, photos[0], caption=msg, buttons=[[btn_webapp]])
81
+ else:
82
+ await client.send_message(chat_id, msg, buttons=[[btn_webapp]])
83
+
84
+ # Iniciar ciclo del editor
85
+ import asyncio
86
+ current_task = asyncio.current_task()
87
+ if chat_id not in active_tasks:
88
+ active_tasks[chat_id] = []
89
+ active_tasks[chat_id].append(current_task)
90
+ try:
91
+ await bot_editor.handle_editor_mode(event)
92
+ finally:
93
+ if current_task in active_tasks.get(chat_id, []):
94
+ active_tasks[chat_id].remove(current_task)
95
+
96
+ @client.on(events.NewMessage(pattern='^/bot_buscador$'))
97
+ async def set_buscador(event):
98
+ chat_id = event.chat_id
99
+ user_modes[chat_id] = 'buscador'
100
+ if chat_id in active_tasks:
101
+ for t in active_tasks[chat_id]:
102
+ t.cancel()
103
+ del active_tasks[chat_id]
104
+
105
+ await send_buscador_welcome(event)
106
+
107
+ print("Iniciando el Bot con Modos Separados...")
108
+ client.start(bot_token=os.getenv('TELEGRAM_BOT_TOKEN'))
109
+
110
+ async def set_commands():
111
+ from telethon.tl.functions.bots import SetBotCommandsRequest
112
+ from telethon.tl.types import BotCommand, BotCommandScopeDefault
113
+ try:
114
+ await client(SetBotCommandsRequest(
115
+ scope=BotCommandScopeDefault(),
116
+ lang_code='',
117
+ commands=[
118
+ BotCommand(command="start", description="Elegir Bot / Volver al inicio"),
119
+ BotCommand(command="bot_subidor", description="Activar Bot Subidor"),
120
+ BotCommand(command="bot_editor", description="Activar Bot Editor"),
121
+ BotCommand(command="bot_buscador", description="Activar Bot Buscador"),
122
+ BotCommand(command="app", description="Abrir la Mini App de Catálogo"),
123
+ BotCommand(command="setting", description="Configuración (Modo Buscador)"),
124
+ BotCommand(command="cancelar", description="Cancelar proceso actual")
125
+ ]
126
+ ))
127
+ print("📁 Menú nativo de comandos (/) actualizado exitosamente.")
128
+ except Exception as e:
129
+ print(f"Error al configurar comandos: {e}")
130
+
131
+ client.loop.run_until_complete(set_commands())
132
+ client.run_until_disconnected()
out.txt ADDED
Binary file (100 Bytes). View file
 
refactor2.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ def add_mode_filter(filename, mode_name):
4
+ with open(filename, 'r', encoding='utf-8') as f:
5
+ lines = f.readlines()
6
+
7
+ out_lines = []
8
+ out_lines.append("import asyncio\nimport uuid\nimport time\n")
9
+ out_lines.append("from telethon import events, Button\n")
10
+ out_lines.append("from telethon.tl.types import KeyboardButtonSimpleWebView, KeyboardButtonWebView\n")
11
+ out_lines.append("from google.cloud.firestore_v1.base_query import FieldFilter\n")
12
+ out_lines.append("from core import *\n\n")
13
+
14
+ i = 0
15
+ while i < len(lines):
16
+ line = lines[i]
17
+ out_lines.append(line)
18
+ if line.strip().startswith('@client.on('):
19
+ # next line is usually async def ...
20
+ i += 1
21
+ if i < len(lines):
22
+ next_line = lines[i]
23
+ out_lines.append(next_line)
24
+ if next_line.strip().startswith('async def '):
25
+ # extract the indent
26
+ indent = next_line[:len(next_line) - len(next_line.lstrip())]
27
+ # get event param name
28
+ match = re.search(r'async def \w+\((.*?)\):', next_line)
29
+ if match:
30
+ param = match.group(1).split(',')[0].strip()
31
+ if param in ('event', 'event_or_query', 'e'):
32
+ out_lines.append(f"{indent} chat_id = getattr({param}, 'chat_id', getattr(getattr({param}, 'message', None), 'chat_id', None))\n")
33
+ out_lines.append(f"{indent} if user_modes.get(chat_id) != '{mode_name}': return\n")
34
+ i += 1
35
+
36
+ with open(filename, 'w', encoding='utf-8') as f:
37
+ f.writelines(out_lines)
38
+
39
+ add_mode_filter('bot_subidor.py', 'subidor')
40
+ add_mode_filter('bot_editor.py', 'editor')
41
+ add_mode_filter('bot_buscador.py', 'buscador')
42
+ print("Done")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ telethon
2
+ firebase-admin
3
+ python-dotenv
4
+ requests
scratch/add_delete_confirm.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ # MOVIE DELETE
9
+ old_movie_del = """ elif resp.data == b"eliminar":
10
+ db.collection('videos').document(movie_id).delete()
11
+ await conv.send_message("✅ Película eliminada.")"""
12
+
13
+ new_movie_del = """ elif resp.data == b"eliminar":
14
+ msg_conf = await conv.send_message(
15
+ f"⚠️ ¿Estás seguro de que deseas eliminar la película **{data.get('title')}**?\\nEsta acción no se puede deshacer.",
16
+ buttons=[
17
+ [Button.inline("⚠️ Sí, eliminar definitivamente", b"confirm_del")],
18
+ [Button.inline("❌ Cancelar", b"cancel_del")]
19
+ ]
20
+ )
21
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
22
+ if isinstance(resp_conf, events.CallbackQuery.Event):
23
+ await resp_conf.answer()
24
+ await msg_conf.edit(buttons=None)
25
+ if resp_conf.data == b"confirm_del":
26
+ db.collection('videos').document(movie_id).delete()
27
+ await conv.send_message("✅ Película eliminada exitosamente.")
28
+ else:
29
+ await conv.send_message("✅ Eliminación cancelada.")"""
30
+
31
+ code = code.replace(old_movie_del, new_movie_del)
32
+
33
+ # SERIES DELETE
34
+ old_series_del = """ elif resp.data == b"eliminar":
35
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
36
+ for c in caps: db.collection('videos').document(c.id).delete()
37
+ db.collection('videos').document(series_id).delete()
38
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados.")
39
+ return"""
40
+
41
+ new_series_del = """ elif resp.data == b"eliminar":
42
+ msg_conf = await conv.send_message(
43
+ f"⚠️ ¿Estás seguro de que deseas eliminar la serie completa **{title}** y **TODOS** sus capítulos?\\nEsta acción no se puede deshacer.",
44
+ buttons=[
45
+ [Button.inline("⚠️ Sí, eliminar serie y capítulos", b"confirm_del")],
46
+ [Button.inline("❌ Cancelar", b"cancel_del")]
47
+ ]
48
+ )
49
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
50
+ if isinstance(resp_conf, events.CallbackQuery.Event):
51
+ await resp_conf.answer()
52
+ await msg_conf.edit(buttons=None)
53
+ if resp_conf.data == b"confirm_del":
54
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
55
+ for c in caps: db.collection('videos').document(c.id).delete()
56
+ db.collection('videos').document(series_id).delete()
57
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados exitosamente.")
58
+ return
59
+ else:
60
+ await conv.send_message("✅ Eliminación cancelada.")"""
61
+
62
+ code = code.replace(old_series_del, new_series_del)
63
+
64
+ # CHAPTER DELETE
65
+ old_chapter_del = """ if resp.data == b"eliminar":
66
+ db.collection('videos').document(cap_id).delete()
67
+ await conv.send_message("✅ Capítulo eliminado.")"""
68
+
69
+ new_chapter_del = """ if resp.data == b"eliminar":
70
+ msg_conf = await conv.send_message(
71
+ f"⚠️ ¿Estás seguro de que deseas eliminar el capítulo **{data.get('title')}**?\\nEsta acción no se puede deshacer.",
72
+ buttons=[
73
+ [Button.inline("⚠️ Sí, eliminar capítulo", b"confirm_del")],
74
+ [Button.inline("❌ Cancelar", b"cancel_del")]
75
+ ]
76
+ )
77
+ resp_conf = await wait_for_message_or_callback(conv, timeout=120)
78
+ if isinstance(resp_conf, events.CallbackQuery.Event):
79
+ await resp_conf.answer()
80
+ await msg_conf.edit(buttons=None)
81
+ if resp_conf.data == b"confirm_del":
82
+ db.collection('videos').document(cap_id).delete()
83
+ await conv.send_message("✅ Capítulo eliminado exitosamente.")
84
+ else:
85
+ await conv.send_message("✅ Eliminación cancelada.")"""
86
+
87
+ code = code.replace(old_chapter_del, new_chapter_del)
88
+
89
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
90
+ f.write(code)
91
+
92
+ print("Delete confirmation patch applied successfully.")
scratch/add_direct_id.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_handle_editor = """ if isinstance(resp, events.CallbackQuery.Event):
9
+ await resp.answer()
10
+ await msg.edit(buttons=None)
11
+
12
+ if resp.data == b"ed_exit":
13
+ editor_mode_active[chat_id] = False
14
+ await conv.send_message("✅ **Modo editor desactivado.**")
15
+ break
16
+ elif resp.data == b"ed_mov":
17
+ await handle_editor_movie_search(conv)
18
+ elif resp.data == b"ed_ser":
19
+ await handle_editor_series_search(conv)"""
20
+
21
+ new_handle_editor = """ if isinstance(resp, events.CallbackQuery.Event):
22
+ await resp.answer()
23
+ await msg.edit(buttons=None)
24
+
25
+ if resp.data == b"ed_exit":
26
+ editor_mode_active[chat_id] = False
27
+ await conv.send_message("✅ **Modo editor desactivado.**")
28
+ break
29
+ elif resp.data == b"ed_mov":
30
+ await handle_editor_movie_search(conv)
31
+ elif resp.data == b"ed_ser":
32
+ await handle_editor_series_search(conv)
33
+ elif getattr(resp, 'raw_text', ''):
34
+ txt = resp.raw_text.strip()
35
+ if txt.startswith('/'): continue
36
+ await msg.edit(buttons=None)
37
+
38
+ doc = db.collection('videos').document(txt).get()
39
+ if doc.exists:
40
+ data = doc.to_dict()
41
+ if data.get('is_folder', False) or data.get('section') == 'series':
42
+ await handle_editor_series_action(conv, txt)
43
+ else:
44
+ await handle_editor_movie_action(conv, txt)
45
+ else:
46
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
47
+ """
48
+
49
+ code = code.replace(old_handle_editor, new_handle_editor)
50
+
51
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
52
+ f.write(code)
53
+
54
+ print("Editor direct ID search applied successfully.")
scratch/add_editor.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ if "editor_mode_active = {}" not in code:
9
+ old_start = """active_tasks = {}
10
+
11
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
12
+ async def start_subir_handler(event):
13
+ chat_id = event.chat_id"""
14
+
15
+ new_start = """active_tasks = {}
16
+ editor_mode_active = {}
17
+
18
+ @client.on(events.NewMessage(pattern='/(start|subir|subir_pelicula|subir_serie)$'))
19
+ async def start_subir_handler(event):
20
+ chat_id = event.chat_id
21
+ if editor_mode_active.get(chat_id, False):
22
+ await event.respond("🛠️ **Estás en Modo Editor.**\\nPor favor, usa `/desactivar_modo_editor` para salir del editor y usar los comandos normales.")
23
+ return"""
24
+ code = code.replace(old_start, new_start)
25
+
26
+ editor_logic = """
27
+ # --- MODO EDITOR ---
28
+ @client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
29
+ async def enable_editor(event):
30
+ chat_id = event.chat_id
31
+ editor_mode_active[chat_id] = True
32
+ await handle_editor_mode(event)
33
+
34
+ @client.on(events.NewMessage(pattern='/(desactivar_modo_editor)$'))
35
+ async def disable_editor(event):
36
+ chat_id = event.chat_id
37
+ editor_mode_active[chat_id] = False
38
+ await event.respond("✅ **Modo editor desactivado.** Ya puedes usar los comandos normales.")
39
+
40
+ async def handle_editor_mode(event):
41
+ chat_id = event.chat_id
42
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
43
+ try:
44
+ while editor_mode_active.get(chat_id, False):
45
+ msg = await conv.send_message(
46
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
47
+ buttons=[
48
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
49
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
50
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
51
+ ]
52
+ )
53
+
54
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
55
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
56
+ break
57
+
58
+ if isinstance(resp, events.CallbackQuery.Event):
59
+ await resp.answer()
60
+ await msg.edit(buttons=None)
61
+
62
+ if resp.data == b"ed_exit":
63
+ editor_mode_active[chat_id] = False
64
+ await conv.send_message("✅ **Modo editor desactivado.**")
65
+ break
66
+ elif resp.data == b"ed_mov":
67
+ await handle_editor_movie_search(conv)
68
+ elif resp.data == b"ed_ser":
69
+ await handle_editor_series_search(conv)
70
+ except Exception as e:
71
+ print("Editor error:", e)
72
+
73
+ async def handle_editor_movie_search(conv):
74
+ uid_back = str(uuid.uuid4()).encode()
75
+ msg = await conv.send_message("🔍 Escribe el nombre de la **película** que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
76
+
77
+ resp = await wait_for_message_or_callback(conv, timeout=300)
78
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
79
+ await resp.answer("Cancelado")
80
+ await msg.edit("Búsqueda cancelada.", buttons=None)
81
+ return
82
+
83
+ query = resp.raw_text.strip()
84
+ await msg.delete()
85
+
86
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
87
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower()]
88
+
89
+ if not results:
90
+ await conv.send_message("❌ No se encontraron películas con ese nombre.")
91
+ return
92
+
93
+ results = results[:10]
94
+ buttons = []
95
+ for r in results:
96
+ data = r.to_dict()
97
+ buttons.append([Button.inline(f"🎬 {data.get('title')[:30]}", f"ed_m_{r.id}".encode('utf-8'))])
98
+
99
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
100
+
101
+ msg_res = await conv.send_message("📌 **Resultados (Películas):**", buttons=buttons)
102
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
103
+
104
+ if isinstance(resp_res, events.CallbackQuery.Event):
105
+ await resp_res.answer()
106
+ await msg_res.edit(buttons=None)
107
+ if resp_res.data == b"ed_back": return
108
+
109
+ movie_id = resp_res.data.decode().replace('ed_m_', '')
110
+ await handle_editor_movie_action(conv, movie_id)
111
+
112
+ async def handle_editor_movie_action(conv, movie_id):
113
+ doc = db.collection('videos').document(movie_id).get()
114
+ if not doc.exists: return
115
+ data = doc.to_dict()
116
+
117
+ msg = await conv.send_message(
118
+ f"🎬 **Editando Película:**\\n`{data.get('title')}`",
119
+ buttons=[
120
+ [Button.inline("✏️ Renombrar Título", b"renombrar")],
121
+ [Button.inline("🗑️ Eliminar Película", b"eliminar")],
122
+ [Button.inline("⬅️ Volver", b"volver")]
123
+ ]
124
+ )
125
+ resp = await wait_for_message_or_callback(conv, timeout=300)
126
+ if isinstance(resp, events.CallbackQuery.Event):
127
+ await resp.answer()
128
+ await msg.edit(buttons=None)
129
+ if resp.data == b"volver": return
130
+ elif resp.data == b"renombrar":
131
+ await conv.send_message("Escribe el **nuevo título** para la película:")
132
+ new_title = await conv.get_response()
133
+ db.collection('videos').document(movie_id).update({"title": new_title.raw_text})
134
+ await conv.send_message(f"✅ Título actualizado a: **{new_title.raw_text}**")
135
+ elif resp.data == b"eliminar":
136
+ db.collection('videos').document(movie_id).delete()
137
+ await conv.send_message("✅ Película eliminada.")
138
+
139
+ async def handle_editor_series_search(conv):
140
+ uid_back = str(uuid.uuid4()).encode()
141
+ msg = await conv.send_message("🔍 Escribe el nombre de la **serie** que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
142
+
143
+ resp = await wait_for_message_or_callback(conv, timeout=300)
144
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
145
+ await resp.answer()
146
+ await msg.edit("Búsqueda cancelada.", buttons=None)
147
+ return
148
+
149
+ query = resp.raw_text.strip()
150
+ await msg.delete()
151
+
152
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
153
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower()]
154
+
155
+ if not results:
156
+ await conv.send_message("❌ No se encontraron series con ese nombre.")
157
+ return
158
+
159
+ results = results[:10]
160
+ buttons = []
161
+ for r in results:
162
+ buttons.append([Button.inline(f"📺 {r.to_dict().get('title')[:30]}", f"ed_s_{r.id}".encode('utf-8'))])
163
+
164
+ buttons.append([Button.inline("⬅️ Volver", b"ed_back")])
165
+
166
+ msg_res = await conv.send_message("📌 **Resultados (Series):**", buttons=buttons)
167
+ resp_res = await wait_for_message_or_callback(conv, timeout=300)
168
+
169
+ if isinstance(resp_res, events.CallbackQuery.Event):
170
+ await resp_res.answer()
171
+ await msg_res.edit(buttons=None)
172
+ if resp_res.data == b"ed_back": return
173
+
174
+ series_id = resp_res.data.decode().replace('ed_s_', '')
175
+ await handle_editor_series_action(conv, series_id)
176
+
177
+ async def handle_editor_series_action(conv, series_id):
178
+ while editor_mode_active.get(conv.chat_id, False):
179
+ doc = db.collection('videos').document(series_id).get()
180
+ if not doc.exists: return
181
+ data = doc.to_dict()
182
+ title = data.get('title')
183
+
184
+ msg = await conv.send_message(
185
+ f"📺 **Editando Serie:**\\n`{title}`",
186
+ buttons=[
187
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
188
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
189
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
190
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
191
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
192
+ ]
193
+ )
194
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
195
+ if getattr(resp, 'raw_text', '').startswith('/'): return
196
+
197
+ if isinstance(resp, events.CallbackQuery.Event):
198
+ await resp.answer()
199
+ await msg.edit(buttons=None)
200
+
201
+ if resp.data == b"volver": return
202
+ elif resp.data == b"renombrar":
203
+ await conv.send_message("Escribe el **nuevo título general** para la serie:")
204
+ new_title = await conv.get_response()
205
+ db.collection('videos').document(series_id).update({"title": new_title.raw_text})
206
+ await conv.send_message(f"✅ Título general actualizado a: **{new_title.raw_text}**")
207
+ elif resp.data == b"eliminar":
208
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
209
+ for c in caps: db.collection('videos').document(c.id).delete()
210
+ db.collection('videos').document(series_id).delete()
211
+ await conv.send_message("✅ Serie y todos sus capítulos eliminados.")
212
+ return
213
+ elif resp.data == b"ver_caps":
214
+ await handle_editor_series_chapters(conv, series_id, title)
215
+ elif resp.data == b"add_caps":
216
+ await handle_editor_add_chapters(conv, series_id, title)
217
+
218
+ async def handle_editor_series_chapters(conv, series_id, series_title):
219
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
220
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
221
+ if not caps:
222
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
223
+ return
224
+
225
+ buttons = []
226
+ for c in caps[:90]:
227
+ c_data = c.to_dict()
228
+ buttons.append([Button.inline(f"Cap {c_data.get('episode', 0)}: {c_data.get('title')[:20]}", f"ed_c_{c.id}".encode('utf-8'))])
229
+
230
+ buttons.append([Button.inline("⬅️ Volver", b"volver_caps")])
231
+
232
+ msg = await conv.send_message(f"📑 **Capítulos de {series_title}**\\nSelecciona uno para editar:", buttons=buttons)
233
+ resp = await wait_for_message_or_callback(conv, timeout=300)
234
+
235
+ if isinstance(resp, events.CallbackQuery.Event):
236
+ await resp.answer()
237
+ await msg.edit(buttons=None)
238
+ if resp.data == b"volver_caps": return
239
+ cap_id = resp.data.decode().replace('ed_c_', '')
240
+ await handle_editor_single_chapter(conv, cap_id)
241
+
242
+ async def handle_editor_single_chapter(conv, cap_id):
243
+ doc = db.collection('videos').document(cap_id).get()
244
+ if not doc.exists: return
245
+ data = doc.to_dict()
246
+
247
+ msg = await conv.send_message(
248
+ f"🎞️ **Editando Capítulo:**\\n`{data.get('title')}`",
249
+ buttons=[
250
+ [Button.inline("✏️ Renombrar", b"renombrar")],
251
+ [Button.inline("🗑️ Eliminar", b"eliminar")],
252
+ [Button.inline("⬅️ Volver", b"volver")]
253
+ ]
254
+ )
255
+ resp = await wait_for_message_or_callback(conv, timeout=300)
256
+ if isinstance(resp, events.CallbackQuery.Event):
257
+ await resp.answer()
258
+ await msg.edit(buttons=None)
259
+ if resp.data == b"volver": return
260
+ if resp.data == b"renombrar":
261
+ await conv.send_message("Escribe el **nuevo nombre** del capítulo:")
262
+ new_title = await conv.get_response()
263
+ db.collection('videos').document(cap_id).update({"title": new_title.raw_text})
264
+ await conv.send_message(f"✅ Capítulo renombrado a: **{new_title.raw_text}**")
265
+ if resp.data == b"eliminar":
266
+ db.collection('videos').document(cap_id).delete()
267
+ await conv.send_message("✅ Capítulo eliminado.")
268
+
269
+ async def handle_editor_add_chapters(conv, series_id, series_title):
270
+ uid_done = str(uuid.uuid4()).encode()
271
+ videos = []
272
+
273
+ msg_v = await conv.send_message(
274
+ f"➕ **Añadiendo capítulos a: {series_title}**\\n\\nEnvía los videos. Cuando termines presiona el botón.",
275
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
276
+ )
277
+
278
+ debounce_task = None
279
+ async def update_button():
280
+ await asyncio.sleep(0.8)
281
+ nonlocal msg_v
282
+ try: await msg_v.delete()
283
+ except: pass
284
+ msg_v = await conv.send_message(
285
+ f"➕ **Añadiendo capítulos a: {series_title}**\\n\\n({len(videos)} recibidos). Envía más o termina.",
286
+ buttons=[[Button.inline("📁 Terminar y Guardar", uid_done)]]
287
+ )
288
+
289
+ async def video_receiver(e):
290
+ is_video = False
291
+ if getattr(e, 'media', None):
292
+ if getattr(e, 'video', None):
293
+ is_video = True
294
+ elif getattr(e, 'document', None):
295
+ mime = getattr(e.file, 'mime_type', '') if hasattr(e, 'file') else ''
296
+ if mime.startswith('video/'):
297
+ is_video = True
298
+ else:
299
+ for attr in e.document.attributes:
300
+ if hasattr(attr, 'file_name'):
301
+ import os
302
+ ext = os.path.splitext(attr.file_name)[1].lower()
303
+ if ext in ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.ts', '.m4v']:
304
+ is_video = True
305
+ break
306
+ if is_video:
307
+ videos.append(e)
308
+ nonlocal debounce_task
309
+ if debounce_task: debounce_task.cancel()
310
+ debounce_task = asyncio.create_task(update_button())
311
+
312
+ client.add_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
313
+ try:
314
+ while True:
315
+ event = await wait_for_message_or_callback(conv, timeout=3600)
316
+ if isinstance(event, events.CallbackQuery.Event):
317
+ if event.data == uid_done:
318
+ if not videos:
319
+ await event.answer("No has enviado videos.", alert=True)
320
+ return
321
+ await event.answer("Guardando...")
322
+ if debounce_task: debounce_task.cancel()
323
+ await msg_v.edit(f"✅ Se recibieron {len(videos)} capítulos.", buttons=None)
324
+ break
325
+ finally:
326
+ client.remove_event_handler(video_receiver, events.NewMessage(chats=conv.chat_id, incoming=True))
327
+
328
+ if not videos: return
329
+
330
+ uid_title = str(uuid.uuid4()).encode()
331
+ uid_file = str(uuid.uuid4()).encode()
332
+ msg_n = await conv.send_message(
333
+ "📁 ¿Cómo nombrar estos capítulos extra?",
334
+ buttons=[
335
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
336
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
337
+ ]
338
+ )
339
+
340
+ naming_strategy = "title"
341
+ while True:
342
+ event = await wait_for_message_or_callback(conv, timeout=300)
343
+ if isinstance(event, events.CallbackQuery.Event):
344
+ if event.data == uid_title:
345
+ naming_strategy = "title"
346
+ await msg_n.edit("Formato: Serie - Capítulo X", buttons=None)
347
+ break
348
+ elif event.data == uid_file:
349
+ naming_strategy = "file"
350
+ await msg_n.edit("Formato: Archivo original", buttons=None)
351
+ break
352
+ else:
353
+ naming_strategy = "manual"
354
+ manual_prefix = event.raw_text
355
+ await msg_n.edit(f"Formato: {manual_prefix}...", buttons=None)
356
+ break
357
+
358
+ status_msg = await conv.send_message("📁 **Procesando capítulos extra...**")
359
+
360
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
361
+ max_ep = 0
362
+ for c in caps:
363
+ ep = c.to_dict().get('episode', 0)
364
+ if ep > max_ep: max_ep = ep
365
+
366
+ for i, video_msg in enumerate(videos):
367
+ max_ep += 1
368
+
369
+ if naming_strategy == "title":
370
+ ep_title = f"{series_title} - Capítulo {max_ep}"
371
+ elif naming_strategy == "manual":
372
+ ep_title = f"{manual_prefix} - Capítulo {max_ep}"
373
+ else:
374
+ doc_name = "Episodio"
375
+ if hasattr(video_msg.media, 'document'):
376
+ for attr in video_msg.media.document.attributes:
377
+ if hasattr(attr, 'file_name'):
378
+ import os
379
+ doc_name = os.path.splitext(attr.file_name)[0]
380
+ break
381
+ ep_title = doc_name
382
+
383
+ await status_msg.edit(f"📁 Subiendo extra: **{ep_title}** ({i+1}/{len(videos)})")
384
+ caption = f"**Twisted Streaming Brody Data**\\n\\n📁 **Serie:** {series_title}\\n📁 **Episodio:** {ep_title}"
385
+ sent_to_channel = await client.send_file(CHANNEL_ID, video_msg.media, caption=caption)
386
+ clean_channel_id = str(CHANNEL_ID).replace("-100", "")
387
+ file_url = f"https://t.me/c/{clean_channel_id}/{sent_to_channel.id}"
388
+
389
+ db.collection('videos').add({
390
+ "title": ep_title,
391
+ "section": "series",
392
+ "is_folder": False,
393
+ "folder_id": series_id,
394
+ "episode": max_ep,
395
+ "season": 1,
396
+ "video_url": file_url,
397
+ "telegram_file_id": str(sent_to_channel.id),
398
+ "description": "",
399
+ "thumbnail_url": "",
400
+ "cover_url": "",
401
+ "views": 0,
402
+ "rating": 0,
403
+ "status": "active",
404
+ "is_public": True,
405
+ "categories": [],
406
+ "servers": [file_url],
407
+ "created_at": firestore.SERVER_TIMESTAMP,
408
+ "updated_at": firestore.SERVER_TIMESTAMP
409
+ })
410
+ await status_msg.edit(f"✅ **¡{len(videos)} capítulos extra añadidos con éxito!**")
411
+
412
+ if __name__ == '__main__':
413
+ """
414
+ code = code.replace("if __name__ == '__main__':", editor_logic)
415
+
416
+ old_cmds = """ BotCommand(command="app", description="Abrir la Mini App de Catálogo"),
417
+ BotCommand(command="setting", description="Configurar envío de videos"),
418
+ BotCommand(command="cancelar", description="Cancelar proceso de subida")"""
419
+ new_cmds = """ BotCommand(command="app", description="Abrir la Mini App de Catálogo"),
420
+ BotCommand(command="setting", description="Configurar envío de videos"),
421
+ BotCommand(command="cancelar", description="Cancelar proceso de subida"),
422
+ BotCommand(command="activar_modo_editor", description="Activar Modo Editor"),
423
+ BotCommand(command="desactivar_modo_editor", description="Desactivar Modo Editor")"""
424
+ code = code.replace(old_cmds, new_cmds)
425
+
426
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
427
+ f.write(code)
428
+
429
+ print("Patch applied successfully.")
scratch/add_id_search.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ # MOVIE SEARCH
9
+ old_movie_search = """async def handle_editor_movie_search(conv):
10
+ uid_back = str(uuid.uuid4()).encode()
11
+ msg = await conv.send_message("🔍 Escribe el nombre de la **película** que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
12
+
13
+ resp = await wait_for_message_or_callback(conv, timeout=300)
14
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
15
+ await resp.answer("Cancelado")
16
+ await msg.edit("Búsqueda cancelada.", buttons=None)
17
+ return
18
+
19
+ query = resp.raw_text.strip()
20
+ await msg.delete()
21
+
22
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
23
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower()]"""
24
+
25
+ new_movie_search = """async def handle_editor_movie_search(conv):
26
+ uid_back = str(uuid.uuid4()).encode()
27
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la película que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
28
+
29
+ resp = await wait_for_message_or_callback(conv, timeout=300)
30
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
31
+ await resp.answer("Cancelado")
32
+ await msg.edit("Búsqueda cancelada.", buttons=None)
33
+ return
34
+
35
+ query = resp.raw_text.strip()
36
+ await msg.delete()
37
+
38
+ movies_ref = db.collection('videos').where(filter=FieldFilter('section', '==', 'peliculas')).get()
39
+ results = [m for m in movies_ref if query.lower() in m.to_dict().get('title', '').lower() or query == m.id]"""
40
+
41
+ code = code.replace(old_movie_search, new_movie_search)
42
+
43
+
44
+ # SERIES SEARCH
45
+ old_series_search = """async def handle_editor_series_search(conv):
46
+ uid_back = str(uuid.uuid4()).encode()
47
+ msg = await conv.send_message("🔍 Escribe el nombre de la **serie** que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
48
+
49
+ resp = await wait_for_message_or_callback(conv, timeout=300)
50
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
51
+ await resp.answer()
52
+ await msg.edit("Búsqueda cancelada.", buttons=None)
53
+ return
54
+
55
+ query = resp.raw_text.strip()
56
+ await msg.delete()
57
+
58
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
59
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower()]"""
60
+
61
+ new_series_search = """async def handle_editor_series_search(conv):
62
+ uid_back = str(uuid.uuid4()).encode()
63
+ msg = await conv.send_message("🔍 Escribe el **nombre o el ID** de la serie que deseas buscar:", buttons=[[Button.inline("⬅️ Cancelar", uid_back)]])
64
+
65
+ resp = await wait_for_message_or_callback(conv, timeout=300)
66
+ if isinstance(resp, events.CallbackQuery.Event) and resp.data == uid_back:
67
+ await resp.answer()
68
+ await msg.edit("Búsqueda cancelada.", buttons=None)
69
+ return
70
+
71
+ query = resp.raw_text.strip()
72
+ await msg.delete()
73
+
74
+ series_ref = db.collection('videos').where(filter=FieldFilter('is_folder', '==', True)).get()
75
+ results = [s for s in series_ref if query.lower() in s.to_dict().get('title', '').lower() or query == s.id]"""
76
+
77
+ code = code.replace(old_series_search, new_series_search)
78
+
79
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
80
+ f.write(code)
81
+
82
+ print("ID Search patch applied successfully.")
scratch/add_mass_edit.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ # 1. ADD BUTTON
9
+ old_series_buttons = """ msg = await conv.send_message(
10
+ f"📺 **Editando Serie:**\\n`{title}`",
11
+ buttons=[
12
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
13
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
14
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
15
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
16
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
17
+ ]
18
+ )"""
19
+
20
+ new_series_buttons = """ msg = await conv.send_message(
21
+ f"📺 **Editando Serie:**\\n`{title}`",
22
+ buttons=[
23
+ [Button.inline("✏️ Renombrar Serie", b"renombrar")],
24
+ [Button.inline("📑 Ver y Editar Capítulos", b"ver_caps")],
25
+ [Button.inline("📝 Edición Masiva de Capítulos", b"editar_lista")],
26
+ [Button.inline("➕ Agregar Nuevos Capítulos", b"add_caps")],
27
+ [Button.inline("🗑️ Eliminar Serie Completa", b"eliminar")],
28
+ [Button.inline("⬅️ Volver al menú principal", b"volver")]
29
+ ]
30
+ )"""
31
+
32
+ code = code.replace(old_series_buttons, new_series_buttons)
33
+
34
+ # 2. ADD LOGIC
35
+ old_series_logic = """ elif resp.data == b"ver_caps":
36
+ await handle_editor_series_chapters(conv, series_id, title)"""
37
+
38
+ new_series_logic = """ elif resp.data == b"ver_caps":
39
+ await handle_editor_series_chapters(conv, series_id, title)
40
+ elif resp.data == b"editar_lista":
41
+ caps = db.collection('videos').where(filter=FieldFilter('folder_id', '==', series_id)).get()
42
+ caps = sorted(caps, key=lambda x: x.to_dict().get('episode', 0))
43
+ if not caps:
44
+ await conv.send_message("❌ Esta serie no tiene capítulos.")
45
+ continue
46
+
47
+ template = f"--- {title} ---\\n"
48
+ for c in caps:
49
+ template += f"{{{c.id}}} {c.to_dict().get('title')}\\n"
50
+
51
+ await conv.send_message(
52
+ "📝 **EDICIÓN MASIVA**\\n\\n"
53
+ "1. Toca el siguiente mensaje para copiarlo.\\n"
54
+ "2. Pégalo en el chat y edita los nombres de los capítulos.\\n"
55
+ "3. Envíamelo.\\n\\n"
56
+ "⚠️ **MUY IMPORTANTE:** ¡NO borres ni modifiques los códigos entre llaves `{ }`!"
57
+ )
58
+ await conv.send_message(f"```{template}```")
59
+
60
+ await conv.send_message("⏳ Esperando tu mensaje con la plantilla editada... (O envía `/cancelar` para abortar)")
61
+
62
+ resp_text = await wait_for_message_or_callback(conv, timeout=3600)
63
+ if isinstance(resp_text, events.CallbackQuery.Event):
64
+ await resp_text.answer("Operación cancelada")
65
+ continue
66
+ if resp_text.raw_text.strip().lower() == '/cancelar':
67
+ await conv.send_message("✅ Edición masiva cancelada.")
68
+ continue
69
+
70
+ new_text = resp_text.raw_text
71
+ import re
72
+ matches = re.findall(r'\\{(.*?)\\}\\s*(.*)', new_text)
73
+
74
+ if not matches:
75
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
76
+ continue
77
+
78
+ status_m = await conv.send_message("⚙️ Guardando cambios...")
79
+ updated_count = 0
80
+ for doc_id, new_title in matches:
81
+ doc_id = doc_id.strip()
82
+ new_title = new_title.strip()
83
+ if new_title:
84
+ try:
85
+ db.collection('videos').document(doc_id).update({"title": new_title})
86
+ updated_count += 1
87
+ except: pass
88
+
89
+ await status_m.edit(f"✅ **¡Listo!** Se actualizaron {updated_count} capítulos correctamente.")"""
90
+
91
+ code = code.replace(old_series_logic, new_series_logic)
92
+
93
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
94
+ f.write(code)
95
+
96
+ print("Mass edit feature applied successfully.")
scratch/add_mass_edit_title.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_mass_edit = """ template = f"--- {title} ---\\n"
9
+ for c in caps:
10
+ template += f"{{{c.id}}} {c.to_dict().get('title')}\\n"
11
+
12
+ await conv.send_message(
13
+ "📝 **EDICIÓN MASIVA**\\n\\n"
14
+ "1. Toca el siguiente mensaje para copiarlo.\\n"
15
+ "2. Pégalo en el chat y edita los nombres de los capítulos.\\n"
16
+ "3. Envíamelo.\\n\\n"
17
+ "⚠️ **MUY IMPORTANTE:** ¡NO borres ni modifiques los códigos entre llaves `{ }`!"
18
+ )
19
+ await conv.send_message(f"```{template}```")
20
+
21
+ await conv.send_message("⏳ Esperando tu mensaje con la plantilla editada... (O envía `/cancelar` para abortar)")
22
+
23
+ resp_text = await wait_for_message_or_callback(conv, timeout=3600)
24
+ if isinstance(resp_text, events.CallbackQuery.Event):
25
+ await resp_text.answer("Operación cancelada")
26
+ continue
27
+ if resp_text.raw_text.strip().lower() == '/cancelar':
28
+ await conv.send_message("✅ Edición masiva cancelada.")
29
+ continue
30
+
31
+ new_text = resp_text.raw_text
32
+ import re
33
+ matches = re.findall(r'\\{(.*?)\\}\\s*(.*)', new_text)
34
+
35
+ if not matches:
36
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
37
+ continue
38
+
39
+ status_m = await conv.send_message("⚙️ Guardando cambios...")
40
+ updated_count = 0
41
+ for doc_id, new_title in matches:
42
+ doc_id = doc_id.strip()
43
+ new_title = new_title.strip()
44
+ if new_title:
45
+ try:
46
+ db.collection('videos').document(doc_id).update({"title": new_title})
47
+ updated_count += 1
48
+ except: pass
49
+
50
+ await status_m.edit(f"✅ **¡Listo!** Se actualizaron {updated_count} capítulos correctamente.")"""
51
+
52
+ new_mass_edit = """ template = f"{{TITULO_GENERAL}} {title}\\n\\n"
53
+ for c in caps:
54
+ template += f"{{{c.id}}} {c.to_dict().get('title')}\\n"
55
+
56
+ await conv.send_message(
57
+ "📝 **EDICIÓN MASIVA**\\n\\n"
58
+ "1. Toca el siguiente mensaje para copiarlo.\\n"
59
+ "2. Pégalo en el chat y edita el nombre de la serie o de los capítulos como desees.\\n"
60
+ "3. Envíamelo.\\n\\n"
61
+ "⚠️ **MUY IMPORTANTE:** ¡NO borres ni modifiques los códigos entre llaves `{ }`!"
62
+ )
63
+ await conv.send_message(f"```{template}```")
64
+
65
+ await conv.send_message("⏳ Esperando tu mensaje con la plantilla editada... (O envía `/cancelar` para abortar)")
66
+
67
+ resp_text = await wait_for_message_or_callback(conv, timeout=3600)
68
+ if isinstance(resp_text, events.CallbackQuery.Event):
69
+ await resp_text.answer("Operación cancelada")
70
+ continue
71
+ if resp_text.raw_text.strip().lower() == '/cancelar':
72
+ await conv.send_message("✅ Edición masiva cancelada.")
73
+ continue
74
+
75
+ new_text = resp_text.raw_text
76
+ import re
77
+ matches = re.findall(r'\\{(.*?)\\}\\s*(.*)', new_text)
78
+
79
+ if not matches:
80
+ await conv.send_message("❌ No se detectó el formato correcto. Recuerda no borrar las llaves { }.")
81
+ continue
82
+
83
+ status_m = await conv.send_message("⚙️ Guardando cambios...")
84
+ updated_count = 0
85
+ for doc_id, new_title in matches:
86
+ doc_id = doc_id.strip()
87
+ new_title = new_title.strip()
88
+ if new_title:
89
+ if doc_id == "TITULO_GENERAL":
90
+ try:
91
+ db.collection('videos').document(series_id).update({"title": new_title})
92
+ title = new_title # update variable
93
+ except: pass
94
+ else:
95
+ try:
96
+ db.collection('videos').document(doc_id).update({"title": new_title})
97
+ updated_count += 1
98
+ except: pass
99
+
100
+ await status_m.edit(f"✅ **¡Listo!** Se actualizó el título general y {updated_count} capítulos correctamente.")"""
101
+
102
+ code = code.replace(old_mass_edit, new_mass_edit)
103
+
104
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
105
+ f.write(code)
106
+
107
+ print("Mass edit title patch applied.")
scratch/add_search_mode.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ # 1. Add search_mode_active dictionary
9
+ if "search_mode_active = {}" not in code:
10
+ code = code.replace("editor_mode_active = {}", "editor_mode_active = {}\nsearch_mode_active = {}")
11
+
12
+ # 2. Update handle_document_id to ONLY work if search_mode_active is True
13
+ old_handle_doc = """@client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
14
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
15
+ async def handle_document_id(event):
16
+ if editor_mode_active.get(event.chat_id, False):
17
+ return"""
18
+
19
+ new_handle_doc = """@client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
20
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
21
+ async def handle_document_id(event):
22
+ if editor_mode_active.get(event.chat_id, False):
23
+ return
24
+
25
+ if not search_mode_active.get(event.chat_id, False):
26
+ return # Ignore links/IDs if search mode is OFF"""
27
+
28
+ code = code.replace(old_handle_doc, new_handle_doc)
29
+
30
+ # 3. Add /buscador_on and /buscador_off and the text search handler
31
+ new_search_logic = """
32
+ # --- MODO BUSCADOR ---
33
+ @client.on(events.NewMessage(pattern='^/buscador_on$'))
34
+ async def enable_search_mode(event):
35
+ chat_id = event.chat_id
36
+
37
+ # Desactivar editor y cancelar subidas
38
+ editor_mode_active[chat_id] = False
39
+ if chat_id in active_tasks:
40
+ for t in active_tasks[chat_id]:
41
+ t.cancel()
42
+ del active_tasks[chat_id]
43
+
44
+ search_mode_active[chat_id] = True
45
+ await event.respond("🔍 **Modo Buscador Activado**\\n\\nAhora puedes buscar enviando el título de una película, serie o capítulo. También puedes pegar enlaces directos o IDs.\\n\\nEnvía /buscador_off para salir.")
46
+
47
+ @client.on(events.NewMessage(pattern='^/buscador_off$'))
48
+ async def disable_search_mode(event):
49
+ chat_id = event.chat_id
50
+ search_mode_active[chat_id] = False
51
+ await event.respond("❌ **Modo Buscador Desactivado**.")
52
+
53
+ @client.on(events.NewMessage(func=lambda e: not e.text.startswith('/') and len(e.text) != 20))
54
+ async def handle_text_search(event):
55
+ chat_id = event.chat_id
56
+ if not search_mode_active.get(chat_id, False):
57
+ return
58
+ if editor_mode_active.get(chat_id, False):
59
+ return
60
+
61
+ query = event.raw_text.strip().lower()
62
+ if not query: return
63
+
64
+ msg = await event.respond("🔍 Buscando...")
65
+
66
+ # Buscar en Firestore (limitado en memoria por diseño simple de Firebase)
67
+ docs = db.collection('videos').get()
68
+ results = []
69
+ for d in docs:
70
+ data = d.to_dict()
71
+ title = data.get('title', '').lower()
72
+ if query in title:
73
+ results.append((d.id, data))
74
+
75
+ if not results:
76
+ await msg.edit("❌ No se encontraron resultados para tu búsqueda.")
77
+ return
78
+
79
+ # Mostrar resultados en botones
80
+ results = results[:20] # Limitar a 20 resultados para no exceder limite de botones
81
+ buttons = []
82
+ for r_id, data in results:
83
+ t = data.get('title', 'Sin titulo')[:40]
84
+ icon = "🎬" if data.get('section') == 'peliculas' else ("📺" if data.get('is_folder') else "🎞️")
85
+ buttons.append([Button.inline(f"{icon} {t}", f"get_vid_{r_id}".encode('utf-8'))])
86
+
87
+ await msg.edit(f"📌 **Resultados para:** `{query}`", buttons=buttons)
88
+
89
+ @client.on(events.CallbackQuery(pattern=b'^get_vid_'))
90
+ async def handle_search_result_click(event):
91
+ if not search_mode_active.get(event.chat_id, False):
92
+ await event.answer("El modo buscador está desactivado.", alert=True)
93
+ return
94
+
95
+ doc_id = event.data.decode('utf-8').replace('get_vid_', '')
96
+ await event.answer()
97
+
98
+ # Simulamos como si el usuario hubiera enviado el ID directamente
99
+ class DummyEvent:
100
+ def __init__(self, chat_id, raw_text):
101
+ self.chat_id = chat_id
102
+ self.raw_text = raw_text
103
+ async def respond(self, *args, **kwargs):
104
+ return await client.send_message(self.chat_id, *args, **kwargs)
105
+
106
+ dummy = DummyEvent(event.chat_id, doc_id)
107
+ await handle_document_id(dummy)
108
+
109
+ # --------------------------
110
+ """
111
+
112
+ # Insert the search logic before handlers
113
+ if "# --- MODO BUSCADOR ---" not in code:
114
+ handler_marker = "# --- MANEJADORES ---"
115
+ if handler_marker in code:
116
+ code = code.replace(handler_marker, handler_marker + "\n" + new_search_logic)
117
+ else:
118
+ # Just append at the end
119
+ code += new_search_logic
120
+
121
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
122
+ f.write(code)
123
+
124
+ print("Search mode added successfully.")
scratch/cancel_tasks_editor.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_enable_editor = """@client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
9
+ async def enable_editor(event):
10
+ chat_id = event.chat_id
11
+ editor_mode_active[chat_id] = True
12
+ await handle_editor_mode(event)"""
13
+
14
+ new_enable_editor = """@client.on(events.NewMessage(pattern='/(activar_modo_editor)$'))
15
+ async def enable_editor(event):
16
+ import asyncio
17
+ chat_id = event.chat_id
18
+
19
+ # Cancel previous tasks to prevent "Botón expirado" background overlap
20
+ if chat_id in active_tasks:
21
+ for old_task in active_tasks[chat_id]:
22
+ if not old_task.done():
23
+ if not getattr(old_task, 'is_uploading', False):
24
+ old_task.cancel()
25
+ try: await asyncio.sleep(0.1)
26
+ except: pass
27
+
28
+ current_task = asyncio.current_task()
29
+ current_task.is_uploading = False
30
+
31
+ if chat_id not in active_tasks:
32
+ active_tasks[chat_id] = []
33
+ active_tasks[chat_id].append(current_task)
34
+
35
+ editor_mode_active[chat_id] = True
36
+ try:
37
+ await handle_editor_mode(event)
38
+ finally:
39
+ if current_task in active_tasks.get(chat_id, []):
40
+ active_tasks[chat_id].remove(current_task)
41
+ if not active_tasks[chat_id]:
42
+ del active_tasks[chat_id]
43
+ """
44
+
45
+ code = code.replace(old_enable_editor, new_enable_editor)
46
+
47
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
48
+ f.write(code)
49
+
50
+ print("Task cancellation patch applied to editor mode.")
scratch/check_db.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import firebase_admin
2
+ from firebase_admin import credentials, firestore
3
+
4
+ cred = credentials.Certificate("firebase-credentials.json")
5
+ if not firebase_admin._apps:
6
+ firebase_admin.initialize_app(cred)
7
+ db = firestore.client()
8
+
9
+ print("--- COLLECTIONS ---")
10
+ collections = db.collections()
11
+ for col in collections:
12
+ print(f"Collection: {col.id}")
13
+
14
+ print("\n--- SAMPLE FROM 'videos' ---")
15
+ docs = db.collection('videos').limit(5).get()
16
+ for doc in docs:
17
+ print(f"ID: {doc.id} => {doc.to_dict()}")
18
+
19
+ print("\n--- SAMPLE FROM 'categories' ---")
20
+ docs = db.collection('categories').limit(5).get()
21
+ for doc in docs:
22
+ print(f"ID: {doc.id} => {doc.to_dict()}")
scratch/check_settings.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import firebase_admin
2
+ from firebase_admin import credentials, firestore
3
+
4
+ cred = credentials.Certificate("firebase-credentials.json")
5
+ if not firebase_admin._apps:
6
+ firebase_admin.initialize_app(cred)
7
+ db = firestore.client()
8
+
9
+ print("--- BOT SETTINGS ---")
10
+ docs = db.collection('bot_settings').get()
11
+ for doc in docs:
12
+ print(f"ID: {doc.id} => {doc.to_dict()}")
13
+
14
+ print("\n--- BOT DATA ---")
15
+ docs = db.collection('bot_data').get()
16
+ for doc in docs:
17
+ print(f"ID: {doc.id} => {doc.to_dict()}")
scratch/delete_editor_msg.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_code = """ elif getattr(resp, 'raw_text', ''):
9
+ txt = resp.raw_text.strip()
10
+ if txt.startswith('/'): continue
11
+ await msg.edit(buttons=None)
12
+
13
+ doc = db.collection('videos').document(txt).get()"""
14
+
15
+ new_code = """ elif getattr(resp, 'raw_text', ''):
16
+ txt = resp.raw_text.strip()
17
+ if txt.startswith('/'): continue
18
+ try:
19
+ await msg.delete()
20
+ except:
21
+ await msg.edit(buttons=None)
22
+
23
+ doc = db.collection('videos').document(txt).get()"""
24
+
25
+ code = code.replace(old_code, new_code)
26
+
27
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
28
+ f.write(code)
29
+
30
+ print("Message delete patch applied successfully.")
scratch/disable_delivery_in_editor.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_handle_document = """@client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
9
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
10
+ async def handle_document_id(event):
11
+ text = event.raw_text.strip()
12
+ is_folder_request = False"""
13
+
14
+ new_handle_document = """@client.on(events.NewMessage(pattern=r'^/start (folder_)?[a-zA-Z0-9_-]{20}$'))
15
+ @client.on(events.NewMessage(pattern=r'^(folder/|folder_)?[a-zA-Z0-9_-]{20}$'))
16
+ async def handle_document_id(event):
17
+ if editor_mode_active.get(event.chat_id, False):
18
+ return
19
+
20
+ text = event.raw_text.strip()
21
+ is_folder_request = False"""
22
+
23
+ code = code.replace(old_handle_document, new_handle_document)
24
+
25
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
26
+ f.write(code)
27
+
28
+ print("Patch for disabling delivery in editor mode applied successfully.")
scratch/editor_concurrency.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_logic = """ elif getattr(resp, 'raw_text', ''):
9
+ txt = resp.raw_text.strip()
10
+ if txt.startswith('/'): continue
11
+ try:
12
+ await msg.delete()
13
+ except:
14
+ await msg.edit(buttons=None)
15
+
16
+ doc = db.collection('videos').document(txt).get()
17
+ if doc.exists:
18
+ data = doc.to_dict()
19
+ if data.get('is_folder', False) or data.get('section') == 'series':
20
+ await handle_editor_series_action(conv, txt)
21
+ else:
22
+ await handle_editor_movie_action(conv, txt)
23
+ else:
24
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")"""
25
+
26
+ new_logic = """ elif getattr(resp, 'raw_text', ''):
27
+ txt = resp.raw_text.strip()
28
+
29
+ if txt.startswith('/start '):
30
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
31
+
32
+ if txt.startswith('/'):
33
+ if txt == '/desactivar_modo_editor':
34
+ break
35
+ continue
36
+
37
+ try:
38
+ await msg.delete()
39
+ except:
40
+ pass # if it can't delete, just ignore or edit
41
+
42
+ doc = db.collection('videos').document(txt).get()
43
+ if doc.exists:
44
+ data = doc.to_dict()
45
+
46
+ # Helper for concurrent editing
47
+ async def spawn_edit(chat_id, func, t_id):
48
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as c:
49
+ try: await func(c, t_id)
50
+ except Exception as e: print("Concur error:", e)
51
+
52
+ if data.get('section') == 'peliculas':
53
+ import asyncio
54
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_movie_action, txt))
55
+ elif data.get('is_folder', False):
56
+ import asyncio
57
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_series_action, txt))
58
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
59
+ import asyncio
60
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_single_chapter, txt))
61
+ else:
62
+ await conv.send_message("❌ Tipo de documento no reconocido.")
63
+
64
+ # Resend the main menu immediately so they can input something else
65
+ msg = await conv.send_message(
66
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué más deseas gestionar?",
67
+ buttons=[
68
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
69
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
70
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
71
+ ]
72
+ )
73
+ else:
74
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")"""
75
+
76
+ code = code.replace(old_logic, new_logic)
77
+
78
+
79
+ # ALSO need to fix handle_document_id so that if editor_mode_active is True, it DOES NOT return,
80
+ # wait, actually handle_document_id SHOULD return if editor mode is active,
81
+ # because we are catching /start ID inside handle_editor_mode's loop!
82
+ # We just need to make sure handle_document_id still returns as it currently does.
83
+
84
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
85
+ f.write(code)
86
+
87
+ print("Concurrent editor patch applied successfully.")
scratch/fix_jump_crash.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_func = """async def handle_editor_mode(event):
9
+ chat_id = event.chat_id
10
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
11
+ msg = await conv.send_message(
12
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
13
+ buttons=[
14
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
15
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
16
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
17
+ ]
18
+ )
19
+ try:
20
+ while editor_mode_active.get(chat_id, False):
21
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
22
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
23
+ break
24
+
25
+ if isinstance(resp, events.CallbackQuery.Event):
26
+ await resp.answer()
27
+ await msg.edit(buttons=None)
28
+
29
+ if resp.data == b"ed_exit":
30
+ editor_mode_active[chat_id] = False
31
+ await conv.send_message("✅ **Modo editor desactivado.**")
32
+ break
33
+ elif resp.data == b"ed_mov":
34
+ await handle_editor_movie_search(conv)
35
+ elif resp.data == b"ed_ser":
36
+ await handle_editor_series_search(conv)
37
+
38
+ msg = await conv.send_message(
39
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
40
+ buttons=[
41
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
42
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
43
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
44
+ ]
45
+ )
46
+ elif getattr(resp, 'raw_text', ''):
47
+ txt = resp.raw_text.strip()
48
+ if txt.startswith('/start '):
49
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
50
+
51
+ if txt.startswith('/'):
52
+ if txt == '/desactivar_modo_editor':
53
+ break
54
+ continue
55
+
56
+ try: await msg.delete()
57
+ except: pass
58
+
59
+ await process_editor_id(conv, txt)
60
+
61
+ msg = await conv.send_message(
62
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
63
+ buttons=[
64
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
65
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
66
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
67
+ ]
68
+ )
69
+
70
+ except EditorJumpException as e:
71
+ try: await msg.delete()
72
+ except: pass
73
+ await process_editor_id(conv, e.jump_id)
74
+ # Re-spawn cleanly after processing the jump
75
+ await handle_editor_mode(event)
76
+ except Exception as e:
77
+ print("Editor error:", e)"""
78
+
79
+
80
+ new_func = """async def handle_editor_mode(event):
81
+ chat_id = event.chat_id
82
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
83
+ current_jump_id = None
84
+ last_msg = None
85
+
86
+ while editor_mode_active.get(chat_id, False):
87
+ try:
88
+ if current_jump_id:
89
+ jump = current_jump_id
90
+ current_jump_id = None
91
+ if last_msg:
92
+ try: await last_msg.delete()
93
+ except: pass
94
+ await process_editor_id(conv, jump)
95
+ continue # Go back to start of loop
96
+
97
+ last_msg = await conv.send_message(
98
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
99
+ buttons=[
100
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
101
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
102
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
103
+ ]
104
+ )
105
+
106
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
107
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
108
+ break
109
+
110
+ if isinstance(resp, events.CallbackQuery.Event):
111
+ await resp.answer()
112
+ try: await last_msg.delete()
113
+ except: pass
114
+
115
+ if resp.data == b"ed_exit":
116
+ editor_mode_active[chat_id] = False
117
+ await conv.send_message("✅ **Modo editor desactivado.**")
118
+ break
119
+ elif resp.data == b"ed_mov":
120
+ await handle_editor_movie_search(conv)
121
+ elif resp.data == b"ed_ser":
122
+ await handle_editor_series_search(conv)
123
+
124
+ elif getattr(resp, 'raw_text', ''):
125
+ txt = resp.raw_text.strip()
126
+ if txt.startswith('/start '):
127
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
128
+
129
+ if txt.startswith('/'):
130
+ if txt == '/desactivar_modo_editor':
131
+ break
132
+ continue
133
+
134
+ try: await last_msg.delete()
135
+ except: pass
136
+
137
+ await process_editor_id(conv, txt)
138
+
139
+ except EditorJumpException as e:
140
+ # A jump occurred from anywhere (main menu or submenu)! Loop back and handle it.
141
+ current_jump_id = e.jump_id
142
+ except Exception as e:
143
+ print("Editor error:", e)
144
+ break"""
145
+
146
+ code = code.replace(old_func, new_func)
147
+
148
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
149
+ f.write(code)
150
+
151
+ print("Infinite robust loop applied.")
scratch/fix_multiple_menus.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+
4
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
5
+
6
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
7
+ code = f.read()
8
+
9
+ # 1. Add EditorJumpException at the top of handlers
10
+ exception_def = """class CancelUploadException(Exception):
11
+ pass"""
12
+ new_exception_def = """class CancelUploadException(Exception):
13
+ pass
14
+
15
+ class EditorJumpException(Exception):
16
+ def __init__(self, jump_id):
17
+ self.jump_id = jump_id"""
18
+ code = code.replace(exception_def, new_exception_def)
19
+
20
+ # 2. Modify wait_for_message_or_callback
21
+ old_wait = """ try:
22
+ event = await asyncio.wait_for(future, timeout=timeout)
23
+ if getattr(event, 'raw_text', getattr(event, 'text', '')) == '/cancelar':
24
+ await client.send_message(chat_id, "📁 **Proceso cancelado.**")
25
+ raise CancelUploadException()
26
+ return event"""
27
+
28
+ new_wait = """ try:
29
+ event = await asyncio.wait_for(future, timeout=timeout)
30
+ txt = getattr(event, 'raw_text', getattr(event, 'text', '')).strip()
31
+
32
+ if txt == '/cancelar':
33
+ await client.send_message(chat_id, "📁 **Proceso cancelado.**")
34
+ raise CancelUploadException()
35
+
36
+ # Global intercept for editor mode jumps
37
+ if editor_mode_active.get(chat_id, False):
38
+ if txt.startswith('/start '):
39
+ extracted = txt.replace('/start ', '').replace('folder_', '').strip()
40
+ raise EditorJumpException(extracted)
41
+ elif len(txt) == 20 and txt.isalnum() and not txt.startswith('/'):
42
+ # Heuristic for Firebase ID jump
43
+ raise EditorJumpException(txt)
44
+
45
+ return event"""
46
+ code = code.replace(old_wait, new_wait)
47
+
48
+
49
+ # 3. Refactor handle_editor_mode
50
+ old_editor_loop = """ # Helper for concurrent editing
51
+ async def spawn_edit(chat_id, func, t_id):
52
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as c:
53
+ try: await func(c, t_id)
54
+ except Exception as e: print("Concur error:", e)
55
+
56
+ if data.get('section') == 'peliculas':
57
+ import asyncio
58
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_movie_action, txt))
59
+ elif data.get('is_folder', False):
60
+ import asyncio
61
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_series_action, txt))
62
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
63
+ import asyncio
64
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_single_chapter, txt))
65
+ else:
66
+ await conv.send_message("❌ Tipo de documento no reconocido.")
67
+ else:
68
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
69
+
70
+ except Exception as e:
71
+ print("Editor error:", e)"""
72
+
73
+ new_editor_loop = """ if data.get('section') == 'peliculas':
74
+ await handle_editor_movie_action(conv, txt)
75
+ elif data.get('is_folder', False):
76
+ await handle_editor_series_action(conv, txt)
77
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
78
+ await handle_editor_single_chapter(conv, txt)
79
+ else:
80
+ await conv.send_message("❌ Tipo de documento no reconocido.")
81
+ else:
82
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
83
+
84
+ except EditorJumpException as e:
85
+ # We caught a jump from a sub-menu! Resimulate raw_text input at the top level
86
+ class DummyResp:
87
+ raw_text = e.jump_id
88
+ resp = DummyResp()
89
+ # We can't jump directly inside the loop from an except block cleanly if we break,
90
+ # so we'll handle the ID recursively.
91
+ await process_editor_id(conv, e.jump_id)
92
+ except Exception as e:
93
+ print("Editor error:", e)"""
94
+
95
+ # Wait, `process_editor_id` doesn't exist. I need to define it or refactor cleanly.
96
+ # Let's write the whole handle_editor_mode loop structure perfectly.
97
+
98
+ old_handle_editor = """async def handle_editor_mode(event):
99
+ chat_id = event.chat_id
100
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
101
+ msg = await conv.send_message(
102
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
103
+ buttons=[
104
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
105
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
106
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
107
+ ]
108
+ )
109
+
110
+ try:
111
+ while True:
112
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
113
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
114
+ break
115
+
116
+ if isinstance(resp, events.CallbackQuery.Event):
117
+ await resp.answer()
118
+ await msg.edit(buttons=None)
119
+
120
+ if resp.data == b"ed_exit":
121
+ editor_mode_active[chat_id] = False
122
+ await conv.send_message("✅ **Modo editor desactivado.**")
123
+ break
124
+ elif resp.data == b"ed_mov":
125
+ await handle_editor_movie_search(conv)
126
+ elif resp.data == b"ed_ser":
127
+ await handle_editor_series_search(conv)
128
+ elif getattr(resp, 'raw_text', ''):
129
+ txt = resp.raw_text.strip()
130
+
131
+ if txt.startswith('/start '):
132
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
133
+
134
+ if txt.startswith('/'):
135
+ if txt == '/desactivar_modo_editor':
136
+ break
137
+ continue
138
+
139
+ try:
140
+ await msg.delete()
141
+ except:
142
+ pass # if it can't delete, just ignore or edit
143
+
144
+ doc = db.collection('videos').document(txt).get()
145
+ if doc.exists:
146
+ data = doc.to_dict()
147
+
148
+ # Helper for concurrent editing
149
+ async def spawn_edit(chat_id, func, t_id):
150
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as c:
151
+ try: await func(c, t_id)
152
+ except Exception as e: print("Concur error:", e)
153
+
154
+ if data.get('section') == 'peliculas':
155
+ import asyncio
156
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_movie_action, txt))
157
+ elif data.get('is_folder', False):
158
+ import asyncio
159
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_series_action, txt))
160
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
161
+ import asyncio
162
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_single_chapter, txt))
163
+ else:
164
+ await conv.send_message("❌ Tipo de documento no reconocido.")
165
+ else:
166
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
167
+
168
+ except Exception as e:
169
+ print("Editor error:", e)"""
170
+
171
+ new_handle_editor = """async def process_editor_id(conv, txt):
172
+ doc = db.collection('videos').document(txt).get()
173
+ if doc.exists:
174
+ data = doc.to_dict()
175
+ if data.get('section') == 'peliculas':
176
+ await handle_editor_movie_action(conv, txt)
177
+ elif data.get('is_folder', False):
178
+ await handle_editor_series_action(conv, txt)
179
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
180
+ await handle_editor_single_chapter(conv, txt)
181
+ else:
182
+ await conv.send_message("❌ Tipo de documento no reconocido.")
183
+ else:
184
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
185
+
186
+ async def handle_editor_mode(event):
187
+ chat_id = event.chat_id
188
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
189
+ msg = await conv.send_message(
190
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
191
+ buttons=[
192
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
193
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
194
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
195
+ ]
196
+ )
197
+
198
+ while True:
199
+ try:
200
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
201
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
202
+ break
203
+
204
+ if isinstance(resp, events.CallbackQuery.Event):
205
+ await resp.answer()
206
+ await msg.edit(buttons=None)
207
+
208
+ if resp.data == b"ed_exit":
209
+ editor_mode_active[chat_id] = False
210
+ await conv.send_message("✅ **Modo editor desactivado.**")
211
+ break
212
+ elif resp.data == b"ed_mov":
213
+ await handle_editor_movie_search(conv)
214
+ elif resp.data == b"ed_ser":
215
+ await handle_editor_series_search(conv)
216
+ elif getattr(resp, 'raw_text', ''):
217
+ txt = resp.raw_text.strip()
218
+
219
+ if txt.startswith('/start '):
220
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
221
+
222
+ if txt.startswith('/'):
223
+ if txt == '/desactivar_modo_editor':
224
+ break
225
+ continue
226
+
227
+ try:
228
+ await msg.delete()
229
+ except:
230
+ pass
231
+
232
+ await process_editor_id(conv, txt)
233
+
234
+ except EditorJumpException as e:
235
+ # We caught a jump! Abort whatever sub-menu we were in and process the new ID globally.
236
+ await process_editor_id(conv, e.jump_id)
237
+ except Exception as e:
238
+ print("Editor error:", e)
239
+ break"""
240
+
241
+ code = code.replace(old_handle_editor, new_handle_editor)
242
+
243
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
244
+ f.write(code)
245
+
246
+ print("Architecture refactored successfully.")
scratch/force_replace.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_code = """async def handle_editor_mode(event):
9
+ chat_id = event.chat_id
10
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
11
+ try:
12
+ while editor_mode_active.get(chat_id, False):
13
+ msg = await conv.send_message(
14
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
15
+ buttons=[
16
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
17
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
18
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
19
+ ]
20
+ )
21
+
22
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
23
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
24
+ break
25
+
26
+ if isinstance(resp, events.CallbackQuery.Event):
27
+ await resp.answer()
28
+ await msg.edit(buttons=None)
29
+
30
+ if resp.data == b"ed_exit":
31
+ editor_mode_active[chat_id] = False
32
+ await conv.send_message("✅ **Modo editor desactivado.**")
33
+ break
34
+ elif resp.data == b"ed_mov":
35
+ await handle_editor_movie_search(conv)
36
+ elif resp.data == b"ed_ser":
37
+ await handle_editor_series_search(conv)
38
+ elif getattr(resp, 'raw_text', ''):
39
+ txt = resp.raw_text.strip()
40
+
41
+ if txt.startswith('/start '):
42
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
43
+
44
+ if txt.startswith('/'):
45
+ if txt == '/desactivar_modo_editor':
46
+ break
47
+ continue
48
+
49
+ try:
50
+ await msg.delete()
51
+ except:
52
+ pass # if it can't delete, just ignore or edit
53
+
54
+ doc = db.collection('videos').document(txt).get()
55
+ if doc.exists:
56
+ data = doc.to_dict()
57
+
58
+ # Helper for concurrent editing
59
+ async def spawn_edit(chat_id, func, t_id):
60
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as c:
61
+ try: await func(c, t_id)
62
+ except Exception as e: print("Concur error:", e)
63
+
64
+ if data.get('section') == 'peliculas':
65
+ import asyncio
66
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_movie_action, txt))
67
+ elif data.get('is_folder', False):
68
+ import asyncio
69
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_series_action, txt))
70
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
71
+ import asyncio
72
+ asyncio.create_task(spawn_edit(chat_id, handle_editor_single_chapter, txt))
73
+ else:
74
+ await conv.send_message("❌ Tipo de documento no reconocido.")
75
+ else:
76
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
77
+
78
+ except Exception as e:
79
+ print("Editor error:", e)"""
80
+
81
+ new_code = """async def process_editor_id(conv, txt):
82
+ doc = db.collection('videos').document(txt).get()
83
+ if doc.exists:
84
+ data = doc.to_dict()
85
+ if data.get('section') == 'peliculas':
86
+ await handle_editor_movie_action(conv, txt)
87
+ elif data.get('is_folder', False):
88
+ await handle_editor_series_action(conv, txt)
89
+ elif data.get('section') == 'series' and not data.get('is_folder', False):
90
+ await handle_editor_single_chapter(conv, txt)
91
+ else:
92
+ await conv.send_message("❌ Tipo de documento no reconocido.")
93
+ else:
94
+ await conv.send_message(f"❌ El ID proporcionado (`{txt}`) no fue encontrado en la base de datos.")
95
+
96
+ async def handle_editor_mode(event):
97
+ chat_id = event.chat_id
98
+ async with client.conversation(chat_id, timeout=3600, exclusive=False) as conv:
99
+ msg = await conv.send_message(
100
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
101
+ buttons=[
102
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
103
+ [Button.inline("�� Gestionar Series", b"ed_ser")],
104
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
105
+ ]
106
+ )
107
+ try:
108
+ while editor_mode_active.get(chat_id, False):
109
+ resp = await wait_for_message_or_callback(conv, timeout=3600)
110
+ if getattr(resp, 'raw_text', '') == '/desactivar_modo_editor':
111
+ break
112
+
113
+ if isinstance(resp, events.CallbackQuery.Event):
114
+ await resp.answer()
115
+ await msg.edit(buttons=None)
116
+
117
+ if resp.data == b"ed_exit":
118
+ editor_mode_active[chat_id] = False
119
+ await conv.send_message("✅ **Modo editor desactivado.**")
120
+ break
121
+ elif resp.data == b"ed_mov":
122
+ await handle_editor_movie_search(conv)
123
+ elif resp.data == b"ed_ser":
124
+ await handle_editor_series_search(conv)
125
+
126
+ msg = await conv.send_message(
127
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
128
+ buttons=[
129
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
130
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
131
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
132
+ ]
133
+ )
134
+ elif getattr(resp, 'raw_text', ''):
135
+ txt = resp.raw_text.strip()
136
+ if txt.startswith('/start '):
137
+ txt = txt.replace('/start ', '').replace('folder_', '').strip()
138
+
139
+ if txt.startswith('/'):
140
+ if txt == '/desactivar_modo_editor':
141
+ break
142
+ continue
143
+
144
+ try: await msg.delete()
145
+ except: pass
146
+
147
+ await process_editor_id(conv, txt)
148
+
149
+ msg = await conv.send_message(
150
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué deseas gestionar?",
151
+ buttons=[
152
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
153
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
154
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
155
+ ]
156
+ )
157
+
158
+ except EditorJumpException as e:
159
+ try: await msg.delete()
160
+ except: pass
161
+ await process_editor_id(conv, e.jump_id)
162
+ # Re-spawn cleanly after processing the jump
163
+ await handle_editor_mode(event)
164
+ except Exception as e:
165
+ print("Editor error:", e)"""
166
+
167
+ code = code.replace(old_code, new_code)
168
+
169
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
170
+ f.write(code)
171
+
172
+ print("Forced replacement applied!")
scratch/list_all_videos.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import firebase_admin
2
+ from firebase_admin import credentials, firestore
3
+
4
+ cred = credentials.Certificate("firebase-credentials.json")
5
+ if not firebase_admin._apps:
6
+ firebase_admin.initialize_app(cred)
7
+ db = firestore.client()
8
+
9
+ print("--- ALL VIDEOS ---")
10
+ docs = db.collection('videos').get()
11
+ for doc in docs:
12
+ d = doc.to_dict()
13
+ print(f"ID: {doc.id} | Title: {d.get('title')} | Section: {d.get('section')} | Fields: {list(d.keys())}")
scratch/patch_editor_abort.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+
4
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
5
+
6
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
7
+ code = f.read()
8
+
9
+ # 1. Movie rename
10
+ old_movie_rename = """ if isinstance(resp_text, events.CallbackQuery.Event):
11
+ await resp_text.answer("Cancelado")
12
+ continue
13
+ new_title = resp_text.raw_text.strip()"""
14
+
15
+ new_movie_rename = """ if isinstance(resp_text, events.CallbackQuery.Event):
16
+ await resp_text.answer("Cancelado")
17
+ continue
18
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
19
+ new_title = resp_text.raw_text.strip()"""
20
+
21
+ code = code.replace(old_movie_rename, new_movie_rename)
22
+
23
+ # 2. Series rename
24
+ old_series_rename = """ if isinstance(resp_text, events.CallbackQuery.Event):
25
+ await resp_text.answer("Cancelado")
26
+ continue
27
+ new_title = resp_text.raw_text.strip()"""
28
+
29
+ new_series_rename = """ if isinstance(resp_text, events.CallbackQuery.Event):
30
+ await resp_text.answer("Cancelado")
31
+ continue
32
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
33
+ new_title = resp_text.raw_text.strip()"""
34
+
35
+ code = code.replace(old_series_rename, new_series_rename)
36
+
37
+ # 3. Series mass edit
38
+ old_mass_edit = """ if isinstance(resp_text, events.CallbackQuery.Event):
39
+ await resp_text.answer("Operación cancelada")
40
+ continue
41
+ if resp_text.raw_text.strip().lower() == '/cancelar':
42
+ await conv.send_message("✅ Edición masiva cancelada.")
43
+ continue
44
+
45
+ new_text = resp_text.raw_text"""
46
+
47
+ new_mass_edit = """ if isinstance(resp_text, events.CallbackQuery.Event):
48
+ await resp_text.answer("Operación cancelada")
49
+ continue
50
+ if resp_text.raw_text.strip().lower() == '/cancelar':
51
+ await conv.send_message("✅ Edición masiva cancelada.")
52
+ continue
53
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
54
+
55
+ new_text = resp_text.raw_text"""
56
+
57
+ code = code.replace(old_mass_edit, new_mass_edit)
58
+
59
+
60
+ # 4. Chapter rename
61
+ old_chapter_rename = """ if isinstance(resp_text, events.CallbackQuery.Event):
62
+ await resp_text.answer("Cancelado")
63
+ continue
64
+ new_title = resp_text.raw_text.strip()"""
65
+
66
+ new_chapter_rename = """ if isinstance(resp_text, events.CallbackQuery.Event):
67
+ await resp_text.answer("Cancelado")
68
+ continue
69
+ if getattr(resp_text, 'raw_text', '').startswith('/'): return
70
+ new_title = resp_text.raw_text.strip()"""
71
+
72
+ code = code.replace(old_chapter_rename, new_chapter_rename)
73
+
74
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
75
+ f.write(code)
76
+
77
+ print("Editor robust text input patch applied.")
scratch/remove_resend.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ old_resend = """ else:
9
+ await conv.send_message("❌ Tipo de documento no reconocido.")
10
+
11
+ # Resend the main menu immediately so they can input something else
12
+ msg = await conv.send_message(
13
+ "🛠️ **Modo Editor Activado**\\n\\n¿Qué más deseas gestionar?",
14
+ buttons=[
15
+ [Button.inline("🎬 Gestionar Películas", b"ed_mov")],
16
+ [Button.inline("📺 Gestionar Series", b"ed_ser")],
17
+ [Button.inline("❌ Salir del Editor", b"ed_exit")]
18
+ ]
19
+ )
20
+ else:"""
21
+
22
+ new_resend = """ else:
23
+ await conv.send_message("❌ Tipo de documento no reconocido.")
24
+ else:"""
25
+
26
+ code = code.replace(old_resend, new_resend)
27
+
28
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
29
+ f.write(code)
30
+
31
+ print("Removed main menu resend.")
scratch/update_text.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ BOT_PATH = r"c:\Users\Gonzalo\Desktop\bot compelte stramger\bot.py"
4
+
5
+ with open(BOT_PATH, "r", encoding="utf-8") as f:
6
+ code = f.read()
7
+
8
+ # Replace block in handle_series_upload (around line 540)
9
+ old_series_upload = """ uid_back = str(uuid.uuid4()).encode()
10
+ msg_n = await conv.send_message(
11
+ "📁 **Paso 3:** ¿Qué nombre llevarán los capítulos?\\n\\n"
12
+ "Escribe un nombre base y se enumerarán automáticamente.\\n\\n"
13
+ f"Por ejemplo, si escribes un nombre o usas el botón **Usar nombre del título general** (`{series_title}`), se nombrarán así:\\n"
14
+ f"- {series_title} - Capítulo 1\\n"
15
+ f"- {series_title} - Capítulo 2\\n"
16
+ f"- {series_title} - Capítulo 3\\n\\n"
17
+ "Si usas el botón **Usar nombres originales de los archivos**, se vería así:\\n"
18
+ "- video_ep1_720p.mp4\\n"
19
+ "- episodio_2_sub.mkv\\n\\n"
20
+ "Elige un atajo rápido o escribe tu propio nombre base:",
21
+ buttons=["""
22
+
23
+ new_series_upload = """ uid_back = str(uuid.uuid4()).encode()
24
+
25
+ sample_names = ""
26
+ for v in videos[:2]:
27
+ doc_name = "Video_desconocido.mp4"
28
+ if hasattr(v.media, 'document'):
29
+ for attr in v.media.document.attributes:
30
+ if hasattr(attr, 'file_name'):
31
+ doc_name = attr.file_name
32
+ break
33
+ sample_names += f"- {doc_name}\\n"
34
+
35
+ msg_n = await conv.send_message(
36
+ "📁 **Paso 3:** ¿Qué nombre llevarán los capítulos?\\n\\n"
37
+ "Escribe un nombre base y se enumerarán automáticamente.\\n\\n"
38
+ f"Por ejemplo, si escribes un nombre o usas el botón **Usar nombre del título general** (`{series_title}`), se nombrarán así:\\n"
39
+ f"- {series_title} - Capítulo 1\\n"
40
+ f"- {series_title} - Capítulo 2\\n"
41
+ f"- {series_title} - Capítulo 3\\n\\n"
42
+ "Si usas el botón **Usar nombres originales de los archivos**, se usarán los nombres reales que acabas de subir:\\n"
43
+ f"{sample_names}\\n"
44
+ "Elige un atajo rápido o escribe tu propio nombre base:",
45
+ buttons=["""
46
+
47
+ code = code.replace(old_series_upload, new_series_upload)
48
+
49
+ # Replace block in handle_editor_add_chapters (around line 1400)
50
+ old_editor_upload = """ uid_file = str(uuid.uuid4()).encode()
51
+ msg_n = await conv.send_message(
52
+ "📁 ¿Cómo nombrar estos capítulos extra?",
53
+ buttons=[
54
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
55
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
56
+ ]
57
+ )"""
58
+
59
+ new_editor_upload = """ uid_file = str(uuid.uuid4()).encode()
60
+
61
+ sample_names = ""
62
+ for v in videos[:2]:
63
+ doc_name = "Video_desconocido.mp4"
64
+ if hasattr(v.media, 'document'):
65
+ for attr in v.media.document.attributes:
66
+ if hasattr(attr, 'file_name'):
67
+ doc_name = attr.file_name
68
+ break
69
+ sample_names += f"- {doc_name}\\n"
70
+
71
+ msg_n = await conv.send_message(
72
+ "📁 ¿Cómo nombrar estos capítulos extra?\\n\\n"
73
+ "Si usas nombres originales, se verán así:\\n"
74
+ f"{sample_names}",
75
+ buttons=[
76
+ [Button.inline("📁 Continuar enumeración general", uid_title)],
77
+ [Button.inline("📁 Usar nombres de archivos originales", uid_file)]
78
+ ]
79
+ )"""
80
+
81
+ code = code.replace(old_editor_upload, new_editor_upload)
82
+
83
+ with open(BOT_PATH, "w", encoding="utf-8") as f:
84
+ f.write(code)
85
+
86
+ print("Text replaced successfully.")
split.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ with open('bot.py', 'r', encoding='utf-8') as f:
4
+ lines = f.readlines()
5
+
6
+ def get_block(start_marker, end_marker=None):
7
+ start_idx = -1
8
+ for i, l in enumerate(lines):
9
+ if start_marker in l:
10
+ start_idx = i
11
+ break
12
+ if start_idx == -1: return []
13
+
14
+ if not end_marker:
15
+ return lines[start_idx:]
16
+
17
+ end_idx = -1
18
+ for i in range(start_idx + 1, len(lines)):
19
+ if end_marker in lines[i]:
20
+ end_idx = i
21
+ break
22
+
23
+ if end_idx == -1: return lines[start_idx:]
24
+ return lines[start_idx:end_idx]
25
+
26
+ core_lines = lines[:214] # Everything before # --- MANEJADORES ---
27
+ buscador_lines_1 = get_block("# --- MODO BUSCADOR ---", "active_tasks = {}")
28
+ subidor_lines = get_block("active_tasks = {}", "# --- CONFIGURACIÓN Y FUNCIONES DE BÚSQUEDA POR ID ---")
29
+ buscador_lines_2 = get_block("# --- CONFIGURACIÓN Y FUNCIONES DE BÚSQUEDA POR ID ---", "# --- MODO EDITOR ---")
30
+ editor_lines = get_block("# --- MODO EDITOR ---", None)
31
+
32
+ with open('core.py', 'w', encoding='utf-8') as f:
33
+ f.writelines(core_lines)
34
+
35
+ with open('bot_buscador.py', 'w', encoding='utf-8') as f:
36
+ f.writelines(buscador_lines_1)
37
+ f.writelines(buscador_lines_2)
38
+
39
+ with open('bot_subidor.py', 'w', encoding='utf-8') as f:
40
+ f.writelines(subidor_lines)
41
+
42
+ with open('bot_editor.py', 'w', encoding='utf-8') as f:
43
+ f.writelines(editor_lines)
44
+
45
+ print("Splitting complete.")