understanding commited on
Commit
fe17591
·
verified ·
1 Parent(s): fc8fccc

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +25 -27
main.py CHANGED
@@ -16,12 +16,10 @@ SESSION_STRING = os.environ.get('SESSION_STRING')
16
 
17
  # --- Storage Path Initialization (Aligned with Dockerfile) ---
18
  # This name MUST match the directory created in the Dockerfile
19
- # (either the default in ARG or how you set it in `RUN mkdir -p ./${APP_TEMPLATE_DIR_NAME}`)
20
  APP_TEMPLATE_SUBDIR_NAME = "app_template_storage"
21
  TEMPLATE_FILENAME = "user_template_content.txt"
22
 
23
  # The data directory is now relative to the WORKDIR (e.g., /app/app_template_storage)
24
- # This path is prepared by the Dockerfile.
25
  DATA_DIR = Path(".") / APP_TEMPLATE_SUBDIR_NAME
26
  TEMPLATE_FILE_PATH = DATA_DIR / TEMPLATE_FILENAME
27
 
@@ -30,15 +28,11 @@ current_template_content = None # Global variable for template
30
  def verify_storage_path_is_writable():
31
  """Verifies that the pre-configured DATA_DIR is writable."""
32
  try:
33
- # The Dockerfile should have created DATA_DIR.
34
- # Python's mkdir with exist_ok=True is safe even if it exists.
35
- # More importantly, we test if we can write into it.
36
  DATA_DIR.mkdir(parents=True, exist_ok=True)
37
-
38
  test_file = DATA_DIR / ".writable_test_py"
39
  with open(test_file, "w") as f:
40
  f.write("test")
41
- test_file.unlink() # Clean up test file
42
  logger.info(f"Successfully verified writable data directory: {DATA_DIR.resolve()}")
43
  return True
44
  except Exception as e:
@@ -48,9 +42,8 @@ def verify_storage_path_is_writable():
48
 
49
  # --- Helper Functions for Template Management ---
50
  async def load_template_from_file():
51
- """Loads template content from the persistent file."""
52
  global current_template_content
53
- if not TEMPLATE_FILE_PATH: # Should not happen if verify_storage_path_is_writable passes
54
  logger.error("Template file path is not configured. Cannot load template.")
55
  current_template_content = None
56
  return
@@ -64,18 +57,15 @@ async def load_template_from_file():
64
  logger.error(f"Error loading template from {TEMPLATE_FILE_PATH}: {e}")
65
  current_template_content = None
66
  else:
67
- logger.info(f"Template file {TEMPLATE_FILE_PATH} not found. No template loaded.")
68
  current_template_content = None
69
 
70
  async def save_template_to_file(content: str):
71
- """Saves template content to the persistent file."""
72
  global current_template_content
73
- if not TEMPLATE_FILE_PATH: # Should not happen
74
  logger.error("Template file path is not configured. Cannot save template.")
75
  return False
76
  try:
77
- # DATA_DIR.mkdir(parents=True, exist_ok=True) # Dockerfile should handle this.
78
- # verify_storage_path_is_writable also calls it.
79
  with open(TEMPLATE_FILE_PATH, "w", encoding="utf-8") as f:
80
  f.write(content)
81
  current_template_content = content
@@ -90,16 +80,19 @@ if not SESSION_STRING:
90
  logger.error("SESSION_STRING environment variable not found. Please set it in Hugging Face secrets.")
91
  exit(1)
92
 
93
- # Verify the storage path *before* initializing the client or doing anything else
94
  if not verify_storage_path_is_writable():
95
  logger.critical("Exiting due to storage path issues. Check Dockerfile and permissions.")
96
  exit(1)
97
 
98
- logger.info("Initializing Hydrogram Client with session string...")
99
  try:
100
  app = Client(
101
- name="user_session_hgs_v3", # Slightly new name again
102
  session_string=SESSION_STRING,
 
 
 
 
103
  )
104
  logger.info("Hydrogram Client initialized.")
105
  except Exception as e:
@@ -107,13 +100,17 @@ except Exception as e:
107
  exit(1)
108
 
109
 
110
- # --- Bot Event Handlers (Unchanged) ---
111
  @app.on_message(filters.command("start") & filters.private)
