import os import requests import logging from hydrogram import Client, filters from hydrogram.types import Message # Import Message type hint # --- 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 Hydrogram (Pyrogram) client # "my_bot" is the session name. A file named my_bot.session will be created. logger.info("Initializing Hydrogram Client...") try: # When using bot_token, api_id and api_hash are used to authorize the bot owner's actions (if needed) # or simply required by the library structure. app = Client( name="my_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN # You might need 'plugins' argument if structuring with plugins # plugins=dict(root="plugins") # Example if you have a 'plugins' folder ) logger.info("Hydrogram Client initialized.") except Exception as e: logger.error(f"Failed to initialize Hydrogram Client: {e}") exit(1) # --- Bot Event Handlers --- @app.on_message(filters.command("start")) async def start_handler(client: Client, message: Message): """Handler for the /start command.""" sender_name = message.from_user.first_name if message.from_user else "User" sender_id = message.from_user.id if message.from_user else "Unknown ID" logger.info(f"Received /start command from {sender_name} (ID: {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 message.reply_text(start_message) # Use reply_text for text messages @app.on_message(filters.command("help")) async def help_handler(client: Client, message: Message): """Handler for the /help command.""" sender_id = message.from_user.id if message.from_user else "Unknown ID" logger.info(f"Received /help command from {sender_id}") await message.reply_text( "This is a sample bot (Hydrogram).\nCommands:\n/start - Show welcome message and template\n/help - Show this help message" ) # Add more handlers as needed # @app.on_message(filters.private & ~filters.command(["start", "help"])) # Example: handle other private messages # async def message_handler(client: Client, message: Message): # """Handles any other message.""" # sender_id = message.from_user.id if message.from_user else "Unknown ID" # logger.info(f"Received message from {sender_id}: {message.text}") # # Process the message... # await message.reply_text(f"You said: {message.text}") # --- Main Execution --- if __name__ == '__main__': 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...") # Run the client app.run() # No code will execute after app.run() until the bot stops logger.info("Bot stopped.")