import os import requests from PIL import Image, ImageDraw, ImageFont from dotenv import load_dotenv load_dotenv("../.env") ACCESS_TOKEN = os.getenv("LINE_CHANNEL_ACCESS_TOKEN") HEADERS = {"Authorization": f"Bearer {ACCESS_TOKEN}"} def create_image(): W, H = 2500, 843 img = Image.new("RGB", (W, H), color="#FFFFFF") draw = ImageDraw.Draw(img) # 分隔線 draw.line([(833, 0), (833, H)], fill="#DDDDDD", width=4) draw.line([(1666, 0), (1666, H)], fill="#DDDDDD", width=4) # 背景色 draw.rectangle([0, 0, 833, H], fill="#F0F9FF") draw.rectangle([834, 0, 1666, H], fill="#F0FFF4") draw.rectangle([1667, 0, W, H], fill="#FFF9F0") sections = [ ("記帳", "類別 金額", 416), ("查今天", "今日明細", 1249), ("查本月", "本月統計", 2083), ] try: # Windows 支援中文的字型 font_large = ImageFont.truetype("C:/Windows/Fonts/msjh.ttc", 120) font_mid = ImageFont.truetype("C:/Windows/Fonts/msjh.ttc", 80) font_small = ImageFont.truetype("C:/Windows/Fonts/msjh.ttc", 55) except: font_large = ImageFont.load_default() font_mid = font_large font_small = font_large for title, subtitle, x in sections: draw.text((x, 280), title, font=font_mid, anchor="mm", fill="#222222") draw.text((x, 450), subtitle, font=font_small, anchor="mm", fill="#888888") img.save("rich_menu.png") print("✅ 圖片建立完成") def create_rich_menu(): data = { "size": {"width": 2500, "height": 843}, "selected": True, "name": "Finance Menu", "chatBarText": "選單", "areas": [ { "bounds": {"x": 0, "y": 0, "width": 833, "height": 843}, "action": {"type": "message", "text": "記帳說明"} }, { "bounds": {"x": 833, "y": 0, "width": 833, "height": 843}, "action": {"type": "message", "text": "查今天"} }, { "bounds": {"x": 1666, "y": 0, "width": 834, "height": 843}, "action": {"type": "message", "text": "查本月"} } ] } res = requests.post( "https://api.line.me/v2/bot/richmenu", headers={**HEADERS, "Content-Type": "application/json"}, json=data ) rich_menu_id = res.json()["richMenuId"] print(f"✅ Rich Menu 建立:{rich_menu_id}") return rich_menu_id def upload_image(rich_menu_id): with open("rich_menu.png", "rb") as f: res = requests.post( f"https://api-data.line.me/v2/bot/richmenu/{rich_menu_id}/content", headers={**HEADERS, "Content-Type": "image/png"}, data=f ) print(f"✅ 圖片上傳:{res.status_code}") def set_default(rich_menu_id): res = requests.post( f"https://api.line.me/v2/bot/user/all/richmenu/{rich_menu_id}", headers=HEADERS ) print(f"✅ 設為預設選單:{res.status_code} {res.text}") if __name__ == "__main__": create_image() rich_menu_id = create_rich_menu() upload_image(rich_menu_id) set_default(rich_menu_id) print("\n🎉 Rich Menu 設定完成!重新開啟 LINE Bot 查看效果")