112
  async def start_handler(client: Client, message: Message):
 
 
 
113
  sender_name = message.from_user.first_name if message.from_user else "User"
114
- logger.info(f"Received /start command from {sender_name} (ID: {message.from_user.id})")
 
115
  welcome_text = f"Hello {sender_name}!\n"
116
- welcome_text += "I am ready to manage your template.\n"
117
  welcome_text += "Template storage is at: " + str(TEMPLATE_FILE_PATH.resolve()) + "\n"
118
  welcome_text += "Use /settemplate <your text> to set a new template.\n"
119
  welcome_text += "Use /gettemplate to view the current template."
@@ -125,8 +122,8 @@ async def start_handler(client: Client, message: Message):
125
 
126
  @app.on_message(filters.command("settemplate") & filters.private)
127
  async def set_template_handler(client: Client, message: Message):
128
- user_id = message.from_user.id
129
- logger.info(f"Received /settemplate command from User ID: {user_id}")
130
  if len(message.command) > 1:
131
  new_template = message.text.split(" ", 1)[1].strip()
132
  if new_template:
@@ -141,24 +138,25 @@ async def set_template_handler(client: Client, message: Message):
141
 
142
  @app.on_message(filters.command("gettemplate") & filters.private)
143
  async def get_template_handler(client: Client, message: Message):
144
- user_id = message.from_user.id
145
- logger.info(f"Received /gettemplate command from User ID: {user_id}")
146
  if current_template_content:
147
  response_text = f"📜 **Current Template:**\n\n{current_template_content}"
148
  else:
149
  response_text = "ℹ️ No template is currently set. Use `/settemplate <your text>` to set one."
150
  await message.reply_text(response_text)
151
 
152
- # --- Main Execution (Unchanged) ---
153
  async def main():
154
  await load_template_from_file()
155
  logger.info("Attempting to connect and start the bot...")
156
  try:
157
  await app.start()
158
  me = await app.get_me()
159
- logger.info(f"Bot started successfully as {me.first_name} (ID: {me.id})")
 
160
  logger.info("Listening for messages...")
161
- await asyncio.Event().wait()
162
  except (SessionPasswordNeeded, PhoneCodeInvalid, PhoneNumberInvalid, PasswordHashInvalid) as e:
163
  logger.error(f"Authorization error: {type(e).__name__} - {e}. Your SESSION_STRING might be invalid or expired.")
164
  except ConnectionError as e:
 
16
 
17
  # --- Storage Path Initialization (Aligned with Dockerfile) ---
18
  # This name MUST match the directory created in the Dockerfile
 
19
  APP_TEMPLATE_SUBDIR_NAME = "app_template_storage"
20
  TEMPLATE_FILENAME = "user_template_content.txt"
21
 
22
  # The data directory is now relative to the WORKDIR (e.g., /app/app_template_storage)
 
23
  DATA_DIR = Path(".") / APP_TEMPLATE_SUBDIR_NAME
24
  TEMPLATE_FILE_PATH = DATA_DIR / TEMPLATE_FILENAME
25
 
 
28
  def verify_storage_path_is_writable():
29
  """Verifies that the pre-configured DATA_DIR is writable."""
30
  try:
 
 
 
31
  DATA_DIR.mkdir(parents=True, exist_ok=True)
 
32
  test_file = DATA_DIR / ".writable_test_py"
33
  with open(test_file, "w") as f:
34
  f.write("test")
35
+ test_file.unlink()
36
  logger.info(f"Successfully verified writable data directory: {DATA_DIR.resolve()}")
37
  return True
38
  except Exception as e:
 
42
 
43
  # --- Helper Functions for Template Management ---
44
  async def load_template_from_file():
 
45
  global current_template_content
46
+ if not TEMPLATE_FILE_PATH:
47
  logger.error("Template file path is not configured. Cannot load template.")
48
  current_template_content = None
49
  return
 
57
  logger.error(f"Error loading template from {TEMPLATE_FILE_PATH}: {e}")
58
  current_template_content = None
59
  else:
60
+ logger.info(f"Template file {TEMPLATE_FILE_PATH.resolve()} not found. No template loaded.")
61
  current_template_content = None
62
 
63
  async def save_template_to_file(content: str):
 
