from requests.auth import HTTPBasicAuth
import requests

# بيانات المصادقة لموقع WordPress
username = "cazanova97"  # اسم المستخدم
app_password = "JgP8 aFHe Nhtd oCuG Kx4p FvDQ"  # كلمة مرور التطبيق
wordpress_url = "https://sports-10.com/wp-json/wp/v2/posts"  # رابط API المنشورات
categories_url = "https://sports-10.com/wp-json/wp/v2/categories"  # رابط API الفئات

# الأخبار المدخلة يدويًا
news_items = [
    "Wednesday, January 1 2025 - 20:00 UTC (SOCCER England Championship) Sunderland - Sheffield United https://www.voodc.cfd/p/voodc37-embed.html?id=969b059db19b95089800949b009e099e96"
]

# مفاتيح Google API
api_keys = ["AIzaSyAdoVtZzz2sbLvihRWANthGPF-If50eKRc"]
cse_id = "539d3fa8fb15f4b6a"

# وظيفة لاستخراج العنوان بعد القوس `)`
def extract_title(text):
    try:
        if ")" in text:
            title = text.split(")")[-1].strip()
            title = " ".join(word for word in title.split() if not word.startswith("http"))
            return title
        return text.strip()
    except Exception as e:
        print(f"Error extracting title: {e}")
        return "Untitled"

# وظيفة لاستخراج الرابط من النص الكامل
def extract_link(text):
    try:
        words = text.split()
        for word in words:
            if word.startswith("http"):
                return word
        return None
    except Exception as e:
        print(f"Error extracting link: {e}")
        return None

# وظيفة لتوليد نصوص إضافية بناءً على العنوان
def generate_additional_content(title):
    try:
        return f"""
        The match "{title}" promises to be an exciting event as two talented players face off in a thrilling showdown. 
        Fans around the world are eagerly waiting to see the outcome of this intense competition. 
        Stay updated with all the latest developments and results from this match and others happening around the globe.
        """
    except Exception as e:
        print(f"Error generating additional content: {e}")
        return ""

# وظيفة لتحسين عنوان الـ SEO
def generate_seo_title(title):
    return title

# وظيفة لإنشاء وصف ميتا
def generate_meta_description(title):
    return f"The exciting match between {title}. Stay updated with live scores, highlights, and expert analysis on Sports 10."

# وظيفة لتحديد الكلمات المفتاحية
def generate_keywords(title):
    return [word for word in title.split() if len(word) > 3]

# وظيفة لتحديد ID الفئة أو إنشائها إذا لم تكن موجودة
def get_or_create_category(name):
    try:
        response = requests.get(categories_url, params={"search": name}, auth=HTTPBasicAuth(username, app_password))
        if response.status_code == 200 and response.json():
            return response.json()[0]["id"]

        data = {"name": name}
        response = requests.post(categories_url, json=data, auth=HTTPBasicAuth(username, app_password))
        if response.status_code == 201:
            return response.json()["id"]
        else:
            print(f"Failed to create category '{name}': {response.status_code}, {response.text}")
            return None
    except Exception as e:
        print(f"Error getting or creating category: {e}")
        return None

# وظيفة استخراج اسم الرياضة من النص
def extract_sport_name(text):
    if "TENNIS" in text:
        return "Tennis"
    elif "FOOTBALL" in text:
        return "Football"
    elif "BASKETBALL" in text:
        return "Basketball"
    elif "CRICKET" in text:
        return "Cricket"
    elif "Mixed" in text:
        return "Mixed Sports"
    else:
        return "General Sports"

# وظيفة لجلب رابط الصورة
def get_image_link(title):
    for api_key in api_keys:
        try:
            url = f"https://www.googleapis.com/customsearch/v1?q={title}+image&key={api_key}&cx={cse_id}&searchType=image&num=1"
            response = requests.get(url)
            response.raise_for_status()
            results = response.json()
            if "items" in results and len(results["items"]) > 0:
                return results["items"][0]["link"]
        except Exception as e:
            print(f"API Key {api_key} failed: {e}")
    return None

# وظيفة لإضافة روابط ذات صلة
def get_related_links(title):
    for api_key in api_keys:
        try:
            url = f"https://www.googleapis.com/customsearch/v1?q={title}+site:example.com&key={api_key}&cx={cse_id}&num=3"
            response = requests.get(url)
            response.raise_for_status()
            results = response.json()
            links = []
            if "items" in results:
                for item in results["items"]:
                    links.append(f'<a href="{item["link"]}" target="_blank">{item["title"]}</a>')
            return links
        except Exception as e:
            print(f"API Key {api_key} failed: {e}")
    return []

# وظيفة نشر الخبر على WordPress
def create_post(title, content, category_name, seo_title, meta_description, keywords):
    try:
        headers = {
            "Content-Type": "application/json"
        }

        category_id = get_or_create_category(category_name)
        if not category_id:
            print(f"Skipping post '{title}': Failed to assign category '{category_name}'")
            return

        data = {
            "title": seo_title,                 # عنوان المنشور
            "content": content,                 # المحتوى
            "status": "draft",                  # حفظ المنشور كمسودة
            "categories": [category_id],
            "meta": {
                "description": meta_description,
                "keywords": ", ".join(keywords)
            }
        }

        response = requests.post(wordpress_url, json=data, auth=HTTPBasicAuth(username, app_password), headers=headers)
        if response.status_code == 201:
            print(f"Post '{seo_title}' created successfully: ID {response.json()['id']}")
        else:
            print(f"Failed to create post '{seo_title}': {response.status_code}, {response.text}")
    except Exception as e:
        print(f"Error creating post: {e}")

# دمج الخطوات
def main():
    if not news_items:
        print("No news to post.")
        return

    for item in news_items:
        title = extract_title(item)
        link = extract_link(item)
        if not link:
            print(f"Skipping item: No link found in '{item}'")
            continue

        additional_content = generate_additional_content(title)
        seo_title = generate_seo_title(title)
        meta_description = generate_meta_description(title)
        keywords = generate_keywords(title)

        content = f"""
        <p>{item.split(link)[0].strip()}</p>
        <iframe src="https://href.li/?{link}" width="100%" height="415" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" sandbox="allow-same-origin allow-scripts allow-forms" allowfullscreen="allowfullscreen"></iframe>
        <h2>Additional Information</h2>
        <p>{additional_content}</p>
        """

        image_link = get_image_link(title)
        if image_link:
            content += f'<img src="{image_link}" alt="{title}" width="100%" style="margin: 20px 0;">'

        related_links = get_related_links(title)
        if related_links:
            content += "<h3>Related Matches:</h3>"
            content += "<ul>" + "".join([f"<li>{link}</li>" for link in related_links]) + "</ul>"

        sport_name = extract_sport_name(item)

        create_post(title, content, sport_name, seo_title, meta_description, keywords)

if __name__ == "__main__":
    main()
 قوم بتطوير هذا الكود