2020年1月13日 星期一

LINE-BOT-SDK套件(Python)介紹

Line提供Python的套件,給Python程式設計者可以使用套件API跟LINE互動,就不需要撰寫太多複雜的程式及JSON傳輸格式。套件是以Flask提供服務,啟動後,就是LINE的Webhook。



下載套件方法:

pip install line-bot-sdk







範例程式碼,可以Echo使用者輸入的字句:





from flask import Flask, request, abort

from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)
userNo = 1
line_bot_api = LineBotApi('')
handler = WebhookHandler('')

@app.route("/")
def hello():
 return "Hello World!"

@app.route("/callback", methods=['POST'])
def callback():
  # get X-Line-Signature header value
  signature = request.headers['X-Line-Signature']
  # get request body as text
  body = request.get_data(as_text=True)
  app.logger.info("Request body: " + body)

  #handle webhook body
  try:
   handler.handle(body, signature)
  except InvalidSignatureError:
   abort(400)
 
  return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
if (event.reply_token == '00000000000000000000000000000000'):
return None
global userNo
text_message = TextSendMessage(text='Hello, world',
quick_reply=QuickReply(items=[
QuickReplyButton(action=MessageAction(label="label", text="text"))
]))
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=userNo))
userNo += 1

 

if __name__ == "__main__":
app.run(
host = '0.0.0.0',
port = 12345,
debug = True,
ssl_context ='adhoc'

)

沒有留言:

張貼留言

IKEA吊櫃廚櫃

 好不容易裝好IKEA買來的吊櫃,花了三天。 從組裝,鑽牆,上牆調水平,累死我了。