huchiahsi commited on
Commit
e4c9f86
·
verified ·
1 Parent(s): 418ef7d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +28 -18
main.py CHANGED
@@ -97,24 +97,34 @@ def handle_message(event):
97
 
98
  @handler.add(MessageEvent, message=ImageMessageContent)
99
  def handle_image_message(event):
100
- # 取得圖片內容
101
- message_content = line_bot_api.get_message_content(event.message.id)
102
- image_path = f"{event.message.id}.jpg"
103
- with open(image_path, 'wb') as fd:
104
- for chunk in message_content.iter_content():
105
- fd.write(chunk)
106
-
107
- # 上傳至 Imgur
108
- uploaded_image = imgur_client.upload_image(image_path, title="Uploaded with PyImgur")
109
- image_url = uploaded_image.link
110
-
111
- os.remove(image_path)
112
-
113
- # 回傳圖片 URL 給使用者
114
- line_bot_api.reply_message(
115
- event.reply_token,
116
- TextSendMessage(text=f"圖片已上傳至 Imgur:{imgur_url}")
117
- )
 
 
 
 
 
 
 
 
 
 
118
 
119
  @app.route('/static/<path:path>')
120
  def send_static_content(path):
 
97
 
98
  @handler.add(MessageEvent, message=ImageMessageContent)
99
  def handle_image_message(event):
100
+ with ApiClient(configuration) as api_client:
101
+ line_bot_api = MessagingApi(api_client)
102
+ # 取得圖片內容
103
+ message_content = line_bot_api.get_message_content(event.message.id)
104
+ # 儲存圖片至暫存檔案
105
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tf:
106
+ for chunk in message_content.iter_content():
107
+ tf.write(chunk)
108
+ temp_file_path = tf.name
109
+ try:
110
+ # 上傳圖片至 Imgur
111
+ uploaded_image = imgur_client.upload_image(temp_file_path, title="Uploaded via LINE Bot")
112
+ image_url = uploaded_image.link
113
+ # 回傳圖片給使用者
114
+ line_bot_api.reply_message(
115
+ ReplyMessageRequest(
116
+ reply_token=event.reply_token,
117
+ messages=[
118
+ ImageMessage(
119
+ original_content_url=image_url,
120
+ preview_image_url=image_url
121
+ )
122
+ ]
123
+ )
124
+ )
125
+ finally:
126
+ # 刪除暫存檔案
127
+ os.remove(temp_file_path)
128
 
129
  @app.route('/static/<path:path>')
130
  def send_static_content(path):