|
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) |
|
events = raw_payload.get("events", [{}])[0] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return {"token": events.get("replyToken"), |
|
"group_id": events.get("source", {}).get("groupId"), |
|
"user_id": events.get("source", {}).get("userId"), |
|
"msg_type": events.get("message", {}).get("type"), |
|
"msg_id": events.get("message", {}).get("id"), |
|
"msg_text": events.get("message", {}).get("text"), |
|
"quoted_msg_id": events.get("message", {}).get("quotedMessageId"), |
|
"unsend_msg_id": events.get("unsend", {}).get("messageId") |
|
} |
|
|
|
|
|
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) |