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
# Add these imports to the top of bot.py
import csv
import io
import database as db

async def export_members(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Exports channel members to a CSV file."""
user = update.effective_user
chat = update.effective_chat

if chat.type != 'channel':
await update.message.reply_text("This command can only be used in a channel.")
return

# --- Permission Check ---
try:
admins = await context.bot.get_chat_administrators(chat.id)
is_creator = False
for admin in admins:
if admin.user.id == user.id and admin.status == 'creator':
is_creator = True
break

if not is_creator:
await update.message.reply_text("Sorry, only the channel creator can use this command.")
return

except Exception as e:
await update.message.reply_text(f"An error occurred while checking permissions: {e}")
return

await update.message.reply_text("Exporting members... This may take a moment for large channels.")

# The rest of the logic will go here in the next step

# In the main() function of bot.py, uncomment and add the handler:
# application.add_handler(CommandHandler("export", export_members))

# At the start of main(), also add the database setup call:
db.setup_database()

# Hashtags: #BotLogic #Permissions #Security #TelegramAPI


---

#Step 4: Fetching Members and Generating the CSV File

This is the continuation of the export_members function. After passing the permission check, the bot will fetch the list of administrators (as a reliable way to get some members) and generate a CSV file in memory.

NOTE: The Bot API has limitations on fetching a complete list of non-admin members in very large channels. This example reliably fetches administrators. A more advanced "userbot" would be needed to guarantee fetching all members.
2
# 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

---