123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- #!/usr/bin/env python3
- """
- Simple Telegram Chat ID Finder
- A more robust version that works better in server environments.
- """
- import sys
- import asyncio
- import signal
- from pathlib import Path
- # Add src directory to Python path
- sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
- try:
- from telegram import Bot
- from telegram.ext import Application, MessageHandler, filters
- except ImportError:
- print("❌ python-telegram-bot not installed!")
- print("💡 Run: pip install python-telegram-bot")
- sys.exit(1)
- # Global variables for graceful shutdown
- running = True
- found_ids = set()
- def signal_handler(signum, frame):
- """Handle shutdown signals gracefully."""
- global running
- print(f"\n🛑 Stopping...")
- running = False
- async def message_handler(update, context):
- """Handle incoming messages and show chat info."""
- global found_ids
-
- try:
- chat_id = update.effective_chat.id
- user = update.effective_user
- message_text = update.message.text if update.message else "No text"
-
- found_ids.add(chat_id)
-
- # Send response
- response = f"""
- 🎯 <b>Chat ID Found!</b>
- 🆔 <b>Chat ID:</b> <code>{chat_id}</code>
- 👤 <b>User:</b> {user.first_name} {user.last_name or ''}
- 📧 <b>Username:</b> @{user.username or 'None'}
- ✅ <b>Add this to your .env file:</b>
- <code>TELEGRAM_CHAT_ID={chat_id}</code>
- """
-
- await update.message.reply_text(response.strip(), parse_mode='HTML')
-
- # Print to console
- print(f"\n🎉 SUCCESS! Chat ID: {chat_id}")
- print(f"👤 User: {user.first_name} {user.last_name or ''}")
- print(f"📧 Username: @{user.username or 'None'}")
- print(f"\n📋 Add to .env file:")
- print(f"TELEGRAM_CHAT_ID={chat_id}")
- print(f"\n✅ Press Ctrl+C to stop")
-
- except Exception as e:
- print(f"❌ Error: {e}")
- async def run_bot(token):
- """Run the bot to find Chat ID."""
- global running
-
- try:
- # Create application
- app = Application.builder().token(token).build()
-
- # Add message handler
- app.add_handler(MessageHandler(filters.ALL, message_handler))
-
- print("🤖 Chat ID finder is running...")
- print("💬 Send ANY message to your bot in Telegram")
- print("🛑 Press Ctrl+C when done\n")
-
- # Start the bot
- async with app:
- await app.start()
- await app.updater.start_polling()
-
- # Keep running until stopped
- while running:
- await asyncio.sleep(0.1)
-
- await app.updater.stop()
-
- except Exception as e:
- print(f"❌ Bot error: {e}")
- raise
- def main():
- """Main function."""
- global running, found_ids
-
- print("🔍 Simple Telegram Chat ID Finder\n")
-
- # Set up signal handlers
- signal.signal(signal.SIGINT, signal_handler)
- signal.signal(signal.SIGTERM, signal_handler)
-
- # Get bot token
- token = input("🤖 Enter your Telegram Bot Token: ").strip()
-
- if not token:
- print("❌ No token provided!")
- return
-
- if ':' not in token:
- print("❌ Invalid token format!")
- print("💡 Should look like: 123456789:ABCdefGHIjklMNOPqrs")
- return
-
- print(f"\n✅ Token looks valid!")
- print(f"🚀 Starting bot...\n")
-
- try:
- # Test the token first
- async def test_token():
- try:
- bot = Bot(token)
- me = await bot.get_me()
- print(f"🤖 Bot: @{me.username} ({me.first_name})")
- return True
- except Exception as e:
- print(f"❌ Invalid token: {e}")
- return False
-
- # Test token
- if not asyncio.run(test_token()):
- return
-
- # Run the bot
- asyncio.run(run_bot(token))
-
- except KeyboardInterrupt:
- pass
- except Exception as e:
- print(f"❌ Error: {e}")
- finally:
- if found_ids:
- print(f"\n📋 Found Chat IDs: {', '.join(map(str, found_ids))}")
- print(f"✅ Add any of these to your .env file")
- else:
- print(f"\n❌ No Chat IDs found")
- print(f"💡 Make sure you sent a message to your bot!")
- if __name__ == "__main__":
- main()
|