get_telegram_chat_id.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #!/usr/bin/env python3
  2. """
  3. Get Telegram Chat ID Helper
  4. This script helps you find your Telegram Chat ID for bot configuration.
  5. """
  6. import sys
  7. import asyncio
  8. import logging
  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 Update
  14. from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
  15. except ImportError:
  16. print("❌ python-telegram-bot not installed!")
  17. print("💡 Run: pip install python-telegram-bot")
  18. sys.exit(1)
  19. # Set up logging
  20. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  21. logger = logging.getLogger(__name__)
  22. class ChatIDBot:
  23. """Simple bot to get your Chat ID."""
  24. def __init__(self, token: str):
  25. self.token = token
  26. self.application = None
  27. self.found_chat_ids = set()
  28. async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  29. """Handle any message and show chat information."""
  30. chat_id = update.effective_chat.id
  31. user = update.effective_user
  32. message_text = update.message.text if update.message else "No text"
  33. # Store found chat ID
  34. self.found_chat_ids.add(chat_id)
  35. # Respond with chat information
  36. response = f"""
  37. 🎯 <b>Found Your Chat Information!</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>Message:</b> {message_text}
  42. ✅ <b>Copy this Chat ID to your .env file:</b>
  43. <code>TELEGRAM_CHAT_ID={chat_id}</code>
  44. """
  45. await update.message.reply_text(response, parse_mode='HTML')
  46. # Print to console
  47. print(f"\n🎉 SUCCESS! Found Chat ID: {chat_id}")
  48. print(f"👤 User: {user.first_name} {user.last_name or ''}")
  49. print(f"📧 Username: @{user.username or 'None'}")
  50. print(f"\n📋 Add this to your .env file:")
  51. print(f"TELEGRAM_CHAT_ID={chat_id}")
  52. print(f"\n✅ You can now stop this script and start your trading bot!")
  53. async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  54. """Handle the /start command."""
  55. await self.handle_message(update, context)
  56. async def run(self):
  57. """Run the Chat ID finder bot."""
  58. self.application = Application.builder().token(self.token).build()
  59. # Add handlers for any message or /start command
  60. self.application.add_handler(CommandHandler("start", self.start_command))
  61. self.application.add_handler(MessageHandler(filters.ALL, self.handle_message))
  62. print("🤖 Chat ID finder bot is running...")
  63. print("💬 Now go to Telegram and send ANY message to your bot")
  64. print("🛑 Press Ctrl+C when done\n")
  65. try:
  66. await self.application.run_polling()
  67. except KeyboardInterrupt:
  68. print(f"\n👋 Chat ID finder stopped")
  69. if self.found_chat_ids:
  70. print(f"📋 Found Chat IDs: {', '.join(map(str, self.found_chat_ids))}")
  71. else:
  72. print("❌ No Chat IDs found - make sure you messaged your bot!")
  73. def main():
  74. """Main function."""
  75. print("🔍 Telegram Chat ID Finder\n")
  76. # Get bot token
  77. token = input("🤖 Enter your Telegram Bot Token: ").strip()
  78. if not token:
  79. print("❌ No token provided!")
  80. return
  81. if ':' not in token:
  82. print("❌ Invalid token format! Should look like: 123456789:ABCdefGHIjklMNOPqrs")
  83. return
  84. print(f"\n✅ Token looks valid!")
  85. print(f"🚀 Starting Chat ID finder bot...")
  86. print(f"\n📱 Instructions:")
  87. print(f"1. Open Telegram")
  88. print(f"2. Find your bot (search for the username you gave it)")
  89. print(f"3. Send ANY message to your bot")
  90. print(f"4. Come back here to see your Chat ID")
  91. print(f"5. Copy the Chat ID to your .env file")
  92. try:
  93. bot = ChatIDBot(token)
  94. asyncio.run(bot.run())
  95. except Exception as e:
  96. print(f"❌ Error: {e}")
  97. print("💡 Make sure your bot token is correct")
  98. if __name__ == "__main__":
  99. main()