1
0
forked from bot/app

擴展event字段

This commit is contained in:
远野千束 2024-08-20 20:38:10 +08:00
parent eb7c8300fa
commit 598bff8c49
8 changed files with 30 additions and 52 deletions

View File

@ -45,7 +45,7 @@ class Matcher:
self.handlers.append(handler) self.handlers.append(handler)
return handler return handler
async def run(self, event: Event) -> None: async def run(self, event: MessageEvent) -> None:
""" """
运行处理函数 运行处理函数
Args: Args:

View File

@ -64,7 +64,7 @@ async def _(bot: T_Bot, event: T_MessageEvent):
btn_restart = md.btn_cmd(ulang.get("liteyuki.restart_now"), "reload-liteyuki") btn_restart = md.btn_cmd(ulang.get("liteyuki.restart_now"), "reload-liteyuki")
pip.main(["install", "-r", "requirements.txt"]) pip.main(["install", "-r", "requirements.txt"])
reply += f"{ulang.get('liteyuki.update_restart', RESTART=btn_restart)}" reply += f"{ulang.get('liteyuki.update_restart', RESTART=btn_restart)}"
await md.send_md(reply, bot, event=event, at_sender=False) await md.send_md(reply, bot)
@on_alconna( @on_alconna(

View File

@ -64,7 +64,7 @@ async def _(event: T_MessageEvent, result: Arparma, bot: T_Bot):
) )
minesweeper_cache.append(new_game) minesweeper_cache.append(new_game)
await minesweeper.send("游戏开始") await minesweeper.send("游戏开始")
await md.send_md(new_game.board_markdown(), bot, event=event) await md.send_md(new_game.board_markdown(), bot)
except AssertionError: except AssertionError:
await minesweeper.finish("参数错误") await minesweeper.finish("参数错误")
elif result.subcommands.get("end"): elif result.subcommands.get("end"):
@ -83,9 +83,9 @@ async def _(event: T_MessageEvent, result: Arparma, bot: T_Bot):
await minesweeper.finish("参数错误") await minesweeper.finish("参数错误")
if not game.reveal(row, col): if not game.reveal(row, col):
minesweeper_cache.remove(game) minesweeper_cache.remove(game)
await md.send_md(game.board_markdown(), bot, event=event) await md.send_md(game.board_markdown(), bot)
await minesweeper.finish("游戏结束") await minesweeper.finish("游戏结束")
await md.send_md(game.board_markdown(), bot, event=event) await md.send_md(game.board_markdown(), bot)
if game.is_win(): if game.is_win():
minesweeper_cache.remove(game) minesweeper_cache.remove(game)
await minesweeper.finish("游戏胜利") await minesweeper.finish("游戏胜利")
@ -98,6 +98,6 @@ async def _(event: T_MessageEvent, result: Arparma, bot: T_Bot):
if not (0 <= row < game.rows and 0 <= col < game.cols): if not (0 <= row < game.rows and 0 <= col < game.cols):
await minesweeper.finish("参数错误") await minesweeper.finish("参数错误")
game.board[row][col].flagged = not game.board[row][col].flagged game.board[row][col].flagged = not game.board[row][col].flagged
await md.send_md(game.board_markdown(), bot, event=event) await md.send_md(game.board_markdown(), bot)
else: else:
await minesweeper.finish("参数错误") await minesweeper.finish("参数错误")

View File

