all repos — albus @ 551d7cbd228803e1f3d4459468907a4469463658

albus/bot.py (view raw)

 1import os
 2from telegram import Update
 3from telegram.ext import ApplicationBuilder, MessageHandler, CommandHandler, ContextTypes, filters
 4from .converter import convert_file, split_extension, join_extension
 5from dotenv import load_dotenv
 6
 7# Load environment variables from .env file
 8load_dotenv()
 9
10# Retrieve the Telegram bot token from the environment variables
11TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
12
13async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
14    await update.message.reply_text('Hello! Send me a file and I will convert it for you.')
15
16async def convert_document(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
17    file_id = update.message.document.file_id
18    file_name_full = update.message.document.file_name
19
20    file_name, file_extension = split_extension(file_name_full)
21
22    # Download the file
23    file_ptr = await context.bot.get_file(file_id)
24    file_path = f"{file_ptr.file_unique_id}.{file_extension}"
25    
26    await file_ptr.download_to_drive(custom_path=file_path)
27
28    # Convert the file
29    converted_file_name, extension = convert_file(file_path)
30
31    # Rename the file
32    converted_file_path = join_extension(converted_file_name, extension)
33    renamed_file_path = join_extension(file_name, extension)
34    os.rename(converted_file_path, renamed_file_path)
35
36    # Send the converted file back
37    with open(renamed_file_path, 'rb') as document:
38        await update.message.reply_document(document)
39
40    # Clean up the files
41    os.remove(file_path)
42    os.remove(renamed_file_path)
43
44def main() -> None:
45    app = ApplicationBuilder().token(TOKEN).build()
46
47    app.add_handler(CommandHandler("start", start))
48    app.add_handler(MessageHandler(filters.ATTACHMENT, convert_document))
49
50    print("Bot is online.")
51    app.run_polling()
52
53if __name__ == '__main__':
54    main()