125 lines
4.1 KiB
Python
125 lines
4.1 KiB
Python
#!/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'),
|
|
('cajapopulardolores', 'Caja Popular Dolores'),
|
|
('cajasolidaria', 'Caja Solidaria'),
|
|
('condorbs-oss', 'Condorsbs-oss'),
|
|
('contingencia', 'Bucket de contingencia'),
|
|
('cooperativa', 'Cooperativa'),
|
|
('comercializado', 'Comercializado'),
|
|
('csguachinango', 'Caja Solidaria Guachinango'),
|
|
('cssmh', 'Caja Solidaria San Miguel Huimilpan'),
|
|
('financieratamazula', 'Financiera Tamazula'),
|
|
('imperialcc', 'Imperialcc'),
|
|
('lenocirochin', 'Lenocirochin'),
|
|
('mario', 'Mario bro'),
|
|
('mizuho', 'Mizuho'),
|
|
('mufg', 'Mufg'),
|
|
('serfimex', 'Serfimex'),
|
|
('tepeyac', 'Tepayac'),
|
|
('test', 'Test'),
|
|
('testb', 'Testb'),
|
|
('tiendapago', 'tiendapago'),
|
|
('walmart', 'Walmart'),
|
|
]
|
|
|
|
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()
|