From b736a5060ce81f3f41d6f75092bd5f391116b14a Mon Sep 17 00:00:00 2001 From: root Date: Fri, 20 Sep 2024 17:41:35 +0200 Subject: [PATCH] Adding files --- docker-compose.yml | 10 ++ telegram-epub-receiver/Dockerfile | 10 ++ telegram-epub-receiver/requirements.txt | 2 + .../telegram-epub-receiver.py | 105 ++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 docker-compose.yml create mode 100644 telegram-epub-receiver/Dockerfile create mode 100644 telegram-epub-receiver/requirements.txt create mode 100644 telegram-epub-receiver/telegram-epub-receiver.py diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e84bc1d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +services: + telegram-epub-receiver: + build: telegram-epub-receiver + image: telegram-epub-receiver:latest + container_name: telegram-epub-receiver + restart: unless-stopped + volumes: + - /tank/Libros:/config + env_file: + - .env diff --git a/telegram-epub-receiver/Dockerfile b/telegram-epub-receiver/Dockerfile new file mode 100644 index 0000000..5b7f697 --- /dev/null +++ b/telegram-epub-receiver/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.11 + +RUN mkdir /app +ADD requirements.txt /app +RUN pip install -r /app/requirements.txt +ADD *.py /app/ + +WORKDIR /app + +CMD [ "python", "/app/telegram-epub-receiver.py" ] \ No newline at end of file diff --git a/telegram-epub-receiver/requirements.txt b/telegram-epub-receiver/requirements.txt new file mode 100644 index 0000000..1769707 --- /dev/null +++ b/telegram-epub-receiver/requirements.txt @@ -0,0 +1,2 @@ +python-telegram-bot==21.4 +EbookLib==0.18 \ No newline at end of file diff --git a/telegram-epub-receiver/telegram-epub-receiver.py b/telegram-epub-receiver/telegram-epub-receiver.py new file mode 100644 index 0000000..d59227a --- /dev/null +++ b/telegram-epub-receiver/telegram-epub-receiver.py @@ -0,0 +1,105 @@ +import os +from telegram import Update +from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes +import logging +from ebooklib import epub +from pathlib import Path +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.base import MIMEBase +from email.mime.text import MIMEText +from email.utils import formatdate +from email import encoders + +logging.basicConfig(level=logging.INFO) + +httpx_logger = logging.getLogger('httpx') +httpx_logger.setLevel(logging.WARNING) + +TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN') +DESTINATION_FOLDER = os.environ.get('DESTINATION_FOLDER') +EMAIL_SENDER = os.environ.get('EMAIL_SENDER') +EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD') +EMAIL_RECIPIENT = os.environ.get('EMAIL_RECIPIENT') + +if not os.path.exists(DESTINATION_FOLDER): + os.makedirs(DESTINATION_FOLDER) + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + await update.message.reply_text('Hola! Envíame un archivo EPUB y lo guardaré.') + +def send_email(file_path, book_name, author_name): + logging.info('Preparando correo...') + msg = MIMEMultipart() + msg['From'] = EMAIL_SENDER + msg['To'] = EMAIL_RECIPIENT + msg['Date'] = formatdate(localtime=True) + msg['Subject'] = f'Nuevo archivo EPUB: {book_name} - {author_name}' + + body = f'¡Hola! Adjunto te envío el archivo EPUB "{book_name}" de {author_name}.' + msg.attach(MIMEText(body, 'plain')) + + logging.info('Adjuntando archivo...') + with open(file_path, 'rb') as attachment: + part = MIMEBase('application', 'epub+zip') + part.set_payload(attachment.read()) + encoders.encode_base64(part) + part.add_header( + 'Content-Disposition', + f'attachment; filename="{book_name}.epub"', + ) + msg.attach(part) + + logging.info('Enviando correo...') + try: + with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: + server.login(EMAIL_SENDER, EMAIL_PASSWORD) + server.sendmail(EMAIL_SENDER, EMAIL_RECIPIENT, msg.as_string()) + logging.info('Correo enviado correctamente') + except Exception as e: + logging.info(f'Error al enviar correo: {e}') + + +async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + document = update.message.document or update.message.reply_to_message.document + if document and document.mime_type == 'application/epub+zip': + logging.info(f'Archivo EPUB recibido: {document.file_name}') + file_id = document.file_id + file = await context.bot.get_file(file_id) + epub_path = os.path.join(DESTINATION_FOLDER, document.file_name) + await file.download_to_drive(epub_path) + + book = epub.read_epub(epub_path) + try: + book_name = f"{book.get_metadata('DC', 'title')[0][0]}" + author_name = book.get_metadata('DC', 'creator')[0][0] + except: + book_name = epub_path + author_name = 'Unknown' + + # Enviar el archivo EPUB por correo + try: + send_email(epub_path, book_name, author_name) + message = f'Archivo EPUB enviado por correo a {EMAIL_RECIPIENT}' + message += f'\n\n📖 Nombre del libro: {book_name}' + message += f'\n✍️ Autor: {author_name}' + message += f'\n💾 Peso: {Path(epub_path).stat().st_size / 1024:.2f} KB' + await update.message.reply_text(message) + except Exception as e: + logging.error(f"Error al enviar el archivo: {e}") + await update.message.reply_text(f'Error al enviar el archivo EPUB por correo electrónico: {e}.') + else: + await update.message.reply_text('Por favor, envíame un archivo EPUB.') + +def main() -> None: + application = ApplicationBuilder().token(TELEGRAM_TOKEN).build() + + # Comandos y manejadores + application.add_handler(CommandHandler("start", start)) + application.add_handler(MessageHandler(filters.Document.ALL, handle_document)) + + # Inicia el bot + application.run_polling() + +if __name__ == "__main__": + main() \ No newline at end of file