import os
from dotenv import load_dotenv
from pyrogram import Client, filters
from flask import Flask, render_template_string, request, Response
from datetime import datetime
# 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:
        # Format the received time
        received_time = message.date.strftime("%Y-%m-%d %H:%M:%S")
        # Replace newlines with 
 tags for HTML rendering
        formatted_message = message.text.replace("\n", "
")
        # Add the formatted message and received time to the list
        messages.append({
            "text": formatted_message,
            "time": received_time
        })
        # 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("""