-
Notifications
You must be signed in to change notification settings - Fork 12
/
manager.py
163 lines (142 loc) · 5.19 KB
/
manager.py
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
import re
from enum import IntEnum
from typing import Any, Dict, Tuple, Union
import yaml
from meme_generator.manager import get_memes
from meme_generator.meme import Meme
from pydantic import BaseModel
import hoshino
from .config import meme_disabled_list
from .meme_optional import *
from pathlib import Path
config_file_path = Path(os.path.join(os.path.dirname(__file__), "config.yml"))
class MemeMode(IntEnum):
BLACK = 0
WHITE = 1
class MemeConfig(BaseModel):
mode: int = MemeMode.BLACK.value
white_list: List[str] = []
black_list: List[str] = []
class Config:
use_enum_values = True
class ActionResult(IntEnum):
SUCCESS = 0
FAILED = 1
NOTFOUND = 2
class MemeManager:
def __init__(self, path: Path = config_file_path):
self.__path = path
self.__meme_list: Dict[str, MemeConfig] = {}
self.memes = list(
filter(
lambda meme: meme.key not in meme_disabled_list,
sorted(get_memes(), key=lambda meme: meme.key),
)
)
self.__load()
self.__dump()
def block(
self, user_id: str, meme_names=None
) -> Dict[str, ActionResult]:
if meme_names is None:
meme_names = []
results = {}
for name in meme_names:
meme, _ = self.find(name)
if not meme:
results[name] = ActionResult.NOTFOUND
continue
config = self.__meme_list[meme.key]
if user_id not in config.black_list:
config.black_list.append(user_id)
if user_id in config.white_list:
config.white_list.remove(user_id)
results[name] = ActionResult.SUCCESS
self.__dump()
return results
def unblock(
self, user_id: str, meme_names=None
) -> Dict[str, ActionResult]:
if meme_names is None:
meme_names = []
results = {}
for name in meme_names:
meme, _ = self.find(name)
if not meme:
results[name] = ActionResult.NOTFOUND
continue
config = self.__meme_list[meme.key]
if user_id not in config.white_list:
config.white_list.append(user_id)
if user_id in config.black_list:
config.black_list.remove(user_id)
results[name] = ActionResult.SUCCESS
self.__dump()
return results
def change_mode(
self, mode: int, meme_names=None
) -> Dict[str, ActionResult]:
if meme_names is None:
meme_names = []
results = {}
for name in meme_names:
meme, _ = self.find(name)
if not meme:
results[name] = ActionResult.NOTFOUND
continue
config = self.__meme_list[meme.key]
config.mode = mode
results[name] = ActionResult.SUCCESS
self.__dump()
return results
def find(self, meme_name: str) -> Tuple[Union[Meme, None], bool]:
for meme in self.memes:
if meme_name.lower() == meme.key.lower():
return meme, False
for keyword in sorted(meme.keywords, reverse=True):
if meme_name.lower() == keyword.lower():
return meme, False
if meme.shortcuts:
for shortcut in meme.shortcuts:
if re.search(shortcut.key, meme_name, re.IGNORECASE):
return meme, True
return None, False
def check(self, user_id: str, meme_key: str) -> bool:
if meme_key not in self.__meme_list:
return False
config = self.__meme_list[meme_key]
if config.mode == MemeMode.BLACK.value:
if user_id in config.black_list:
return False
return True
elif config.mode == MemeMode.WHITE.value:
if user_id in config.white_list:
return True
return False
return False
def __load(self):
raw_list: Dict[str, Any] = {}
if self.__path.exists():
with self.__path.open("r", encoding="utf-8") as f:
try:
raw_list = yaml.safe_load(f)
except UnicodeDecodeError:
hoshino.logger.warning("表情列表解析失败,将重新生成")
try:
meme_list = {
name: MemeConfig.model_validate(config) for name, config in raw_list.items()
}
except AttributeError:
meme_list = {}
hoshino.logger.warning("表情列表解析失败,将重新生成")
self.__meme_list = {meme.key: MemeConfig() for meme in self.memes}
self.__meme_list.update(meme_list)
def __dump(self):
self.__path.parent.mkdir(parents=True, exist_ok=True)
try:
meme_list = {name: config.model_dump() for name, config in self.__meme_list.items()}
except: # compatible with pydantic 1.x
meme_list = {name: config.dict() for name, config in self.__meme_list.items()}
with self.__path.open("w", encoding="utf-8") as f:
yaml.dump(meme_list, f, allow_unicode=True)
meme_manager = MemeManager()