simple_chat_id.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python3
  2. """
  3. Simple Telegram Chat ID Finder
  4. A more robust version that works better in server environments.
  5. """
  6. import sys
  7. import asyncio
  8. import signal
  9. from pathlib import Path
  10. # Add src directory to Python path
  11. sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
  12. try:
  13. from telegram import Bot
  14. from telegram.ext import Application, MessageHandler, filters
  15. except ImportError:
  16. print("❌ python-telegram-bot not installed!")
  17. print("💡 Run: pip install python-telegram-bot")
  18. sys.exit(1)
  19. # Global variables for graceful shutdown
  20. running = True
  21. found_ids = set()
  22. def signal_handler(signum, frame):
  23. """Handle shutdown signals gracefully."""
  24. global running
  25. print(f"\n🛑 Stopping...")
  26. running = False
  27. async def message_handler(update, context):
  28. """Handle incoming messages and show chat info."""
  29. global found_ids
  30. try:
  31. chat_id = update.effective_chat.id
  32. user = update.effective_user
  33. message_text = update.message.text if update.message else "No text"
  34. found_ids.add(chat_id)
  35. # Send response
  36. response = f"""
  37. 🎯 <b>Chat ID Found!</b>
  38. 🆔 <b>Chat ID:</b> <code>{chat_id}</code>
  39. 👤 <b>User:</b> {user.first_name} {user.last_name or ''}
  40. 📧 <b>Username:</b> @{user.username or 'None'}
  41. ✅ <b>Add this to your .env file:</b>
  42. <code>TELEGRAM_CHAT_ID={chat_id}</code>
  43. """
  44. await update.message.reply_text(response.strip(), parse_mode='HTML')
  45. # Print to console
  46. print(f"\n🎉 SUCCESS! Chat ID: {chat_id}")
  47. print(f"👤 User: {user.first_name} {user.last_name or ''}")
  48. print(f"📧 Username: @{user.username or 'None'}")
  49. print(f"\n📋 Add to .env file:")
  50. print(f"TELEGRAM_CHAT_ID={chat_id}")
  51. print(f"\n✅ Press Ctrl+C to stop")
  52. except Exception as e:
  53. print(f"❌ Error: {e}")
  54. async def run_bot(token):
  55. """Run the bot to find Chat ID."""
  56. global running
  57. try:
  58. # Create application
  59. app = Application.builder().token(token).build()
  60. # Add message handler
  61. app.add_handler(MessageHandler(filters.ALL, message_handler))
  62. print("🤖 Chat ID finder is running...")
  63. print("💬 Send ANY message to your bot in Telegram")
  64. print("🛑 Press Ctrl+C when done\n")
  65. # Start the bot
  66. async with app:
  67. await app.start()
  68. await app.updater.start_polling()
  69. # Keep running until stopped
  70. while running:
  71. await asyncio.sleep(0.1)
  72. await app.updater.stop()
  73. except Exception as e:
  74. print(f"❌ Bot error: {e}")
  75. raise
  76. def main():
  77. """Main function."""
  78. global running, found_ids
  79. print("🔍 Simple Telegram Chat ID Finder\n")
  80. # Set up signal handlers
  81. signal.signal(signal.SIGINT, signal_handler)
  82. signal.signal(signal.SIGTERM, signal_handler)
  83. # Get bot token
  84. token = input("🤖 Enter your Telegram Bot Token: ").strip()
  85. if not token:
  86. print("❌ No token provided!")
  87. return
  88. if ':' not in token:
  89. print("❌ Invalid token format!")
  90. print("💡 Should look like: 123456789:ABCdefGHIjklMNOPqrs")
  91. return
  92. print(f"\n✅ Token looks valid!")
  93. print(f"🚀 Starting bot...\n")
  94. try:
  95. # Test the token first
  96. async def test_token():
  97. try:
  98. bot = Bot(token)
  99. me = await bot.get_me()
  100. print(f"🤖 Bot: @{me.username} ({me.first_name})")
  101. return True
  102. except Exception as e:
  103. print(f"❌ Invalid token: {e}")
  104. return False
  105. # Test token
  106. if not asyncio.run(test_token()):
  107. return
  108. # Run the bot
  109. asyncio.run(run_bot(token))
  110. except KeyboardInterrupt:
  111. pass
  112. except Exception as e:
  113. print(f"❌ Error: {e}")
  114. finally:
  115. if found_ids:
  116. print(f"\n📋 Found Chat IDs: {', '.join(map(str, found_ids))}")
  117. print(f"✅ Add any of these to your .env file")
  118. else:
  119. print(f"\n❌ No Chat IDs found")
  120. print(f"💡 Make sure you sent a message to your bot!")
  121. if __name__ == "__main__":
  122. main()