Bot De Telegram Para Cambiar Caras En Videos

CPU processing is extremely slow (minutes per second of video). Use a GPU VPS (e.g., Google Colab, AWS g4dn.xlarge, or RunPod).


user_data = {}

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Send me a video, then a photo of the face to swap in.")

async def handle_video(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.effective_user.id video_file = await update.message.video.get_file() video_path = f"temp_user_id_video.mp4" await video_file.download_to_drive(video_path) user_data[user_id] = "video_path": video_path await update.message.reply_text("Video received. Now send the face photo.")

async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.effective_user.id if user_id not in user_data or "video_path" not in user_data[user_id]: await update.message.reply_text("Please send a video first.") return

photo_file = await update.message.photo[-1].get_file()
photo_path = f"temp_user_id_face.jpg"
await photo_file.download_to_drive(photo_path)
await update.message.reply_text("Processing video (may take a few minutes)...")
output_path = f"output_user_id.mp4"
try:
    swap_faces_in_video(user_data[user_id]["video_path"], photo_path, output_path)
    with open(output_path, 'rb') as video:
        await update.message.reply_video(video=video, caption="Here's your face-swapped video!")
except Exception as e:
    await update.message.reply_text(f"Error: str(e)")
finally:
    # Cleanup
    for f in [user_data[user_id]["video_path"], photo_path, output_path]:
        if os.path.exists(f):
            os.remove(f)
    del user_data[user_id]

Carlos era un estudiante de cine en Madrid. Pasaba horas editando videos para sus proyectos universitarios, pero siempre se frustraba con el mismo problema: cambiar caras en videos era complicado y costoso.

Una noche, mientras charlaba con su amigo Miguel en Telegram, dijo:

"Ojalá existiera algo simple... un bot donde subas un video, una foto, y listo."

Miguel, programador desde los 15 años, sonrió.

"Eso se puede hacer."


You can find a ready-to-run template on GitHub:
Search for telegram face swap bot insightface or use this as a base:

# Full bot with queue, GPU check, and error handling
# (Expand the snippets above with async queue and tempfile cleanup)

Esto es crítico. No intentes ejecutar esto en un servidor compartido barato o en la CPU de tu laptop.

  • Almacenamiento temporal: disco local o S3 si escalas.
  • GPU recomendable (NVIDIA) para procesado rápido (CUDA).
  • FFmpeg instalado en servidor.
  • Most bots require the face photo first. Send the image. The bot will reply with a confirmation that it has detected one face (or ask you to select which face if there are multiple). Command example: Keep this face as ID 1.

    No todo fue perfecto.

    Un día, Miguel revisó los logs y encontró algo que le heló la sangre. Alguien intentó subir: bot de telegram para cambiar caras en videos

    El sistema tenía un filtro de contenido, pero Miguel entendió que no era suficiente.

    Esa misma noche, implementó tres medidas de seguridad:

    🔒 1. Detector de contenido inapropiado (NudeNet)
    🔒 2. Watermark obligatorio en videos procesados
    🔒 3. Reporte manual para casos sospechosos
    

    También añadió un mensaje al iniciar el bot:

    "⚠️ Este bot es para entretenimiento creativo. Está prohibido usar imágenes de personas sin su consentimiento. El uso indebido resultará en baneo permanente."