@ -292,7 +292,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
reply += f"\n{ulang.get('npm.too_many_results', HIDE_NUM=len(rs) - max_show)}" reply += f"\n{ulang.get('npm.too_many_results', HIDE_NUM=len(rs) - max_show)}"
else: else:
reply = ulang.get("npm.search_no_result") reply = ulang.get("npm.search_no_result")
await md.send_md(reply, bot, event=event) await md.send_md(reply, bot)
elif sc.get("install") and perm_s: elif sc.get("install") and perm_s:
plugin_name: str = result.subcommands["install"].args.get("plugin_name") plugin_name: str = result.subcommands["install"].args.get("plugin_name")
@ -320,7 +320,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
info = md.escape( info = md.escape(
ulang.get("npm.install_success", NAME=store_plugin.name) ulang.get("npm.install_success", NAME=store_plugin.name)
) # markdown转义 ) # markdown转义
await md.send_md(f"{info}\n\n" f"```\n{log}\n```", bot, event=event) await md.send_md(f"{info}\n\n" f"```\n{log}\n```", bot)
else: else:
await npm.finish( await npm.finish(
ulang.get( ulang.get(
@ -331,12 +331,12 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
info = ulang.get( info = ulang.get(
"npm.load_failed", NAME=plugin_name, HOMEPAGE=homepage_btn "npm.load_failed", NAME=plugin_name, HOMEPAGE=homepage_btn
).replace("_", r"\\_") ).replace("_", r"\\_")
await md.send_md(f"{info}\n\n" f"```\n{log}\n```\n", bot, event=event) await md.send_md(f"{info}\n\n" f"```\n{log}\n```\n", bot)
else: else:
info = ulang.get( info = ulang.get(
"npm.install_failed", NAME=plugin_name, HOMEPAGE=homepage_btn "npm.install_failed", NAME=plugin_name, HOMEPAGE=homepage_btn
).replace("_", r"\\_") ).replace("_", r"\\_")
await md.send_md(f"{info}\n\n" f"```\n{log}\n```", bot, event=event) await md.send_md(f"{info}\n\n" f"```\n{log}\n```", bot)
elif sc.get("uninstall") and perm_s: elif sc.get("uninstall") and perm_s:
plugin_name: str = result.subcommands["uninstall"].args.get("plugin_name") # type: ignore plugin_name: str = result.subcommands["uninstall"].args.get("plugin_name") # type: ignore
@ -464,7 +464,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
else ulang.get("npm.next_page") else ulang.get("npm.next_page")
) )
reply += f"\n{btn_prev} {page}/{total} {btn_next}" reply += f"\n{btn_prev} {page}/{total} {btn_next}"
await md.send_md(reply, bot, event=event) await md.send_md(reply, bot)
else: else:
if await SUPERUSER(bot, event): if await SUPERUSER(bot, event):
@ -517,7 +517,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
f"\n\n>page为页数num为每页显示数量" f"\n\n>page为页数num为每页显示数量"
f"\n\n>*{md.escape('npm list [page] [num]')}*" f"\n\n>*{md.escape('npm list [page] [num]')}*"
) )
await md.send_md(reply, bot, event=event) await md.send_md(reply, bot)
else: else:
btn_list = md.btn_cmd( btn_list = md.btn_cmd(
@ -539,7 +539,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot, npm: Matcher):
f"\n\n>page为页数num为每页显示数量" f"\n\n>page为页数num为每页显示数量"
f"\n\n>*{md.escape('npm list [page] [num]')}*" f"\n\n>*{md.escape('npm list [page] [num]')}*"
) )
await md.send_md(reply, bot, event=event) await md.send_md(reply, bot)
@on_alconna( @on_alconna(
@ -679,7 +679,7 @@ async def _(result: Arparma, matcher: Matcher, event: T_MessageEvent, bot: T_Bot
else mdc.paragraph(ulang.get("npm.homepage")) else mdc.paragraph(ulang.get("npm.homepage"))
), ),
] ]
await md.send_md(compile_md(reply), bot, event=event) await md.send_md(compile_md(reply), bot)
else: else:
await matcher.finish(ulang.get("npm.plugin_not_found", NAME=plugin_name)) await matcher.finish(ulang.get("npm.plugin_not_found", NAME=plugin_name))
else: else:

View File

@ -181,6 +181,6 @@ async def _(bot: T_Bot, event: T_MessageEvent, result: Arparma, matcher: Matcher
else: else:
pass pass
if send_as_md: if send_as_md:
await md.send_md(reply, bot, event=event) await md.send_md(reply, bot)
else: else:
await matcher.finish(reply) await matcher.finish(reply)

View File

@ -65,7 +65,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot):
# 未输入值,尝试呼出菜单 # 未输入值,尝试呼出菜单
menu = get_profile_menu(result.args["key"], ulang) menu = get_profile_menu(result.args["key"], ulang)
if menu: if menu:
await md.send_md(menu, bot, event=event) await md.send_md(menu, bot)
else: else:
await profile_alc.finish(ulang.get("user.profile.input_value", ATTR=ulang.get(f"user.profile.{result.args['key']}"))) await profile_alc.finish(ulang.get("user.profile.input_value", ATTR=ulang.get(f"user.profile.{result.args['key']}")))
@ -97,7 +97,7 @@ async def _(result: Arparma, event: T_MessageEvent, bot: T_Bot):
reply += (f"\n**{key_text}** **{val}**\n" reply += (f"\n**{key_text}** **{val}**\n"
f"\n> {ulang.get(f'user.profile.{key}.desc')}" f"\n> {ulang.get(f'user.profile.{key}.desc')}"
f"\n> {btn_set} \n\n***\n") f"\n> {btn_set} \n\n***\n")
await md.send_md(reply, bot, event=event) await md.send_md(reply, bot)
def get_profile_menu(key: str, ulang: Language) -> Optional[str]: def get_profile_menu(key: str, ulang: Language) -> Optional[str]:

