linebot / app.py
Hongrulee's picture
Create app.py
3e837a6 verified
raw
history blame
1.29 kB
from fastapi import FastAPI, Request, HTTPException
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import os
# 設定 LINE Channel Access Token 和 Channel Secret
LINE_CHANNEL_ACCESS_TOKEN = os.getenv("LINE_CHANNEL_ACCESS_TOKEN")
LINE_CHANNEL_SECRET = os.getenv("LINE_CHANNEL_SECRET")
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)
app = FastAPI()
# Webhook endpoint for LINE messages
@app.post("/callback")
async def callback(request: Request):
signature = request.headers['X-Line-Signature']
body = await request.body()
try:
handler.handle(body.decode('utf-8'), signature)
except InvalidSignatureError:
raise HTTPException(status_code=400, detail="Invalid signature")
return 'OK'
# 處理文字訊息的事件
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
# 回應同樣的訊息給使用者
reply_text = event.message.text
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=reply_text)
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)