File size: 3,472 Bytes
c5c98b4
9c0494a
 
 
 
 
c5c98b4
9c0494a
 
 
 
 
c5c98b4
 
d8d8775
 
 
c5c98b4
 
 
 
 
d8d8775
9c0494a
 
c5c98b4
9c0494a
d8d8775
c5c98b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8d8775
 
 
 
9c0494a
c5c98b4
 
 
 
 
 
 
 
 
d8d8775
 
 
 
 
 
 
 
 
 
 
 
 
c5c98b4
9c0494a
 
d8d8775
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
import requests
import gradio as gr
from huggingface_hub import WebhooksServer

with gr.Blocks() as ui:
    gr.Markdown("# πŸš€ Webhook Translator is Running (Secure Mode)!")

app = WebhooksServer(ui=ui)

@app.add_webhook("/discord")
async def forward_to_discord(payload: dict):
    print("--- NEW WEBHOOK RECEIVED ---")
    
    # 1. Securely grab the URL and clean it (removes invisible spaces and fixes capital 'Https')
    raw_url = os.environ.get("DISCORD_WEBHOOK_URL", "")
    discord_url = raw_url.strip().replace("Https://", "https://")
    
    if not discord_url:
        print("ERROR: Could not find DISCORD_WEBHOOK_URL in Space Secrets.")
        return {"status": "Error"}

    # 2. Extract the data
    repo_name = payload.get("repo", {}).get("name", "Unknown Repo")
    action = payload.get("event", {}).get("action", "updated")
    scope = payload.get("event", {}).get("scope", "repo")
    
    # 3. Format the message
    if scope == "discussion.comment":
        discussion_title = payload.get("discussion", {}).get("title", "a discussion")
        comment = payload.get("comment", {}).get("content", "")
        url = payload.get("comment", {}).get("url", {}).get("web", f"https://huggingface.co/{repo_name}")
        message = f"πŸ’¬ **New Comment on `{repo_name}`**\n**Thread:** {discussion_title}\n> {comment}\nπŸ”— {url}"
    elif scope == "discussion":
        discussion_title = payload.get("discussion", {}).get("title", "a discussion")
        url = payload.get("discussion", {}).get("url", {}).get("web", f"https://huggingface.co/{repo_name}")
        message = f"πŸ“’ **New Discussion in `{repo_name}`**\n**Thread:** {discussion_title}\nπŸ”— {url}"
    else:
        repo_type = payload.get("repo", {}).get("type", "model")
        url = payload.get("repo", {}).get("url", {}).get("web", f"https://huggingface.co/{repo_name}")
        message = f"πŸš€ **Hugging Face Alert:** The {repo_type} `{repo_name}` was just **{action}**.\nπŸ”— {url}"

    discord_message = {"content": message}
    print("Attempting to send message to Discord...")
    
    # 4. Send the message with a fallback mechanism
    headers = {"User-Agent": "HuggingFace-Webhook-Catcher/1.0", "Content-Type": "application/json"}
    
    try:
        response = requests.post(discord_url, json=discord_message, headers=headers)
        if response.status_code in [200, 204]:
            print("SUCCESS! Message sent to Discord.")
        else:
            print(f"ERROR! Discord rejected it. Reason: {response.text}")
            
    except Exception as e:
        print(f"CRASH: Failed to connect to Discord: {e}")
        # If HF blocks the DNS resolution, try Discord's legacy API domain
        if "NameResolutionError" in str(e):
            print("Attempting fallback to discordapp.com...")
            fallback_url = discord_url.replace("discord.com", "discordapp.com")
            try:
                fallback_response = requests.post(fallback_url, json=discord_message, headers=headers)
                if fallback_response.status_code in [200, 204]:
                     print("SUCCESS using fallback URL!")
                else:
                     print(f"Fallback failed. Reason: {fallback_response.text}")
            except Exception as e2:
                print(f"Fallback also failed: {e2}")

    return {"status": "Processed"}

if __name__ == "__main__":
    # Disable SSR to fix the 405 Method Not Allowed error
    app.launch(ssr_mode=False)