understanding commited on
Commit
b8d7c4e
·
verified ·
1 Parent(s): 13d9680

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +59 -57
main.py CHANGED
@@ -1,92 +1,94 @@
1
  import os
2
  import requests
3
  import logging
 
 
4
  from hydrogram import Client, filters
5
- from hydrogram.types import Message # Import Message type hint
6
 
7
  # --- Configuration ---
8
- # Set up basic logging
9
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
10
  logger = logging.getLogger(__name__)
11
 
12
- # Retrieve secrets from Hugging Face secrets (environment variables)
13
- # These MUST be set in your Hugging Face Space/Repo secrets settings
14
  API_ID = os.environ.get('API_ID')
15
  API_HASH = os.environ.get('API_HASH')
16
  BOT_TOKEN = os.environ.get('BOT_TOKEN')
17
-
18
- # Your "Permanent Template" URL
19
  TEMPLATE_URL = "https://mediaflare.adasin.workers.dev/dl/4AmNTDcYQSPNQS"
20
 
21
- # --- Helper Function to Fetch Template ---
22
  def fetch_template(url):
23
- """Fetches content from the template URL."""
24
  logger.info(f"Fetching template from {url}")
25
  try:
26
- response = requests.get(url, timeout=10) # Added timeout
27
- response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
28
- logger.info("Template fetched successfully.")
29
- # Assuming the template is text-based. Adjust if it's JSON, binary, etc.
30
- return response.text
31
  except requests.exceptions.RequestException as e:
32
  logger.error(f"Error fetching template from {url}: {e}")
33
- return None # Return None or a default value if fetching fails
34
 
35
  # --- Initialization ---
36
- # Check if essential secrets are loaded
37
  if not all([API_ID, API_HASH, BOT_TOKEN]):
38
  logger.error("Missing required environment variables (API_ID, API_HASH, BOT_TOKEN). Ensure they are set in Hugging Face secrets.")
39
- exit(1) # Exit if secrets are missing
40
 
41
  try:
42
- # Convert API_ID to integer
43
  API_ID = int(API_ID)
44
  except ValueError:
45
  logger.error("API_ID environment variable is not a valid integer.")
46
  exit(1)
47
 
48
- # Fetch the template content on startup
49
- template_content = fetch_template(TEMPLATE_URL)
50
- if template_content is None:
51
- logger.warning("Proceeding without template content due to fetch error.")
52
- # You might want to exit(1) here or use a default fallback template
53
- # template_content = "Default template: An error occurred fetching the primary one."
54
 
55
  # Initialize the Hydrogram (Pyrogram) client
56
- # "my_bot" is the session name. A file named my_bot.session will be created.
57
  logger.info("Initializing Hydrogram Client...")
58
  try:
59
- # When using bot_token, api_id and api_hash are used to authorize the bot owner's actions (if needed)
60
- # or simply required by the library structure.
61
  app = Client(
62
- name="my_bot",
63
  api_id=API_ID,
64
  api_hash=API_HASH,
65
- bot_token=BOT_TOKEN
66
- # You might need 'plugins' argument if structuring with plugins
67
- # plugins=dict(root="plugins") # Example if you have a 'plugins' folder
68
  )
69
  logger.info("Hydrogram Client initialized.")
70
  except Exception as e:
71
- logger.error(f"Failed to initialize Hydrogram Client: {e}")
 
72
  exit(1)
73
 
74
  # --- Bot Event Handlers ---
75
  @app.on_message(filters.command("start"))
76
  async def start_handler(client: Client, message: Message):
77
- """Handler for the /start command."""
78
  sender_name = message.from_user.first_name if message.from_user else "User"
79
  sender_id = message.from_user.id if message.from_user else "Unknown ID"
80
  logger.info(f"Received /start command from {sender_name} (ID: {sender_id})")
81
 
82
- # Example of using the fetched template content
83
- start_message = f"Hello {sender_name}!\n\n"
84
- if template_content:
85
- start_message += f"Here's the template content:\n---\n{template_content}\n---"
 
 
 
 
 
 
 
 
 
 
 
86
  else:
87
- start_message += "Could not load the template content."
 
88
 
89
- await message.reply_text(start_message) # Use reply_text for text messages
90
 
91
  @app.on_message(filters.command("help"))
92
  async def help_handler(client: Client, message: Message):
@@ -94,29 +96,29 @@ async def help_handler(client: Client, message: Message):
94
  sender_id = message.from_user.id if message.from_user else "Unknown ID"
95
  logger.info(f"Received /help command from {sender_id}")
96
  await message.reply_text(
97
- "This is a sample bot (Hydrogram).\nCommands:\n/start - Show welcome message and template\n/help - Show this help message"
98
  )
99
 
100
- # Add more handlers as needed
101
- # @app.on_message(filters.private & ~filters.command(["start", "help"])) # Example: handle other private messages
102
- # async def message_handler(client: Client, message: Message):
103
- # """Handles any other message."""
104
- # sender_id = message.from_user.id if message.from_user else "Unknown ID"
105
- # logger.info(f"Received message from {sender_id}: {message.text}")
106
- # # Process the message...
107
- # await message.reply_text(f"You said: {message.text}")
108
-
109
-
110
  # --- Main Execution ---
111
  if __name__ == '__main__':
112
- if template_content is not None:
113
- logger.info("Template Content Loaded:\n" + template_content[:200] + "..." if len(template_content) > 200 else template_content) # Log first 200 chars
 
114
  else:
115
- logger.warning("Template content is not available.")
116
 
117
  logger.info("Starting bot...")
118
- # Run the client
119
- app.run()
120
- # No code will execute after app.run() until the bot stops
121
- logger.info("Bot stopped.")
122
-
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import requests
3
  import logging
