Skip to content

Commit 14197ae

Browse files
committed
fix: fixed variable in init
1 parent 39ca727 commit 14197ae

File tree

1 file changed

+29
-8
lines changed

1 file changed

+29
-8
lines changed

userbot/__init__.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import sys
44
from typing import Dict, Optional, Any, List
55

6+
from faker import Faker
67
from telethon import TelegramClient as TelethonTelegramClient, events
78
from telethon.sessions import StringSession
89

@@ -22,6 +23,10 @@
2223
# --- Globals ---
2324
ACTIVE_CLIENTS: Dict[int, "TelegramClient"] = {}
2425
LOOP: asyncio.AbstractEventLoop = asyncio.get_event_loop()
26+
# Re-adding FAKE and GLOBAL_HELP_INFO to resolve the ImportError in __main__.py
27+
FAKE: Faker = Faker()
28+
GLOBAL_HELP_INFO: Dict[int, Dict[str, str]] = {}
29+
2530

2631
# --- Core TelegramClient Class ---
2732
class TelegramClient(TelethonTelegramClient):
@@ -35,7 +40,12 @@ def __init__(self, *args, **kwargs):
3540

3641
@property
3742
def current_account_id(self) -> Optional[int]:
38-
"""Retrieves the account_id from the current DbSession."""
43+
"""
44+
Retrieves the account_id from the current DbSession.
45+
46+
Returns:
47+
Optional[int]: The account ID if the session is a valid DbSession, otherwise None.
48+
"""
3949
if hasattr(self, 'session') and isinstance(self.session, DbSession):
4050
return self.session.account_id
4151
return None
@@ -61,7 +71,11 @@ async def db_setup() -> None:
6171
logger.critical("API_ID or API_HASH is not set. Please run 'python3 -m scripts.setup'. Exiting.")
6272
sys.exit(1)
6373

64-
await initialize_database()
74+
try:
75+
await initialize_database()
76+
except Exception as e:
77+
logger.critical(f"Fatal error during database initialization: {e}", exc_info=True)
78+
sys.exit(1)
6579

6680
db_handler: DBLogHandler = DBLogHandler()
6781
root_logger: logging.Logger = logging.getLogger()
@@ -78,7 +92,7 @@ async def start_individual_client(client: TelegramClient, account: Account) -> N
7892
toggle_account_handler, list_accounts_handler, set_lang_handler
7993
)
8094

81-
client.lang_code = account.lang_code # Set the client's language
95+
client.lang_code = account.lang_code
8296
account_name = account.account_name
8397
account_id = account.account_id
8498

@@ -87,7 +101,8 @@ async def start_individual_client(client: TelegramClient, account: Account) -> N
87101
await client.start()
88102
if await client.is_user_authorized():
89103
logger.info(f"Client for account '{account_name}' (ID: {account_id}) is authorized.")
90-
GLOBAL_HELP_INFO[account_id] = {} # Reset help info
104+
# Initialize help_info dict for this client
105+
GLOBAL_HELP_INFO[account_id] = {}
91106

92107
# Register core handlers
93108
client.add_event_handler(help_commands_handler, events.NewMessage(outgoing=True, pattern=r"^\.help$"))
@@ -98,7 +113,8 @@ async def start_individual_client(client: TelegramClient, account: Account) -> N
98113
client.add_event_handler(toggle_account_handler, events.NewMessage(outgoing=True, pattern=r"^\.toggleacc\s+([a-zA-Z0-9_]+)$"))
99114
client.add_event_handler(set_lang_handler, events.NewMessage(outgoing=True, pattern=r"^\.setlang\s+([a-zA-Z]{2,5})$"))
100115

101-
await load_account_modules(account_id, client, GLOBAL_HELP_INFO[account_id])
116+
# Placeholder for module handlers
117+
# await load_account_modules(account_id, client, GLOBAL_HELP_INFO[account_id])
102118
else:
103119
logger.warning(f"Client for '{account_name}' started, but user is NOT authorized.")
104120
except Exception as e:
@@ -110,12 +126,16 @@ async def manage_clients() -> None:
110126
"""Fetches all enabled accounts from DB and starts them concurrently."""
111127
logger.info("Fetching all enabled accounts from the database...")
112128
all_accounts: List[Account] = []
113-
async with get_db() as db_session:
114-
all_accounts = await db_manager.get_all_active_accounts(db_session)
129+
try:
130+
async with get_db() as db_session:
131+
all_accounts = await db_manager.get_all_active_accounts(db_session)
132+
except Exception as e:
133+
logger.critical(f"Could not fetch accounts from database. Is it running and configured correctly? Error: {e}")
134+
return
115135

116136
if not all_accounts:
117137
logger.warning("No enabled accounts found in the database. No clients will be started.")
118-
logger.info("Use 'python3 -m scripts.manage_account add <name>' to add your first account.")
138+
logger.info("Use 'docker compose exec userbot python3 -m scripts.manage_account add <name>' to add your first account.")
119139
return
120140

121141
logger.info(f"Found {len(all_accounts)} enabled accounts. Starting clients...")
@@ -142,6 +162,7 @@ async def manage_clients() -> None:
142162
await asyncio.gather(*tasks)
143163

144164
# --- Main Execution Block ---
165+
# This logic ensures the script can be run directly but not when imported.
145166
if __name__ != "userbot":
146167
if LOOP.is_running():
147168
asyncio.ensure_future(db_setup())

0 commit comments

Comments
 (0)