# import asyncio
# import json
# from telethon import TelegramClient, functions

# api_id = 33743429
# api_hash = "5478d12b3b6f77ff7dc71bf02ef5f9b2"

# SESSION_NAME = "selfbot_session"
# STATE_FILE = "state.json"

# client = TelegramClient(SESSION_NAME, api_id, api_hash)

# # ---------- Load / Save State ----------
# def load_state():
#     try:
#         with open(STATE_FILE, "r") as f:
#             return json.load(f)
#     except:
#         return {}

# def save_state(state):
#     with open(STATE_FILE, "w") as f:
#         json.dump(state, f, indent=4)

# # ---------- Market Scan ----------
# async def scan_market():
#     state = load_state()
#     mode = state.get("mode", 0)

#     # اسکن مارکت
#     result = await client(functions.payments.GetStarGiftsRequest(hash=0))

#     # -------- MODE 1: New Gifts --------
#     if mode == 1:
#         known = set(state.get("last_seen", []))
#         current = []
#         new_gifts = []

#         for g in result.gifts:
#             gid = str(g.id)
#             current.append(gid)
#             if gid not in known:
#                 new_gifts.append({"id": gid, "stars": g.stars})

#         if new_gifts:
#             state["new_gifts"] = new_gifts  # ← ربات رسمی اینو میخونه و پیام میده

#         state["last_seen"] = current
#         save_state(state)

#     # -------- MODE 2: Price / Spec --------
#     elif mode == 2:
#         gift_id = state.get("gift_id")
#         watch_price = state.get("watch_gift")  # اگر کاربر دنبال قیمت خاص بود

#         for g in result.gifts:
#             if str(g.id) == str(gift_id):
#                 # ذخیره اطلاعات گیفت
#                 state["found"] = {
#                     "id": g.id,
#                     "stars": g.stars,
#                     "sold_out": g.sold_out
#                 }

#                 # اگر دنبال قیمت بود و قیمت مناسب بود، mark کن
#                 if watch_price and g.stars <= watch_price:
#                     state["new_gifts"] = [{"id": g.id, "stars": g.stars}]

#                 save_state(state)
#                 break

#     # -------- MODE 3: Auto Buy --------
#     elif mode == 3:
#         buy = state.get("buy")
#         if buy:
#             for g in result.gifts:
#                 if buy["min"] <= g.stars <= buy["max"]:
#                     # خرید خودکار انجام می‌شود
#                     state["bought"] = {
#                         "id": g.id,
#                         "price": g.stars
#                     }
#                     # بعد از خرید، حالت را صفر می‌کنیم
#                     state["mode"] = 0
#                     save_state(state)
#                     break

# # ---------- Main Loop ----------
# async def main():
#     await client.start()
#     print("👁 Selfbot running and scanning Telegram Gift Market...")

#     while True:
#         await scan_market()
#         await asyncio.sleep(180)  # هر 3 دقیقه

# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())

# import asyncio
# import json
# import os
# import requests
# from telethon import TelegramClient, functions

# # ---------- CONFIG ----------
# api_id = 33743429
# api_hash = "5478d12b3b6f77ff7dc71bf02ef5f9b2"
# SESSION_NAME = "selfbot_session"
# STATE_FILE = "state.json"

# CONTROL_BOT_TOKEN = "PUT_YOUR_TOKEN"
# CONTROL_BOT_CHAT_ID = 5090980892

# MIN_STARS = 125

# client = TelegramClient(SESSION_NAME, api_id, api_hash)

# # ---------- STATE ----------
# def load_state():
#     try:
#         with open(STATE_FILE, "r") as f:
#             return json.load(f)
#     except:
#         return {
#             "active_mode": None,
#             "mode_data": {},
#             "last_seen": []
#         }

# def save_state(state):
#     with open(STATE_FILE, "w") as f:
#         json.dump(state, f, indent=4)

# # ---------- SEND TO CONTROL BOT ----------
# def notify_control_bot(text):
#     try:
#         url = "https://api.telegram.org/bot{}/sendMessage".format(CONTROL_BOT_TOKEN)
#         requests.post(url, data={
#             "chat_id": CONTROL_BOT_CHAT_ID,
#             "text": text
#         }, timeout=10)
#     except Exception as e:
#         print("Notify error:", e)

# # ---------- SCAN MARKET ----------
# async def scan_market():
#     state = load_state()
#     mode = state.get("active_mode")

#     if not mode:
#         return

#     try:
#         result = await client(functions.payments.GetStarGiftsRequest(hash=0))
#     except Exception as e:
#         print("API error:", e)
#         return

#     known = set(state.get("last_seen", []))
#     current_ids = []

