🎨 统一发送格式

This commit is contained in:
HibiKier
2024-08-10 02:25:04 +08:00
parent 5e4de123b0
commit e0a3fe526e
61 changed files with 758 additions and 665 deletions
+16 -14
View File
@@ -1,10 +1,12 @@
from nonebot_plugin_alconna import At
from nonebot_plugin_alconna import At as alcAt
from nonebot_plugin_alconna import Image
from nonebot_plugin_alconna import Image as alcImage
from nonebot_plugin_alconna import Text as alcText
from nonebot_plugin_alconna import UniMessage, UniMsg
from nonebot_plugin_saa import Image, Mention, MessageFactory, Text
from zhenxun.utils.image_utils import ImageTemplate
from zhenxun.utils.message import MessageUtils
from ._model import WordBank
@@ -210,7 +212,7 @@ class WordBankManage:
index: int | None = None,
group_id: str | None = None,
word_scope: int | None = 1,
) -> Text | MessageFactory | Image:
) -> UniMessage:
"""获取群词条
参数:
@@ -228,25 +230,25 @@ class WordBankManage:
word_scope,
)
if not _problem_list:
return Text(problem)
return MessageUtils.build_message(problem)
for msg in _problem_list:
_text = str(msg)
if isinstance(msg, Mention):
_text = f"[at:{msg.data}]"
if isinstance(msg, At):
_text = f"[at:{msg.target}]"
elif isinstance(msg, Image):
_text = msg.data
_text = msg.url or msg.path
elif isinstance(msg, list):
_text = []
for m in msg:
__text = str(m)
if isinstance(m, Mention):
__text = f"[at:{m.data['user_id']}]"
if isinstance(m, At):
__text = f"[at:{m.target}]"
elif isinstance(m, Image):
# TODO: 显示词条回答图片
# __text = (m.data["image"], 30, 30)
__text = "[图片]"
_text.append(__text)
msg_list.append("".join(_text))
msg_list.append("".join(str(_text)))
column_name = ["序号", "回答内容"]
data_list = []
for index, msg in enumerate(msg_list):
@@ -254,7 +256,7 @@ class WordBankManage:
template_image = await ImageTemplate.table_page(
f"词条 {problem} 的回答", None, column_name, data_list
)
return Image(template_image.pic2bytes())
return MessageUtils.build_message(template_image)
else:
result = []
if group_id:
@@ -265,7 +267,7 @@ class WordBankManage:
raise Exception("群组id和词条范围不能都为空")
global_problem_list = await WordBank.get_problem_by_scope(0)
if not _problem_list and not global_problem_list:
return Text("未收录任何词条...")
return MessageUtils.build_message("未收录任何词条...")
column_name = ["序号", "关键词", "匹配类型", "收录用户"]
data_list = [list(s) for s in _problem_list]
for i in range(len(data_list)):
@@ -273,7 +275,7 @@ class WordBankManage:
group_image = await ImageTemplate.table_page(
"群组内词条" if group_id else "私聊词条", None, column_name, data_list
)
result.append(Image(group_image.pic2bytes()))
result.append(group_image)
if global_problem_list:
data_list = [list(s) for s in global_problem_list]
for i in range(len(data_list)):
@@ -281,5 +283,5 @@ class WordBankManage:
global_image = await ImageTemplate.table_page(
"全局词条", None, column_name, data_list
)
result.append(Image(global_image.pic2bytes()))
return MessageFactory(result)
result.append(global_image)
return MessageUtils.build_message(result)
+12 -11
View File
@@ -8,7 +8,7 @@ from typing import Any
from nonebot_plugin_alconna import At as alcAt
from nonebot_plugin_alconna import Image as alcImage
from nonebot_plugin_alconna import Text as alcText
from nonebot_plugin_saa import Image, Mention, MessageFactory, Text
from nonebot_plugin_alconna import UniMessage
from tortoise import Tortoise, fields
from tortoise.expressions import Q
from typing_extensions import Self
@@ -17,6 +17,7 @@ from zhenxun.configs.path_config import DATA_PATH
from zhenxun.services.db_context import Model
from zhenxun.utils.http_utils import AsyncHttpx
from zhenxun.utils.image_utils import get_img_hash
from zhenxun.utils.message import MessageUtils
from ._config import int2type
@@ -208,7 +209,7 @@ class WordBank(Model):
user_id: int,
group_id: int,
query: Self | None = None,
) -> MessageFactory | Text:
) -> UniMessage:
"""将占位符转换为实际内容
参数:
@@ -232,16 +233,16 @@ class WordBank(Model):
answer_split = re.split(rf"\[.*:placeholder_.*?]", answer)
placeholder_split = query.placeholder.split(",")
for index, ans in enumerate(answer_split):
result_list.append(Text(ans))
result_list.append(ans)
if index < len(type_list):
t = type_list[index]
p = placeholder_split[index]
if t == "image":
result_list.append(Image(path / p))
result_list.append(path / p)
elif t == "at":
result_list.append(Mention(p))
return MessageFactory(result_list)
return Text(answer)
result_list.append(alcAt(flag="user", target=p))
return MessageUtils.build_message(result_list)
return MessageUtils.build_message(answer)
@classmethod
async def check_problem(
@@ -296,7 +297,7 @@ class WordBank(Model):
problem: str,
word_scope: int | None = None,
word_type: int | None = None,
) -> Text | MessageFactory | None:
) -> UniMessage | None:
"""根据问题内容获取随机回答
参数:
@@ -324,7 +325,7 @@ class WordBank(Model):
random_answer,
)
if random_answer.placeholder
else Text(random_answer.answer)
else MessageUtils.build_message(random_answer.answer)
)
@classmethod
@@ -334,7 +335,7 @@ class WordBank(Model):
index: int | None = None,
group_id: str | None = None,
word_scope: int | None = 0,
) -> tuple[str, list[Text | MessageFactory]]:
) -> tuple[str, list[UniMessage]]:
"""获取指定问题所有回答
参数:
@@ -344,7 +345,7 @@ class WordBank(Model):
word_scope: 词条范围
返回:
tuple[str, list[Text | MessageFactory]]: 问题和所有回答
tuple[str, list[UniMessage]]: 问题和所有回答
"""
if index is not None:
# TODO: group_by和order_by不能同时使用
+33 -26
View File
@@ -9,14 +9,15 @@ from nonebot.params import RegexGroup
from nonebot.plugin import PluginMetadata
from nonebot.typing import T_State
from nonebot_plugin_alconna import AlconnaQuery, Arparma
from nonebot_plugin_alconna import Image
from nonebot_plugin_alconna import Image as alcImage
from nonebot_plugin_alconna import Match, Query, UniMsg
from nonebot_plugin_saa import Image, MessageFactory, Text
from nonebot_plugin_session import EventSession
from zhenxun.configs.config import Config
from zhenxun.configs.utils import PluginExtraData
from zhenxun.services.log import logger
from zhenxun.utils.message import MessageUtils
from ._config import scope2int, type2int
from ._data_source import WordBankManage, get_answer, get_img_and_at_list, get_problem
@@ -96,7 +97,7 @@ async def _(
user_id = session.id1
group_id = session.id3 or session.id2
if not group_id and user_id not in bot.config.superusers:
await Text("权限不足捏...").finish(reply=True)
await MessageUtils.build_message("权限不足捏...").finish(reply_to=True)
word_scope, word_type, problem, answer = reg_group
if not word_scope and not group_id:
word_scope = "私聊"
@@ -105,11 +106,13 @@ async def _(
and word_scope in ["全局", "私聊"]
and user_id not in bot.config.superusers
):
await Text("权限不足,无法添加该范围词条...").finish(reply=True)
await MessageUtils.build_message("权限不足,无法添加该范围词条...").finish(
reply_to=True
)
if (not problem or not problem.strip()) and word_type != "图片":
await Text("词条问题不能为空!").finish(reply=True)
await MessageUtils.build_message("词条问题不能为空!").finish(reply_to=True)
if (not answer or not answer.strip()) and not len(img_list) and not len(at_list):
await Text("词条回答不能为空!").finish(reply=True)
await MessageUtils.build_message("词条回答不能为空!").finish(reply_to=True)
if word_type != "图片":
state["problem_image"] = "YES"
temp_problem = message.copy()
@@ -118,7 +121,7 @@ async def _(
# if at_list:
answer = get_answer(message.copy())
# text = str(message.pop(0)).split("答", maxsplit=1)[-1].strip()
# temp_problem.insert(0, alcText(text))
# temp_problem.insert(0, alcMessageUtils.build_message(text))
state["word_scope"] = word_scope
state["word_type"] = word_type
state["problem"] = get_problem(temp_problem)
@@ -141,7 +144,7 @@ async def _(
answer: Any = Arg("answer"),
):
if not session.id1:
await Text("用户id不存在...").finish()
await MessageUtils.build_message("用户id不存在...").finish()
user_id = session.id1
group_id = session.id3 or session.id2
try:
@@ -152,16 +155,16 @@ async def _(
try:
re.compile(problem)
except re.error:
await Text(f"添加词条失败,正则表达式 {problem} 非法!").finish(
reply=True
)
await MessageUtils.build_message(
f"添加词条失败,正则表达式 {problem} 非法!"
).finish(reply_to=True)
# if str(event.user_id) in bot.config.superusers and isinstance(event, PrivateMessageEvent):
# word_scope = "私聊"
nickname = None
if problem and bot.config.nickname:
nickname = [nk for nk in bot.config.nickname if problem.startswith(nk)]
if not problem:
await Text("获取问题失败...").finish(reply=True)
await MessageUtils.build_message("获取问题失败...").finish(reply_to=True)
await WordBank.add_problem_answer(
user_id,
(
@@ -186,13 +189,15 @@ async def _(
session=session,
e=e,
)
await Text(
await MessageUtils.build_message(
f"添加词条 {problem if word_type != '图片' else '图片'} 发生错误!"
).finish(reply=True)
).finish(reply_to=True)
if word_type == "图片":
result = MessageFactory([Text("添加词条 "), Image(problem), Text(" 成功!")])
result = MessageUtils.build_message(
["添加词条 ", Image(url=problem), " 成功!"]
)
else:
result = Text(f"添加词条 {problem} 成功!")
result = MessageUtils.build_message(f"添加词条 {problem} 成功!")
await result.send()
logger.info(
f"添加词条 {problem} 成功!",
@@ -212,9 +217,9 @@ async def _(
all: Query[bool] = AlconnaQuery("all.value", False),
):
if not problem.available and not index.available:
await Text("此命令之后需要跟随指定词条或id,通过“显示词条“查看").finish(
reply=True
)
await MessageUtils.build_message(
"此命令之后需要跟随指定词条或id,通过“显示词条“查看"
).finish(reply_to=True)
word_scope = 1 if session.id3 or session.id2 else 2
if all.result:
word_scope = 0
@@ -228,7 +233,7 @@ async def _(
)
else:
if session.id1 not in bot.config.superusers:
await Text("权限不足捏...").finish(reply=True)
await MessageUtils.build_message("权限不足捏...").finish(reply_to=True)
result, _ = await WordBankManage.delete_word(
problem.result,
index.result if index.available else None,
@@ -236,7 +241,7 @@ async def _(
None,
word_scope,
)
await Text(result).send(reply=True)
await MessageUtils.build_message(result).send(reply_to=True)
logger.info(f"删除词条: {problem.result}", arparma.header_result, session=session)
@@ -251,9 +256,9 @@ async def _(
all: Query[bool] = AlconnaQuery("all.value", False),
):
if not problem.available and not index.available:
await Text("此命令之后需要跟随指定词条或id,通过“显示词条“查看").finish(
reply=True
)
await MessageUtils.build_message(
"此命令之后需要跟随指定词条或id,通过“显示词条“查看"
).finish(reply_to=True)
word_scope = 1 if session.id3 or session.id2 else 2
if all.result:
word_scope = 0
@@ -267,7 +272,7 @@ async def _(
)
else:
if session.id1 not in bot.config.superusers:
await Text("权限不足捏...").finish(reply=True)
await MessageUtils.build_message("权限不足捏...").finish(reply_to=True)
result, old_problem = await WordBankManage.update_word(
replace,
problem.result if problem.available else "",
@@ -275,7 +280,7 @@ async def _(
session.id3 or session.id2,
word_scope,
)
await Text(result).send(reply=True)
await MessageUtils.build_message(result).send(reply_to=True)
logger.info(
f"更新词条词条: {old_problem} -> {replace}",
arparma.header_result,
@@ -303,7 +308,9 @@ async def _(
if index.result < 0 or index.result > len(
await WordBank.get_problem_by_scope(2)
):
await Text("id必须在范围内...").finish(reply=True)
await MessageUtils.build_message("id必须在范围内...").finish(
reply_to=True
)
result = await WordBankManage.show_word(
problem.result,
index.result if index.available else None,