get_telegram_chat_id.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. import signal
  10. from pathlib import Path
  11. # Add src directory to Python path
  12. sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
  13. try:
  14. from telegram import Update
  15. from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
  16. except ImportError:
  17. print("❌ python-telegram-bot not installed!")
  18. print("💡 Run: pip install python-telegram-bot")
  19. sys.exit(1)
  20. # Set up logging to reduce noise
  21. logging.basicConfig(
  22. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  23. level=logging.WARNING # Reduce log noise
  24. )
  25. logger = logging.getLogger(__name__)
  26. class ChatIDBot:
  27. """Simple bot to get your Chat ID."""
  28. def __init__(self, token: str):
  29. self.token = token
  30. self.application = None
  31. self.found_chat_ids = set()
  32. self.running = True
  33. async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  34. """Handle any message and show chat information."""
  35. try:
  36. chat_id = update.effective_chat.id
  37. user = update.effective_user
  38. message_text = update.message.text if update.message else "No text"
  39. # Store found chat ID
  40. self.found_chat_ids.add(chat_id)
  41. # Respond with chat information
  42. response = f"""
  43. 🎯 <b>Found Your Chat Information!</b>
  44. 🆔 <b>Chat ID:</b> <code>{chat_id}</code>
  45. 👤 <b>User:</b> {user.first_name} {user.last_name or ''}
  46. 📧 <b>Username:</b> @{user.username or 'None'}
  47. 💬 <b>Message:</b> {message_text}
  48. ✅ <b>Copy this Chat ID to your .env file:</b>
  49. <code>TELEGRAM_CHAT_ID={chat_id}</code>
  50. 🛑 <b>Press Ctrl+C to stop this script</b>
  51. """
  52. await update.message.reply_text(response.strip(), parse_mode='HTML')
  53. # Print to console
  54. print(f"\n🎉 SUCCESS! Found Chat ID: {chat_id}")
  55. print(f"👤 User: {user.first_name} {user.last_name or ''}")
  56. print(f"📧 Username: @{user.username or 'None'}")
  57. print(f"\n📋 Add this to your .env file:")
  58. print(f"TELEGRAM_CHAT_ID={chat_id}")
  59. print(f"\n✅ You can now stop this script (Ctrl+C) and start your trading bot!")
  60. print(f"💬 Or send another message to test again...")
  61. except Exception as e:
  62. print(f"❌ Error handling message: {e}")
  63. async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  64. """Handle the /start command."""
  65. await self.handle_message(update, context)
  66. async def stop_bot(self):
  67. """Gracefully stop the bot."""
  68. if self.application:
  69. try:
  70. await self.application.stop()
  71. await self.application.shutdown()
  72. except Exception as e:
  73. print(f"⚠️ Warning during shutdown: {e}")
  74. async def run(self):
  75. """Run the Chat ID finder bot."""
  76. try:
  77. # Build application
  78. self.application = Application.builder().token(self.token).build()
  79. # Add handlers for any message or /start command
  80. self.application.add_handler(CommandHandler("start", self.start_command))
  81. self.application.add_handler(MessageHandler(filters.ALL, self.handle_message))
  82. print("🤖 Chat ID finder bot is running...")
  83. print("💬 Now go to Telegram and send ANY message to your bot")
  84. print("🛑 Press Ctrl+C when done\n")
  85. # Initialize and run
  86. await self.application.initialize()
  87. await self.application.start()
  88. await self.application.updater.start_polling()
  89. # Keep running until interrupted
  90. while self.running:
  91. await asyncio.sleep(1)
  92. except KeyboardInterrupt:
  93. print(f"\n👋 Chat ID finder stopped by user")
  94. except Exception as e:
  95. print(f"\n❌ Error running bot: {e}")
  96. finally:
  97. # Cleanup
  98. try:
  99. if self.application:
  100. if self.application.updater.running:
  101. await self.application.updater.stop()
  102. await self.application.stop()
  103. await self.application.shutdown()
  104. except Exception as e:
  105. pass # Ignore cleanup errors
  106. # Show results
  107. if self.found_chat_ids:
  108. print(f"\n📋 Found Chat IDs: {', '.join(map(str, self.found_chat_ids))}")
  109. print(f"✅ Copy any of these Chat IDs to your .env file")
  110. else:
  111. print("\n❌ No Chat IDs found - make sure you messaged your bot!")
  112. def signal_handler(bot):
  113. """Handle shutdown signals."""
  114. def handler(signum, frame):
  115. print(f"\n🛑 Received shutdown signal...")
  116. bot.running = False
  117. return handler
  118. def main():
  119. """Main function."""
  120. print("🔍 Telegram Chat ID Finder\n")
  121. # Get bot token
  122. token = input("🤖 Enter your Telegram Bot Token: ").strip()
  123. if not token:
  124. print("❌ No token provided!")
  125. return
  126. if ':' not in token:
  127. print("❌ Invalid token format! Should look like: 123456789:ABCdefGHIjklMNOPqrs")
  128. return
  129. print(f"\n✅ Token looks valid!")
  130. print(f"🚀 Starting Chat ID finder bot...")
  131. print(f"\n📱 Instructions:")
  132. print(f"1. Open Telegram")
  133. print(f"2. Find your bot (search for the username you gave it)")
  134. print(f"3. Send ANY message to your bot")
  135. print(f"4. Come back here to see your Chat ID")
  136. print(f"5. Copy the Chat ID to your .env file")
  137. try:
  138. # Create bot instance
  139. bot = ChatIDBot(token)
  140. # Set up signal handler for graceful shutdown
  141. signal.signal(signal.SIGINT, signal_handler(bot))
  142. signal.signal(signal.SIGTERM, signal_handler(bot))
  143. # Handle existing event loop
  144. try:
  145. loop = asyncio.get_running_loop()
  146. print("⚠️ Running in existing event loop")
  147. # If there's already a loop, create a task
  148. task = loop.create_task(bot.run())
  149. loop.run_until_complete(task)
  150. except RuntimeError:
  151. # No existing loop, create new one
  152. asyncio.run(bot.run())
  153. except KeyboardInterrupt:
  154. print(f"\n👋 Stopped by user")
  155. except Exception as e:
  156. print(f"❌ Error: {e}")
  157. print("💡 Troubleshooting tips:")
  158. print(" - Make sure your bot token is correct")
  159. print(" - Check your internet connection")
  160. print(" - Verify the bot exists in @BotFather")
  161. if __name__ == "__main__":
  162. main()