feat: linbot

restruct the project
This commit is contained in:
2026-03-10 10:15:22 +08:00
parent 00c76bec37
commit c0edc06ab1
11 changed files with 748 additions and 241 deletions

59
app/Line/Router.py Normal file
View File

@@ -0,0 +1,59 @@
from fastapi import APIRouter, Request, HTTPException
from linebot.v3 import WebhookHandler
from linebot.v3.messaging import (
Configuration,
ApiClient,
MessagingApi,
ReplyMessageRequest,
TextMessage,
)
from linebot.v3.webhooks import MessageEvent, TextMessageContent, FollowEvent
from linebot.v3.exceptions import InvalidSignatureError
from app.config import LINE_CHANNEL_ACCESS_TOKEN, LINE_CHANNEL_SECRET
from app.line.handlers import handle_text, handle_captcha
router = APIRouter()
configuration = Configuration(access_token=LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)
@router.post("/webhook")
async def webhook(request: Request):
signature = request.headers.get("X-Line-Signature", "")
body = await request.body()
try:
handler.handle(body.decode(), signature)
except InvalidSignatureError:
raise HTTPException(status_code=400, detail="Invalid signature")
return "OK"
def _reply(reply_token: str, text: str):
with ApiClient(configuration) as api_client:
MessagingApi(api_client).reply_message(
ReplyMessageRequest(
reply_token=reply_token,
messages=[TextMessage(text=text)]
)
)
@handler.add(MessageEvent, message=TextMessageContent)
def on_message(event):
line_user_id = event.source.user_id
msg = event.message.text.strip()
if handle_captcha(msg):
_reply(event.reply_token, "✅ 驗證碼已送出!")
else:
_reply(event.reply_token, handle_text(line_user_id, msg))
@handler.add(FollowEvent)
def on_follow(event):
_reply(event.reply_token, (
"👋 歡迎使用 Myfinance 記帳 Bot\n\n"
"📝 點下方「記帳」開始記帳\n"
"📊 點「查今天」或「查本月」查詢\n\n"
"開始記帳吧!💪"
))