Linebot / Uploading_images_file.py
alanchen1115's picture
Update Uploading_images_file.py
6fca75f verified
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!'}