File size: 10,440 Bytes
baf6302
 
a90bf74
c2ef410
b8d7c4e
13d9680
b8d7c4e
a90bf74
bc39fa8
 
 
 
 
a90bf74
 
bc39fa8
c2ef410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a90bf74
 
 
 
 
 
 
 
c2ef410
 
 
 
 
a90bf74
 
 
 
 
 
 
c2ef410
a90bf74
 
 
 
 
 
 
c2ef410
 
 
 
baf6302
c2ef410
 
 
 
a90bf74
 
 
 
 
 
 
 
bc39fa8
 
a90bf74
 
b8d7c4e
bc39fa8
c2ef410
 
 
 
 
a90bf74
bc39fa8
13d9680
c2ef410
a90bf74
13d9680
 
bc39fa8
b8d7c4e
bc39fa8
 
a90bf74
c2ef410
a90bf74
13d9680
 
a90bf74
 
 
 
 
 
 
bc39fa8
a90bf74
 
bc39fa8
a90bf74
 
 
 
 
c2ef410
a90bf74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc39fa8
a90bf74
 
bc39fa8
a90bf74
 
c2ef410
a90bf74
b8d7c4e
a90bf74
 
 
 
c2ef410
a90bf74
 
 
 
b8d7c4e
a90bf74
b8d7c4e
c2ef410
a90bf74
 
 
 
c2ef410
a90bf74
 
 
 
 
 
c2ef410
 
a90bf74
c2ef410
a90bf74
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import os
import logging
import asyncio
from pathlib import Path

from hydrogram import Client, filters
from hydrogram.types import Message
from hydrogram.errors import SessionPasswordNeeded, PhoneCodeInvalid, PhoneNumberInvalid, PasswordHashInvalid

# --- Configuration ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Retrieve Session String from Hugging Face secrets
SESSION_STRING = os.environ.get('SESSION_STRING')

# --- Dynamic Storage Path Initialization ---
# Define potential base directories for storage and a subdirectory name
PERSISTENT_STORAGE_CANDIDATES = [
    Path("/data"),  # Common absolute path for persistent data in containers
    Path("."),      # Current working directory (e.g., /app if WORKDIR is /app)
]
APP_STORAGE_SUBDIR_NAME = "app_template_storage" # Subdirectory to hold our template
TEMPLATE_FILENAME = "user_template_content.txt"

DATA_DIR: Path = None
TEMPLATE_FILE_PATH: Path = None

def initialize_storage_paths():
    """Tries to find/create a writable directory for the template file."""
    global DATA_DIR, TEMPLATE_FILE_PATH

    # 1. Try creating a subdirectory in candidate locations
    for base_candidate in PERSISTENT_STORAGE_CANDIDATES:
        potential_data_dir = base_candidate / APP_STORAGE_SUBDIR_NAME
        try:
            potential_data_dir.mkdir(parents=True, exist_ok=True)
            # Test if we can actually write a dummy file here
            test_file = potential_data_dir / ".writable_test"
            with open(test_file, "w") as f:
                f.write("test")
            test_file.unlink() # Clean up test file

            DATA_DIR = potential_data_dir
            TEMPLATE_FILE_PATH = DATA_DIR / TEMPLATE_FILENAME
            logger.info(f"Successfully established writable data directory: {DATA_DIR}")
            return
        except PermissionError:
            logger.warning(f"Permission denied to create/use directory {potential_data_dir}. Trying next candidate.")
        except Exception as e:
            logger.warning(f"Failed to create/use directory {potential_data_dir} due to {type(e).__name__}: {e}. Trying next candidate.")

    # 2. If subdirectory creation failed, try to place the file directly in a candidate base directory
    logger.warning("Could not create/use a dedicated subdirectory. Attempting to use a base directory directly for the file.")
    for base_candidate in PERSISTENT_STORAGE_CANDIDATES:
        potential_template_file_path = base_candidate / TEMPLATE_FILENAME
        try:
            # Test writability by trying to open the file in append mode (creates if not exists)
            with open(potential_template_file_path, 'a'):
                pass # Just testing if open works without error
            # If we are here, it means we can probably write the file directly.
            DATA_DIR = base_candidate # The "data directory" is now the base itself
            TEMPLATE_FILE_PATH = potential_template_file_path
            logger.info(f"Using base directory {DATA_DIR.resolve()} directly for template file: {TEMPLATE_FILE_PATH}")
            return
        except PermissionError:
            logger.warning(f"Permission denied to write template file directly in {base_candidate.resolve()}. Trying next candidate.")
        except Exception as e:
            logger.warning(f"Failed to write template file in {base_candidate.resolve()} due to {type(e).__name__}: {e}. Trying next candidate.")

    # If all attempts fail
    logger.error("CRITICAL: Unable to find or create a writable location for the template file.")
    # Set paths to None to indicate failure; the app might crash or malfunction later.
    # A more robust solution would be to exit here.
    DATA_DIR = None
    TEMPLATE_FILE_PATH = None
    # Consider exiting: exit("Failed to initialize storage.")

# Call this ONCE at the start of the script
initialize_storage_paths()

# Global variable to hold the loaded template content
current_template_content = None

