linebot / 程設 /main.py
kyle9574's picture
Upload 26 files
9b5b012 verified
raw
history blame
1.28 kB
from flask import Flask, request, abort
from linebot.v3.messaging import MessagingApi, ReplyMessageRequest, TextMessage
from linebot.v3 import ApiClient, Configuration
import json
app = Flask(__name__)
channel_access_token = "你的channel_access_token"
configuration = Configuration(access_token=channel_access_token)
@app.route("/callback", methods=["POST"])
def callback():
body = request.get_data(as_text=True)
signature = request.headers.get("X-Line-Signature") # v3 可能不需要,但保留檢查比較好
# 解析事件 JSON
events = json.loads(body).get("events", [])
with ApiClient(configuration) as api_client:
messaging_api = MessagingApi(api_client)
for event in events:
if event["type"] == "message" and event["message"]["type"] == "text":
reply_token = event["replyToken"]
user_text = event["message"]["text"]
reply_message = ReplyMessageRequest(
reply_token=reply_token,
messages=[TextMessage(text=f"你說了: {user_text}")]
)
messaging_api.reply_message(reply_message)
return "OK", 200
if __name__ == "__main__":
app.run(port=8000)