CCCPaste

main.py

#!/usr/bin/env python3
# main.py - API Scan & Auto Connect Dual Bot
import time
import requests
from dual import DualBot
from prompt import debug_prompt, status_prompt

def scan_apis():
    """Scan semua API keys dan test functionality"""
    print("๐Ÿ” Scanning API Keys...")

    apis_to_test = [
        {
            "name": "Groq",
            "key": "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",
            "url": "https://api.groq.com/openai/v1/chat/completions",
            "method": "groq"
        },
        {
            "name": "DeepSeek", 
            "key": "sk-018cc05d3a574de68947e669673fdf65",
            "url": "https://api.deepseek.com/chat/completions",
            "method": "deepseek"
        },
        {
            "name": "Gemini",
            "key": "AIzaSyDVoBSniv6CtvNZDPxvPNRPfRXWvj3304M",
            "url": "https://generativelanguage.googleapis.com/v1/models/gemini-2.0-flash:generateContent",
            "method": "gemini"
        }
    ]

    working_apis = []

    for api in apis_to_test:
        print(f"๐Ÿงช Testing {api['name']}...")
        try:
            if test_api(api):
                print(f"โœ… {api['name']} - WORKING")
                working_apis.append(api['name'])
            else:
                print(f"โŒ {api['name']} - FAILED")
        except Exception as e:
            print(f"โŒ {api['name']} - ERROR: {e}")

    return working_apis

def test_api(api):
    """Test individual API"""
    test_prompt = "Hai! Beri salam pendek dalam Bahasa Malaysia."

    try:
        if api['method'] == 'groq':
            headers = {"Authorization": f"Bearer {api['key']}"}
            data = {
                "model": "llama-3.1-8b-instant",
                "messages": [{"role": "user", "content": test_prompt}],
                "max_tokens": 50
            }
            response = requests.post(api['url'], headers=headers, json=data, timeout=10)
            return response.status_code == 200

        elif api['method'] == 'deepseek':
            headers = {"Authorization": f"Bearer {api['key']}"}
            data = {
                "model": "deepseek-chat",
                "messages": [{"role": "user", "content": test_prompt}],
                "max_tokens": 50
            }
            response = requests.post(api['url'], headers=headers, json=data, timeout=10)
            return response.status_code == 200

        elif api['method'] == 'gemini':
            url = f"{api['url']}?key={api['key']}"
            data = {"contents": [{"parts": [{"text": test_prompt}]}]}
            response = requests.post(url, json=data, timeout=10)
            return response.status_code == 200

    except:
        return False

def start_system():
    """Start system dengan timing adjustment"""
    print(status_prompt("SYSTEM", "Starting Dual Bot System..."))

    # FASA 1: API Testing dengan TIMEOUT AWARENESS
    print(debug_prompt("Phase 1: Quick API Scan"))
    start_scan_time = time.time()

    working_apis = scan_apis()
    scan_duration = time.time() - start_scan_time

    print(debug_prompt(f"API scan took {scan_duration:.1f}s"))

    # Adjust connection timeout based on scan time
    remaining_time = 25 - scan_duration  # 25s total allocation
    if remaining_time < 10:
        print(debug_prompt(f"โš ๏ธ Low time remaining: {remaining_time:.1f}s"))

    if not working_apis:
        print("โš ๏ธ Some APIs failed, but continuing with available ones...")

    # FASA 2: Auto Connect dengan adjusted timing
    print(debug_prompt("Phase 2: Auto Connecting Dual Bot"))
    dual_bot = DualBot()

    # ๐Ÿ†• SET CONNECTION TIMEOUT based on remaining time
    min_timeout = max(15, remaining_time - 5)  # Minimum 15s, keep 5s buffer
    print(debug_prompt(f"Set connection timeout: {min_timeout}s"))

    return dual_bot.start()

def main():
    print(status_prompt("SYSTEM", "Starting API Scan & Auto Connect..."))

    # FASA 1: Scan API Keys
    print(debug_prompt("Phase 1: Scanning APIs"))
    working_apis = scan_apis()

    if not working_apis:
        print("โŒ CRITICAL: No working APIs found!")
        return

    print(status_prompt("API", f"Working: {', '.join(working_apis)}"))

    # FASA 2: Auto Connect Dual Bot
    print(debug_prompt("Phase 2: Auto Connecting Dual Bot"))
    bot = DualBot()

    try:
        if bot.start():
            print(status_prompt("SYSTEM", "โœ… Dual Bot Connected & Running!"))
            print(debug_prompt("Press Ctrl+C to stop"))

            # Monitor loop
            while bot.is_running():
                time.sleep(10)
        else:
            print(status_prompt("SYSTEM", "โŒ Dual Bot failed to connect"))

    except KeyboardInterrupt:
        print(status_prompt("SYSTEM", "Shutdown requested..."))
        bot.stop()
    except Exception as e:
        print(debug_prompt(f"System error: {e}"))
        bot.stop()

if __name__ == "__main__":
    main()