Adding files

This commit is contained in:
root
2024-09-20 17:41:35 +02:00
parent 21bd8ccd72
commit b736a5060c
4 changed files with 127 additions and 0 deletions

10
docker-compose.yml Normal file
View File

@@ -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

View File

@@ -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" ]

View File

@@ -0,0 +1,2 @@
python-telegram-bot==21.4
EbookLib==0.18

View File

@@ -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()