# catch_once_cooldown_per_channel.py
import re
import time
import asyncio
from datetime import datetime
from collections import defaultdict
from discord.ext import commands

# === Konfigurasi ===
DISCORD_USER_TOKEN = "Njc2Nzg1NDg3ODI1ODYyNjY3.G7kDqn.zyXtGWvfUtd4uMCs6hp6h_n0OFX8FTmzUJVGxw"   # <-- ganti dengan token (jaga kerahasiaan)
CHANNEL_IDS = [
    1376397525631897742,  # frostyfyo
    1399043503996010619,  # ameame
    1177938259305844766,
]
COOLDOWN_SECONDS = 300  # cooldown per channel (detik)
IGNORE_BOTS = False     # True = abaikan pesan dari akun bot lain

# === Inisialisasi client (legacy selfbot style) ===
client = commands.Bot(command_prefix="!", self_bot=True)

# state per channel
last_triggered = {}                # channel_id -> last_trigger_time (float seconds)
channel_locks = {}                 # channel_id -> asyncio.Lock()

# precompile regex
CATCH_RE = re.compile(r'catch', re.IGNORECASE)

def get_channel_lock(channel_id):
    """Ambil atau buat lock untuk channel tertentu"""
    lock = channel_locks.get(channel_id)
    if lock is None:
        lock = asyncio.Lock()
        channel_locks[channel_id] = lock
    return lock

@client.event
async def on_ready():
    print(f"[✅] Logged in as {client.user}")
    print(f"📡 Monitoring {len(CHANNEL_IDS)} channel untuk kata 'catch'...")

@client.event
async def on_message(message):
    # abaikan pesan sendiri
    if message.author == client.user:
        return

    # opsional: abaikan pesan dari bot
    if IGNORE_BOTS and getattr(message.author, "bot", False):
        return

    # hanya proses channel yang ada di daftar
    ch_id = getattr(message.channel, "id", None)
    if ch_id not in CHANNEL_IDS:
        return

    content = (message.content or "")
    if not content:
        return

    # deteksi "catch" di mana saja dalam pesan
    if not CATCH_RE.search(content):
        return

    # gunakan lock per-channel untuk menghindari race condition
    lock = get_channel_lock(ch_id)
    async with lock:
        now = time.time()
        last = last_triggered.get(ch_id, 0)
        if (now - last) < COOLDOWN_SECONDS:
            # masih di cooldown untuk channel ini — abaikan
            print(f"[{datetime.now()}] ⏳ Cooldown aktif di channel {ch_id}, lewati...")
            return

        # set last_triggered lebih dulu agar flood tidak menyebabkan multi-responses
        last_triggered[ch_id] = now

    # di luar lock: kirim satu kali "catch"
    try:
        await message.channel.send("catch")
        print(f"[{datetime.now()}] ✅ Terdeteksi 'catch' di channel {ch_id} → dikirim 1x")
    except Exception as e:
        print(f"[{datetime.now()}] ❌ Gagal kirim 'catch' di {ch_id}: {e}")

if __name__ == "__main__":
    client.run(DISCORD_USER_TOKEN)
