LINE heroku python

Code recording

from flask import Flask, request, abort
import os

import vision as v
import vision1 as v1
import base64

from linebot import (
   LineBotApi, WebhookHandler
)
from linebot.exceptions import (
   InvalidSignatureError
)
from linebot.models import (
   MessageEvent, TextMessage, TextSendMessage, ImageMessage,ButtonsTemplate,TemplateSendMessage,MessageAction #Added ImageMessage, ButtonsTemplate and TemplateSendMessage and MessageAction
)

app = Flask(__name__)

#Get environment variables
YOUR_CHANNEL_ACCESS_TOKEN = os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]
YOUR_CHANNEL_SECRET = os.environ["YOUR_CHANNEL_SECRET"]

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)


@app.route("/")
def hello_world():
   return "hello world!"


#Specify a URL for the LINE Developers webhook so that the webhook sends an event to the URL
@app.route("/callback", methods=['POST'])
def callback():
   #Get the value for signature verification from the request header
   signature = request.headers['X-Line-Signature']

   #Get request body
   body = request.get_data(as_text=True)
   app.logger.info("Request body: " + body)

   #Validate the signature and call the function defined in handle if there is no problem
   try:
       handler.handle(body, signature)
   except InvalidSignatureError:
       abort(400)
   return 'OK'

#Echolalia for text
# @handler.add(MessageEvent, message=TextMessage)
# def handle_message(event):
#    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text))


#Pattern to get profile and display in rich text
@handler.add(MessageEvent, message=TextMessage)
def response_message(event):
    profile = line_bot_api.get_profile(event.source.user_id)

    status_msg = profile.status_message
    if status_msg != "None":
        #Status registered in LINE_If message is empty,"None"Use the string as an alternative value
        status_msg = "None"

    messages = TemplateSendMessage(alt_text="Buttons template",
                                   template=ButtonsTemplate(
                                       thumbnail_image_url=profile.picture_url,
                                       title=profile.display_name,
                                       text=f"User Id: {profile.user_id[:5]}...\n"
                                            f"Status Message: {status_msg}",
                                       actions=[MessageAction(label="success", text="What should we implement next?")]))

    line_bot_api.reply_message(event.reply_token, messages=messages)



@handler.add(MessageEvent, message=ImageMessage)
def handle_image_message(event):
   push_img_id = event.message.id #Get the posted image ID
   message_content = line_bot_api.get_message_content(push_img_id) #Get images automatically saved on the LINE server
   push_img = b""
   for chunk in message_content.iter_content(): 
       push_img += chunk #Image iter_push with content_Substitute sequentially for img
   push_img = base64.b64encode(push_img).decode("utf-8") #Base64 encoding to pass the API
   msg = v1.recognize_image2(push_img)
   line_bot_api.reply_message(event.reply_token, TextSendMessage(text=msg))

if __name__ == "__main__":
   #    app.run()
   port = int(os.getenv("PORT"))
   app.run(host="0.0.0.0", port=port)

reference

Make LINE BOT

Recommended Posts

LINE heroku python
Fizzbuzz in Python (in one line)
Python
[Line / Python] Beacon implementation memo
python> print> N line breaks> print ('\ n'* 3)> 4 line breaks> print ('\ n'* 3),> 3 line breaks
Try LINE Notify in Python
I made a LINE BOT with Python and Heroku
Broadcast on LINE using python
Run LINE Bot implemented in Python (Flask) "without using Heroku"
Command line argument processing (Python docopt)
Make python segfault in one line
[Python] Make your own LINE bot
Try the Python LINE Pay SDK
Print with python3 without line breaks
python + django + scikit-learn + mecab (1) on heroku
Next, use Python (Flask) for Heroku!
python + django + scikit-learn + mecab (2) on heroku
Python json.loads () returns str on Heroku
I tried Line notification in Python
[Introduction] Insert line breaks in Python 3
Implemented in 1 minute! LINE Notify in Python
Periodically run Python on Heroku Scheduler
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
CGI server (1) python edition in one line
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
ufo-> python (3)
Python comprehension
install python
Python Singleton
python memo
Line graphs and scale lines in python
Python Jinja2
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Let Heroku do background processing with Python
Python algorithm
Favicon placement (when using Python, Flask, Heroku)
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore