yuripeyamashita's picture
Update app.py
40f689d verified
raw
history blame
3.05 kB
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}")
# {"msgid":{
# "payer": "userid"
# "debtor":{
# "userid": -10,
# "userid": -20
# }
# }
# }
except:
pass
return "", 200
def get_payload_dict(raw_payload):
print(raw_payload)
events = raw_payload.get("events", [{}])[0]
# token = raw_payload.get("events", [{}])[0].get("replyToken")
# 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")
# quoted_msg_id = raw_payload.get("events", [{}])[0].get("message", {}).get("quotedMessageId")
# unsend_msg_id = raw_payload.get("events", [{}])[0].get("unsend", {}).get("messageId")
# postback_data = raw_payload.get("events", [{}])[0].get("postback", {}).get("data")
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)