Spaces:
Running
Running
from fastapi.middleware.cors import CORSMiddleware | |
from fastapi import FastAPI, Request, Header, HTTPException, status | |
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=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
line_bot_api = LineBotApi(os.environ["line_bot_api"]) | |
line_handler = WebhookHandler(os.environ["line_handler"]) | |
working_status = working_status = os.getenv("DEFALUT_TALKING", default = "true").lower() == "true" | |
def root(): | |
return {"title": "Echo Bot"} | |
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' | |
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)) |