import asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

# توکن ربات شما
TOKEN = "8920884274:AAG8KoRyePTFfKSx6gtQMyz2JQfsEQ6jqdQ"

# پیام یا اوری که هر ۱۰ دقیقه ارسال می‌شود (می‌توانید تغییر دهید)
AD_MESSAGE = "استراحتت⭕"

async def check_admin(update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool:
    """بررسی می‌کند که آیا کاربری که دستور را داده در گروه ادمین است یا خیر"""
    if update.effective_chat.type == "private":
        # در چت خصوصی، هر کاربری اجازه استفاده دارد
        return True
        
    user_id = update.effective_user.id
    chat_id = update.effective_chat.id

    try:
        member = await context.bot.get_chat_member(chat_id, user_id)
        if member.status in ['administrator', 'creator']:
            return True
        else:
          
            return False
    except Exception as e:
        print(f"Error checking admin: {e}")
        return False

async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """شروع ارسال پیام‌های خودکار"""
    if not await check_admin(update, context):
        return

    chat_id = update.effective_chat.id
    job_name = f"ad_{chat_id}"
    
    current_jobs = context.job_queue.get_jobs_by_name(job_name)
    if current_jobs:
        await update.message.reply_text("✅ ربات از قبل در این گروه فعال است.")
        return

    # افزودن جاب جدید برای هر ۱۰ دقیقه (۶۰۰ ثانیه)
    context.job_queue.run_repeating(
        send_ad_message,
        interval=600, 
        first=1, # اولین پیام بلافاصله ارسال شود
        name=job_name,
        chat_id=chat_id
    )
    
    await update.message.reply_text("ربات فعال شد")

async def send_ad_message(context: ContextTypes.DEFAULT_TYPE):
    """تابع ارسال پیام دوره‌ای"""
    chat_id = context.job.chat_id
    await context.bot.send_message(chat_id=chat_id, text=AD_MESSAGE)

async def end_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """توقف ارسال پیام‌های خودکار"""
    if not await check_admin(update, context):
        return

    chat_id = update.effective_chat.id
    job_name = f"ad_{chat_id}"
    
    current_jobs = context.job_queue.get_jobs_by_name(job_name)
    if not current_jobs:
        await update.message.reply_text("⛔ ربات در حال حاضر در این گروه فعال نیست.")
        return

    for job in current_jobs:
        job.schedule_removal()
        
    await update.message.reply_text("🛑 ارسال پیام‌های خودکار متوقف شد.")

from telegram.request import HTTPXRequest

def main():
    """ساخت و راه‌اندازی ربات"""
    # افزایش زمان تایم‌اوت به ۶۰ ثانیه برای جلوگیری از قطع شدن در هاست اشتراکی
    request = HTTPXRequest(connect_timeout=60.0, read_timeout=60.0)
    
    # ساخت اپلیکیشن با تایم‌اوت جدید
    application = Application.builder().token(TOKEN).request(request).build()

    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("end", end_command))

    print("Bot is running...")
    # شروع ربات
    application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == '__main__':
    main()