浏览代码

Fix Telegram Chat ID finder asyncio issues - Add robust event loop handling and alternative simple script

Carles Sentis 4 天之前
父节点
当前提交
a456b4a88a
共有 2 个文件被更改,包括 268 次插入38 次删除
  1. 111 38
      utils/get_telegram_chat_id.py
  2. 157 0
      utils/simple_chat_id.py

+ 111 - 38
utils/get_telegram_chat_id.py

@@ -8,6 +8,7 @@ This script helps you find your Telegram Chat ID for bot configuration.
 import sys
 import asyncio
 import logging
+import signal
 from pathlib import Path
 
 # Add src directory to Python path
@@ -21,8 +22,11 @@ except ImportError:
     print("💡 Run: pip install python-telegram-bot")
     sys.exit(1)
 
-# Set up logging
-logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
+# Set up logging to reduce noise
+logging.basicConfig(
+    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 
+    level=logging.WARNING  # Reduce log noise
+)
 logger = logging.getLogger(__name__)
 
 class ChatIDBot:
@@ -32,18 +36,20 @@ class ChatIDBot:
         self.token = token
         self.application = None
         self.found_chat_ids = set()
+        self.running = True
     
     async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
         """Handle any message and show chat information."""
-        chat_id = update.effective_chat.id
-        user = update.effective_user
-        message_text = update.message.text if update.message else "No text"
-        
-        # Store found chat ID
-        self.found_chat_ids.add(chat_id)
-        
-        # Respond with chat information
-        response = f"""
+        try:
+            chat_id = update.effective_chat.id
+            user = update.effective_user
+            message_text = update.message.text if update.message else "No text"
+            
+            # Store found chat ID
+            self.found_chat_ids.add(chat_id)
+            
+            # Respond with chat information
+            response = f"""
 🎯 <b>Found Your Chat Information!</b>
 
 🆔 <b>Chat ID:</b> <code>{chat_id}</code>
@@ -53,42 +59,88 @@ class ChatIDBot:
 
 ✅ <b>Copy this Chat ID to your .env file:</b>
 <code>TELEGRAM_CHAT_ID={chat_id}</code>
-        """
-        
-        await update.message.reply_text(response, parse_mode='HTML')
-        
-        # Print to console
-        print(f"\n🎉 SUCCESS! Found 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 this to your .env file:")
-        print(f"TELEGRAM_CHAT_ID={chat_id}")
-        print(f"\n✅ You can now stop this script and start your trading bot!")
+
+🛑 <b>Press Ctrl+C to stop this script</b>
+            """
+            
+            await update.message.reply_text(response.strip(), parse_mode='HTML')
+            
+            # Print to console
+            print(f"\n🎉 SUCCESS! Found 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 this to your .env file:")
+            print(f"TELEGRAM_CHAT_ID={chat_id}")
+            print(f"\n✅ You can now stop this script (Ctrl+C) and start your trading bot!")
+            print(f"💬 Or send another message to test again...")
+            
+        except Exception as e:
+            print(f"❌ Error handling message: {e}")
     
     async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
         """Handle the /start command."""
         await self.handle_message(update, context)
     
+    async def stop_bot(self):
+        """Gracefully stop the bot."""
+        if self.application:
+            try:
+                await self.application.stop()
+                await self.application.shutdown()
+            except Exception as e:
+                print(f"⚠️ Warning during shutdown: {e}")
+    
     async def run(self):
         """Run the Chat ID finder bot."""
-        self.application = Application.builder().token(self.token).build()
-        
-        # Add handlers for any message or /start command
-        self.application.add_handler(CommandHandler("start", self.start_command))
-        self.application.add_handler(MessageHandler(filters.ALL, self.handle_message))
-        
-        print("🤖 Chat ID finder bot is running...")
-        print("💬 Now go to Telegram and send ANY message to your bot")
-        print("🛑 Press Ctrl+C when done\n")
-        
         try:
-            await self.application.run_polling()
+            # Build application
+            self.application = Application.builder().token(self.token).build()
+            
+            # Add handlers for any message or /start command
+            self.application.add_handler(CommandHandler("start", self.start_command))
+            self.application.add_handler(MessageHandler(filters.ALL, self.handle_message))
+            
+            print("🤖 Chat ID finder bot is running...")
+            print("💬 Now go to Telegram and send ANY message to your bot")
+            print("🛑 Press Ctrl+C when done\n")
+            
+            # Initialize and run
+            await self.application.initialize()
+            await self.application.start()
+            await self.application.updater.start_polling()
+            
+            # Keep running until interrupted
+            while self.running:
+                await asyncio.sleep(1)
+                
         except KeyboardInterrupt:
-            print(f"\n👋 Chat ID finder stopped")
+            print(f"\n👋 Chat ID finder stopped by user")
+        except Exception as e:
+            print(f"\n❌ Error running bot: {e}")
+        finally:
+            # Cleanup
+            try:
+                if self.application:
+                    if self.application.updater.running:
+                        await self.application.updater.stop()
+                    await self.application.stop()
+                    await self.application.shutdown()
+            except Exception as e:
+                pass  # Ignore cleanup errors
+            
+            # Show results
             if self.found_chat_ids:
-                print(f"📋 Found Chat IDs: {', '.join(map(str, self.found_chat_ids))}")
+                print(f"\n📋 Found Chat IDs: {', '.join(map(str, self.found_chat_ids))}")
+                print(f"✅ Copy any of these Chat IDs to your .env file")
             else:
-                print("❌ No Chat IDs found - make sure you messaged your bot!")
+                print("\n❌ No Chat IDs found - make sure you messaged your bot!")
+
+def signal_handler(bot):
+    """Handle shutdown signals."""
+    def handler(signum, frame):
+        print(f"\n🛑 Received shutdown signal...")
+        bot.running = False
+    return handler
 
 def main():
     """Main function."""
@@ -115,11 +167,32 @@ def main():
     print(f"5. Copy the Chat ID to your .env file")
     
     try:
+        # Create bot instance
         bot = ChatIDBot(token)
-        asyncio.run(bot.run())
+        
+        # Set up signal handler for graceful shutdown
+        signal.signal(signal.SIGINT, signal_handler(bot))
+        signal.signal(signal.SIGTERM, signal_handler(bot))
+        
+        # Handle existing event loop
+        try:
+            loop = asyncio.get_running_loop()
+            print("⚠️ Running in existing event loop")
+            # If there's already a loop, create a task
+            task = loop.create_task(bot.run())
+            loop.run_until_complete(task)
+        except RuntimeError:
+            # No existing loop, create new one
+            asyncio.run(bot.run())
+            
+    except KeyboardInterrupt:
+        print(f"\n👋 Stopped by user")
     except Exception as e:
         print(f"❌ Error: {e}")
-        print("💡 Make sure your bot token is correct")
+        print("💡 Troubleshooting tips:")
+        print("  - Make sure your bot token is correct")
+        print("  - Check your internet connection")
+        print("  - Verify the bot exists in @BotFather")
 
 if __name__ == "__main__":
     main() 

+ 157 - 0
utils/simple_chat_id.py

@@ -0,0 +1,157 @@
+#!/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()