我刚刚开始使用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)
我缺少什么,或者如何与线路应用程序连接以发送和接收消息?
答案 0 :(得分:0)
我遵循了该教程,并且能够成功创建一个仅以大写形式回显消息的机器人:
您的问题是如何“连接”您的机器人代码与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
}