Rolaficus commited on
Commit
73b8598
·
verified ·
1 Parent(s): 255fd45

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +15 -40
main.py CHANGED
@@ -1,10 +1,8 @@
1
  from fastapi import FastAPI, Request, Header, HTTPException
2
  from pydantic import BaseModel
3
  from typing import Optional, Any, Dict, List
4
- import httpx
5
  import os
6
- import socket
7
- from urllib.parse import urlparse
8
 
9
  app = FastAPI()
10
 
@@ -38,43 +36,22 @@ class HFPayload(BaseModel):
38
  webhook: Optional[Dict[str, Any]] = None
39
 
40
  @app.on_event("startup")
41
- async def startup_event():
42
- print("--- STARTUP DIAGNOSTICS ---")
43
- # 1. Check if Variable Exists
44
  if DISCORD_WEBHOOK_URL:
45
- # Mask the URL for safety in logs
46
  masked = DISCORD_WEBHOOK_URL[:8] + "..." + DISCORD_WEBHOOK_URL[-4:]
47
  print(f"INFO: Webhook URL loaded: {masked}")
48
-
49
- # 2. Extract Hostname
50
- try:
51
- parsed = urlparse(DISCORD_WEBHOOK_URL)
52
- hostname = parsed.hostname
53
- if not hostname:
54
- print("ERROR: Could not extract hostname from URL. Is the format 'https://...'?")
55
- else:
56
- print(f"DEBUG: Hostname extracted: '{hostname}'")
57
-
58
- # 3. Test DNS Resolution (The "Network Doctor")
59
- try:
60
- # Note: socket.gethostbyname is blocking, but okay for a quick startup check
61
- ip = socket.gethostbyname(hostname)
62
- print(f"SUCCESS: DNS resolved {hostname} to {ip}")
63
- except socket.gaierror as e:
64
- print(f"CRITICAL FAILURE: Could not resolve {hostname}. Error: {e}")
65
- print("-> This means the URL is wrong OR the container has no internet access.")
66
- except Exception as e:
67
- print(f"ERROR parsing URL: {e}")
68
  else:
69
  print("WARNING: No DISCORD_WEBHOOK_URL found. Discord messages will not be sent.")
70
- print("---------------------------")
71
 
72
  @app.get("/")
73
  def home():
74
  return {"status": "Webhook listener is running"}
75
 
 
 
76
  @app.post("/webhook")
77
- async def handle_webhook(
78
  payload: HFPayload,
79
  x_webhook_secret: Optional[str] = Header(None)
80
  ):
@@ -90,19 +67,17 @@ async def handle_webhook(
90
  if DISCORD_WEBHOOK_URL:
91
  print(f"Sending notification for {payload.repo.name}...")
92
  try:
93
- # Added a timeout to prevent hanging
94
- async with httpx.AsyncClient(timeout=10.0) as client:
95
- resp = await client.post(
96
- DISCORD_WEBHOOK_URL,
97
- json={"embeds": [embed]}
98
- )
99
- resp.raise_for_status()
100
- print(f"Sent to Discord: {resp.status_code}")
101
- except httpx.ConnectError as e:
102
- print(f"CONNECTION ERROR: Could not connect to Discord. Check DNS/Network. Details: {e}")
103
- return {"message": "Connection Failed", "error": str(e)}
104
  except Exception as e:
105
  print(f"ERROR connecting to Discord: {e}")
 
106
  return {"message": "Error sending to Discord", "error": str(e)}
107
 
108
  return {"message": "Processed"}
 
1
  from fastapi import FastAPI, Request, Header, HTTPException
2
  from pydantic import BaseModel
3
  from typing import Optional, Any, Dict, List
4
+ import requests
5
  import os
 
 
6
 
7
  app = FastAPI()
8
 
 
36
  webhook: Optional[Dict[str, Any]] = None
37
 
38
  @app.on_event("startup")
39
+ def startup_event():
40
+ # Simple check to see if the URL loaded correctly
 
41
  if DISCORD_WEBHOOK_URL:
 
42
  masked = DISCORD_WEBHOOK_URL[:8] + "..." + DISCORD_WEBHOOK_URL[-4:]
43
  print(f"INFO: Webhook URL loaded: {masked}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  else:
45
  print("WARNING: No DISCORD_WEBHOOK_URL found. Discord messages will not be sent.")
 
46
 
47
  @app.get("/")
48
  def home():
49
  return {"status": "Webhook listener is running"}
50
 
51
+ # CHANGED: 'async def' -> 'def'
52
+ # This tells FastAPI to run this in a threadpool so 'requests' doesn't block the server
53
  @app.post("/webhook")
54
+ def handle_webhook(
55
  payload: HFPayload,
56
  x_webhook_secret: Optional[str] = Header(None)
57
  ):
 
67
  if DISCORD_WEBHOOK_URL:
68
  print(f"Sending notification for {payload.repo.name}...")
69
  try:
70
+ # Using standard requests library
71
+ response = requests.post(
72
+ DISCORD_WEBHOOK_URL,
73
+ json={"embeds": [embed]},
74
+ timeout=10 # Good practice to prevent hanging forever
75
+ )
76
+ response.raise_for_status()
77
+ print(f"Sent to Discord: {response.status_code}")
 
 
 
78
  except Exception as e:
79
  print(f"ERROR connecting to Discord: {e}")
80
+ # We return 200 to HF so it stops retrying, but log the error
81
  return {"message": "Error sending to Discord", "error": str(e)}
82
 
83
  return {"message": "Processed"}