# --- Helper Functions for Template Management ---
async def load_template_from_file():
    """Loads template content from the persistent file."""
    global current_template_content
    if not TEMPLATE_FILE_PATH:
        logger.error("Template file path is not configured. Cannot load template.")
        current_template_content = None
        return

    if TEMPLATE_FILE_PATH.exists():
        try:
            with open(TEMPLATE_FILE_PATH, "r", encoding="utf-8") as f:
                current_template_content = f.read()
            logger.info(f"Template loaded successfully from {TEMPLATE_FILE_PATH}")
        except Exception as e:
            logger.error(f"Error loading template from {TEMPLATE_FILE_PATH}: {e}")
            current_template_content = None
    else:
        logger.info(f"Template file {TEMPLATE_FILE_PATH} not found. No template loaded.")
        current_template_content = None

async def save_template_to_file(content: str):
    """Saves template content to the persistent file."""
    global current_template_content
    if not TEMPLATE_FILE_PATH:
        logger.error("Template file path is not configured. Cannot save template.")
        return False

    try:
        # Ensure the parent directory exists (it should if initialize_storage_paths worked for a subdir)
        if TEMPLATE_FILE_PATH.parent != Path("."): # Avoid trying to create "." if file is in current dir
             TEMPLATE_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)

        with open(TEMPLATE_FILE_PATH, "w", encoding="utf-8") as f:
            f.write(content)
        current_template_content = content
        logger.info(f"Template saved successfully to {TEMPLATE_FILE_PATH}")
        return True
    except Exception as e:
        logger.error(f"Error saving template to {TEMPLATE_FILE_PATH}: {e}")
        return False

# --- Initialization ---
if not SESSION_STRING:
    logger.error("SESSION_STRING environment variable not found. Please set it in Hugging Face secrets.")
    exit(1)

if not TEMPLATE_FILE_PATH:
    logger.critical("CRITICAL: Template storage path could not be initialized. The application cannot manage templates. Exiting.")
    exit(1)


logger.info("Initializing Hydrogram Client with session string...")
try:
    app = Client(
        name="user_session_hgs", # Changed name slightly to avoid old session file conflicts if any
        session_string=SESSION_STRING,
    )
    logger.info("Hydrogram Client initialized.")
except Exception as e:
    logger.error(f"Failed to initialize Hydrogram Client: {type(e).__name__} - {e}")
    exit(1)


# --- Bot Event Handlers (Unchanged from your previous version) ---
@app.on_message(filters.command("start") & filters.private)
async def start_handler(client: Client, message: Message):
    sender_name = message.from_user.first_name if message.from_user else "User"
    logger.info(f"Received /start command from {sender_name} (ID: {message.from_user.id})")
    welcome_text = f"Hello {sender_name}!\n"
    welcome_text += "I am ready to manage your template.\n"
    welcome_text += "Use /settemplate <your text> to set a new template.\n"
    welcome_text += "Use /gettemplate to view the current template."
    if current_template_content:
        welcome_text += "\n\nA template is currently set."
    else:
        welcome_text += "\n\nNo template is currently set."
    await message.reply_text(welcome_text)

@app.on_message(filters.command("settemplate") & filters.private)
async def set_template_handler(client: Client, message: Message):
    user_id = message.from_user.id
    logger.info(f"Received /settemplate command from User ID: {user_id}")
    if len(message.command) > 1:
        new_template = message.text.split(" ", 1)[1].strip()
        if new_template:
            if await save_template_to_file(new_template):
                await message.reply_text("✅ Template updated successfully!")
            else:
                await message.reply_text("❌ Failed to save the template. Please check the logs.")
        else:
            await message.reply_text("⚠️ Please provide content for the template. Usage: `/settemplate Your template text here`")
    else:
        await message.reply_text("ℹ️ Usage: `/settemplate Your template text here`")

@app.on_message(filters.command("gettemplate") & filters.private)
async def get_template_handler(client: Client, message: Message):
    user_id = message.from_user.id
    logger.info(f"Received /gettemplate command from User ID: {user_id}")
    if current_template_content:
        response_text = f"📜 **Current Template:**\n\n{current_template_content}"
    else:
        response_text = "ℹ️ No template is currently set. Use `/settemplate <your text>` to set one."
    await message.reply_text(response_text)

# --- Main Execution ---
async def main():
    await load_template_from_file()
    logger.info("Attempting to connect and start the bot...")
    try:
        await app.start()
        me = await app.get_me()
        logger.info(f"Bot started successfully as {me.first_name} (ID: {me.id})")
        logger.info("Listening for messages...")
        await asyncio.Event().wait()
    except (SessionPasswordNeeded, PhoneCodeInvalid, PhoneNumberInvalid, PasswordHashInvalid) as e:
        logger.error(f"Authorization error: {type(e).__name__} - {e}. Your SESSION_STRING might be invalid or expired.")
    except ConnectionError as e:
        logger.error(f"Connection error: {e}. Check your network or Telegram's status.")
    except Exception as e:
        logger.error(f"An unexpected error occurred during bot startup or runtime: {type(e).__name__} - {e}", exc_info=True)
    finally:
        if app.is_initialized and app.is_connected: # Check if initialized before checking is_connected
            logger.info("Stopping the bot...")
            await app.stop()
            logger.info("Bot stopped.")
        else:
            logger.info("Bot was not fully connected or already stopped.")

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Bot manually interrupted. Exiting...")
    except SystemExit as e: # Catch explicit exits
        logger.info(f"Application exiting with status: {e.code}")
    except Exception as e:
        logger.critical(f"Critical error in main execution block: {type(e).__name__} - {e}", exc_info=True)