File size: 19,857 Bytes
fa6e3b2 bf00a95 fa6e3b2 822d179 fa6e3b2 f76a4e9 fa6e3b2 8300a7c 6a17841 d5e4b99 6a17841 d1db829 fa6e3b2 416b9fb fa6e3b2 77bb999 2ba3143 eb1cacb fa6e3b2 2ba3143 4d05f6a ebe584c 4d05f6a c915bab da3b0f7 35130c5 53558ec da3b0f7 a33cbc3 da3b0f7 ed0747c 2445a33 ed0747c cac428c 7555506 cac428c 2445a33 da3b0f7 ed0747c ebe584c ed0747c 76efe7b ed0747c 76efe7b ed0747c 76efe7b ed0747c bd4d44f a33cbc3 ed0747c 2ba3143 5c18dcf 6376372 b406846 6376372 81b69ab 6376372 5c18dcf fa6e3b2 d1df012 fa6e3b2 61ddc9c d1df012 fa6e3b2 c915bab d1df012 c915bab d1df012 0de3336 d1df012 0de3336 d1df012 553c037 c915bab fa6e3b2 eb1cacb 9497451 d1db829 9497451 6a17841 fa6e3b2 d1df012 f76a4e9 4d05f6a f76a4e9 4d05f6a af688b0 c915bab fa6e3b2 fb4f1a7 fa6e3b2 6a17841 fb4f1a7 6a17841 4bc235e fa6e3b2 0de3336 fa6e3b2 ed0747c ebe584c 13edd55 ed0747c 0a39678 1bb9b5d 9da9263 f76a4e9 fa6e3b2 35130c5 fa6e3b2 9da9263 fa6e3b2 553c037 a33cbc3 553c037 a33cbc3 80a7dc7 a33cbc3 553c037 fa6e3b2 0de3336 a33cbc3 ed0747c 0de3336 ed0747c 0de3336 76efe7b 0de3336 a33cbc3 0de3336 ed0747c 0de3336 ed0747c 0de3336 ed0747c 0de3336 ed0747c 0de3336 ed0747c a33cbc3 b8bb4b3 a33cbc3 ea4341d a33cbc3 d1db829 a33cbc3 9497451 a33cbc3 ea4341d a33cbc3 ed0747c a33cbc3 ed0747c 696d3f8 ed0747c a33cbc3 ed0747c a33cbc3 ed0747c a33cbc3 ed0747c a33cbc3 ed0747c 27407e5 fa6e3b2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
import os
import requests
from flask import Flask, request
from simpleeval import simple_eval
app = Flask(__name__)
GROUP_ID = os.environ.get("GROUP_ID")
LINE_CHANNEL_ACCESS_TOKEN = os.environ.get("LINE_CHANNEL_ACCESS_TOKEN")
message_list = {}
group_id = ""
@app.route('/', methods=['GET'])
def index():
return {}, 200
@app.route("/api/", methods=["POST"])
def api():
global message_list
try:
payload = get_payload_dict(request.get_json())
print(group_id)
if group_id != GROUP_ID:
raise ValueError("Invalid Group")
if payload.get("unsend_msg_id"):
unsend_msg_id = payload.get("unsend_msg_id")
message_list.pop(unsend_msg_id, None)
message_list = {key: value for key, value in message_list.items() if value.get("quoted_msg_id") != unsend_msg_id}
raise ValueError("Unsend Success")
if "$$$" in payload.get("msg_text"):
if "清除" in payload.get("msg_text"):
message_list = {}
return "", 200
if "結算" in payload.get("msg_text"):
users_number = get_users_number()
users = list({item["user_id"] for item in message_list.values()})
if len(users) != users_number:
users.append("others")
print(users)
matrix = [[0.0 for _ in range(len(users))] for _ in range(len(users))]
should_checkout = True
for msg_id, data in message_list.items():
quoted_msg_id = data.get("quoted_msg_id")
quoted_msg_list = {key: value for key, value in message_list.items() if value.get("quoted_msg_id") == msg_id}
if not quoted_msg_id and len(quoted_msg_list) != 0: # 檢查是否付清
amount: float = data.get("amount")
paid: float = 0.0
for _, value in quoted_msg_list.items():
paid += value.get("amount")
if amount-paid > 1:
send_text(payload.get("token"), f"$ {amount-paid} 未付清", data.get("quote_token"))
should_checkout = False
break
if not quoted_msg_id and len(quoted_msg_list) == 0: # 要平分的情況
to = users.index(data.get("user_id"))
for row in matrix:
row[to] += (data.get("amount") / users_number)
if quoted_msg_id:
fr = users.index(data.get("user_id"))
to = users.index(message_list.get(quoted_msg_id).get("user_id"))
matrix[fr][to] += data.get("amount")
print(matrix)
if not should_checkout:
return "", 200
matrix_copy = [[0 for _ in range(len(matrix))] for _ in range(len(matrix))]
for i in range(len(matrix_copy)):
for j in range(len(matrix_copy)):
if i < j:
matrix_copy[i][j] = matrix[i][j] - matrix[j][i]
result = []
for i in range(len(matrix_copy)):
for j in range(len(matrix_copy)):
amount = matrix_copy[i][j]
if amount > 0:
result.append({"from": get_username(users[i]), "to": get_username(users[j]), "amount": amount})
if amount < 0:
result.append({"from": get_username(users[j]), "to": get_username(users[i]), "amount": -amount})
if result:
sorted_result = sorted(result, key=lambda x: x["from"])
bubble = get_checkout_bubble(sorted_result)
send_flex_text(payload.get("token"), bubble)
message_list = {}
raise ValueError("Action Success")
if "$" not in payload.get("msg_text"):
if "計算" in payload.get("msg_text"):
try:
text = payload.get("msg_text")
number = float(simple_eval(text.split("計算")[1]))
send_text(payload.get("token"), f"$ {round(number,2)}", payload.get("quote_token"))
except:
raise ValueError("Calculation Error")
raise ValueError("Calculation Successful")
raise ValueError("Keyword not Found")
if get_amount(payload.get("msg_text")) == None:
raise ValueError("Amount is None")
if payload.get("quoted_msg_id"):
message_list[payload.get("msg_id")] = {"user_id": payload.get("user_id"),
"amount": get_amount(payload.get("msg_text")),
"quoted_msg_id": payload.get("quoted_msg_id")}
else:
message_list[payload.get("msg_id")] = {"user_id": payload.get("user_id"),
"amount": get_amount(payload.get("msg_text")),
"quote_token": payload.get("quote_token"),
"msg_text": payload.get("msg_text")}
for msg_id, data in message_list.items():
quoted_msg_id = data.get("quoted_msg_id")
quoted_msg_list = {key: value for key, value in message_list.items() if value.get("quoted_msg_id") == msg_id}
if not quoted_msg_id and len(quoted_msg_list) != 0:
amount: float = data.get("amount")
paid: float = 0.0
for _, value in quoted_msg_list.items():
paid += value.get("amount")
if amount-paid <= 1 and payload.get("quoted_msg_id") == msg_id:
borrowers = []
for _, q_data in quoted_msg_list.items():
borrowers.append({"name": get_username(q_data.get("user_id")), "amount": q_data.get("amount")})
bubble = get_summary_bubble(data.get("msg_text"), get_username(data.get("user_id")), borrowers)
send_flex_text(payload.get("token"), bubble)
break
if amount-paid > 1 and payload.get("quoted_msg_id") != msg_id:
send_text(payload.get("token"), f"$ {amount-paid} 未付清", data.get("quote_token"))
break
except Exception as e:
print(f"An error occurred: {e}")
print("="*20)
for key in message_list:
print(message_list[key])
print("="*20, end="\n\n")
return "", 200
def get_payload_dict(raw_payload) -> dict:
# print(raw_payload)
global group_id
events = raw_payload.get("events", [{}])[0]
group_id = events.get("source", {}).get("groupId")
return {"token": events.get("replyToken"),
"quote_token": events.get("message", {}).get("quoteToken"),
"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: str, text: str, quote_token: str | None = None):
requests.post("https://api.line.me/v2/bot/message/reply", headers={
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + LINE_CHANNEL_ACCESS_TOKEN
}, json={
"replyToken": token,
"messages": [{"type": "text", "text": text, "quoteToken": quote_token}]
})
def send_flex_text(token, bubble):
requests.post("https://api.line.me/v2/bot/message/reply", headers={
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + LINE_CHANNEL_ACCESS_TOKEN
}, json={
"replyToken": token,
"messages": [{
"type": "flex",
"altText": "您有一則新訊息",
"contents": bubble
}]
})
def get_username(user_id: str):
if user_id == "others":
return "其他人"
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 "未知"
def get_users_number() -> int:
global group_id
url = f"https://api.line.me/v2/bot/group/{group_id}/members/count"
try:
res_json = requests.get(url, headers={"Authorization": "Bearer " + LINE_CHANNEL_ACCESS_TOKEN}).json()
return int(res_json.get("count"))
except:
return 0
def get_amount(text: str) -> float | None:
try:
after_dollar = text.split("$")[1]
rows = after_dollar.split("\n")
number = float(simple_eval(rows[0]))
divisor = 1
if len(rows) > 1 and "/" in rows[1]:
divisor = int(rows[1].replace("/", ""))
if divisor % 3 == 0:
number += 0.3
if divisor == 0:
raise ValueError("divisor = 0")
return round(number/divisor, 2)
except:
return None
def get_summary_bubble(title: str, payer: str, borrowers: list):
total = 0.0
borrower_contents = []
for borrower in borrowers:
amount = float(borrower.get("amount"))
total += amount
borrower_contents.append({
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": borrower.get("name"),
"size": "sm",
"color": "#555555",
"flex": 0
},
{
"type": "text",
"text": f"${round(amount,2)}",
"size": "sm",
"color": "#111111",
"align": "end"
}
]
})
return {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "對帳明細",
"weight": "bold",
"color": "#1DB446",
"size": "sm"
},
{
"type": "text",
"text": title,
"weight": "bold",
"size": "xxl",
"wrap": True,
"margin": "md"
},
{
"type": "text",
"text": f"由 {payer} 付款",
"size": "sm",
"color": "#aaaaaa",
"wrap": True,
"weight": "bold"
},
{
"type": "separator",
"margin": "lg"
},
{
"type": "box",
"layout": "vertical",
"margin": "lg",
"spacing": "sm",
"contents": borrower_contents
},
{
"type": "separator",
"margin": "lg"
},
{
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "合計",
"size": "sm",
"color": "#555555"
},
{
"type": "text",
"text": f"${round(total,2)}",
"size": "sm",
"color": "#111111",
"align": "end",
"weight": "bold"
}
],
"margin": "lg"
}
]
},
"styles": {
"footer": {
"separator": True
}
}
}
def get_checkout_bubble(checkout_list: list):
carousel_contents = []
checkout_total = 0.0
checkout_contents = []
checkout_items = {key: value for key, value in message_list.items() if not value.get("quoted_msg_id")}
for _, value in checkout_items.items():
msg_text = value.get("msg_text")
amount = round(float(value.get("amount")), 2)
checkout_total += amount
if msg_text:
msg_text = msg_text.split("$")[0]
checkout_contents.append({
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": msg_text,
"size": "sm",
"color": "#555555",
"flex": 0
},
{
"type": "text",
"text": f"${amount}",
"size": "sm",
"color": "#111111",
"align": "end"
}
],
"margin": "sm"
})
carousel_contents.append({
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "結算明細",
"weight": "bold",
"color": "#1DB446",
"size": "sm"
},
{
"type": "text",
"text": "此次結算包含:",
"size": "sm",
"color": "#aaaaaa",
"wrap": True,
"margin": "lg"
},
{
"type": "box",
"layout": "vertical",
"margin": "md",
"spacing": "sm",
"contents": checkout_contents},
{
"type": "separator",
"margin": "lg"
},
{
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "合計",
"size": "sm",
"color": "#555555"
},
{
"type": "text",
"text": f"${round(checkout_total,2)}",
"size": "sm",
"color": "#111111",
"align": "end",
"weight": "bold"
}
],
"margin": "lg"
}
]
},
"styles": {
"footer": {
"separator": True
}
}
}
)
current_user = checkout_list[0].get("from")
current_total = 0.0
current_pay_to_contents = []
checkout_list.append({"from": None, "to": None, "amount": 0})
for item in checkout_list:
if current_user != item.get("from"):
carousel_contents.append({
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "結算明細",
"weight": "bold",
"color": "#1DB446",
"size": "sm"
},
{
"type": "text",
"text": current_user,
"weight": "bold",
"size": "xxl",
"wrap": True,
"margin": "md"
},
{
"type": "text",
"text": "需付款給:",
"size": "sm",
"color": "#aaaaaa",
"wrap": True,
"margin": "lg"
},
{
"type": "box",
"layout": "vertical",
"margin": "md",
"spacing": "sm",
"contents": current_pay_to_contents},
{
"type": "separator",
"margin": "lg"
},
{
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "合計",
"size": "sm",
"color": "#555555"
},
{
"type": "text",
"text": f"${round(current_total,2)}",
"size": "sm",
"color": "#111111",
"align": "end",
"weight": "bold"
}
],
"margin": "lg"
}
]
},
"styles": {
"footer": {
"separator": True
}
}
}
)
current_user = item.get("from")
current_total = 0.0
current_pay_to_contents = []
amount = round(float(item.get("amount")), 2)
current_total += amount
current_pay_to_contents.append({
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": item.get("to"),
"size": "sm",
"color": "#555555",
"flex": 0
},
{
"type": "text",
"text": f"${amount}",
"size": "sm",
"color": "#111111",
"align": "end"
}
]
},)
return {
"type": "carousel",
"contents": carousel_contents
}
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)
|