From db6d71d4ff21e99ac9df690cd53b948c7fb7a3ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20Mu=C3=B1oz?= Date: Tue, 5 Mar 2024 09:49:16 -0500 Subject: [PATCH] initial commit --- .env.example | 5 ++ .gitignore | 7 +++ README.md | 137 +++++++++++++++++++++++++++++++++++++++++++++++ bots3.py | 125 ++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 21 ++++++++ s3bot.service | 13 +++++ 6 files changed, 308 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 bots3.py create mode 100644 requirements.txt create mode 100644 s3bot.service diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7f29ede --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +TELEGRAM_BOT_TOKEN=AAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBBBBBBBB +MINIO_ENDPOINT=https://play.min.io +MINIO_ACCESS_KEY= +MINIO_SECRET_KEY= + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ff6527 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +venv/ +.venv/ +env/ +.env/ +ENV/ + diff --git a/README.md b/README.md new file mode 100644 index 0000000..a76ec5a --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ + + +# 🤖 Botsito para Subir Archivos al S3 MinIO + + +Este bot de Telegram te permite subir archivos de forma sencilla a tu servidor MinIO S3. Utiliza una interfaz de chat amigable para seleccionar el bucket al que deseas cargar tus archivos y te proporciona información detallada sobre los archivos subidos, incluidos los metadatos asociados. + + +[![Arch linux](https://img.shields.io/badge/Arch%20Linux-1793D1?logo=arch-linux&logoColor=fff&style=flat-square)]() + + +## Variables de entorno + +Para ejecutar este proyecto, deberá agregar las siguientes variables de entorno a su archivo .env + +`TELEGRAM_BOT_TOKEN=AAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBBBBBBBB` + +`MINIO_ENDPOINT=https://play.min.io` + +`MINIO_ACCESS_KEY=` + +`MINIO_SECRET_KEY=` + +## 🚀 Caracteristicas + +- **Interfaz Intuitiva**: Utiliza comandos simples y una interfaz de chat para interactuar con el bot. +- **Subida de Archivos**: Permite subir archivos directamente desde Telegram al servidor MinIO S3. +- **Selección de Bucket**: Elige el bucket de destino para tus archivos de una lista de opciones proporcionadas. +- **Metadatos Detallados**: Muestra información detallada sobre los archivos subidos, incluidos los metadatos. + + +## 📚 Comandos Disponibles: + +- `/start`: Inicia el bot y muestra la lista de buckets disponibles para seleccionar. +- `/help`: Muestra la ayuda con información sobre cómo usar el bot y los comandos disponibles. + +## 💼 Lista de Buckets Disponibles: +- Bancoppel +- Caja Dr.Arroyo +- Caja Oblatos +- Caja Popular Dolores +- Caja Solidaria +- Comomfort +- Bucket de contingencia +- Cooperativa Suljaa +- Caja Popular 15 de Mayo +- Caja Popular Merced +- Caja Popular Santuario Guadalupano +- Caja Solidaria Guachinango +- Caja Solidaria San Miguel Huimilpan +- Financiera Tamazula +- Imperialcc +- Lenocirochin +- Mario bro +- Mizuho +- Mufg +- Tepayac +- Test +- Walmart +- XHash + +## 📝 Uso del Bot: +1. **Inicio**: Inicia el bot con el comando `/start`. +2. **Selección de Bucket**: Elige uno de los buckets de la lista proporcionada. +3. **Subida de Archivos**: Envía el archivo que deseas subir al bucket seleccionado. +4. **Confirmación y Metadatos**: El bot te informará una vez que el archivo haya sido subido correctamente y te mostrará los metadatos asociados. + +## Deployment + +Para implementar este proyecto, ejecute + +```bash +$ python -m venv .venv +``` +```bash +$ source .venv/bin/activate +``` + +```bash +$ pip install -r requirements.txt +``` + +```bash +$ deactivate +``` +Modifique las lineas de archivo s3bot.service segun donde dejo la carpeta del bot y su entorno virtual + +``` +[Unit] +Description=Telegram Bot Service +After=network.target + +[Service] +WorkingDirectory=/home/mrhacker/botS3 +ExecStart=/home/mrhacker/botS3/venv/bin/python /home/mrhacker/botS3/bots3.py +Restart=always +RestartSec=3 + +[Install] +WantedBy=multi-user.target + +``` + +Copie el archivo .service + +```bash +# cp s3bot.service /etc/systemd/system/s3bot.service +``` + +Reinicie el servidor de demonios y active el servicio del BotS3 + +```bash +# systemctl daemon-reload +``` + +Inicie el demonio del bot + +```bash +# systemctl start s3bot +``` + +Active el inicio automatico + +```bash +# systemctl enable s3bot +``` +## 🛠️ Tecnologías Utilizadas: + +- Python +- Telebot (Wrapper de la API de Telegram) +- Boto3 (Cliente de AWS SDK para Python) + +## Autor + +- [@MrHacker]() + + diff --git a/bots3.py b/bots3.py new file mode 100644 index 0000000..11e4027 --- /dev/null +++ b/bots3.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python + +import telebot +import boto3 +from dotenv import load_dotenv +from telebot import types +import os + +load_dotenv() + +TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') +MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT') +MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY') +MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY') + +bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN) + +BUCKETS = [ + ('bancoppel', 'Bancoppel'), + ('cajadrarroyo', 'Caja Dr.Arroyo'), + ('cajaoblatos', 'Caja Oblatos'), + ('cajapopulardolores', 'Caja Popular Dolores'), + ('cajasolidaria', 'Caja Solidaria'), + ('comonfort', 'Comomfort'), + ('contingency', 'Bucket de contingencia'), + ('coopsuljaa', 'Cooperativa Suljaa'), + ('cp15demayo', 'Caja Popular 15 de Mayo'), + ('cpmerced', 'Caja Popular Merced'), + ('cpsantuarioguadalupano', 'Caja Popular Santuario Guadalupano'), + ('csguachinango', 'Caja Solidaria Guachinango'), + ('cssmh', 'Caja Solidaria San Miguel Huimilpan'), + ('financieratamazula', 'Financiera Tamazula'), + ('imperialcc', 'Imperialcc'), + ('lenocirochin', 'Lenocirochin'), + ('mario', 'Mario bro'), + ('mizuho', 'Mizuho'), + ('mufg', 'Mufg'), + ('tepeyac', 'Tepayac'), + ('test', 'Test'), + ('walmart', 'Walmart'), + ('xhash', 'XHash'), +] + +selected_buckets = {} + +@bot.message_handler(commands=['start']) +def start(message): + bot.reply_to(message, """ +**Hola! Este bot te permite subir archivos a tu servidor MinIO S3.** + +**Selecciona un bucket para subir tu archivo:** + +""", reply_markup=generar_teclado_buckets()) + +@bot.message_handler(commands=['help']) +def help_message(message): + bot.reply_to(message, """ +**Bienvenido a la ayuda de este bot!** + +Para subir un archivo: +- Simplemente envía el archivo que deseas subir y selecciona el bucket al que deseas subirlo. + +Para ver la lista de comandos disponibles: +- Usa el comando /help + +""") + +@bot.callback_query_handler(func=lambda call: True) +def handle_callback(call): + bucket_name = call.data + chat_id = call.message.chat.id + selected_buckets[chat_id] = bucket_name + bot.answer_callback_query(callback_query_id=call.id, text=f'Selected bucket: {bucket_name}') + bot.send_message(chat_id, f"Bucket seleccionado: {bucket_name}\n\nAhora enviame el archivo que quieres almacenar en el nombre del bucket") + +@bot.message_handler(content_types=['document']) +def handle_document(message): + try: + chat_id = message.chat.id + if chat_id not in selected_buckets: + bot.reply_to(message, "Por favor selecciona un bucket primero.") + return + + file_info = bot.get_file(message.document.file_id) + file_buffer = bot.download_file(file_info.file_path) # Descargar archivo en memoria + file_bytes = bytes(file_buffer) # Convertir a bytes + filename = message.document.file_name + bucket_name = selected_buckets[chat_id] + + s3 = boto3.client('s3', endpoint_url=MINIO_ENDPOINT, + aws_access_key_id=MINIO_ACCESS_KEY, + aws_secret_access_key=MINIO_SECRET_KEY) # Crear cliente de S3 con las claves de MinIO + + # Define los metadatos que deseas adjuntar al archivo + metadata = { + 'user': str(message.from_user.id), + 'file_name': filename, + 'content_type': message.document.mime_type + } + + # Sube el archivo con los metadatos definidos + s3.put_object(Bucket=bucket_name, Key=filename, Body=file_bytes, Metadata=metadata) + + bot.reply_to(message, f"Archivo {filename} subido exitosamente al bucket {bucket_name}") + + # Muestra los metadatos del archivo subido + bot.send_message(chat_id, f"Metadatos del archivo {filename}:\n\n{metadata}") + except Exception as e: + bot.reply_to(message, f"Error al subir el archivo: {e}") + +def generar_teclado_buckets(): + keyboard = telebot.types.InlineKeyboardMarkup() + buckets_row = [] + + for bucket_name, bucket_text in BUCKETS: + buckets_row.append(telebot.types.InlineKeyboardButton(bucket_text, callback_data=bucket_name)) + if len(buckets_row) == 3: + keyboard.row(*buckets_row) + buckets_row = [] + if buckets_row: + keyboard.row(*buckets_row) + + return keyboard + +bot.polling() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1cdc4cd --- /dev/null +++ b/requirements.txt @@ -0,0 +1,21 @@ +argon2-cffi==23.1.0 +argon2-cffi-bindings==21.2.0 +boto3==1.34.55 +botocore==1.34.55 +certifi==2024.2.2 +cffi==1.16.0 +charset-normalizer==3.3.2 +configparser==6.0.1 +idna==3.6 +jmespath==1.0.1 +pycparser==2.21 +pycryptodome==3.20.0 +pyTelegramBotAPI==4.16.1 +python-dateutil==2.9.0.post0 +python-dotenv==1.0.1 +pytz==2024.1 +requests==2.31.0 +s3transfer==0.10.0 +six==1.16.0 +typing_extensions==4.10.0 +urllib3==2.0.7 diff --git a/s3bot.service b/s3bot.service new file mode 100644 index 0000000..861327e --- /dev/null +++ b/s3bot.service @@ -0,0 +1,13 @@ +[Unit] +Description=Telegram Bot Service +After=network.target + +[Service] +WorkingDirectory=/home/mrhacker/botS3 +ExecStart=/home/mrhacker/botS3/venv/bin/python /home/mrhacker/botS3/bots3.py +Restart=always +RestartSec=3 + +[Install] +WantedBy=multi-user.target +