Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
import asyncio
|
| 4 |
-
from pathlib import Path
|
| 5 |
|
| 6 |
from hydrogram import Client, filters
|
| 7 |
from hydrogram.types import Message
|
|
@@ -12,26 +12,85 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(level
|
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
# Retrieve Session String from Hugging Face secrets
|
| 15 |
-
# MUST be set in your Hugging Face Space/Repo secrets settings as SESSION_STRING
|
| 16 |
SESSION_STRING = os.environ.get('SESSION_STRING')
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Global variable to hold the loaded template content
|
| 23 |
current_template_content = None
|
| 24 |
|
| 25 |
# --- Helper Functions for Template Management ---
|
| 26 |
-
def ensure_data_dir_exists():
|
| 27 |
-
"""Ensures the data directory exists."""
|
| 28 |
-
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 29 |
-
logger.info(f"Data directory '{DATA_DIR}' ensured.")
|
| 30 |
-
|
| 31 |
async def load_template_from_file():
|
| 32 |
"""Loads template content from the persistent file."""
|
| 33 |
global current_template_content
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
if TEMPLATE_FILE_PATH.exists():
|
| 36 |
try:
|
| 37 |
with open(TEMPLATE_FILE_PATH, "r", encoding="utf-8") as f:
|
|
@@ -39,7 +98,7 @@ async def load_template_from_file():
|
|
| 39 |
logger.info(f"Template loaded successfully from {TEMPLATE_FILE_PATH}")
|
| 40 |
except Exception as e:
|
| 41 |
logger.error(f"Error loading template from {TEMPLATE_FILE_PATH}: {e}")
|
| 42 |
-
current_template_content = None
|
| 43 |
else:
|
| 44 |
logger.info(f"Template file {TEMPLATE_FILE_PATH} not found. No template loaded.")
|
| 45 |
current_template_content = None
|
|
@@ -47,8 +106,15 @@ async def load_template_from_file():
|
|
| 47 |
async def save_template_to_file(content: str):
|
| 48 |
"""Saves template content to the persistent file."""
|
| 49 |
global current_template_content
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
with open(TEMPLATE_FILE_PATH, "w", encoding="utf-8") as f:
|
| 53 |
f.write(content)
|
| 54 |
current_template_content = content
|
|
@@ -63,17 +129,16 @@ if not SESSION_STRING:
|
|
| 63 |
logger.error("SESSION_STRING environment variable not found. Please set it in Hugging Face secrets.")
|
| 64 |
exit(1)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
logger.info("Initializing Hydrogram Client with session string...")
|
| 70 |
try:
|
| 71 |
app = Client(
|
| 72 |
-
name="
|
| 73 |
session_string=SESSION_STRING,
|
| 74 |
-
# workdir="." # workdir is not strictly necessary for session file when session_string is used,
|
| 75 |
-
# but good if other client files are ever created.
|
| 76 |
-
# The template file path is handled separately.
|
| 77 |
)
|
| 78 |
logger.info("Hydrogram Client initialized.")
|
| 79 |
except Exception as e:
|
|
@@ -81,33 +146,27 @@ except Exception as e:
|
|
| 81 |
exit(1)
|
| 82 |
|
| 83 |
|
| 84 |
-
# --- Bot Event Handlers ---
|
| 85 |
@app.on_message(filters.command("start") & filters.private)
|
| 86 |
async def start_handler(client: Client, message: Message):
|
| 87 |
-
"""Handler for the /start command."""
|
| 88 |
sender_name = message.from_user.first_name if message.from_user else "User"
|
| 89 |
logger.info(f"Received /start command from {sender_name} (ID: {message.from_user.id})")
|
| 90 |
-
|
| 91 |
welcome_text = f"Hello {sender_name}!\n"
|
| 92 |
welcome_text += "I am ready to manage your template.\n"
|
| 93 |
welcome_text += "Use /settemplate <your text> to set a new template.\n"
|
| 94 |
welcome_text += "Use /gettemplate to view the current template."
|
| 95 |
-
|
| 96 |
if current_template_content:
|
| 97 |
welcome_text += "\n\nA template is currently set."
|
| 98 |
else:
|
| 99 |
welcome_text += "\n\nNo template is currently set."
|
| 100 |
-
|
| 101 |
await message.reply_text(welcome_text)
|
| 102 |
|
| 103 |
@app.on_message(filters.command("settemplate") & filters.private)
|
| 104 |
async def set_template_handler(client: Client, message: Message):
|
| 105 |
-
"""Handler for the /settemplate command."""
|
| 106 |
user_id = message.from_user.id
|
| 107 |
logger.info(f"Received /settemplate command from User ID: {user_id}")
|
| 108 |
-
|
| 109 |
if len(message.command) > 1:
|
| 110 |
-
new_template = message.text.split(" ", 1)[1].strip()
|
| 111 |
if new_template:
|
| 112 |
if await save_template_to_file(new_template):
|
| 113 |
await message.reply_text("✅ Template updated successfully!")
|
|
@@ -120,10 +179,8 @@ async def set_template_handler(client: Client, message: Message):
|
|
| 120 |
|
| 121 |
@app.on_message(filters.command("gettemplate") & filters.private)
|
| 122 |
async def get_template_handler(client: Client, message: Message):
|
| 123 |
-
"""Handler for the /gettemplate command."""
|
| 124 |
user_id = message.from_user.id
|
| 125 |
logger.info(f"Received /gettemplate command from User ID: {user_id}")
|
| 126 |
-
|
| 127 |
if current_template_content:
|
| 128 |
response_text = f"📜 **Current Template:**\n\n{current_template_content}"
|
| 129 |
else:
|
|
@@ -132,16 +189,14 @@ async def get_template_handler(client: Client, message: Message):
|
|
| 132 |
|
| 133 |
# --- Main Execution ---
|
| 134 |
async def main():
|
| 135 |
-
|
| 136 |
-
await load_template_from_file() # Load any existing template on startup
|
| 137 |
-
|
| 138 |
logger.info("Attempting to connect and start the bot...")
|
| 139 |
try:
|
| 140 |
await app.start()
|
| 141 |
me = await app.get_me()
|
| 142 |
logger.info(f"Bot started successfully as {me.first_name} (ID: {me.id})")
|
| 143 |
logger.info("Listening for messages...")
|
| 144 |
-
await asyncio.Event().wait()
|
| 145 |
except (SessionPasswordNeeded, PhoneCodeInvalid, PhoneNumberInvalid, PasswordHashInvalid) as e:
|
| 146 |
logger.error(f"Authorization error: {type(e).__name__} - {e}. Your SESSION_STRING might be invalid or expired.")
|
| 147 |
except ConnectionError as e:
|
|
@@ -149,19 +204,20 @@ async def main():
|
|
| 149 |
except Exception as e:
|
| 150 |
logger.error(f"An unexpected error occurred during bot startup or runtime: {type(e).__name__} - {e}", exc_info=True)
|
| 151 |
finally:
|
| 152 |
-
if app.is_connected:
|
| 153 |
logger.info("Stopping the bot...")
|
| 154 |
await app.stop()
|
| 155 |
logger.info("Bot stopped.")
|
| 156 |
else:
|
| 157 |
-
logger.info("Bot was not connected or already stopped.")
|
| 158 |
|
| 159 |
if __name__ == '__main__':
|
| 160 |
-
# Run the main function in the asyncio event loop
|
| 161 |
try:
|
| 162 |
asyncio.run(main())
|
| 163 |
except KeyboardInterrupt:
|
| 164 |
logger.info("Bot manually interrupted. Exiting...")
|
|
|
|
|
|
|
| 165 |
except Exception as e:
|
| 166 |
-
logger.critical(f"Critical error in main execution block: {e}", exc_info=True)
|
| 167 |
|
|
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
import asyncio
|
| 4 |
+
from pathlib import Path
|
| 5 |
|
| 6 |
from hydrogram import Client, filters
|
| 7 |
from hydrogram.types import Message
|
|
|
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
# Retrieve Session String from Hugging Face secrets
|
|
|
|
| 15 |
SESSION_STRING = os.environ.get('SESSION_STRING')
|
| 16 |
|
| 17 |
+
# --- Dynamic Storage Path Initialization ---
|
| 18 |
+
# Define potential base directories for storage and a subdirectory name
|
| 19 |
+
PERSISTENT_STORAGE_CANDIDATES = [
|
| 20 |
+
Path("/data"), # Common absolute path for persistent data in containers
|
| 21 |
+
Path("."), # Current working directory (e.g., /app if WORKDIR is /app)
|
| 22 |
+
]
|
| 23 |
+
APP_STORAGE_SUBDIR_NAME = "app_template_storage" # Subdirectory to hold our template
|
| 24 |
+
TEMPLATE_FILENAME = "user_template_content.txt"
|
| 25 |
+
|
| 26 |
+
DATA_DIR: Path = None
|
| 27 |
+
TEMPLATE_FILE_PATH: Path = None
|
| 28 |
+
|
| 29 |
+
def initialize_storage_paths():
|
| 30 |
+
"""Tries to find/create a writable directory for the template file."""
|
| 31 |
+
global DATA_DIR, TEMPLATE_FILE_PATH
|
| 32 |
+
|
| 33 |
+
# 1. Try creating a subdirectory in candidate locations
|
| 34 |
+
for base_candidate in PERSISTENT_STORAGE_CANDIDATES:
|
| 35 |
+
potential_data_dir = base_candidate / APP_STORAGE_SUBDIR_NAME
|
| 36 |
+
try:
|
| 37 |
+
potential_data_dir.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
# Test if we can actually write a dummy file here
|
| 39 |
+
test_file = potential_data_dir / ".writable_test"
|
| 40 |
+
with open(test_file, "w") as f:
|
| 41 |
+
f.write("test")
|
| 42 |
+
test_file.unlink() # Clean up test file
|
| 43 |
+
|
| 44 |
+
DATA_DIR = potential_data_dir
|
| 45 |
+
TEMPLATE_FILE_PATH = DATA_DIR / TEMPLATE_FILENAME
|
| 46 |
+
logger.info(f"Successfully established writable data directory: {DATA_DIR}")
|
| 47 |
+
return
|
| 48 |
+
except PermissionError:
|
| 49 |
+
logger.warning(f"Permission denied to create/use directory {potential_data_dir}. Trying next candidate.")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.warning(f"Failed to create/use directory {potential_data_dir} due to {type(e).__name__}: {e}. Trying next candidate.")
|
| 52 |
+
|
| 53 |
+
# 2. If subdirectory creation failed, try to place the file directly in a candidate base directory
|
| 54 |
+
logger.warning("Could not create/use a dedicated subdirectory. Attempting to use a base directory directly for the file.")
|
| 55 |
+
for base_candidate in PERSISTENT_STORAGE_CANDIDATES:
|
| 56 |
+
potential_template_file_path = base_candidate / TEMPLATE_FILENAME
|
| 57 |
+
try:
|
| 58 |
+
# Test writability by trying to open the file in append mode (creates if not exists)
|
| 59 |
+
with open(potential_template_file_path, 'a'):
|
| 60 |
+
pass # Just testing if open works without error
|
| 61 |
+
# If we are here, it means we can probably write the file directly.
|
| 62 |
+
DATA_DIR = base_candidate # The "data directory" is now the base itself
|
| 63 |
+
TEMPLATE_FILE_PATH = potential_template_file_path
|
| 64 |
+
logger.info(f"Using base directory {DATA_DIR.resolve()} directly for template file: {TEMPLATE_FILE_PATH}")
|
| 65 |
+
return
|
| 66 |
+
except PermissionError:
|
| 67 |
+
logger.warning(f"Permission denied to write template file directly in {base_candidate.resolve()}. Trying next candidate.")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
logger.warning(f"Failed to write template file in {base_candidate.resolve()} due to {type(e).__name__}: {e}. Trying next candidate.")
|
| 70 |
+
|
| 71 |
+
# If all attempts fail
|
| 72 |
+
logger.error("CRITICAL: Unable to find or create a writable location for the template file.")
|
| 73 |
+
# Set paths to None to indicate failure; the app might crash or malfunction later.
|
| 74 |
+
# A more robust solution would be to exit here.
|
| 75 |
+
DATA_DIR = None
|
| 76 |
+
TEMPLATE_FILE_PATH = None
|
| 77 |
+
# Consider exiting: exit("Failed to initialize storage.")
|
| 78 |
+
|
| 79 |
+
# Call this ONCE at the start of the script
|
| 80 |
+
initialize_storage_paths()
|
| 81 |
|
| 82 |
# Global variable to hold the loaded template content
|
| 83 |
current_template_content = None
|
| 84 |
|
| 85 |
# --- Helper Functions for Template Management ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
async def load_template_from_file():
|
| 87 |
"""Loads template content from the persistent file."""
|
| 88 |
global current_template_content
|
| 89 |
+
if not TEMPLATE_FILE_PATH:
|
| 90 |
+
logger.error("Template file path is not configured. Cannot load template.")
|
| 91 |
+
current_template_content = None
|
| 92 |
+
return
|
| 93 |
+
|
| 94 |
if TEMPLATE_FILE_PATH.exists():
|
| 95 |
try:
|
| 96 |
with open(TEMPLATE_FILE_PATH, "r", encoding="utf-8") as f:
|
|
|
|
| 98 |
logger.info(f"Template loaded successfully from {TEMPLATE_FILE_PATH}")
|
| 99 |
except Exception as e:
|
| 100 |
logger.error(f"Error loading template from {TEMPLATE_FILE_PATH}: {e}")
|
| 101 |
+
current_template_content = None
|
| 102 |
else:
|
| 103 |
logger.info(f"Template file {TEMPLATE_FILE_PATH} not found. No template loaded.")
|
| 104 |
current_template_content = None
|
|
|
|
| 106 |
async def save_template_to_file(content: str):
|
| 107 |
"""Saves template content to the persistent file."""
|
| 108 |
global current_template_content
|
| 109 |
+
if not TEMPLATE_FILE_PATH:
|
| 110 |
+
logger.error("Template file path is not configured. Cannot save template.")
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
try:
|
| 114 |
+
# Ensure the parent directory exists (it should if initialize_storage_paths worked for a subdir)
|
| 115 |
+
if TEMPLATE_FILE_PATH.parent != Path("."): # Avoid trying to create "." if file is in current dir
|
| 116 |
+
TEMPLATE_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 117 |
+
|
| 118 |
with open(TEMPLATE_FILE_PATH, "w", encoding="utf-8") as f:
|
| 119 |
f.write(content)
|
| 120 |
current_template_content = content
|
|
|
|
| 129 |
logger.error("SESSION_STRING environment variable not found. Please set it in Hugging Face secrets.")
|
| 130 |
exit(1)
|
| 131 |
|
| 132 |
+
if not TEMPLATE_FILE_PATH:
|
| 133 |
+
logger.critical("CRITICAL: Template storage path could not be initialized. The application cannot manage templates. Exiting.")
|
| 134 |
+
exit(1)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
logger.info("Initializing Hydrogram Client with session string...")
|
| 138 |
try:
|
| 139 |
app = Client(
|
| 140 |
+
name="user_session_hgs", # Changed name slightly to avoid old session file conflicts if any
|
| 141 |
session_string=SESSION_STRING,
|
|
|
|
|
|
|
|
|
|
| 142 |
)
|
| 143 |
logger.info("Hydrogram Client initialized.")
|
| 144 |
except Exception as e:
|
|
|
|
| 146 |
exit(1)
|
| 147 |
|
| 148 |
|
| 149 |
+
# --- Bot Event Handlers (Unchanged from your previous version) ---
|
| 150 |
@app.on_message(filters.command("start") & filters.private)
|
| 151 |
async def start_handler(client: Client, message: Message):
|
|
|
|
| 152 |
sender_name = message.from_user.first_name if message.from_user else "User"
|
| 153 |
logger.info(f"Received /start command from {sender_name} (ID: {message.from_user.id})")
|
|
|
|
| 154 |
welcome_text = f"Hello {sender_name}!\n"
|
| 155 |
welcome_text += "I am ready to manage your template.\n"
|
| 156 |
welcome_text += "Use /settemplate <your text> to set a new template.\n"
|
| 157 |
welcome_text += "Use /gettemplate to view the current template."
|
|
|
|
| 158 |
if current_template_content:
|
| 159 |
welcome_text += "\n\nA template is currently set."
|
| 160 |
else:
|
| 161 |
welcome_text += "\n\nNo template is currently set."
|
|
|
|
| 162 |
await message.reply_text(welcome_text)
|
| 163 |
|
| 164 |
@app.on_message(filters.command("settemplate") & filters.private)
|
| 165 |
async def set_template_handler(client: Client, message: Message):
|
|
|
|
| 166 |
user_id = message.from_user.id
|
| 167 |
logger.info(f"Received /settemplate command from User ID: {user_id}")
|
|
|
|
| 168 |
if len(message.command) > 1:
|
| 169 |
+
new_template = message.text.split(" ", 1)[1].strip()
|
| 170 |
if new_template:
|
| 171 |
if await save_template_to_file(new_template):
|
| 172 |
await message.reply_text("✅ Template updated successfully!")
|
|
|
|
| 179 |
|
| 180 |
@app.on_message(filters.command("gettemplate") & filters.private)
|
| 181 |
async def get_template_handler(client: Client, message: Message):
|
|
|
|
| 182 |
user_id = message.from_user.id
|
| 183 |
logger.info(f"Received /gettemplate command from User ID: {user_id}")
|
|
|
|
| 184 |
if current_template_content:
|
| 185 |
response_text = f"📜 **Current Template:**\n\n{current_template_content}"
|
| 186 |
else:
|
|
|
|
| 189 |
|
| 190 |
# --- Main Execution ---
|
| 191 |
async def main():
|
| 192 |
+
await load_template_from_file()
|
|
|
|
|
|
|
| 193 |
logger.info("Attempting to connect and start the bot...")
|
| 194 |
try:
|
| 195 |
await app.start()
|
| 196 |
me = await app.get_me()
|
| 197 |
logger.info(f"Bot started successfully as {me.first_name} (ID: {me.id})")
|
| 198 |
logger.info("Listening for messages...")
|
| 199 |
+
await asyncio.Event().wait()
|
| 200 |
except (SessionPasswordNeeded, PhoneCodeInvalid, PhoneNumberInvalid, PasswordHashInvalid) as e:
|
| 201 |
logger.error(f"Authorization error: {type(e).__name__} - {e}. Your SESSION_STRING might be invalid or expired.")
|
| 202 |
except ConnectionError as e:
|
|
|
|
| 204 |
except Exception as e:
|
| 205 |
logger.error(f"An unexpected error occurred during bot startup or runtime: {type(e).__name__} - {e}", exc_info=True)
|
| 206 |
finally:
|
| 207 |
+
if app.is_initialized and app.is_connected: # Check if initialized before checking is_connected
|
| 208 |
logger.info("Stopping the bot...")
|
| 209 |
await app.stop()
|
| 210 |
logger.info("Bot stopped.")
|
| 211 |
else:
|
| 212 |
+
logger.info("Bot was not fully connected or already stopped.")
|
| 213 |
|
| 214 |
if __name__ == '__main__':
|
|
|
|
| 215 |
try:
|
| 216 |
asyncio.run(main())
|
| 217 |
except KeyboardInterrupt:
|
| 218 |
logger.info("Bot manually interrupted. Exiting...")
|
| 219 |
+
except SystemExit as e: # Catch explicit exits
|
| 220 |
+
logger.info(f"Application exiting with status: {e.code}")
|
| 221 |
except Exception as e:
|
| 222 |
+
logger.critical(f"Critical error in main execution block: {type(e).__name__} - {e}", exc_info=True)
|
| 223 |
|