Repository navigation
Expand file tree
/
Copy pathbot_fixed.py
More file actions
290 lines (252 loc) Β· 10 KB
/
Copy pathbot_fixed.py
File metadata and controls
290 lines (252 loc) Β· 10 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
"""
SessionMaster - Advanced Telegram Session Management Bot
Fixed main application file
"""
import telebot
import asyncio
import os
import logging
import sys
import time
import threading
from pathlib import Path
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
# Import modules
try:
from config import config
from database import db
from utils import sanitize_log_input, setup_logging, create_directories, check_config
from session_manager import validate_session, get_session_info
from exceptions import ConfigurationError
except ImportError as e:
print(f"Import error: {e}")
print("Some modules may be missing. Continuing with basic functionality...")
# Global variables
bot = None
TOKEN = None
pending_message = {}
def get_user_session(user_id):
"""Get user session path"""
session_path = f"sessions/id_{user_id}.session"
if os.path.exists(session_path):
return session_path
return None
def run_coro_sync(coro):
"""Run coroutine synchronously"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop.run_until_complete(coro)
except Exception as e:
logging.error(f"Error running coroutine: {e}")
return None
finally:
loop.close()
def send_session_info(message, session_id, info):
"""Send session information to user"""
if not info:
bot.send_message(message.chat.id, "Error getting session information.")
return
text = f"π± **Session Info**\\n\\n"
text += f"π€ **Name:** {info.get('name', 'Unknown')}\\n"
text += f"π **ID:** {info.get('id', 'Unknown')}\\n"
text += f"π **Phone:** {info.get('phone', 'Unknown')}\\n"
if info.get('username'):
text += f"π **Username:** @{info['username']}\\n"
text += f"π¬ **Dialogs:** {info.get('dialogs', 0)}\\n"
text += f"π’ **Channels:** {info.get('channels', 0)}\\n"
text += f"π₯ **Groups:** {info.get('groups', 0)}\\n"
text += f"π€ **Bots:** {info.get('bots', 0)}\\n"
text += f"π **Private Chats:** {info.get('private_chats', 0)}\\n"
if info.get('premium'):
text += "β **Premium Account**\\n"
if info.get('verified'):
text += "β
**Verified Account**\\n"
# Create inline keyboard
markup = InlineKeyboardMarkup()
markup.row(
InlineKeyboardButton("π Update", callback_data="update"),
InlineKeyboardButton("π« Spam Check", callback_data="spamcheck")
)
markup.row(
InlineKeyboardButton("π¬ Send Message", callback_data="message_user"),
InlineKeyboardButton("π’ Subscribe", callback_data="subscribe")
)
markup.row(
InlineKeyboardButton("ποΈ Delete Dialogs", callback_data="delete"),
InlineKeyboardButton("π Export Contacts", callback_data="import_contacts")
)
markup.row(
InlineKeyboardButton("πΎ Generate TData", callback_data="tdata"),
InlineKeyboardButton("π° Check Wallet", callback_data="toggle_crypto")
)
try:
if info.get('avatar'):
bot.send_photo(message.chat.id, info['avatar'], caption=text,
reply_markup=markup, parse_mode='Markdown')
else:
bot.send_message(message.chat.id, text, reply_markup=markup, parse_mode='Markdown')
except Exception as e:
logging.error(f"Error sending session info: {e}")
# Fallback without markdown
bot.send_message(message.chat.id, text.replace('*', ''), reply_markup=markup)
def register_handlers():
"""Register bot handlers"""
@bot.message_handler(commands=["start"])
def start_handler(message):
session_path = get_user_session(message.chat.id)
if session_path:
try:
info = run_coro_sync(get_session_info(session_path))
session_id = f"id_{message.chat.id}"
send_session_info(message, session_id, info)
except Exception as e:
logging.error(f"Error getting session info: {e}")
bot.send_message(message.chat.id, "Error getting session information.")
else:
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton("π± Add by Phone", callback_data="add_session_phone"))
bot.send_message(message.chat.id, "π **Welcome to SessionMaster!**\\n\\nNo sessions found. Choose how to add your account:", reply_markup=markup, parse_mode='Markdown')
bot.send_message(message.chat.id, "Or send a .session file directly")
@bot.message_handler(commands=["help"])
def help_handler(message):
help_text = """
π **SessionMaster Commands:**
/start - Main menu and session selection
/help - Show this help message
/wallet - Check crypto wallet balance
/cancel - Cancel current operation
**Features:**
π± Session Management
π¬ Send Messages
π’ Channel Subscription
ποΈ Dialog Cleanup
π Contact Export
πΎ TData Generation
π° Crypto Wallet Check
Send a .session file to get started!
"""
bot.send_message(message.chat.id, help_text, parse_mode='Markdown')
@bot.message_handler(content_types=['document'])
def handle_session_file(message):
if not message.document.file_name.endswith(".session"):
bot.reply_to(message, "Please send a .session file")
return
try:
file_info = bot.get_file(message.document.file_id)
downloaded_file = bot.download_file(file_info.file_path)
except Exception as e:
logging.error(f"Error downloading file: {e}")
bot.reply_to(message, "Error downloading file.")
return
session_path = f"sessions/id_{message.chat.id}.session"
try:
with open(session_path, "wb") as f:
f.write(downloaded_file)
logging.debug(f"Session file saved to {session_path}")
except Exception as e:
logging.error(f"Error saving session file: {e}")
bot.reply_to(message, "Error saving file.")
return
if run_coro_sync(validate_session(session_path)):
try:
info = run_coro_sync(get_session_info(session_path))
session_id = f"id_{message.chat.id}"
bot.reply_to(message, "β
Session file uploaded successfully!")
send_session_info(message, session_id, info)
except Exception as e:
logging.error(f"Error processing session info: {e}")
bot.reply_to(message, "Session uploaded but error getting info.")
else:
os.remove(session_path)
logging.warning(f"Session file {session_path} is invalid.")
bot.reply_to(message, "β Invalid session file.")
@bot.callback_query_handler(func=lambda call: call.data == "update")
def handle_update(call):
session_path = get_user_session(call.message.chat.id)
if not session_path:
bot.answer_callback_query(call.id, "Session not found!")
return
try:
info = run_coro_sync(get_session_info(session_path))
session_id = f"id_{call.message.chat.id}"
bot.send_message(call.message.chat.id, "π Updated data:")
send_session_info(call.message, session_id, info)
except Exception as e:
logging.error(f"Error updating session info: {e}")
bot.answer_callback_query(call.id, "Error updating info!")
@bot.callback_query_handler(func=lambda call: call.data == "add_session_phone")
def handle_add_phone(call):
bot.send_message(call.message.chat.id, "π± Phone authentication is not implemented yet. Please upload a .session file instead.")
bot.answer_callback_query(call.id)
# Placeholder handlers for other callbacks
@bot.callback_query_handler(func=lambda call: True)
def handle_callback(call):
bot.answer_callback_query(call.id, f"Feature '{call.data}' is not implemented yet.")
def initialize_bot():
"""Initialize the bot instance"""
global TOKEN, bot
TOKEN = config.get('bot_token')
if not TOKEN:
raise ConfigurationError("Bot token not configured")
bot = telebot.TeleBot(TOKEN)
register_handlers()
logging.info("Bot initialized successfully")
def start_bot():
"""Start the Telegram bot"""
try:
print("π Starting SessionMaster bot...")
while True:
try:
bot.polling(none_stop=True, timeout=60)
except Exception as e:
logging.error(f"Polling error: {sanitize_log_input(str(e))}")
time.sleep(15)
except Exception as e:
logging.error(f"Bot error: {e}")
time.sleep(5)
start_bot() # Restart on error
def main():
"""Main launcher function"""
print("SessionMaster v2.0")
print("=" * 50)
# Setup
try:
setup_logging()
except:
logging.basicConfig(level=logging.INFO)
try:
if not check_config():
print("β Configuration check failed")
sys.exit(1)
except:
print("β οΈ Config check failed, continuing anyway...")
try:
create_directories()
except:
print("β οΈ Directory creation failed, continuing anyway...")
# Create basic directories
os.makedirs("sessions", exist_ok=True)
os.makedirs("temp", exist_ok=True)
os.makedirs("logs", exist_ok=True)
try:
initialize_bot()
except Exception as e:
print(f"β Bot initialization failed: {e}")
sys.exit(1)
print("β
Configuration validated")
print("β
Directories created")
print("β
Bot initialized")
# Start bot
try:
start_bot()
except KeyboardInterrupt:
print("\\nπ Shutting down SessionMaster...")
sys.exit(0)
except Exception as e:
logging.error(f"Startup error: {e}")
print(f"β Startup error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()