import os from dotenv import load_dotenv from pyrogram import Client, filters from flask import Flask, render_template_string, request, Response # Load environment variables from .env file load_dotenv() # Get the API ID, API Hash, and Chat ID from the .env file api_id = os.getenv("API_ID") api_hash = os.getenv("API_HASH") chat_id = int(os.getenv("CHAT_ID")) web_username = os.getenv("WEB_USERNAME") web_password = os.getenv("WEB_PASSWORD") # Create a Pyrogram Client app = Client("listen", api_id=api_id, api_hash=api_hash) # Create a Flask app flask_app = Flask(__name__) # Store messages in a list messages = [] # Define a message handler for the specific chat @app.on_message(filters.chat(chat_id)) def handle_message(client, message): # Check if the message contains the specific string if "[SIM2(Dhiraagu) Receive SMS]" in message.text: # Replace newlines with
tags for HTML rendering formatted_message = message.text.replace("\n", "
") # Add the formatted message to the list messages.append(formatted_message) # Keep only the last 50 messages (optional) if len(messages) > 50: messages.pop(0) # Basic authentication decorator def check_auth(username, password): return username == web_username and password == web_password def authenticate(): return Response( "Unauthorized. Please log in.", 401, {"WWW-Authenticate": 'Basic realm="Login Required"'} ) # Flask route to display messages @flask_app.route("/") def index(): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return render_template_string(""" Telegram Messages
{% for message in messages %}
{{ message | safe }}
{% endfor %}
""", messages=messages) # Run the Flask app and Pyrogram client if __name__ == "__main__": import threading # Start the Flask app in a separate thread flask_thread = threading.Thread(target=lambda: flask_app.run(host="0.0.0.0", port=5000)) flask_thread.daemon = True flask_thread.start() # Start the Pyrogram client print(f"Listening to chat ID {chat_id} and filtering for '[SIM2(Dhiraagu) Receive SMS]'...") app.run()