Facebook
From Speedy Peafowl, 4 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 55
  1. from flask import Flask, request, abort
  2.  
  3. from linebot import (
  4.     LineBotApi, WebhookHandler
  5. )
  6. from linebot.exceptions import (
  7.     InvalidSignatureError
  8. )
  9. from linebot.models import (
  10.     MessageEvent, TextMessage, TextSendMessage,
  11. )
  12.  
  13. app = Flask(__name__)
  14.  
  15. line_bot_api = LineBotApi('')
  16. handler = WebhookHandler('')
  17.  
  18.  
  19. @app.route("/callback", methods=['POST'])
  20. def callback():
  21.     # get X-Line-Signature header value
  22.     signature = request.headers['X-Line-Signature']
  23.  
  24.     # get request body as text
  25.     body = request.get_data(as_text=True)
  26.     app.logger.info("Request body: " + body)
  27.  
  28.     # handle webhook body
  29.     try:
  30.         handler.handle(body, signature)
  31.     except InvalidSignatureError:
  32.         print("Invalid signature. Please check your channel access token/channel secret.")
  33.         abort(400)
  34.  
  35.     return 'OK'
  36.  
  37.  
  38. @handler.add(MessageEvent, message=TextMessage)
  39. def handle_message(event):
  40.     line_bot_api.reply_message(
  41.         event.reply_token,
  42.         TextSendMessage(text=event.message.text))
  43.  
  44. '''
  45.  
  46. 當用戶發照片的時候,將用戶照片從line上下載回來,存到本地端
  47. line_bot_api get content python
  48.  
  49. '''
  50. from linebot.models import  ImageMessage
  51. import boto3
  52. @handler.add(MessageEvent,message=ImageMessage)
  53. def handle_image_message(event):
  54.  
  55.     # 麻煩line_bot_api去跟line要照片回來,並且存回本地端
  56.     message_content = line_bot_api.get_message_content(event.message.id)
  57.     file_name= event.message.id +'.jpg'
  58.  
  59.     with open(file_name, 'wb') as fd:
  60.         for chunk in message_content.iter_content():
  61.             fd.write(chunk)
  62.  
  63.     '''
  64.         用python的套件boto3將圖片上傳到S3
  65.         python boto3 upload object to s3
  66.     '''
  67.     s3_client= boto3.client('s3')
  68.     # s3_client.upload_file(file_name, bucket, object_name)
  69.     s3_client.upload_file(file_name,'iii-tutorial-v2','student99/'+file_name)
  70.  
  71.     '''
  72.         未來做圖片分析
  73.     '''
  74.  
  75.  
  76.     line_bot_api.reply_message(
  77.         event.reply_token,
  78.         TextSendMessage(text="已收到圖片"))
  79.  
  80.  
  81. if __name__ == "__main__":
  82.     app.run('0.0.0.0',port=28888)