-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
171 lines (139 loc) Β· 5.66 KB
/
utils.py
File metadata and controls
171 lines (139 loc) Β· 5.66 KB
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
import os
from zoneinfo import ZoneInfo
from datetime import datetime
from typing import List, Tuple
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes
from telegram.helpers import (
escape_markdown,
) # to allow special characters from being processed as markdown
import db
from api import fetch_ac_submissions, get_question_details
from api import LeetCodeQuestion
TIMEZONE = ZoneInfo(os.getenv("TIMEZONE", "Asia/Singapore"))
def solved_today(username: str, now: datetime) -> Tuple[bool, List[str]]:
day_start = datetime(now.year, now.month, now.day, tzinfo=TIMEZONE).timestamp()
day_end = datetime(
now.year, now.month, now.day, 23, 59, 59, tzinfo=TIMEZONE
).timestamp()
titles = []
res = fetch_ac_submissions(username)
if res:
submissions = res.get("submission", [])
for sub in submissions:
ts = int(sub.get("timestamp", 0))
if day_start <= ts <= day_end:
t = sub.get("titleSlug")
titles.append(t)
if titles:
return True, titles
return False, []
def get_difficulty_icon(difficulty: str) -> str:
mapping = {"Easy": "π’", "Medium": "π‘", "Hard": "π΄"}
return mapping.get(difficulty, "β")
def build_question_links(title_slugs: list[str]) -> list[str]:
links: list[str] = []
for title_slug in title_slugs:
url = f"https://leetcode.com/problems/{title_slug}/"
title = title_slug.replace("-", " ").title()
difficulty_icon = get_difficulty_icon(None)
try:
question: LeetCodeQuestion = get_question_details(title_slug)
except Exception as e:
question = None
if question:
url = question.get("link", url)
title = question.get("questionTitle", title)
difficulty_icon = get_difficulty_icon(question.get("difficulty"))
escaped_title = escape_markdown(title)
links.append(f"[{escaped_title}]({url}) {difficulty_icon}")
return links
async def send_status_message(
update: Update, context: ContextTypes.DEFAULT_TYPE, players: dict, is_refresh=False
):
# no players present
if not players:
msg = "No players linked yet. Use `/link <username>` to join!"
if is_refresh:
# if refreshing, edit the existing message
await update.callback_query.edit_message_text(msg)
else:
# else send a new message
await update.message.reply_text(msg)
return
# players present, build status message
now = datetime.now(TIMEZONE)
escaped_date_str = escape_markdown(now.strftime("%d/%m/%Y, %H:%M:%S"))
lines = [f"_Last Updated: {escaped_date_str}_\n"]
for player in players.values():
# get lc username
lc_username = player.get_lc_username()
# check if solved today
is_solved, question_slugs = solved_today(lc_username, now)
# --- MOCK DATA FOR TESTING ---
if lc_username == "lc_username_1":
is_solved = True
question_slugs = ["two-sum", "add-two-numbers"]
# --------------------------------
# update streak logic
if is_solved:
last_upgrade = player.get_last_streak_upgrade()
should_upgrade = False
if last_upgrade is None:
should_upgrade = True
else:
try:
# convert to same timezone to compare dates
local_last_upgrade = last_upgrade.astimezone(TIMEZONE)
if local_last_upgrade.date() < now.date():
should_upgrade = True
except Exception:
# fallback if timezone conversion fails
should_upgrade = True
if should_upgrade:
new_streak = player.increment_streak()
success = db.update_streak(player.get_tele_id(), new_streak, now)
if success:
player.set_streak(new_streak)
player.set_last_streak_upgrade(now)
# retrieve tele username; fallback to tele id
tele_username = player.get_tele_username()
# build usernames
escaped_lc_username = escape_markdown(lc_username)
escaped_tele_username = escape_markdown(tele_username)
streak_count = player.get_streak()
status_emoji = "β
" if is_solved else "β"
# build streak line
streak_emoji = "π₯" if streak_count > 0 else "π"
lines.append(
f"{status_emoji} @{escaped_tele_username} ({escaped_lc_username}) {streak_emoji} {streak_count} {'day' if streak_count == 1 else 'days'}"
)
# build question links if solved
if is_solved and question_slugs:
links = build_question_links(question_slugs)
for link in links:
lines.append(f"β {link}")
lines.append("")
text = "\n".join(lines)
# add refresh button
keyboard = [[InlineKeyboardButton("π REFRESH", callback_data="refresh_status")]]
reply_markup = InlineKeyboardMarkup(keyboard)
if is_refresh:
# if refreshing, edit the existing message
try:
await update.callback_query.edit_message_text(
text,
parse_mode="Markdown",
reply_markup=reply_markup,
disable_web_page_preview=True,
)
except Exception as e:
pass
else:
# send new message
await update.message.reply_text(
text,
parse_mode="Markdown",
reply_markup=reply_markup,
disable_web_page_preview=True,
)