-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreminder.py
More file actions
173 lines (137 loc) · 4.72 KB
/
reminder.py
File metadata and controls
173 lines (137 loc) · 4.72 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
172
173
from __future__ import annotations
import json
import re
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
from mcdreforged.api.all import (
Info,
PluginServerInterface,
RAction,
RColor,
RText,
RTextBase,
RTextList,
)
config_path = Path("config/reminder.json")
FORMAT_CODE = re.compile(r"(?<!\$)\$[0-9a-gklmnor]")
PREFIX = "!!motd"
HELP_MESSAGE = (
"================== §bjoin reminder§r ==================\n"
f"§b{PREFIX} §r 顯示所有提醒\n"
f"§b{PREFIX} help §r 顯示幫助\n"
f"§b{PREFIX} del <name> §r 刪除提醒\n"
f"§b{PREFIX} <name> [duration] §r 添加 <name> 提醒 <duration> 為提醒截止間隔 (1d2h3m4s)\n"
)
list_dic: dict[str, float] = {}
def read() -> dict[str, float]:
global list_dic # pylint: disable=global-statement
try:
if config_path.exists():
list_dic = json.loads(config_path.read_text(encoding="utf-8"))
else:
save()
except Exception:
save()
return list_dic
def save():
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(
json.dumps(list_dic, indent=4, ensure_ascii=False),
encoding="utf-8",
)
def search(name: str) -> Optional[tuple[str, float]]:
for k, v in list_dic.items():
if name == k:
return k, v
return None
def parse_format(text: str) -> str:
return FORMAT_CODE.sub(
lambda x: x.group(0).replace("$", "§"),
text,
).replace("$$", "$")
def parse_interval(str_interval: str) -> float:
if str_interval.startswith("-"):
return -1.0
digit, result = "", 0.0
time_map = {"s": 1, "m": 60, "h": 3600, "d": 86400}
def get_increment(s: str = "") -> float:
return float(digit or 1) * time_map.get(s, 1)
for s in str_interval:
if s.isdigit():
digit += s
elif s in time_map:
result += get_increment(s)
digit = ""
if digit:
result += float(digit)
return (datetime.now() + timedelta(seconds=result)).timestamp()
def list_info(null: bool = False) -> RTextBase:
elements: list[RTextBase] = []
current_list = list(read().items())
for name, time_val in current_list:
if time_val == -1:
time_str = "永久"
elif (time_dt := datetime.fromtimestamp(time_val)) < datetime.now():
if name in list_dic:
del list_dic[name]
save()
continue
else:
time_str = time_dt.strftime("%Y-%m-%d %H:%M:%S")
line = RTextList(
"- ",
RText("[x]", color=RColor.red)
.c(RAction.suggest_command, f"{PREFIX} del {name}")
.h(RText("刪除提醒", color=RColor.red)),
RText(f" {parse_format(name)}", color=RColor.aqua)
.c(RAction.suggest_command, f"{PREFIX} {name} {time_val}")
.h(
RTextList(
"點擊以修改或延長\n",
RText("截止時間: ", color=RColor.gray),
RText(time_str, color=RColor.gold),
)
),
"\n",
)
elements.append(line)
if not elements:
return RText("目前無任何提醒", color=RColor.gray) if null else RText("")
return RTextList(*elements)
def on_info(server: PluginServerInterface, info: Info):
if info.is_user and info.content and info.content.startswith(PREFIX):
args = info.content.split()
len_args = len(args)
# !!motd
if len_args == 1:
server.reply(info, list_info(null=True))
return
arg1 = args[1]
# !!motd help
if arg1 == "help" and len_args == 2:
server.reply(info, HELP_MESSAGE)
return
# !!motd del <name>
if arg1 in ("del", "delete", "rm", "remove", "d") and len_args >= 3:
target = args[2]
if target in list_dic:
del list_dic[target]
save()
server.reply(info, RTextList("§b", parse_format(target), "§r 已成功刪除"))
else:
server.reply(info, RTextList("§b", parse_format(target), "§r 不存在"))
return
# !!motd <name> [duration]
name = arg1
if len_args == 2:
list_dic[name] = -1.0
else:
list_dic[name] = parse_interval(args[2])
save()
server.reply(info, "添加/更新提醒完成")
server.reply(info, list_info(null=True))
def on_player_joined(server: PluginServerInterface, player_name: str, _info: Info):
message = list_info()
if message.to_plain_text().strip():
server.tell(player_name, message)