#!/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"""
šÆ Chat ID Found!
š Chat ID: {chat_id}
š¤ User: {user.first_name} {user.last_name or ''}
š§ Username: @{user.username or 'None'}
ā
Add this to your .env file:
TELEGRAM_CHAT_ID={chat_id}
"""
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()