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('k2j34l2kj34l2kj34l2kh143;kljh51;kl2h5;l1k2hj;45lkh12;l3k4h2kj3hn4kj2lh34lkj2h34lk2jh34lkjh1242kl3jh4lk2jh34lk2jh34lk1jh243lkjh2lk3j4hlk23h4')
handler = WebhookHandler('kj2h34lkj2h433lk2jh4lk3j2h4')
@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'
)
沒有留言:
張貼留言