ABRAHAM OJEDA
< WEB DEVELOPER />

🤖 GUÍA DE BOTS

>> Aprende a crear bots increíbles con Python

[ Face Swapping | IA Generativa | Telegram ]

🐍 PYTHON 🤖 TELEGRAM 🎨 IA GENERATIVA 📸 COMPUTER VISION
🎭

01. BOT DE FACE SWAP

>> Este bot te permitirá intercambiar caras en imágenes y vídeos usando Python y visión por computadora. 🚀

Crea un entorno virtual para mantener tus dependencias organizadas.

python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

Instala las librerías necesarias:

pip install opencv-python dlib face-recognition numpy

Usaremos face_recognition para localizar los rostros y sus 68 puntos de referencia faciales.

💡 TIP: Estos puntos son como un mapa de tu rostro.

Aquí ocurre la magia ✨. Usamos Triangulación de Delaunay para dividir y deformar la cara.

🔺 Triangulación

Divide la cara en triángulos

🔄 Transformación

Ajusta cada triángulo al destino

Usamos seamlessClone de OpenCV para fusión perfecta.

RESULTADO: Fusión perfecta sin bordes visibles.

Procesa cada fotograma del vídeo aplicando el face swap frame a frame.

NOTA: Considera usar GPU para acelerar.

🤖

02. BOT DE TELEGRAM + IA

>> Bot que genera imágenes con IA usando Telegram y APIs de generación. 🎨✨

Busca @BotFather en Telegram y usa /newbot

🔐 IMPORTANTE: Guarda tu token de acceso (API key) en secreto.

Instala las librerías:

pip install python-telegram-bot google-generativeai requests

Código del bot:

# main.py
import telegram
from telegram.ext import Updater, CommandHandler
import requests

TELEGRAM_TOKEN = "TU_TOKEN"
IMAGE_API_URL = "URL_API"
IMAGE_API_KEY = "TU_API_KEY"

def start(update, context):
    update.message.reply_text('¡Hola! /generate + texto')

def generate_image(update, context):
    prompt = " ".join(context.args)
    if not prompt:
        update.message.reply_text('Uso: /generate un gato')
        return

    try:
        headers = {"Authorization": f"Bearer {IMAGE_API_KEY}"}
        response = requests.post(IMAGE_API_URL, 
            json={"prompt": prompt}, headers=headers)
        
        context.bot.send_photo(
            chat_id=update.effective_chat.id, 
            photo=response.content)
    except Exception as e:
        update.message.reply_text('Error al generar')

def main():
    updater = Updater(TELEGRAM_TOKEN, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("generate", generate_image))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Instala dependencias:

npm init -y
npm install node-telegram-bot-api axios
// bot.js
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');

const bot = new TelegramBot('TU_TOKEN', { polling: true });

bot.onText(/\/start/, (msg) => {
    bot.sendMessage(msg.chat.id, "¡Usa /generate!");
});

bot.onText(/\/generate (.+)/, async (msg, match) => {
    const prompt = match[1];
    
    try {
        const response = await axios.post(IMAGE_API_URL, 
            { prompt },
            { 
                headers: { 'Authorization': `Bearer ${KEY}` },
                responseType: 'arraybuffer'
            }
        );
        
        const buffer = Buffer.from(response.data, 'binary');
        bot.sendPhoto(msg.chat.id, buffer);
    } catch (error) {
        bot.sendMessage(msg.chat.id, 'Error');
    }
});

console.log('Bot iniciado...');