修改查看词条图片等显示问题

This commit is contained in:
HibiKier 2023-05-23 00:23:07 +08:00
parent 848de7f4fe
commit ac98ec8351
4 changed files with 91 additions and 57 deletions

View File

@ -335,6 +335,7 @@ PS: **ARM平台** 请使用全量版 同时 **如果你的机器 RAM < 1G 可能
* 群聊中B站订阅所有管理员共享增删操作 * 群聊中B站订阅所有管理员共享增删操作
* 数据库中所有user_qq改名以及user_id和group_id改为字符串 * 数据库中所有user_qq改名以及user_id和group_id改为字符串
* 修改查看词条图片等显示问题
### 2023/5/16 ### 2023/5/16

View File

@ -17,7 +17,7 @@ driver = nonebot.get_driver()
async def get_problem_str( async def get_problem_str(
id_: Union[str, int], group_id: Optional[int] = None, word_scope: int = 1 id_: Union[str, int], group_id: Optional[str] = None, word_scope: int = 1
) -> Tuple[str, int]: ) -> Tuple[str, int]:
""" """
说明: 说明:
@ -29,16 +29,20 @@ async def get_problem_str(
""" """
if word_scope in [0, 2]: if word_scope in [0, 2]:
all_problem = await WordBank.get_problem_by_scope(word_scope) all_problem = await WordBank.get_problem_by_scope(word_scope)
else: elif group_id:
all_problem = await WordBank.get_group_all_problem(group_id) all_problem = await WordBank.get_group_all_problem(group_id)
if id_.startswith("id:"): else:
raise Exception("词条类型与群组id不能为空")
if isinstance(id_, str) and id_.startswith("id:"):
id_ = id_.split(":")[-1] id_ = id_.split(":")[-1]
if not is_number(id_) or int(id_) < 0 or int(id_) > len(all_problem): if not is_number(id_) or int(id_) < 0 or int(id_) > len(all_problem):
return "id必须为数字且在范围内", 999 return "id必须为数字且在范围内", 999
return all_problem[int(id_)][0], 200 return all_problem[int(id_)][0], 200
async def update_word(params: str, group_id: Optional[int] = None, word_scope: int = 1) -> str: async def update_word(
params: str, group_id: Optional[str] = None, word_scope: int = 1
) -> str:
""" """
说明: 说明:
修改群词条 修改群词条
@ -50,7 +54,9 @@ async def update_word(params: str, group_id: Optional[int] = None, word_scope: i
return await word_handle(params, group_id, "update", word_scope) return await word_handle(params, group_id, "update", word_scope)
async def delete_word(params: str, group_id: Optional[int] = None, word_scope: int = 1) -> str: async def delete_word(
params: str, group_id: Optional[str] = None, word_scope: int = 1
) -> str:
""" """
说明: 说明:
删除群词条 删除群词条
@ -62,7 +68,9 @@ async def delete_word(params: str, group_id: Optional[int] = None, word_scope: i
return await word_handle(params, group_id, "delete", word_scope) return await word_handle(params, group_id, "delete", word_scope)
async def word_handle(params: str, group_id: Optional[int], type_: str, word_scope: int = 0) -> str: async def word_handle(
params_: str, group_id: Optional[str], type_: str, word_scope: int = 0
) -> str:
""" """
说明: 说明:
词条操作 词条操作
@ -72,7 +80,7 @@ async def word_handle(params: str, group_id: Optional[int], type_: str, word_sco
:param type_: 类型 :param type_: 类型
:param word_scope: 词条范围 :param word_scope: 词条范围
""" """
params = params.split() params = params_.split()
problem = params[0] problem = params[0]
if problem.startswith("id:"): if problem.startswith("id:"):
problem, code = await get_problem_str(problem, group_id, word_scope) problem, code = await get_problem_str(problem, group_id, word_scope)
@ -81,57 +89,60 @@ async def word_handle(params: str, group_id: Optional[int], type_: str, word_sco
if type_ == "delete": if type_ == "delete":
index = params[1] if len(params) > 1 else None index = params[1] if len(params) > 1 else None
if index: if index:
answer_num = len(await WordBank.get_problem_all_answer(problem, group_id)) answer_num = len(
await WordBank.get_problem_all_answer(problem, group_id=group_id)
)
if not is_number(index) or int(index) < 0 or int(index) > answer_num: if not is_number(index) or int(index) < 0 or int(index) > answer_num:
return "指定回答下标id必须为数字且在范围内" return "指定回答下标id必须为数字且在范围内"
index = int(index) index = int(index)
if await WordBank.delete_group_problem(problem, group_id, index, word_scope): if await WordBank.delete_group_problem(problem, group_id, index, word_scope): # type: ignore
return "删除词条成功" return "删除词条成功"
return "词条不存在" return "词条不存在"
if type_ == "update": if type_ == "update":
replace_str = params[1] replace_str = params[1]
await WordBank.update_group_problem(problem, replace_str, group_id, word_scope=word_scope) await WordBank.update_group_problem(
problem, replace_str, group_id, word_scope=word_scope
)
return "修改词条成功" return "修改词条成功"
return "类型错误"
async def show_word( async def show_word(
problem: str, problem: str,
id_: Optional[int], id_: Optional[int],
gid: Optional[int], gid: Optional[int],
group_id: Optional[int] = None, group_id: Optional[str] = None,
word_scope: Optional[int] = None, word_scope: Optional[int] = None,
) -> Union[str, List[Union[str, Message]]]: ) -> Union[str, List[Union[str, Message]]]:
if problem: if problem:
msg_list = [] msg_list = []
if word_scope is not None: if word_scope is not None:
problem = (await WordBank.get_problem_by_scope(word_scope))[id_][0] problem = (await WordBank.get_problem_by_scope(word_scope))[id_][0] # type: ignore
id_ = None id_ = None
_problem_list = await WordBank.get_problem_all_answer( _problem_list = await WordBank.get_problem_all_answer(
problem, id_ if id_ is not None else gid, group_id if gid is None else None, word_scope problem,
id_ if id_ is not None else gid,
group_id if gid is None else None,
word_scope,
) )
for index, msg in enumerate(_problem_list): for index, msg in enumerate(_problem_list):
if isinstance(msg, Message): if isinstance(msg, Message):
temp = "" tmp = ""
for seg in msg: for seg in msg:
if seg.type == "text": tmp += seg
temp += seg msg = tmp
elif seg.type == "face": msg_list.append(f"{index}." + msg)
temp += f"[face:{seg.data.id}]"
elif seg.type == "at":
temp += f'[at:{seg.data["qq"]}]'
elif seg.type == "image":
temp += f"[image]"
msg += temp
msg_list.append(f"{index}." + msg if isinstance(msg, str) else msg[1])
msg_list = [ msg_list = [
f'词条:{problem or (f"id: {id_}" if id_ is not None else f"gid: {gid}")} 的回答' f'词条:{problem or (f"id: {id_}" if id_ is not None else f"gid: {gid}")} 的回答'
] + msg_list ] + msg_list
return msg_list return msg_list # type: ignore
else: else:
if group_id: if group_id:
_problem_list = await WordBank.get_group_all_problem(group_id) _problem_list = await WordBank.get_group_all_problem(group_id)
else: elif word_scope is not None:
_problem_list = await WordBank.get_problem_by_scope(word_scope) _problem_list = await WordBank.get_problem_by_scope(word_scope)
else:
raise Exception("群组id和词条范围不能都为空")
global_problem_list = await WordBank.get_problem_by_scope(0) global_problem_list = await WordBank.get_problem_by_scope(0)
if not _problem_list and not global_problem_list: if not _problem_list and not global_problem_list:
return "未收录任何词条.." return "未收录任何词条.."
@ -190,11 +201,11 @@ async def _():
return return
if await WordBank.get_group_all_problem(0): if await WordBank.get_group_all_problem(0):
return return
logger.info('开始迁移词条 纯文本 数据') logger.info("开始迁移词条 纯文本 数据")
try: try:
word_list = await OldWordBank.get_all() word_list = await OldWordBank.get_all()
new_answer_path = Path() / 'data' / 'word_bank' / 'answer' new_answer_path = Path() / "data" / "word_bank" / "answer"
new_problem_path = Path() / 'data' / 'word_bank' / 'problem' new_problem_path = Path() / "data" / "word_bank" / "problem"
new_answer_path.mkdir(exist_ok=True, parents=True) new_answer_path.mkdir(exist_ok=True, parents=True)
for word in word_list: for word in word_list:
problem: str = word.problem problem: str = word.problem
@ -203,35 +214,57 @@ async def _():
format_ = word.format format_ = word.format
answer = word.answer answer = word.answer
# 仅对纯文本做处理 # 仅对纯文本做处理
if '[CQ' not in problem and '[CQ' not in answer and '[_to_me' not in problem: if (
"[CQ" not in problem
and "[CQ" not in answer
and "[_to_me" not in problem
):
if not format_: if not format_:
await WordBank.add_problem_answer(user_id, group_id, 1, 0, problem, answer) await WordBank.add_problem_answer(
user_id, group_id, 1, 0, problem, answer
)
else: else:
placeholder = [] placeholder = []
for m in format_.split('<format>'): for m in format_.split("<format>"):
x = m.split('<_s>') x = m.split("<_s>")
if x[0]: if x[0]:
idx, file_name = x[0], x[1] idx, file_name = x[0], x[1]
if 'jpg' in file_name: if "jpg" in file_name:
answer = answer.replace(f'[__placeholder_{idx}]', f'[image:placeholder_{idx}]') answer = answer.replace(
file = Path() / 'data' / 'word_bank' / f'{group_id}' / file_name f"[__placeholder_{idx}]",
f"[image:placeholder_{idx}]",
)
file = (
Path()
/ "data"
/ "word_bank"
/ f"{group_id}"
/ file_name
)
rand = int(time.time()) + random.randint(1, 100000) rand = int(time.time()) + random.randint(1, 100000)
if file.exists(): if file.exists():
new_file = new_answer_path / f'{group_id}' / f'{user_id}_{rand}.jpg' new_file = (
new_answer_path
/ f"{group_id}"
/ f"{user_id}_{rand}.jpg"
)
new_file.parent.mkdir(exist_ok=True, parents=True) new_file.parent.mkdir(exist_ok=True, parents=True)
with open(file, 'rb') as rb: with open(file, "rb") as rb:
with open(new_file, 'wb') as wb: with open(new_file, "wb") as wb:
wb.write(rb.read()) wb.write(rb.read())
# file.rename(new_file) # file.rename(new_file)
placeholder.append(f'answer/{group_id}/{user_id}_{rand}.jpg') placeholder.append(
await WordBank._move(user_id, group_id, problem, answer, ",".join(placeholder)) f"answer/{group_id}/{user_id}_{rand}.jpg"
await WordBank.add_problem_answer(0, 0, 999, 0, '_[OK', '_[OK') )
logger.info('词条 纯文本 数据迁移完成') await WordBank._move(
(Path() / 'plugins' / 'word_bank' / '_old_model.py').unlink() user_id,
group_id,
problem,
answer,
",".join(placeholder),
)
await WordBank.add_problem_answer(0, 0, 999, 0, "_[OK", "_[OK")
logger.info("词条 纯文本 数据迁移完成")
(Path() / "plugins" / "word_bank" / "_old_model.py").unlink()
except Exception as e: except Exception as e:
logger.warning(f'迁移词条发生错误,如果为首次安装请无视 {type(e)}{e}') logger.warning(f"迁移词条发生错误,如果为首次安装请无视 {type(e)}{e}")

View File

@ -324,7 +324,7 @@ class WordBank(Model):
cls, cls,
problem: str, problem: str,
index: Optional[int] = None, index: Optional[int] = None,
group_id: Optional[int] = None, group_id: Optional[str] = None,
word_scope: Optional[int] = 0, word_scope: Optional[int] = 0,
) -> List[Union[str, Message]]: ) -> List[Union[str, Message]]:
""" """
@ -351,7 +351,7 @@ class WordBank(Model):
async def delete_group_problem( async def delete_group_problem(
cls, cls,
problem: str, problem: str,
group_id: str, group_id: Optional[str],
index: Optional[int] = None, index: Optional[int] = None,
word_scope: int = 1, word_scope: int = 1,
): ):
@ -386,7 +386,7 @@ class WordBank(Model):
cls, cls,
problem: str, problem: str,
replace_str: str, replace_str: str,
group_id: str, group_id: Optional[str],
index: Optional[int] = None, index: Optional[int] = None,
word_scope: int = 1, word_scope: int = 1,
): ):

View File

@ -228,7 +228,7 @@ async def _(
async def _(event: GroupMessageEvent, arg: Message = CommandArg()): async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
if not (msg := arg.extract_plain_text().strip()): if not (msg := arg.extract_plain_text().strip()):
await delete_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") await delete_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
result = await delete_word(msg, event.group_id) result = await delete_word(msg, str(event.group_id))
await delete_word_matcher.send(result) await delete_word_matcher.send(result)
logger.info(f"删除词条:" + msg, "删除词条", event.user_id, event.group_id) logger.info(f"删除词条:" + msg, "删除词条", event.user_id, event.group_id)
@ -255,7 +255,7 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
await update_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") await update_word_matcher.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
if len(msg.split()) < 2: if len(msg.split()) < 2:
await update_word_matcher.finish("此命令需要两个参数,请查看帮助") await update_word_matcher.finish("此命令需要两个参数,请查看帮助")
result = await update_word(msg, event.group_id) result = await update_word(msg, str(event.group_id))
await update_word_matcher.send(result) await update_word_matcher.send(result)
logger.info(f"更新词条词条:" + msg, "更新词条", event.user_id, event.group_id) logger.info(f"更新词条词条:" + msg, "更新词条", event.user_id, event.group_id)
@ -302,9 +302,9 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
): ):
await show_word_matcher.finish("gid必须为数字且在范围内") await show_word_matcher.finish("gid必须为数字且在范围内")
gid = int(gid) gid = int(gid)
msg_list = await show_word(problem, id_, gid, None if gid else event.group_id) msg_list = await show_word(problem, id_, gid, None if gid else str(event.group_id))
else: else:
msg_list = await show_word(problem, None, None, event.group_id) msg_list = await show_word(problem, None, None, str(event.group_id))
if isinstance(msg_list, str): if isinstance(msg_list, str):
await show_word_matcher.send(msg_list) await show_word_matcher.send(msg_list)
else: else: