File size: 1,872 Bytes
aacd8dd
 
 
64800c8
ec365d0
aacd8dd
 
 
 
f9a0365
aacd8dd
 
 
 
 
 
 
204de69
aacd8dd
 
204de69
aacd8dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246e678
4edc6ed
aacd8dd
 
 
 
 
 
 
 
 
 
 
 
 
 
6fca75f
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import io
import PIL.Image
from collections import defaultdict
from linebot import LineBotApi

#==========================
# 使用者上傳圖片
#==========================
line_bot_api = LineBotApi(os.environ["CHANNEL_ACCESS_TOKEN"])
def get_image_url(message_id):
    try:
        message_content = line_bot_api.get_message_content(message_id)
        file_path = f"/tmp/{message_id}.png"
        with open(file_path, "wb") as f:
            for chunk in message_content.iter_content():
                f.write(chunk)
        print(f"✅ 圖片成功儲存到:{file_path}")
        return file_path
    except Exception as e:
        print(f"❌ 圖片取得失敗:{e}")
        return None

# 使用字典模擬用戶訊息歷史存儲
user_message_history = defaultdict(list)
def store_user_message(user_id, message_type, message_content):
    """
    儲存用戶的訊息
    """
    user_message_history[user_id].append({
        "type": message_type,
        "content": message_content})
    
def analyze_with_gemini(image_path, user_text):
    """
    分析用戶問題和圖片,並返回 Gemini 的回應
    """
    try:
        # 確保圖片存在
        if not os.path.exists(image_path):
            raise FileNotFoundError(f"圖片路徑無效:{image_path}")
        
        img_user = PIL.Image.open(image_path)
        response = chat.send_message([user_text, img_user])
        
        # 提取回應內容
        return response.text

    except Exception as e:
        return f"發生錯誤: {e}"
    
def get_previous_message(user_id):
    """
    獲取用戶的上一則訊息
    """
    if user_id in user_message_history and len(user_message_history[user_id]) > 0:
        # 返回最後一則訊息
        return user_message_history[user_id][-1]
    return {
        "type": 'text',
        "content": 'No message!'}