Mr-Help commited on
Commit
ea53751
·
verified ·
1 Parent(s): 485f33c

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +53 -13
main.py CHANGED
@@ -1,20 +1,60 @@
1
  # main.py
 
 
2
  from fastapi import FastAPI, Request
3
 
4
  app = FastAPI()
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  @app.post("/webhook")
7
  async def webhook(request: Request):
8
- # جرّب تقرأ البودي كـ JSON
9
- try:
10
- data = await request.json()
11
- except Exception:
12
- # لو مش JSON هنقراه كنص عادي
13
- data = await request.body()
14
- data = data.decode("utf-8")
15
-
16
- print("===== NEW REQUEST =====")
17
- print(data) # يطبع اللي وصله
18
- print("======================")
19
-
20
- return {"status": "ok", "received": data}
 
 
 
 
 
 
 
 
 
 
 
1
  # main.py
2
+ import os
3
+ import httpx
4
  from fastapi import FastAPI, Request
5
 
6
  app = FastAPI()
7
 
8
+ NOTION_SECRET = os.getenv("NOTION_SECRET") # ضع secret هنا أو كمتغير بيئة
9
+ NOTION_VERSION = "2022-06-28"
10
+
11
+
12
+ async def get_page_title(page_id: str) -> str:
13
+ """Fetch page title from Notion."""
14
+ async with httpx.AsyncClient() as client:
15
+ res = await client.get(
16
+ f"https://api.notion.com/v1/pages/{page_id}",
17
+ headers={
18
+ "Authorization": f"Bearer {NOTION_SECRET}",
19
+ "Notion-Version": NOTION_VERSION,
20
+ },
21
+ )
22
+
23
+ data = res.json()
24
+
25
+ # نجيب الـ Title من الـ property الخاص بالاسم
26
+ props = data.get("properties", {})
27
+ for prop in props.values():
28
+ if prop.get("type") == "title":
29
+ title_items = prop.get("title", [])
30
+ if len(title_items) > 0:
31
+ return title_items[0].get("plain_text", "")
32
+
33
+ return "(No Title)"
34
+
35
+
36
  @app.post("/webhook")
37
  async def webhook(request: Request):
38
+ body = await request.json()
39
+
40
+ event_type = body.get("type")
41
+ page_id = body.get("entity", {}).get("id")
42
+ timestamp = body.get("timestamp")
43
+
44
+ print("\n===== NEW WEBHOOK EVENT =====")
45
+
46
+ # لو الحدث page.created أو page.deleted
47
+ if event_type in ["page.created", "page.deleted"]:
48
+ title = await get_page_title(page_id)
49
+
50
+ print(f"Event Type : {event_type}")
51
+ print(f"Page Title : {title}")
52
+ print(f"Page ID : {page_id}")
53
+ print(f"Timestamp : {timestamp}")
54
+
55
+ else:
56
+ print("Event received but ignored:", event_type)
57
+
58
+ print("================================\n")
59
+
60
+ return {"status": "ok"}