View File

@ -1,18 +0,0 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:30
@Author : snowykami
@Email : snowykami@outlook.com
@File : __init__.py.py
@Software: PyCharm
"""
from nonebot import require
from liteyuki.comm.storage import shared_memory
require("nonebot_plugin_alconna")
from nonebot_plugin_alconna import UniMessage, Command, on_alconna

View File

@ -22,9 +22,6 @@ config = load_from_yaml("config.yml")
can_send_markdown = {} # 用于存储机器人是否支持发送markdown消息id->bool can_send_markdown = {} # 用于存储机器人是否支持发送markdown消息id->bool
class TencentBannedMarkdownError(BaseException):
pass
async def broadcast_to_superusers(message: str | T_Message, markdown: bool = False): async def broadcast_to_superusers(message: str | T_Message, markdown: bool = False):
"""广播消息给超级用户""" """广播消息给超级用户"""
@ -42,10 +39,7 @@ class MarkdownMessage:
markdown: str, markdown: str,
bot: T_Bot, *, bot: T_Bot, *,
message_type: str = None, message_type: str = None,
session_id: str | int = None, session_id: str | int = None
event: T_MessageEvent = None,
retry_as_image: bool = True,
**kwargs
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
""" """
发送Markdown消息支持自动转为图片发送 发送Markdown消息支持自动转为图片发送
@ -54,20 +48,23 @@ class MarkdownMessage:
bot: bot:
message_type: message_type:
session_id: session_id:
event:
retry_as_image: 发送失败后是否尝试以图片形式发送否则失败返回None
**kwargs:
Returns: Returns:
""" """
formatted_md = v11.unescape(markdown).replace("\n", r"\n").replace('"', r'\\\"') plain_markdown = markdown.replace("[🔗", "[")
plain_markdown = formatted_md.replace("[🔗", "[")
md_image_bytes = await md_to_pic( md_image_bytes = await md_to_pic(
md=plain_markdown, md=plain_markdown,
width=540, width=540,
device_scale_factor=4 device_scale_factor=4
) )
if md_image_bytes is None:
data = await bot.send_msg(
message_type=message_type,
group_id=session_id,
user_id=session_id,
message=markdown,
)
return data
data = await bot.send_msg( data = await bot.send_msg(
message_type=message_type, message_type=message_type,
group_id=session_id, group_id=session_id,
@ -105,8 +102,8 @@ class MarkdownMessage:
base64_string = base64.b64encode(image).decode("utf-8") base64_string = base64.b64encode(image).decode("utf-8")
data = await bot.call_api("upload_image", file=f"base64://{base64_string}") data = await bot.call_api("upload_image", file=f"base64://{base64_string}")
await MarkdownMessage.send_md(MarkdownMessage.image(data, Image.open(io.BytesIO(image)).size), bot, await MarkdownMessage.send_md(MarkdownMessage.image(data, Image.open(io.BytesIO(image)).size), bot,
event=event, message_type=message_type, message_type=message_type,
session_id=session_id, **kwargs) session_id=session_id)
# 其他实现端方案 # 其他实现端方案
else: else:
@ -119,8 +116,7 @@ class MarkdownMessage:
image_url = (await bot.get_msg(message_id=image_message_id))["message"][0]["data"]["url"] image_url = (await bot.get_msg(message_id=image_message_id))["message"][0]["data"]["url"]
image_size = Image.open(io.BytesIO(image)).size image_size = Image.open(io.BytesIO(image)).size
image_md = MarkdownMessage.image(image_url, image_size) image_md = MarkdownMessage.image(image_url, image_size)
return await MarkdownMessage.send_md(image_md, bot, message_type=message_type, session_id=session_id, return await MarkdownMessage.send_md(image_md, bot, message_type=message_type, session_id=session_id)
event=event, **kwargs)
if data is None: if data is None:
data = await bot.send_msg( data = await bot.send_msg(