Untitled
unknown
plain_text
10 months ago
8.8 kB
9
Indexable
import os
import json
from telegram import Update
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
filters,
ContextTypes,
ConversationHandler,
)
from telethon import TelegramClient
from telethon.sessions import StringSession
from telethon.errors import SessionPasswordNeededError
ACCOUNTS_FILE = "accounts.json"
user_sessions = {}
API_CREDENTIALS, PHONE_NUMBER, LOGIN_CODE, PASSWORD = range(4)
def load_accounts():
if os.path.exists(ACCOUNTS_FILE):
with open(ACCOUNTS_FILE, "r") as file:
return json.load(file)
return {}
def save_accounts(accounts):
with open(ACCOUNTS_FILE, "w") as file:
json.dump(accounts, file, indent=4)
def add_account(user_id, api_id, api_hash, session_string):
accounts = load_accounts()
accounts[str(user_id)] = {
"api_id": api_id,
"api_hash": api_hash,
"session_string": session_string,
}
save_accounts(accounts)
def get_account(user_id):
accounts = load_accounts()
return accounts.get(str(user_id))
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Welcome to the Manager Bot! 🤖\n\n"
"📌 Use /addaccount to add a new Telegram account.\n"
"📌 Use /viewaccounts to see your saved accounts.\n"
"📌 Use /startbot to launch the main bot."
)
async def add_account_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Please send your `API_ID API_HASH` in this format:\n\n"
"`123456 abcdef1234567890abcdef1234567890`\n\n"
"🔹 Example: `123456 abcdef1234567890abcdef1234567890`",
parse_mode="Markdown",
)
return API_CREDENTIALS
async def handle_api_credentials(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
text = update.message.text.strip()
try:
api_id, api_hash = text.split()
api_id = int(api_id)
user_sessions[user_id] = {
"api_id": api_id,
"api_hash": api_hash,
}
await update.message.reply_text("📞 Please send your phone number (including country code, e.g., +1234567890).")
return PHONE_NUMBER
except ValueError:
await update.message.reply_text("❌ Invalid format! Please use `/addaccount` and try again.")
return ConversationHandler.END
async def handle_phone_number(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
phone_number = update.message.text.strip()
if user_id not in user_sessions:
await update.message.reply_text("❌ Please send API_ID and API_HASH first using /addaccount.")
return ConversationHandler.END
user_sessions[user_id]["phone"] = phone_number
credentials = user_sessions[user_id]
client = TelegramClient(StringSession(), credentials["api_id"], credentials["api_hash"])
try:
await client.connect()
if not await client.is_user_authorized():
result = await client.send_code_request(phone_number)
user_sessions[user_id]["phone_code_hash"] = result.phone_code_hash # Store phone_code_hash
await update.message.reply_text("🔑 Please enter the login code you received via Telegram.")
return LOGIN_CODE
else:
session_string = client.session.save()
add_account(user_id, credentials["api_id"], credentials["api_hash"], session_string)
await update.message.reply_text("✅ You're already logged in.")
return ConversationHandler.END
except Exception as e:
await update.message.reply_text(f"❌ Error while connecting to Telegram: {e}")
return ConversationHandler.END
async def handle_login_code(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
login_code = update.message.text.strip()
if user_id not in user_sessions or "phone" not in user_sessions[user_id]:
await update.message.reply_text("❌ Please restart with /addaccount.")
return ConversationHandler.END
credentials = user_sessions[user_id]
client = TelegramClient(StringSession(), credentials["api_id"], credentials["api_hash"])
try:
await client.connect()
phone_code_hash = user_sessions[user_id].get("phone_code_hash")
await client.sign_in(phone=credentials["phone"], code=login_code, phone_code_hash=phone_code_hash)
if await client.is_user_authorized():
session_string = client.session.save()
add_account(user_id, credentials["api_id"], credentials["api_hash"], session_string)
await update.message.reply_text("✅ Account added successfully!")
else:
await update.message.reply_text("❌ Login failed. Please try again.")
except Exception as e:
if "confirmation code has expired" in str(e):
await update.message.reply_text("❌ The code has expired. Please send your phone number again to receive a new code.")
return PHONE_NUMBER
else:
await update.message.reply_text(f"❌ Error: {e}")
return ConversationHandler.END
async def handle_password(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
password = update.message.text.strip()
if user_id not in user_sessions or "awaiting_password" not in user_sessions[user_id]:
await update.message.reply_text("❌ No password was requested.")
return ConversationHandler.END
credentials = user_sessions[user_id]
client = TelegramClient(StringSession(), credentials["api_id"], credentials["api_hash"])
try:
await client.connect()
await client.sign_in(password=password)
if await client.is_user_authorized():
session_string = client.session.save()
add_account(user_id, credentials["api_id"], credentials["api_hash"], session_string)
await update.message.reply_text("✅ Account added successfully!")
else:
await update.message.reply_text("❌ Login failed. Please try again.")
except Exception as e:
await update.message.reply_text(f"❌ Error: {e}")
return ConversationHandler.END
async def view_accounts_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
account = get_account(user_id)
if account:
await update.message.reply_text(
f"Your account details:\n\n"
f"API ID: {account['api_id']}\n"
f"API Hash: {account['api_hash']}\n"
"✅ Session is stored securely."
)
else:
await update.message.reply_text("No account found. Use /addaccount to add one.")
async def start_bot_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.message.from_user.id
account = get_account(user_id)
if account:
await update.message.reply_text("Starting the main bot...")
# Run bot.py with API credentials
os.system(f"python bot.py {account['api_id']} {account['api_hash']} {account['session_string']}")
else:
await update.message.reply_text("No account found. Use /addaccount to add one.")
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("❌ Operation canceled.")
return ConversationHandler.END
def main():
application = Application.builder().token("***************").build()
conv_handler = ConversationHandler(
entry_points=[CommandHandler("addaccount", add_account_command)],
states={
API_CREDENTIALS: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_api_credentials)],
PHONE_NUMBER: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_phone_number)],
LOGIN_CODE: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_login_code)],
PASSWORD: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_password)],
},
fallbacks=[CommandHandler("cancel", cancel)],
)
application.add_handler(conv_handler)
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("viewaccounts", view_accounts_command))
application.add_handler(CommandHandler("startbot", start_bot_command))
application.run_polling()
if __name__ == "__main__":
main()Editor is loading...
Leave a Comment