优化提醒 UX
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-10-25 00:28:29 +08:00
parent 881f38d187
commit 6abc963ccf

View File

@ -1,23 +1,19 @@
import aiohttp import aiohttp
import asyncio as asynkio import asyncio as asynkio
import datetime
from math import ceil from math import ceil
from pathlib import Path from pathlib import Path
from typing import Any, Literal from typing import Any
import nanoid import nanoid
import nonebot import nonebot
import ptimeparse import ptimeparse
from loguru import logger from loguru import logger
from nonebot import get_plugin_config, on_message from nonebot import get_plugin_config, on_message
from nonebot.adapters import Bot, Event from nonebot.adapters import Event
from nonebot.adapters.onebot.v11 import Bot as OBBot
from nonebot.adapters.console import Bot as CBot
from nonebot.adapters.discord import Bot as DCBot
from nonebot_plugin_alconna import Alconna, Args, Subcommand, UniMessage, UniMsg, on_alconna from nonebot_plugin_alconna import Alconna, Args, Subcommand, UniMessage, UniMsg, on_alconna
from pydantic import BaseModel from pydantic import BaseModel
from konabot.common.longtask import DepLongTaskTarget, LongTask, LongTaskTarget, create_longtask, handle_long_task, longtask_data from konabot.common.longtask import DepLongTaskTarget, LongTask, create_longtask, handle_long_task, longtask_data
evt = on_message() evt = on_message()
@ -32,27 +28,8 @@ PAGE_SIZE = 6
FMT_STRING = "%Y年%m月%d%H:%M:%S" FMT_STRING = "%Y年%m月%d%H:%M:%S"
class NotifyMessage(BaseModel):
message: str
class Notify(BaseModel):
platform: Literal["console", "qq", "discord"]
target: str
"需要接受通知的个体"
target_env: str | None
"在哪里进行通知,如果是 None 代表私聊通知"
notify_time: datetime.datetime
notify_msg: str
class NotifyConfigFile(BaseModel): class NotifyConfigFile(BaseModel):
version: int = 2 version: int = 2
notifies: list[Notify] = []
unsent: list[Notify] = []
notify_channels: dict[str, str] = {} notify_channels: dict[str, str] = {}
@ -78,36 +55,6 @@ async def send_notify_to_ntfy_instance(msg: str, channel: str):
logger.info(f"访问 {url} 的结果是 {response.status}") logger.info(f"访问 {url} 的结果是 {response.status}")
def _get_bot_of(_type: type[Bot]):
for bot in nonebot.get_bots().values():
if isinstance(bot, _type):
return bot.self_id
return ""
def get_target_from_notify(notify: Notify) -> LongTaskTarget:
if notify.platform == "console":
return LongTaskTarget(
platform="console",
self_id=_get_bot_of(CBot),
channel_id=notify.target_env or "",
target_id=notify.target,
)
if notify.platform == "discord":
return LongTaskTarget(
platform="discord",
self_id=_get_bot_of(DCBot),
channel_id=notify.target_env or "",
target_id=notify.target,
)
return LongTaskTarget(
platform="qq",
self_id=_get_bot_of(OBBot),
channel_id=notify.target_env or "",
target_id=notify.target,
)
def load_notify_config() -> NotifyConfigFile: def load_notify_config() -> NotifyConfigFile:
if not DATA_FILE_PATH.exists(): if not DATA_FILE_PATH.exists():
return NotifyConfigFile() return NotifyConfigFile()
@ -160,40 +107,6 @@ async def _(msg: UniMsg, mEvt: Event, target: DepLongTaskTarget):
driver = nonebot.get_driver() driver = nonebot.get_driver()
NOTIFIED_FLAG = {
"task_added": False,
}
@driver.on_bot_connect
async def _():
if NOTIFIED_FLAG["task_added"]:
return
NOTIFIED_FLAG["task_added"] = True
DELTA = 2
logger.info(f"第一次探测到 Bot 连接,等待 {DELTA} 秒后开始通知")
await asynkio.sleep(DELTA)
await DATA_FILE_LOCK.acquire()
cfg = load_notify_config()
if cfg.version == 1:
logger.info("将配置文件的版本升级为 2")
cfg.version = 2
else:
for notify in [*cfg.notifies]:
await create_longtask(
handler=LONG_TASK_NAME,
data={ "message": notify.notify_msg },
target=get_target_from_notify(notify),
deadline=notify.notify_time,
)
cfg.notifies = []
save_notify_config(cfg)
DATA_FILE_LOCK.release()
@handle_long_task("TASK_SIMPLE_NOTIFY") @handle_long_task("TASK_SIMPLE_NOTIFY")
async def _(task: LongTask): async def _(task: LongTask):
@ -284,7 +197,17 @@ cmd_notify_channel = on_alconna(Alconna(
@cmd_notify_channel.assign("$main") @cmd_notify_channel.assign("$main")
async def _(target: DepLongTaskTarget): async def _(target: DepLongTaskTarget):
async with DATA_FILE_LOCK:
data = load_notify_config()
target_channel = data.notify_channels.get(target.target_id)
if target_channel is None:
channel_msg = "目前还没有配置 ntfy 地址"
else:
channel_msg = f"配置的 ntfy Channel 为:{target_channel}\n\n服务器地址:{config.plugin_notify_base_url}"
await target.send_message(UniMessage.text( await target.send_message(UniMessage.text(
f"{channel_msg}\n\n"
"配置 ntfy 通知:\n\n" "配置 ntfy 通知:\n\n"
"- ntfy 创建: 启用 ntfy 通知,并为你随机生成一个通知渠道\n" "- ntfy 创建: 启用 ntfy 通知,并为你随机生成一个通知渠道\n"
"- ntfy 删除:禁用 ntfy 通知\n" "- ntfy 删除:禁用 ntfy 通知\n"