File size: 1,571 Bytes
55b1be9
cca3a00
55b1be9
2cf7795
 
 
76eaf5a
 
 
 
 
 
 
 
 
55b1be9
 
 
 
 
d476587
55b1be9
 
 
 
a444b94
 
9a45992
b03572e
2cf7795
55b1be9
6482098
55b1be9
2cf7795
6482098
0a52d39
 
3a2e91a
519fee6
3a2e91a
0a52d39
4a7f8d2
2cf7795
4a7f8d2
3a2e91a
4a7f8d2
2cf7795
4a7f8d2
 
 
 
 
3a2e91a
4a7f8d2
 
0ea605e
4a7f8d2
 
 
 
55b1be9
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
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, Request,  Header

import json
import os

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, ImageSendMessage, AudioMessage
)

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

line_bot_api = LineBotApi(os.environ["line_bot_api"])
line_handler = WebhookHandler(os.environ["line_handler"])

working_status = 'True'

@app.get("/")
def root():
     return {"title": "Echo Bot"}

@app.post("/webhook")
async def webhook(request: Request, x_line_signature: str = Header(None)):
    body = await request.body()
    try:
        line_handler.handle(body.decode("utf-8"), x_line_signature)
    except InvalidSignatureError:
        raise HTTPException(status_code=400, detail="chatbot handle body error.")
    return 'OK'

@line_handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    global working_status

    if event.message.text == "再見":
        working_status = True
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="Bye!"))
        return

    if working_status:
        out = event.message.text
        if not out:
            out = "不懂您的意思!"
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=out))