File size: 4,588 Bytes
baf6302
bc39fa8
baf6302
bc39fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baf6302
bc39fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baf6302
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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())