jak*_*ong 5 python direct-line-botframework
我刚刚开始使用line-bot并遵循这里的教程:https : //developers.line.biz/en/docs/messaging-api/building-bot/
但是,我仍然不明白如何与我的line app account进行连接以发送消息,并使这些消息重新出现在python中。
以下是我从line教程中复制的脚本。
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__)
line_bot_api = LineBotApi('foo', timeout=20)
handler = WebhookHandler('bar')
user_profile = 'far'
@app.route("/", methods=['GET'])
def home():
profile = line_bot_api.get_profile(user_profile)
print(profile.display_name)
print(profile.user_id)
print(profile.picture_url)
print(profile.status_message)
return '<div><h1>ok</h1></div>'
@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):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='hello world'))
if __name__ == "__main__":
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
我缺少什么,或者如何与线路应用程序连接以发送和接收消息?
我按照该教程成功创建了一个仅以大写形式回显消息的机器人:
您的问题是如何将您的机器人代码与 LINE 应用程序“连接”。本教程最重要的三个部分可能是:
https://asdfasdf.execute-api.us-east-1.amazonaws.com/default/MyLineBotFunction。这是我为我的机器人输入的 Webhook URL。replyToken消息附带的唯一信息发布到 LINE API 即可进行响应。以下是我的简单 yell-back-in-caps 机器人的 Lambda 函数代码:
import json
from botocore.vendored import requests
def lambda_handler(event, context):
if 'body' in event:
message_event = json.loads(event['body'])['events'][0]
reply_token = message_event['replyToken']
message_text = message_event['message']['text']
requests.post('https://api.line.me/v2/bot/message/reply',
data=json.dumps({
'replyToken': reply_token,
'messages': [{'type': 'text', 'text': message_text.upper()}]
}),
headers={
# TODO: Put your channel access token in the Authorization header
'Authorization': 'Bearer YOUR_CHANNEL_ACCESS_TOKEN_HERE',
'Content-Type': 'application/json'
}
)
return {
'statusCode': 200
}
Run Code Online (Sandbox Code Playgroud)