Imgpost / main.py
understanding's picture
Update main.py
bc39fa8 verified
raw
history blame
4.59 kB
import os
import requests
import logging
from telethon import TelegramClient, events
# --- Configuration ---
# Set up basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Retrieve secrets from Hugging Face secrets (environment variables)
# These MUST be set in your Hugging Face Space/Repo secrets settings
API_ID = os.environ.get('API_ID')
API_HASH = os.environ.get('API_HASH')
BOT_TOKEN = os.environ.get('BOT_TOKEN')
# Your "Permanent Template" URL
TEMPLATE_URL = "https://mediaflare.adasin.workers.dev/dl/4AmNTDcYQSPNQS"
# --- Helper Function to Fetch Template ---
def fetch_template(url):
"""Fetches content from the template URL."""
logger.info(f"Fetching template from {url}")
try:
response = requests.get(url, timeout=10) # Added timeout
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
logger.info("Template fetched successfully.")
# Assuming the template is text-based. Adjust if it's JSON, binary, etc.
return response.text
except requests.exceptions.RequestException as e:
logger.error(f"Error fetching template from {url}: {e}")
return None # Return None or a default value if fetching fails
# --- Initialization ---
# Check if essential secrets are loaded
if not all([API_ID, API_HASH, BOT_TOKEN]):
logger.error("Missing required environment variables (API_ID, API_HASH, BOT_TOKEN). Ensure they are set in Hugging Face secrets.")
exit(1) # Exit if secrets are missing
try:
# Convert API_ID to integer
API_ID = int(API_ID)
except ValueError:
logger.error("API_ID environment variable is not a valid integer.")
exit(1)
# Fetch the template content on startup
template_content = fetch_template(TEMPLATE_URL)
if template_content is None:
logger.warning("Proceeding without template content due to fetch error.")
# You might want to exit(1) here or use a default fallback template
# template_content = "Default template: An error occurred fetching the primary one."
# Initialize the Telethon client
# 'bot_session' is the name of the session file that will be created.
logger.info("Initializing Telegram Client...")
try:
client = TelegramClient('bot_session', API_ID, API_HASH)
logger.info("Telegram Client initialized.")
except Exception as e:
logger.error(f"Failed to initialize Telegram Client: {e}")
exit(1)
# --- Bot Event Handlers ---
@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
"""Handler for the /start command."""
sender = await event.get_sender()
sender_name = getattr(sender, 'first_name', 'User') # Get sender's first name
logger.info(f"Received /start command from {sender_name} (ID: {event.sender_id})")
# Example of using the fetched template content
start_message = f"Hello {sender_name}!\n\n"
if template_content:
start_message += f"Here's the template content:\n---\n{template_content}\n---"
else:
start_message += "Could not load the template content."
await event.reply(start_message)
@client.on(events.NewMessage(pattern='/help'))
async def help_handler(event):
"""Handler for the /help command."""
logger.info(f"Received /help command from {event.sender_id}")
await event.reply("This is a sample bot.\nCommands:\n/start - Show welcome message and template\n/help - Show this help message")
# Add more handlers as needed
# @client.on(events.NewMessage)
# async def message_handler(event):
# """Handles any other message."""
# logger.info(f"Received message from {event.sender_id}: {event.text}")
# # Process the message...
# # await event.reply(f"You said: {event.text}")
# --- Main Execution ---
async def main():
"""Main function to start the bot."""
if template_content is not None:
logger.info("Template Content Loaded:\n" + template_content[:200] + "..." if len(template_content) > 200 else template_content) # Log first 200 chars
else:
logger.warning("Template content is not available.")
logger.info("Starting bot...")
# Start the client using the bot token
await client.start(bot_token=BOT_TOKEN)
logger.info("Bot started successfully and listening for messages.")
# Keep the client running until disconnected
await client.run_until_disconnected()
logger.info("Bot stopped.")
if __name__ == '__main__':
# Run the main function in the asyncio event loop
client.loop.run_until_complete(main())