|
1 | 1 | import logging |
2 | | -import os |
| 2 | +import json |
3 | 3 |
|
4 | 4 | from linebot.models import ( |
5 | 5 | TextSendMessage, |
6 | 6 | QuickReply, |
7 | 7 | QuickReplyButton, |
8 | 8 | MessageAction, |
9 | 9 | SendMessage, |
| 10 | + FlexSendMessage, |
10 | 11 | ) |
11 | 12 | from ..api.vision import process_image |
12 | 13 | from ..config.line_config import line_bot_api |
@@ -37,12 +38,43 @@ def handle_text_message(self, event) -> TextSendMessage: |
37 | 38 | # 產生回應訊息 |
38 | 39 | quick_reply = None |
39 | 40 | if user_input in COMMANDS: |
40 | | - quick_reply = self._create_quick_reply() |
41 | 41 | response_text = COMMANDS[user_input] |
42 | | - else: |
43 | | - response_text = inference(user_input, user_id) |
44 | | - |
45 | | - return TextSendMessage(text=response_text, quick_reply=quick_reply) |
| 42 | + quick_reply = self._create_quick_reply() |
| 43 | + return [TextSendMessage(text=response_text, quick_reply=quick_reply)] |
| 44 | + |
| 45 | + # 處理一般查詢 |
| 46 | + response_text = inference(user_input, user_id) |
| 47 | + quick_reply = self._create_quick_reply() |
| 48 | + |
| 49 | + # 處理可能包含 Flex Message 的回應 |
| 50 | + if "===FLEX_MESSAGE===" in response_text: |
| 51 | + parts = response_text.split("===FLEX_MESSAGE===") |
| 52 | + text_content = parts[0].strip() |
| 53 | + text_message = TextSendMessage( |
| 54 | + text=text_content, quick_reply=quick_reply |
| 55 | + ) |
| 56 | + |
| 57 | + # 檢查是否有 Flex Message 部分 |
| 58 | + if len(parts) > 1: |
| 59 | + flex_content = ( |
| 60 | + parts[1].strip().replace("```", "").replace("json", "") |
| 61 | + ) |
| 62 | + if flex_content and flex_content != "False": |
| 63 | + try: |
| 64 | + flex_json = json.loads(flex_content) |
| 65 | + return [ |
| 66 | + text_message, |
| 67 | + FlexSendMessage( |
| 68 | + alt_text="詳細資訊", contents=flex_json |
| 69 | + ), |
| 70 | + ] |
| 71 | + except Exception as e: |
| 72 | + logger.error(f"Flex訊息解析錯誤: {str(e)}", exc_info=True) |
| 73 | + |
| 74 | + return [text_message] |
| 75 | + |
| 76 | + # 純文字回應 |
| 77 | + return [TextSendMessage(text=response_text, quick_reply=quick_reply)] |
46 | 78 |
|
47 | 79 | except Exception as e: |
48 | 80 | logger.error(f"處理訊息時發生錯誤: {str(e)}", exc_info=True) |
|
0 commit comments