alanchen1115 commited on
Commit
3a2e91a
1 Parent(s): f52fad2

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +35 -14
main.py CHANGED
@@ -1,17 +1,38 @@
1
  from fastapi import FastAPI
2
- from fastapi.middleware.cors import CORSMiddleware
3
-
 
 
 
 
4
  app = FastAPI()
5
-
6
- app.add_middleware(
7
- CORSMiddleware,
8
- allow_origins=['*']
9
- )
10
-
11
  @app.get("/")
12
- def read_root():
13
- return {"message": "Hello World"}
14
-
15
- @app.get("/api/python")
16
- def hello_python():
17
- return {"message": "Hello Python"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI
2
+ from linebot import LineBotApi, WebhookHandler
3
+ from linebot.exceptions import InvalidSignatureError
4
+ from linebot.models import MessageEvent, TextMessage
5
+ from starlette.exceptions import HTTPException
6
+ import os
7
+
8
  app = FastAPI()
9
+ line_bot_api = LineBotApi(os.environ["LINE_CHANNEL_ACCESS_TOKEN"])
10
+ handler = WebhookHandler(os.environ["LINE_CHANNEL_SECRET"])
11
+
 
 
 
12
  @app.get("/")
13
+ def root():
14
+ return {"title": "Echo Bot"}
15
+
16
+ @app.post("/callback")
17
+ async def callback(
18
+ request: Request,
19
+ background_tasks: BackgroundTasks,
20
+ x_line_signature=Header(None),
21
+ ):
22
+ body = await request.body()
23
+
24
+ try:
25
+ background_tasks.add_task(
26
+ handler.handle, body.decode("utf-8"), x_line_signature
27
+ )
28
+ except InvalidSignatureError:
29
+ raise HTTPException(status_code=400, detail="Invalid signature")
30
+
31
+ return "ok"
32
+
33
+ @handler.add(MessageEvent)
34
+ def handle_message(event):
35
+ if event.type != "message" or event.message.type != "text":
36
+ return
37
+ message = TextMessage(text=event.message.text)
38
+ line_bot_api.reply_message(event.reply_token, message)