Hongrulee commited on
Commit
3e837a6
1 Parent(s): e2cc78c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, HTTPException
2
+ from linebot import LineBotApi, WebhookHandler
3
+ from linebot.exceptions import InvalidSignatureError
4
+ from linebot.models import MessageEvent, TextMessage, TextSendMessage
5
+
6
+ import os
7
+
8
+ # 設定 LINE Channel Access Token 和 Channel Secret
9
+ LINE_CHANNEL_ACCESS_TOKEN = os.getenv("LINE_CHANNEL_ACCESS_TOKEN")
10
+ LINE_CHANNEL_SECRET = os.getenv("LINE_CHANNEL_SECRET")
11
+
12
+ line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
13
+ handler = WebhookHandler(LINE_CHANNEL_SECRET)
14
+
15
+ app = FastAPI()
16
+
17
+ # Webhook endpoint for LINE messages
18
+ @app.post("/callback")
19
+ async def callback(request: Request):
20
+ signature = request.headers['X-Line-Signature']
21
+ body = await request.body()
22
+
23
+ try:
24
+ handler.handle(body.decode('utf-8'), signature)
25
+ except InvalidSignatureError:
26
+ raise HTTPException(status_code=400, detail="Invalid signature")
27
+
28
+ return 'OK'
29
+
30
+ # 處理文字訊息的事件
31
+ @handler.add(MessageEvent, message=TextMessage)
32
+ def handle_text_message(event):
33
+ # 回應同樣的訊息給使用者
34
+ reply_text = event.message.text
35
+ line_bot_api.reply_message(
36
+ event.reply_token,
37
+ TextSendMessage(text=reply_text)
38
+ )
39
+
40
+ if __name__ == "__main__":
41
+ import uvicorn
42
+ uvicorn.run(app, host="0.0.0.0", port=8000)