Spaces:
Running
on
Zero
Running
on
Zero
File size: 3,391 Bytes
024edca b8c8e0a 024edca |
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 77 |
import os
import subprocess
import logging
from fastapi import FastAPI, Request, HTTPException
import requests
import json
from datetime import datetime
from mysite.utilities import validate_signature, no_process_file
logger = logging.getLogger(__name__)
def setup_webhook_routes(app: FastAPI):
@app.post("/webhook")
async def webhook(request: Request):
logger.info("[Start] ====== LINE webhook ======")
try:
body = await request.body()
received_headers = dict(request.headers)
body_str = body.decode("utf-8")
logger.info("Received Body: %s", body_str)
body_json = json.loads(body_str)
events = body_json.get("events", [])
for event in events:
if event["type"] == "message" and event["message"]["type"] == "text":
user_id = event["source"]["userId"]
text = event["message"]["text"]
logger.info("------------------------------------------")
logger.info(f"User ID: {user_id}, Text: {text}")
no_process_file(text, "ai")
for event in events:
if event["type"] == "message" and event["message"]["type"] == "text":
user_id = event["source"]["userId"]
text = event["message"]["text"]
logger.info(event)
logger.info(f"User ID: {user_id}, Text: {text}")
now = datetime.now().strftime("%Y%m%d%H%M%S")
title = text[:10]
user_id_with_timestamp = f"{now}_{title}_{user_id}"
no_process_file(text, user_id_with_timestamp)
logger.info("Received Headers: %s", received_headers)
logger.info("Received Body: %s", body.decode("utf-8"))
line_signature = received_headers.get("x-line-signature")
if not line_signature:
raise HTTPException(status_code=400, detail="X-Line-Signature header is missing.")
if not validate_signature(body.decode("utf-8"), line_signature, os.getenv("CHANNEL_SECRET")):
raise HTTPException(status_code=400, detail="Invalid signature.")
if not os.getenv("WEBHOOK_URL") or not os.getenv("WEBHOOK_URL").startswith("https://"):
raise HTTPException(status_code=400, detail="Invalid webhook URL")
headers = {
"Content-Type": "application/json",
"X-Line-Signature": line_signature,
"Authorization": f"Bearer {os.getenv('CHANNEL_ACCESS_TOKEN')}",
}
logger.info("Forwarding to URL: %s", os.getenv("WEBHOOK_URL"))
logger.info("Forwarding Headers: %s", headers)
logger.info("Forwarding Body: %s", body.decode("utf-8"))
response = requests.post(os.getenv("WEBHOOK_URL"), headers=headers, data=body)
logger.info("Response Code: %s", response.status_code)
logger.info("Response Content: %s", response.text)
logger.info("Response Headers: %s", response.headers)
return {"status": "success", "response_content": response.text}, response.status_code
except Exception as e:
logger.error("Error: %s", str(e))
raise HTTPException(status_code=500, detail=str(e))
|