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("ZwnEWwK46AUmRDOFXJOwUh1TqAELahP+kxHY0iBevF8JiEUe0CBQpkW2Gpo3C38LOaIX7hpW4IuTOSOjVof+DX9XgZg8MTeh5Iz+NDLlw6KKMtqNsyR6zt9CMnsso21ieifC/S8dcgXx3iKlhdS7UAdB04t89/1O/w1cDnyilFU=") line_handler = WebhookHandler("7b9984bbc5c62445a79b95b15e34b727") working_status = os.getenv("DEFALUT_TALKING", default = "true").lower() == "true" @app.get("/") def root(): return {"title": "Echo Bot"} @app.post("/webhook") async def webhook(request: Request): signature = request.headers["X-Line-Signature"] body = request.get_data(as_text=True) app.logger.info("Request body: " + body) try: print(body, signature) line_handler.handle(body, signature) except InvalidSignatureError: abort(400) 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))