Python | Machine Learning | Coding | R
67.4K subscribers
1.25K photos
89 videos
153 files
907 links
Help and ads: @hussein_sheikho

Discover powerful insights with Python, Machine Learning, Coding, and R—your essential toolkit for data-driven solutions, smart alg

List of our channels:
https://t.me/addlist/8_rRW2scgfRhOTc0

https://telega.io/?r=nikapsOH
Download Telegram
# converter_bot.py (continued)

def run_conversion(input_path: str, output_path: str) -> bool:
"""Runs the ebook-convert command and returns True on success."""
try:
command = ['ebook-convert', input_path, output_path]
result = subprocess.run(command, check=True, capture_output=True, text=True)
logging.info(f"Calibre output: {result.stdout}")
return True
except FileNotFoundError:
logging.error("CRITICAL: 'ebook-convert' command not found. Is Calibre installed and in the system's PATH?")
return False
except subprocess.CalledProcessError as e:
logging.error(f"Conversion failed for {input_path}. Error: {e.stderr}")
return False


#Conversion #Calibre #Subprocess

---

Part 5: Database Logging Function

This helper function will connect to our SQLite database and insert a new record for each successful conversion.

# converter_bot.py (continued)

def log_to_db(user_id: int, original_file: str, converted_file: str, conv_type: str):
"""Logs a successful conversion to the SQLite database."""
try:
conn = sqlite3.connect('conversions.db')
cursor = conn.cursor()
cursor.execute(
"INSERT INTO conversions (user_id, original_filename, converted_filename, conversion_type) VALUES (?, ?, ?, ?)",
(user_id, original_file, converted_file, conv_type)
)
conn.commit()
conn.close()
except sqlite3.Error as e:
logging.error(f"Database error: {e}")


#Database #Logging #SQLite

---

Part 6: Handling Incoming Files

This is the main handler that will be triggered when a user sends a document. It downloads the file, determines the target format, calls the conversion function, sends the result back, logs it, and cleans up.

# converter_bot.py (continued)

async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
doc = update.message.document
file_id = doc.file_id
file_name = doc.file_name

input_path = os.path.join("downloads", file_name)
os.makedirs("downloads", exist_ok=True) # Ensure download directory exists

new_file = await context.bot.get_file(file_id)
await new_file.download_to_drive(input_path)

await update.message.reply_text(f"Received '{file_name}'. Starting conversion...")

output_path = ""
conversion_type = ""

if file_name.lower().endswith('.pdf'):
output_path = input_path.rsplit('.', 1)[0] + '.epub'
conversion_type = "PDF -> EPUB"
elif file_name.lower().endswith('.epub'):
output_path = input_path.rsplit('.', 1)[0] + '.pdf'
conversion_type = "EPUB -> PDF"
else:
await update.message.reply_text("Sorry, I only support PDF and EPUB files.")
os.remove(input_path)
return

# Run the conversion
success = run_conversion(input_path, output_path)

if success and os.path.exists(output_path):
await update.message.reply_text("Conversion successful! Uploading your file...")
await context.bot.send_document(chat_id=update.effective_chat.id, document=open(output_path, 'rb'))

# Log to database
log_to_db(update.effective_user.id, file_name, os.path.basename(output_path), conversion_type)
else:
await update.message.reply_text("An error occurred during conversion. Please check the file and try again. The file might be corrupted or protected.")

# Cleanup
if os.path.exists(input_path):
os.remove(input_path)
if os.path.exists(output_path):
os.remove(output_path)


#FileHandler #BotLogic

---