#     for g in result.gifts:
#         gid = str(g.id)
#         current_ids.append(gid)

#         # فیلتر قیمت
#         if g.stars < MIN_STARS:
#             continue

#         # لینک واقعی
#         link = "https://t.me/nft/{}".format(gid)

#         text = (
#             "🎁 Gift Found\n"
#             "ID: {}\n"
#             "Stars: {}\n"
#             "Limited: {}\n"
#             "Sold out: {}\n"
#             "Link: {}"
#         ).format(gid, g.stars, g.limited, g.sold_out, link)

#         # ===== مود گیفت جدید =====
#         if mode == 1 and gid not in known:
#             notify_control_bot(text)

#         # ===== مود واچ =====
#         elif mode == 2:
#             watch_id = state.get("mode_data", {}).get("gift_id")
#             if watch_id and watch_id == gid:
#                 notify_control_bot(text)

#         # ===== مود خرید =====
#         elif mode == 3:
#             buy = state.get("mode_data", {}).get("buy")
#             if buy:
#                 if buy.get("min", 0) <= g.stars <= buy.get("max", 999999):
#                     notify_control_bot("🛒 AUTO BUY\n" + text)
#                     state["active_mode"] = None
#                     save_state(state)
#                     break

#     state["last_seen"] = current_ids
#     save_state(state)

# # ---------- MAIN ----------
# async def main():
#     await client.start()
#     print("👁 Selfbot running...")

#     while True:
#         try:
#             await scan_market()
#         except Exception as e:
#             print("⚠️ Loop error:", e)

#         await asyncio.sleep(30)  # برای Python 3.6 پایدار

# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
import asyncio
import json
import requests
from telethon import TelegramClient, functions

# ---------- CONFIG ----------
api_id = 33743429
api_hash = "5478d12b3b6f77ff7dc71bf02ef5f9b2"
SESSION_NAME = "selfbot_session"
STATE_FILE = "state.json"

CONTROL_BOT_TOKEN = "8541007672:AAHzuYtlbV4XtHvsd8RiucV4zDbywMQWE8k"
CONTROL_BOT_CHAT_ID = 5090980892

MIN_STARS = 125

client = TelegramClient(SESSION_NAME, api_id, api_hash)

# ---------- STATE ----------
def load_state():
    try:
        with open(STATE_FILE, "r") as f:
            return json.load(f)
    except:
        return {"active_mode": None, "mode_data": {}, "last_seen": []}

def save_state(state):
    with open(STATE_FILE, "w") as f:
        json.dump(state, f, indent=4)

# ---------- SEND TO CONTROL BOT ----------
def notify_control_bot(text):
    try:
        url = f"https://api.telegram.org/bot{CONTROL_BOT_TOKEN}/sendMessage"
        requests.post(url, data={"chat_id": CONTROL_BOT_CHAT_ID, "text": text}, timeout=10)
    except Exception as e:
        print("Notify error:", e)

# ---------- SCAN MARKET ----------
async def scan_market():
    state = load_state()
    mode = state.get("active_mode")

    if not mode:
        return

    try:
        result = await client(functions.payments.GetStarGiftsRequest(hash=0))
    except Exception as e:
        print("API error:", e)
        return

    known = set(state.get("last_seen", []))
    current_ids = []

    for g in result.gifts:
        gid = str(g.id)
        current_ids.append(gid)

        if g.stars < MIN_STARS:
            continue

        link = f"https://t.me/nft/{gid}"  # لینک واقعی گیفت

        text = f"🎁 Gift Found\nID: {gid}\nStars: {g.stars}\nLimited: {g.limited}\nSold out: {g.sold_out}\nLink: {link}"

        # ===== مود گیفت جدید =====
        if mode == "new_gift" and gid not in known:
            notify_control_bot(text)

        # ===== مود واچ =====
        elif mode == "watch_gift":
            watch_id = state.get("mode_data", {}).get("gift_id")
            if watch_id and watch_id == gid:
                notify_control_bot(text)

        # ===== مود خرید خودکار =====
        elif mode == "auto_buy":
            buy = state.get("mode_data", {}).get("buy")
            if buy and buy.get("min", 0) <= g.stars <= buy.get("max", 999999):
                notify_control_bot("🛒 AUTO BUY\n" + text)
                state["active_mode"] = None
                save_state(state)
                break

    state["last_seen"] = current_ids
    save_state(state)

# ---------- MAIN ----------
async def main():
    await client.start()
    print("👁 Selfbot running...")

    while True:
        try:
            await scan_market()
        except Exception as e:
            print("⚠️ Loop error:", e)
        await asyncio.sleep(30)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
