Skip to content

Commit

Permalink
perf: 优化update、help等指令的输出效果
Browse files Browse the repository at this point in the history
  • Loading branch information
Soulter committed Jun 3, 2024
1 parent b6ebb39 commit 7d88283
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 44 deletions.
19 changes: 12 additions & 7 deletions model/command/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ async def check_command(self,
return True, self.web_search(message)
if self.command_start_with(message, "update"):
return True, self.update(message, role)
if message == "t2i":
return True, "t2i", self.t2i_toggle(message, role)
if not self.provider and message == "help":
return True, await self.help()

Expand All @@ -120,18 +122,22 @@ def web_search(self, message):
elif l[1] == 'off':
self.global_object.web_search = False
return True, "已关闭网页搜索", "web"

def t2i_toggle(self, message, role):
p = cc.get("qq_pic_mode", True)
if p:
cc.put("qq_pic_mode", False)
return True, "已关闭文本转图片模式。", "t2i"
cc.put("qq_pic_mode", True)
return True, "已开启文本转图片模式。", "t2i"

def get_my_id(self, message_obj, platform):
try:
user_id = str(message_obj.user_id)
user_id = str(message_obj.sender.user_id)
return True, f"你在此平台上的ID:{user_id}", "plugin"
except BaseException as e:
return False, f"在{platform}上获取你的ID失败,原因: {str(e)}", "plugin"

'''
插件指令
'''

async def plugin_oper(self, message: str, role: str, ctx: GlobalObject, platform: str):
l = message.split(" ")
if len(l) < 2:
Expand Down Expand Up @@ -227,7 +233,6 @@ async def help_messager(self, commands: dict, platform: str, cached_plugins: Lis
for key, value in commands.items():
msg += f"- `{key}`: {value}\n"
# plugins
print(cached_plugins)
if cached_plugins:
plugin_list_info = ""
for plugin in cached_plugins:
Expand Down Expand Up @@ -261,7 +266,7 @@ def update(self, message: str, role: str):
if len(l) == 1:
try:
update_info = util.updator.check_update()
update_info += "\nTips:\n输入「update latest」更新到最新版本\n输入「update <版本号如v3.1.3>」切换到指定版本\n输入「update r」重启机器人\n"
update_info += "\n> Tips: 输入「update latest」更新到最新版本,输入「update <版本号如v3.1.3>」切换到指定版本,输入「update r」重启机器人\n"
return True, update_info, "update"
except BaseException as e:
return False, "检查更新失败: "+str(e), "update"
Expand Down
12 changes: 8 additions & 4 deletions model/platform/_message_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import botpy.message
from type.message import *
from typing import List, Union
import time
from util.general_utils import save_temp_img
import time, base64

# QQ官方消息类型转换

Expand All @@ -18,11 +19,14 @@ def qq_official_message_parse(message: List[BaseMessageComponent]):
for i in message:
if isinstance(i, Plain):
plain_text += i.text
elif isinstance(i, Image) and image_path == None:
if i.path is not None:
elif isinstance(i, Image) and not image_path:
if i.path:
image_path = i.path
elif i.file and i.file.startswith("base64://"):
img_data = base64.b64decode(i.file[9:])
image_path = save_temp_img(img_data)
else:
image_path = i.file
image_path = save_temp_img(i.file)
return plain_text, image_path

# QQ官方消息类型 2 AstrBotMessage
Expand Down
74 changes: 48 additions & 26 deletions model/platform/qq_official.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)
from type.message import *
from typing import Union, List
from nakuru.entities.components import BaseMessageComponent
from nakuru.entities.components import *
from util.image_render.helper import text_to_image_base
from SparkleLogging.utils.core import LogManager
from logging import Logger
Expand Down Expand Up @@ -65,6 +65,7 @@ def __init__(self, cfg: dict, message_handler: callable, global_object) -> None:
self.secret = cfg['qqbot_secret']
self.unique_session = cfg['uniqueSessionMode']
qq_group = cfg['qqofficial_enable_group_message']
self.pic_mode = cfg['qq_pic_mode']

if qq_group:
self.intents = botpy.Intents(
Expand Down Expand Up @@ -170,33 +171,54 @@ async def reply_msg(self,
image_path = ''
msg_ref = None

# if isinstance(res, list):
# plain_text, image_path = qq_official_message_parse(res)
# elif isinstance(res, str):
# plain_text = res

# if self.cfg['qq_pic_mode']:
# # 文本转图片,并且加上原来的图片
# if plain_text != '' or image_path != '':
# if image_path is not None and image_path != '':
# if image_path.startswith("http"):
# plain_text += "\n\n" + "![](" + image_path + ")"
# else:
# plain_text += "\n\n" + \
# "![](file:///" + image_path + ")"
# # image_path = gu.create_markdown_image("".join(plain_text))
# image_path = await text_to_image_base("".join(plain_text))
# plain_text = ""

# else:
# if image_path is not None and image_path != '':
# msg_ref = None
# if image_path.startswith("http"):
# async with aiohttp.ClientSession() as session:
# async with session.get(image_path) as response:
# if response.status == 200:
# image = PILImage.open(io.BytesIO(await response.read()))
# image_path = gu.save_temp_img(image)
if self.pic_mode:
plains = []
news = []
if isinstance(res, str):
res = [Plain(text=res, convert=False),]
for i in res:
if isinstance(i, Plain):
plains.append(i.text)
else:
news.append(i)
plains_str = "".join(plains).strip()
if plains_str and len(plains_str) > 50:
p = await text_to_image_base(plains_str, return_url=False)
with open(p, "rb") as f:
news.append(Image.fromBytes(f.read()))
res = news

if isinstance(res, list):
plain_text, image_path = qq_official_message_parse(res)
elif isinstance(res, str):
plain_text = res

if self.cfg['qq_pic_mode']:
# 文本转图片,并且加上原来的图片
if plain_text != '' or image_path != '':
if image_path is not None and image_path != '':
if image_path.startswith("http"):
plain_text += "\n\n" + "![](" + image_path + ")"
else:
plain_text += "\n\n" + \
"![](file:///" + image_path + ")"
# image_path = gu.create_markdown_image("".join(plain_text))
image_path = await text_to_image_base("".join(plain_text))
plain_text = ""

else:
if image_path is not None and image_path != '':
msg_ref = None
if image_path.startswith("http"):
async with aiohttp.ClientSession() as session:
async with session.get(image_path) as response:
if response.status == 200:
image = PILImage.open(io.BytesIO(await response.read()))
image_path = gu.save_temp_img(image)
plain_text = res

if source is not None and image_path == '': # file_image与message_reference不能同时传入
msg_ref = Reference(message_id=source.id,
Expand All @@ -217,7 +239,7 @@ async def reply_msg(self,
data['guild_id'] = source.guild_id
else:
raise ValueError(f"未知的消息类型: {message.type}")
if image_path != '':
if image_path:
data['file_image'] = image_path

try:
Expand Down
2 changes: 1 addition & 1 deletion util/image_render/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async def text_to_image_base(text: str, return_url: bool = False) -> str:
"json": return_url,
"tmpldata": {
"text": text,
"version": f"v{VERSION}"
"version": f"v{VERSION}",
},
"options": {
"full_page": True
Expand Down
14 changes: 8 additions & 6 deletions util/updator.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,18 +106,20 @@ def check_update() -> str:
if curr_commit.startswith(new_commit):
return f"当前已经是最新版本: v{VERSION}"
else:
update_info = f"""有新版本可用。
=== 当前版本 ===
update_info = f"""> 有新版本可用,请及时更新
# 当前版本
v{VERSION}
=== 新版本 ===
# 最新版本
{update_data[0]['version']}
=== 发布时间 ===
# 发布时间
{update_data[0]['published_at']}
=== 更新内容 ===
{update_data[0]['body']}"""
# 更新内容
---
{update_data[0]['body']}
---"""
return update_info

def update_project(update_data: list,
Expand Down

0 comments on commit 7d88283

Please sign in to comment.