專題:記帳小幫手
記帳小幫手是一個完整的 LINE Bot 專題:使用者輸入「早餐 80」就記一筆,輸入「今天」或「本月」會收到 Flex Message 統計卡片,每則回覆下方都有 Quick Reply 按鈕。這個專題把前面學的東西串在一起,並加上資料庫(SQLite)與指令解析,做完就是一個每天用得到的工具。
完整程式:examples/python/expense-bot/
功能規劃
| 使用者輸入 | Bot 回應 |
|---|---|
早餐 80 或 80 早餐 |
記一筆,並回覆今日累計 |
今天 |
Flex 卡片:今日各項目小計與合計 |
本月 |
Flex 卡片:本月各項目小計與合計 |
刪除 |
刪除自己最後一筆紀錄 |
說明 |
使用說明 |
| 加好友 | 歡迎訊息與使用說明 |
每個使用者的資料用 user_id 分開,大家共用同一個 Bot 也不會看到別人的帳。
建立專案
.env 與 Echo Bot 相同,可以直接複製過來。SQLite 是 Python 內建的資料庫,不用另外安裝。
資料庫:用 SQLite 存紀錄
SQLite 把整個資料庫存成一個檔案(expense.db),適合學習與小型專案。資料表只有一張 expenses:
def db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
with closing(db()) as conn, conn:
conn.execute(
"""CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
item TEXT NOT NULL,
amount INTEGER NOT NULL,
created_at TEXT NOT NULL
)"""
)
def add_expense(user_id, item, amount):
now = datetime.now(TW).isoformat(timespec="seconds")
with closing(db()) as conn, conn:
conn.execute(
"INSERT INTO expenses (user_id, item, amount, created_at) VALUES (?, ?, ?, ?)",
(user_id, item, amount, now),
)
def delete_last(user_id):
with closing(db()) as conn, conn:
row = conn.execute(
"SELECT id, item, amount FROM expenses WHERE user_id = ? ORDER BY id DESC LIMIT 1",
(user_id,),
).fetchone()
if row:
conn.execute("DELETE FROM expenses WHERE id = ?", (row["id"],))
return row
def summary(user_id, since):
"""回傳 (各項目小計清單, 總額);since 是 ISO 字串,例如 '2026-12-04'。"""
with closing(db()) as conn:
rows = conn.execute(
"""SELECT item, SUM(amount) AS total FROM expenses
WHERE user_id = ? AND created_at >= ?
GROUP BY item ORDER BY total DESC""",
(user_id, since),
).fetchall()
return rows, sum(r["total"] for r in rows)
重點:
- SQL 參數一律用
?佔位,不要用字串拼接,避免 SQL injection。 - 時間存成台灣時區的 ISO 字串(
2026-12-04T08:30:00+08:00),查詢「今天」只要比較created_at >= '2026-12-04'。 with closing(db()) as conn, conn:會在區塊結束時 commit 並關閉連線。
訊息:Quick Reply 與 Flex 卡片
每則文字回覆都附上同一組 Quick Reply 按鈕;統計結果用 Flex Message 排成卡片。Flex 的結構可以先在 Flex Message Simulator 設計好,再改寫成 Python dict(Flex 詳細說明見 Flex Message):
QUICK_REPLY = QuickReply(
items=[
QuickReplyItem(action=MessageAction(label="今天花多少", text="今天")),
QuickReplyItem(action=MessageAction(label="本月統計", text="本月")),
QuickReplyItem(action=MessageAction(label="刪除上一筆", text="刪除")),
QuickReplyItem(action=MessageAction(label="說明", text="說明")),
]
)
HELP_TEXT = "記帳方式:輸入「項目 金額」\n例如:早餐 80、捷運 25\n\n查詢:今天、本月\n修正:刪除(刪掉最後一筆)"
def text(msg):
return TextMessage(text=msg, quick_reply=QUICK_REPLY)
def summary_flex(title, rows, total):
"""把統計結果組成 Flex Message bubble。"""
item_rows = [
{
"type": "box",
"layout": "horizontal",
"contents": [
{"type": "text", "text": r["item"], "size": "sm", "color": "#555555", "flex": 3},
{"type": "text", "text": f"${r['total']:,}", "size": "sm", "align": "end", "flex": 2},
],
}
for r in rows[:10] # 最多列 10 項,避免訊息太長
] or [{"type": "text", "text": "還沒有紀錄", "size": "sm", "color": "#999999"}]
bubble = {
"type": "bubble",
"header": {
"type": "box",
"layout": "vertical",
"backgroundColor": "#06C755",
"contents": [
{"type": "text", "text": title, "color": "#FFFFFF", "weight": "bold", "size": "lg"}
],
},
"body": {"type": "box", "layout": "vertical", "spacing": "sm", "contents": item_rows},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{"type": "text", "text": "合計", "weight": "bold"},
{"type": "text", "text": f"${total:,}", "weight": "bold", "align": "end", "color": "#06C755"},
],
},
}
return FlexMessage(
alt_text=f"{title}:合計 ${total:,}", # 通知列與不支援 Flex 的裝置會顯示這段文字
contents=FlexContainer.from_dict(bubble),
quick_reply=QUICK_REPLY,
)
alt_text 是必填欄位:手機通知列、聊天列表預覽,以及不支援 Flex 的環境,都只會顯示這段文字。
指令解析
把「看到什麼文字要回什麼」寫成一個純函式 handle_command(),它只回傳訊息物件,不直接呼叫 LINE API。這樣可以不用 LINE 就測試邏輯:
PATTERNS = [
re.compile(r"^(?P<item>\D\S*)\s+(?P<amount>\d+)$"), # 早餐 80
re.compile(r"^(?P<amount>\d+)\s+(?P<item>\S+)$"), # 80 早餐
]
def handle_command(user_id, msg):
"""依使用者輸入回傳要回覆的訊息;把邏輯和 LINE API 分開,方便測試。"""
now = datetime.now(TW)
if msg in ("說明", "help"):
return text(HELP_TEXT)
if msg == "今天":
rows, total = summary(user_id, now.strftime("%Y-%m-%d"))
return summary_flex(f"{now:%m/%d} 花費", rows, total)
if msg == "本月":
rows, total = summary(user_id, now.strftime("%Y-%m-01"))
return summary_flex(f"{now:%Y 年 %m 月}花費", rows, total)
if msg == "刪除":
row = delete_last(user_id)
return text(f"已刪除:{row['item']} ${row['amount']}" if row else "沒有可以刪除的紀錄")
for pattern in PATTERNS:
if m := pattern.match(msg):
item, amount = m["item"], int(m["amount"])
add_expense(user_id, item, amount)
_, today_total = summary(user_id, now.strftime("%Y-%m-%d"))
return text(f"已記錄 {item} ${amount:,}\n今天累計 ${today_total:,}")
return text("看不懂這個指令 🤔\n" + HELP_TEXT)
用兩個正規表示式支援「項目 金額」與「金額 項目」兩種寫法。\D\S* 表示項目不能以數字開頭,避免「80 120」被誤判。
組合完整程式
把上面幾段加上 webhook 路由,就是完整的 app.py:
完整 app.py(點開)
"""記帳小幫手:用 LINE 記錄每日花費,並用 Flex Message 顯示統計。
指令:
早餐 80 記一筆(項目 金額),也可以寫成「80 早餐」
今天 / 本月 查看統計
刪除 刪除最後一筆
說明 顯示使用說明
"""
import os
import re
import sqlite3
from contextlib import closing
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
from flask import Flask, abort, request
from linebot.v3 import WebhookHandler
from linebot.v3.exceptions import InvalidSignatureError
from linebot.v3.messaging import (
ApiClient,
Configuration,
FlexContainer,
FlexMessage,
MessageAction,
MessagingApi,
QuickReply,
QuickReplyItem,
ReplyMessageRequest,
TextMessage,
)
from linebot.v3.webhooks import FollowEvent, MessageEvent, TextMessageContent
load_dotenv()
configuration = Configuration(access_token=os.environ["LINE_CHANNEL_ACCESS_TOKEN"])
handler = WebhookHandler(os.environ["LINE_CHANNEL_SECRET"])
DB_PATH = os.environ.get("DB_PATH", "expense.db")
TW = timezone(timedelta(hours=8)) # 台灣時間
app = Flask(__name__)
# ---------- 資料庫 ----------
def db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
with closing(db()) as conn, conn:
conn.execute(
"""CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
item TEXT NOT NULL,
amount INTEGER NOT NULL,
created_at TEXT NOT NULL
)"""
)
def add_expense(user_id, item, amount):
now = datetime.now(TW).isoformat(timespec="seconds")
with closing(db()) as conn, conn:
conn.execute(
"INSERT INTO expenses (user_id, item, amount, created_at) VALUES (?, ?, ?, ?)",
(user_id, item, amount, now),
)
def delete_last(user_id):
with closing(db()) as conn, conn:
row = conn.execute(
"SELECT id, item, amount FROM expenses WHERE user_id = ? ORDER BY id DESC LIMIT 1",
(user_id,),
).fetchone()
if row:
conn.execute("DELETE FROM expenses WHERE id = ?", (row["id"],))
return row
def summary(user_id, since):
"""回傳 (各項目小計清單, 總額);since 是 ISO 字串,例如 '2026-12-04'。"""
with closing(db()) as conn:
rows = conn.execute(
"""SELECT item, SUM(amount) AS total FROM expenses
WHERE user_id = ? AND created_at >= ?
GROUP BY item ORDER BY total DESC""",
(user_id, since),
).fetchall()
return rows, sum(r["total"] for r in rows)
# ---------- 訊息組裝 ----------
QUICK_REPLY = QuickReply(
items=[
QuickReplyItem(action=MessageAction(label="今天花多少", text="今天")),
QuickReplyItem(action=MessageAction(label="本月統計", text="本月")),
QuickReplyItem(action=MessageAction(label="刪除上一筆", text="刪除")),
QuickReplyItem(action=MessageAction(label="說明", text="說明")),
]
)
HELP_TEXT = "記帳方式:輸入「項目 金額」\n例如:早餐 80、捷運 25\n\n查詢:今天、本月\n修正:刪除(刪掉最後一筆)"
def text(msg):
return TextMessage(text=msg, quick_reply=QUICK_REPLY)
def summary_flex(title, rows, total):
"""把統計結果組成 Flex Message bubble。"""
item_rows = [
{
"type": "box",
"layout": "horizontal",
"contents": [
{"type": "text", "text": r["item"], "size": "sm", "color": "#555555", "flex": 3},
{"type": "text", "text": f"${r['total']:,}", "size": "sm", "align": "end", "flex": 2},
],
}
for r in rows[:10] # 最多列 10 項,避免訊息太長
] or [{"type": "text", "text": "還沒有紀錄", "size": "sm", "color": "#999999"}]
bubble = {
"type": "bubble",
"header": {
"type": "box",
"layout": "vertical",
"backgroundColor": "#06C755",
"contents": [
{"type": "text", "text": title, "color": "#FFFFFF", "weight": "bold", "size": "lg"}
],
},
"body": {"type": "box", "layout": "vertical", "spacing": "sm", "contents": item_rows},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{"type": "text", "text": "合計", "weight": "bold"},
{"type": "text", "text": f"${total:,}", "weight": "bold", "align": "end", "color": "#06C755"},
],
},
}
return FlexMessage(
alt_text=f"{title}:合計 ${total:,}", # 通知列與不支援 Flex 的裝置會顯示這段文字
contents=FlexContainer.from_dict(bubble),
quick_reply=QUICK_REPLY,
)
# ---------- 指令處理 ----------
PATTERNS = [
re.compile(r"^(?P<item>\D\S*)\s+(?P<amount>\d+)$"), # 早餐 80
re.compile(r"^(?P<amount>\d+)\s+(?P<item>\S+)$"), # 80 早餐
]
def handle_command(user_id, msg):
"""依使用者輸入回傳要回覆的訊息;把邏輯和 LINE API 分開,方便測試。"""
now = datetime.now(TW)
if msg in ("說明", "help"):
return text(HELP_TEXT)
if msg == "今天":
rows, total = summary(user_id, now.strftime("%Y-%m-%d"))
return summary_flex(f"{now:%m/%d} 花費", rows, total)
if msg == "本月":
rows, total = summary(user_id, now.strftime("%Y-%m-01"))
return summary_flex(f"{now:%Y 年 %m 月}花費", rows, total)
if msg == "刪除":
row = delete_last(user_id)
return text(f"已刪除:{row['item']} ${row['amount']}" if row else "沒有可以刪除的紀錄")
for pattern in PATTERNS:
if m := pattern.match(msg):
item, amount = m["item"], int(m["amount"])
add_expense(user_id, item, amount)
_, today_total = summary(user_id, now.strftime("%Y-%m-%d"))
return text(f"已記錄 {item} ${amount:,}\n今天累計 ${today_total:,}")
return text("看不懂這個指令 🤔\n" + HELP_TEXT)
@app.post("/callback")
def callback():
signature = request.headers.get("X-Line-Signature", "")
body = request.get_data(as_text=True)
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return "OK"
def reply(event, message):
with ApiClient(configuration) as api_client:
MessagingApi(api_client).reply_message(
ReplyMessageRequest(reply_token=event.reply_token, messages=[message])
)
@handler.add(FollowEvent)
def handle_follow(event):
reply(event, text("歡迎使用記帳小幫手!\n" + HELP_TEXT))
@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
reply(event, handle_command(event.source.user_id, event.message.text.strip()))
init_db()
if __name__ == "__main__":
app.run(port=int(os.environ.get("PORT", 8080)), debug=True)
執行與測試
-
先不用 LINE,在終端機直接測邏輯:
-
沒問題後啟動程式與 ngrok,更新 Webhook URL(步驟同 Echo Bot):
-
在 LINE 依序輸入
早餐 80、捷運 25、午餐 120、今天、刪除、本月,確認每個指令的回覆。
延伸挑戰
- 加上圖文選單:把「今天」「本月」「說明」做成聊天室底部的固定選單,見 圖文選單,範例的選單正好對應這個專題。
- 預算提醒:設定每月預算,超過 80% 時回覆警告。
- 匯出 CSV:輸入「匯出」時產生 CSV 檔,上傳到雲端儲存後回傳下載連結。
- 改用雲端資料庫:見下方注意事項。
部署後 SQLite 資料會不見?
Cloud Run、Render 免費方案等平台的磁碟是暫時性的,程式重啟或重新部署時 expense.db 會被清空。練習可以接受;正式使用請改用 Firestore、Cloud SQL、Supabase 等雲端資料庫,或把 Bot 部署在有永久磁碟的主機上。詳見 部署與託管。