import os, json, requests from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return {}, 200 LINE_REPLY_URL = "https://api.line.me/v2/bot/message/reply" LINE_CHANNEL_ACCESS_TOKEN = os.environ.get("LINE_CHANNEL_ACCESS_TOKEN") LINE_REPLY_HEADERS = { "Content-Type": "application/json; charset=UTF-8", "Authorization": "Bearer " + LINE_CHANNEL_ACCESS_TOKEN } @app.route("/api/", methods=["POST"]) def api(): try: payload = get_payload_dict(request.get_json()) print(payload) username = get_username(payload) text = payload.get("msg_text") print(username) send_text(payload.get("token"), f"{username}:{text}") except: pass return "", 200 def get_payload_dict(raw_payload): print(raw_payload) token = raw_payload.get("events", [{}])[0].get("replyToken") sender_type = raw_payload.get("events", [{}])[0].get("source", {}).get("type", "user") group_id = raw_payload.get("events", [{}])[0].get("source", {}).get("groupId") user_id = raw_payload.get("events", [{}])[0].get("source", {}).get("userId") msg_type = raw_payload.get("events", [{}])[0].get("message", {}).get("type") msg_id = raw_payload.get("events", [{}])[0].get("message", {}).get("id") msg_text = raw_payload.get("events", [{}])[0].get("message", {}).get("text") postback_data = raw_payload.get("events", [{}])[0].get("postback", {}).get("data") payload = {"token": token, "sender_type": sender_type, "group_id": group_id, "user_id": user_id, "msg_type": msg_type, "msg_id": msg_id, "msg_text": msg_text, "postback_data": postback_data } return payload def send_text(token, text): res = requests.post(LINE_REPLY_URL, headers=LINE_REPLY_HEADERS, json={ "replyToken": token, "messages": [ { "type": "text", "text": text } ] }) def get_username(payload): group_id = payload.get("group_id") user_id = payload.get("user_id") url = f"https://api.line.me/v2/bot/group/{group_id}/member/{user_id}" try: res_json = requests.get(url, headers={"Authorization": "Bearer " + LINE_CHANNEL_ACCESS_TOKEN}).json() return res_json.get("displayName") except: return "Unknow" if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)