64
  global current_template_content
65
+ if not TEMPLATE_FILE_PATH:
66
  logger.error("Template file path is not configured. Cannot save template.")
67
  return False
68
  try:
 
 
69
  with open(TEMPLATE_FILE_PATH, "w", encoding="utf-8") as f:
70
  f.write(content)
71
  current_template_content = content
 
80
  logger.error("SESSION_STRING environment variable not found. Please set it in Hugging Face secrets.")
81
  exit(1)
82
 
 
83
  if not verify_storage_path_is_writable():
84
  logger.critical("Exiting due to storage path issues. Check Dockerfile and permissions.")
85
  exit(1)
86
 
87
+ logger.info("Initializing Hydrogram Client with BOT session string...") # Clarified log
88
  try:
89
  app = Client(
90
+ name="my_bot_session_v4", # Use a distinct session name
91
  session_string=SESSION_STRING,
92
+ # For bot sessions, api_id and api_hash are not strictly needed here
93
+ # if they were embedded in the session string (Hydrogram handles this).
94
+ # However, some older versions or ways of creating session strings might benefit
95
+ # from having them. If your session string already works, this is fine.
96
  )
97
  logger.info("Hydrogram Client initialized.")
98
  except Exception as e:
 
100
  exit(1)
101
 
102
 
103
+ # --- Bot Event Handlers ---
104
  @app.on_message(filters.command("start") & filters.private)
105
  async def start_handler(client: Client, message: Message):
106
+ # THIS IS THE CRUCIAL DIAGNOSTIC LOG:
107
+ logger.info(f"!!!!!! START HANDLER TRIGGERED by user {message.from_user.id} in chat {message.chat.id} with text: '{message.text}'")
108
+
109
  sender_name = message.from_user.first_name if message.from_user else "User"
110
+ logger.info(f"Received /start command from {sender_name} (ID: {message.from_user.id})") # Original log
111
+
112
  welcome_text = f"Hello {sender_name}!\n"
113
+ welcome_text += "I am your template management bot.\n"
114
  welcome_text += "Template storage is at: " + str(TEMPLATE_FILE_PATH.resolve()) + "\n"
115
  welcome_text += "Use /settemplate <your text> to set a new template.\n"
116
  welcome_text += "Use /gettemplate to view the current template."
 
122
 
123
  @app.on_message(filters.command("settemplate") & filters.private)
124
  async def set_template_handler(client: Client, message: Message):
125
+ logger.info(f"!!!!!! SETTEMPLATE HANDLER TRIGGERED by user {message.from_user.id} in chat {message.chat.id}")
126
+ user_id = message.from_user.id # Retained for potential future use
127
  if len(message.command) > 1:
128
  new_template = message.text.split(" ", 1)[1].strip()
129
  if new_template:
 
138
 
139
  @app.on_message(filters.command("gettemplate") & filters.private)
140
  async def get_template_handler(client: Client, message: Message):
141
+ logger.info(f"!!!!!! GETTEMPLATE HANDLER TRIGGERED by user {message.from_user.id} in chat {message.chat.id}")
142
+ user_id = message.from_user.id # Retained for potential future use
143
  if current_template_content:
144
  response_text = f"📜 **Current Template:**\n\n{current_template_content}"
145
  else:
146
  response_text = "ℹ️ No template is currently set. Use `/settemplate <your text>` to set one."
147
  await message.reply_text(response_text)
148
 
149
+ # --- Main Execution ---
150
  async def main():
151
  await load_template_from_file()
152
  logger.info("Attempting to connect and start the bot...")
153
  try:
154
  await app.start()
155
  me = await app.get_me()
156
+ # For bots, me.username is also useful
157
+ logger.info(f"Bot started successfully as '{me.first_name}' (ID: {me.id}, Username: @{me.username or 'N/A'})")
158
  logger.info("Listening for messages...")
159
+ await asyncio.Event().wait() # Keep the bot running
160
  except (SessionPasswordNeeded, PhoneCodeInvalid, PhoneNumberInvalid, PasswordHashInvalid) as e:
161
  logger.error(f"Authorization error: {type(e).__name__} - {e}. Your SESSION_STRING might be invalid or expired.")
162
  except ConnectionError as e: