Now prints image files.

Added image handling.
Can't print inline images, but will remind the user to send the image as a file.
This commit is contained in:
Clarth 2024-01-02 17:20:51 -05:00
parent 4ca6b82761
commit 3cd1137b84
1 changed files with 63 additions and 55 deletions

View File

@ -2,6 +2,7 @@ import sys
import os import os
import telebot import telebot
import subprocess import subprocess
from pathlib import Path
# Telegram API token # Telegram API token
TOKEN = 'TOKEN' TOKEN = 'TOKEN'
@ -26,30 +27,37 @@ def start(message):
# Handle incoming files # Handle incoming files
@bot.message_handler(content_types=['document', 'audio', 'photo']) @bot.message_handler(content_types=['document', 'audio', 'photo'])
def handle_file(message): def handle_file(message):
if message.photo: try:
# Handle photos if message.photo:
bot.send_message(CHAT_ID, 'Printing Images isn\'t supported') # Handle photos
elif message.audio: file_info = bot.get_file(message.photo[-1].file_id)
# Handle audio file_name = f"photo_{message.photo[-1].file_id}{Path(file_info.file_path).suffix}"
bot.send_message(CHAT_ID, "I can't print sounds!") bot.send_message(CHAT_ID, 'Printing Images isn\'t supported. Please send the image as a file. Like this --> https://i.imgur.com/JcTtCvR.png')
else: elif message.audio:
# Handle other file types # Handle audio
# Download the file bot.send_message(CHAT_ID, "I can't print sounds!")
file_info = bot.get_file(message.document.file_id) elif message.document:
file_name = message.document.file_name # Handle other file types
downloaded_file = bot.download_file(file_info.file_path) # Download the file
file_info = bot.get_file(message.document.file_id)
file_name = message.document.file_name
downloaded_file = bot.download_file(file_info.file_path)
# Save the file to the download directory # Save the file to the download directory
file_path = os.path.join(DOWNLOAD_DIR, file_name) file_path = os.path.join(DOWNLOAD_DIR, file_name)
with open(file_path, 'wb') as new_file: with open(file_path, 'wb') as new_file:
new_file.write(downloaded_file) new_file.write(downloaded_file)
# Print the file # Print the file
print_command = ["/usr/bin/lp", "-o", "fit-to-page", "-d", printer, file_path] print_command = ["/usr/bin/lp", "-o", "fit-to-page", "-d", printer, file_path]
subprocess.run(print_command) subprocess.run(print_command)
# Send a message to the channel indicating that a file has been downloaded and printed # Send a message to the channel indicating that a file has been downloaded and printed
bot.send_message(CHAT_ID, f'File "{file_name}" has been downloaded and printed!') bot.send_message(CHAT_ID, f'File "{file_name}" has been downloaded and printed!')
except Exception as e:
# Handle any other exceptions
print(f"Error: {e}")
bot.send_message(CHAT_ID, 'An error occurred while processing the file. Please try again.')
# Start the bot # Start the bot
bot.polling() bot.polling()