understanding commited on
Commit
baf6302
·
verified ·
1 Parent(s): 5b30b57

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +103 -0
main.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py
2
+ import os
3
+ import logging
4
+ import asyncio
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+ from hydrogram import Client, idle
8
+ from hydrogram.errors import AuthKeyUnregistered
9
+
10
+ from config import Config
11
+ import handlers # To access register_handlers
12
+
13
+ # --- Global Executor ---
14
+ # Defined here so it can be imported by handlers if structured that way,
15
+ # or simply passed/used within main_async_logic.
16
+ # max_workers can be adjusted based on CPU cores or expected load.
17
+ executor = ThreadPoolExecutor(max_workers=(os.cpu_count() or 1) + 4)
18
+
19
+
20
+ # --- Logging Setup ---
21
+ def setup_logging():
22
+ logging.basicConfig(
23
+ level=logging.INFO,
24
+ format='%(asctime)s - %(name)s - %(levelname)s - [%(module)s.%(funcName)s:%(lineno)d] - %(message)s',
25
+ )
26
+ logging.getLogger("hydrogram").setLevel(logging.WARNING) # Reduce hydrogram verbosity
27
+ return logging.getLogger(__name__)
28
+
29
+ logger = setup_logging()
30
+
31
+
32
+ # --- Directory and Font Checks ---
33
+ def run_startup_checks():
34
+ logger.info("Running startup checks...")
35
+ # Check directories (expected to be created by Dockerfile or COPY . .)
36
+ if not os.path.isdir(Config.PREDEFINED_TEMPLATES_DIR):
37
+ logger.error(f"FATAL: Templates directory '{Config.PREDEFINED_TEMPLATES_DIR}' not found or is not a directory in the repository root.")
38
+ return False
39
+ if not os.path.isdir(Config.OUTPUT_DIR): # This one is created by Dockerfile if not present
40
+ logger.info(f"Output directory '{Config.OUTPUT_DIR}' not found, will be created by Dockerfile.")
41
+ # It's okay if this one is missing initially, Dockerfile handles it.
42
+ # But templates dir *must* come from repo.
43
+
44
+ # Check if templates directory has content (optional but good)
45
+ try:
46
+ if os.path.isdir(Config.PREDEFINED_TEMPLATES_DIR) and not os.listdir(Config.PREDEFINED_TEMPLATES_DIR):
47
+ logger.warning(f"Templates directory '{Config.PREDEFINED_TEMPLATES_DIR}' is empty. Predefined templates will not work.")
48
+ except Exception as e:
49
+ logger.warning(f"Could not check contents of templates directory: {e}")
50
+
51
+
52
+ logger.info("Required directories check complete.")
53
+ logger.info(f"Attempting to use font: '{Config.FONT_PATH}' (requires system font access).")
54
+ return True
55
+
56
+ # --- Main Application Logic ---
57
+ async def main_async_logic():
58
+ logger.info("Initializing Hydrogram Bot Client...")
59
+
60
+ app = Client(
61
+ name=Config.SESSION_NAME,
62
+ api_id=Config.API_ID,
63
+ api_hash=Config.API_HASH,
64
+ bot_token=Config.BOT_TOKEN,
65
+ workdir="/app" # Ensures .session file is stored in /app (writable)
66
+ )
67
+
68
+ handlers.register_handlers(app)
69
+ logger.info("Message handlers registered.")
70
+
71
+ try:
72
+ logger.info("Starting Hydrogram client (as BOT)...")
73
+ await app.start()
74
+ me = await app.get_me()
75
+ logger.info(f"Successfully started. Bot: {me.first_name} (Username: @{me.username}, ID: {me.id})")
76
+ logger.info("Bot is up and listening for messages from admins!")
77
+ await idle()
78
+ except AuthKeyUnregistered:
79
+ logger.critical("BOT TOKEN INVALID or REVOKED. Please check your BOT_TOKEN secret in Hugging Face.")
80
+ except Exception as e:
81
+ logger.critical(f"Error starting or running Hydrogram client: {e}", exc_info=True)
82
+ finally:
83
+ logger.info("Shutting down executor...")
84
+ executor.shutdown(wait=True)
85
+ if app.is_initialized and app.is_connected: # Check if client was started
86
+ logger.info("Stopping Hydrogram client...")
87
+ await app.stop()
88
+ logger.info("Shutdown complete.")
89
+
90
+ if __name__ == "__main__":
91
+ if not run_startup_checks():
92
+ logger.critical("Startup checks failed. Exiting.")
93
+ exit(1)
94
+
95
+ try:
96
+ asyncio.run(main_async_logic())
97
+ except KeyboardInterrupt:
98
+ logger.info("Bot stopped by KeyboardInterrupt.")
99
+ except Exception as e:
100
+ logger.critical(f"Unhandled exception in main: {e}", exc_info=True)
101
+ finally:
102
+ logger.info("Application terminated.")
103
+