4
+ import io # Import io for BytesIO
5
+
6
  from hydrogram import Client, filters
7
+ from hydrogram.types import Message
8
 
9
  # --- Configuration ---
 
10
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
11
  logger = logging.getLogger(__name__)
12
 
 
 
13
  API_ID = os.environ.get('API_ID')
14
  API_HASH = os.environ.get('API_HASH')
15
  BOT_TOKEN = os.environ.get('BOT_TOKEN')
 
 
16
  TEMPLATE_URL = "https://mediaflare.adasin.workers.dev/dl/4AmNTDcYQSPNQS"
17
 
18
+ # --- Helper Function to Fetch Template (Handles Binary Content) ---
19
  def fetch_template(url):
20
+ """Fetches binary content (like an image) from the template URL."""
21
  logger.info(f"Fetching template from {url}")
22
  try:
23
+ response = requests.get(url, timeout=10)
24
+ response.raise_for_status()
25
+ logger.info(f"Template fetched successfully (Content-Type: {response.headers.get('Content-Type')}).")
26
+ # Return the raw binary content
27
+ return response.content
28
  except requests.exceptions.RequestException as e:
29
  logger.error(f"Error fetching template from {url}: {e}")
30
+ return None
31
 
32
  # --- Initialization ---
 
33
  if not all([API_ID, API_HASH, BOT_TOKEN]):
34
  logger.error("Missing required environment variables (API_ID, API_HASH, BOT_TOKEN). Ensure they are set in Hugging Face secrets.")
35
+ exit(1)
36
 
37
  try:
 
38
  API_ID = int(API_ID)
39
  except ValueError:
40
  logger.error("API_ID environment variable is not a valid integer.")
41
  exit(1)
42
 
43
+ # Fetch the template image content (bytes)
44
+ template_image_bytes = fetch_template(TEMPLATE_URL)
45
+ if template_image_bytes is None:
46
+ logger.warning("Proceeding without template image due to fetch error.")
 
 
47
 
48
  # Initialize the Hydrogram (Pyrogram) client
49
+ # *** Add workdir='.' to explicitly use the current directory for the session file ***
50
  logger.info("Initializing Hydrogram Client...")
51
  try:
 
 
52
  app = Client(
53
+ name="my_bot", # Session file will be my_bot.session
54
  api_id=API_ID,
55
  api_hash=API_HASH,
56
+ bot_token=BOT_TOKEN,
57
+ workdir="." # <--- Explicitly set workdir to the current directory
 
58
  )
59
  logger.info("Hydrogram Client initialized.")
60
  except Exception as e:
61
+ # Log the specific exception
62
+ logger.error(f"Failed to initialize Hydrogram Client: {type(e).__name__} - {e}")
63
  exit(1)
64
 
65
  # --- Bot Event Handlers ---
66
  @app.on_message(filters.command("start"))
67
  async def start_handler(client: Client, message: Message):
68
+ """Handler for the /start command. Sends the template image if available."""
69
  sender_name = message.from_user.first_name if message.from_user else "User"
70
  sender_id = message.from_user.id if message.from_user else "Unknown ID"
71
  logger.info(f"Received /start command from {sender_name} (ID: {sender_id})")
72
 
73
+ start_message_caption = f"Hello {sender_name}!" # Caption for the photo
74
+
75
+ if template_image_bytes:
76
+ logger.info("Attempting to send template image...")
77
+ try:
78
+ # Send the image bytes directly using io.BytesIO
79
+ await message.reply_photo(
80
+ photo=io.BytesIO(template_image_bytes),
81
+ caption=start_message_caption + "\n\nHere's the template image."
82
+ )
83
+ logger.info("Template image sent successfully.")
84
+ except Exception as e:
85
+ logger.error(f"Failed to send template image: {e}")
86
+ # Fallback to text message if sending photo fails
87
+ await message.reply_text(start_message_caption + "\n\n(Could not send the template image due to an error.)")
88
  else:
89
+ # If template wasn't loaded, just send text
90
+ await message.reply_text(start_message_caption + "\n\n(Could not load the template image.)")
91
 
 
92
 
93
  @app.on_message(filters.command("help"))
94
  async def help_handler(client: Client, message: Message):
 
96
  sender_id = message.from_user.id if message.from_user else "Unknown ID"
97
  logger.info(f"Received /help command from {sender_id}")
98
  await message.reply_text(
99
+ "This is a sample bot (Hydrogram).\nCommands:\n/start - Show welcome message and template image\n/help - Show this help message"
100
  )
101
 
 
 
 
 
 
 
 
 
 
 
102
  # --- Main Execution ---
103
  if __name__ == '__main__':
104
+ if template_image_bytes is not None:
105
+ # Log that we have image bytes, maybe length
106
+ logger.info(f"Template image content loaded ({len(template_image_bytes)} bytes).")
107
  else:
108
+ logger.warning("Template image content is not available.")
109
 
110
  logger.info("Starting bot...")
111
+ try:
112
+ app.run()
113
+ except sqlite3.OperationalError as e:
114
+ # Catch the specific error again if setting workdir didn't help
115
+ logger.error(f"Caught sqlite3 error during app.run(): {e}. Check filesystem permissions for '.' directory.")
116
+ # You might try workdir='/data' if '.' doesn't work on HF Spaces specifically
117
+ logger.error("Consider trying workdir='/data' in Client initialization if '.' is not writable.")
118
+ except Exception as e:
119
+ # Catch any other exception during startup/runtime
120
+ logger.error(f"An unexpected error occurred during app.run(): {type(e).__name__} - {e}")
121
+ finally:
122
+ # This might not be reached if app.run() blocks indefinitely,
123
+ # but good practice if it were to exit cleanly.
124
+ logger.info("Bot stopped or encountered a fatal error.")