OnmyojiAutoScript 通知推送功能优化实践
2026-02-04 04:25:45作者:申梦珏Efrain
概述
OnmyojiAutoScript(阴阳师自动化脚本)的通知推送功能是其核心特性之一,能够在脚本运行过程中及时向用户推送关键信息,如任务完成状态、错误报警、异常情况等。本文将从技术实现角度深入分析通知推送模块的架构设计、优化策略以及最佳实践。
通知推送系统架构
核心组件
classDiagram
class Notifier {
-config_name: str
-enable: bool
-config: dict
-provider_name: str
-notifier: Provider
-required: list[str]
+__init__(config: str, enable: bool)
+push(**kwargs) bool
}
class Config {
-model: ConfigModel
-config_name: str
+notifier: Notifier
+get_next() Function
+task_call(task: str) bool
}
class Script {
-config: Config
-device: Device
+run(command: str) bool
+loop()
}
Script --> Config : 使用
Config --> Notifier : 包含
Notifier --> onepush.Provider : 依赖
配置结构
通知推送系统采用YAML配置格式,支持多种推送提供商:
provider: "custom" # 推送提供商
method: "post" # 请求方法
url: "https://your-webhook-url" # 推送地址
datatype: "json" # 数据格式
data: # 自定义数据
title: "推送标题"
content: "推送内容"
错误处理与通知触发机制
异常类型与通知策略
OnmyojiAutoScript定义了多种异常类型,每种异常都会触发相应的通知:
| 异常类型 | 触发条件 | 通知内容 | 处理方式 |
|---|---|---|---|
| GameStuckError | 游戏卡死或点击过多 | GameStuckError or GameTooManyClickError | 重启游戏 |
| GamePageUnknownError | 游戏页面未知 | GamePageUnknownError | 检查服务器状态 |
| ScriptError | 脚本开发错误 | ScriptError | 退出脚本 |
| RequestHumanTakeover | 需要人工干预 | RequestHumanTakeover | 退出脚本 |
| Exception | 未捕获异常 | Exception occured | 退出脚本 |
通知推送实现代码
def push(self, **kwargs) -> bool:
if not self.enable:
return False
# 更新配置
kwargs["title"] = f"{self.config_name} {kwargs['title']}"
self.config.update(kwargs)
# 参数预检查
for key in self.required:
if key not in self.config:
logger.warning(f"Notifier {self.notifier} require param '{key}' but not provided")
# 自定义提供商特殊处理
if isinstance(self.notifier, Custom):
if "method" not in self.config or self.config["method"] == "post":
self.config["datatype"] = "json"
if not ("data" in self.config or isinstance(self.config["data"], dict)):
self.config["data"] = {}
if "title" in kwargs:
self.config["data"]["title"] = kwargs["title"]
if "content" in kwargs:
self.config["data"]["content"] = kwargs["content"]
# GoCqHttp特殊处理
if self.provider_name.lower() == "gocqhttp":
access_token = self.config.get("access_token")
if access_token:
self.config["token"] = access_token
try:
resp = self.notifier.notify(**self.config)
# 响应状态检查
if isinstance(resp, Response):
if resp.status_code != 200:
logger.warning("Push notify failed!")
logger.warning(f"HTTP Code:{resp.status_code}")
return False
else:
if self.provider_name.lower() == "gocqhttp":
return_data: dict = resp.json()
if return_data["status"] == "failed":
logger.warning("Push notify failed!")
logger.warning(f"Return message:{return_data['wording']}")
return False
except SMTPResponseException:
logger.warning("Appear SMTPResponseException")
pass
except OnePushException:
logger.exception("Push notify failed")
return False
except Exception as e:
logger.exception(e)
return False
logger.info("Push notify success")
return True
性能优化策略
1. 懒加载机制
通知推送器采用懒加载设计,只有在真正需要推送时才初始化:
@cached_property
def notifier(self):
notifier = Notifier(self.model.script.error.notify_config,
enable=self.model.script.error.notify_enable)
notifier.config_name = self.config_name.upper()
logger.info(f'Notifier: {notifier.config_name}')
return notifier
2. 错误重试机制
系统实现了智能的错误重试机制:
# 检查失败次数
failed = self.failure_record[task] if task in self.failure_record else 0
failed = 0 if success else failed + 1
self.failure_record[task] = failed
if failed >= 3:
logger.critical(f"Task `{task}` failed 3 or more times.")
logger.critical("Possible reason #1: You haven't used it correctly.")
logger.critical("Possible reason #2: There is a problem with this task.")
logger.critical('Request human takeover')
exit(1)
3. 异步处理优化
对于高频率的通知推送,建议采用异步处理:
import asyncio
from concurrent.futures import ThreadPoolExecutor
class AsyncNotifier(Notifier):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.executor = ThreadPoolExecutor(max_workers=3)
async def async_push(self, **kwargs):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(self.executor, self.push, **kwargs)
配置最佳实践
1. 多提供商配置示例
# Discord Webhook 配置
provider: "custom"
method: "post"
url: "https://discord.com/api/webhooks/your-webhook"
datatype: "json"
data:
username: "OnmyojiBot"
avatar_url: "https://example.com/avatar.png"
embeds:
- title: "{{title}}"
description: "{{content}}"
color: 5814783
# 即时通讯 Bot 配置
provider: "im_bot"
token: "your-bot-token"
chat_id: "your-chat-id"
parse_mode: "HTML"
# Server酱配置
provider: "serverchan"
sckey: "your-sckey"
2. 消息模板优化
# 自定义消息模板函数
def format_notification(task_name, error_type, config_name):
"""格式化通知消息"""
templates = {
"GameStuckError": f"🚨 游戏卡死报警 - {task_name}\n"
f"配置: {config_name}\n"
f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"建议: 检查游戏网络连接或重启游戏",
"ScriptError": f"🐛 脚本错误 - {task_name}\n"
f"配置: {config_name}\n"
f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"建议: 联系开发者或查看错误日志",
}
return templates.get(error_type, f"{error_type} - {task_name}")
监控与日志分析
1. 推送成功率监控
class NotificationMonitor:
def __init__(self):
self.success_count = 0
self.failure_count = 0
self.last_notification = None
def record_success(self):
self.success_count += 1
self.last_notification = datetime.now()
def record_failure(self):
self.failure_count += 1
@property
def success_rate(self):
total = self.success_count + self.failure_count
return self.success_count / total if total > 0 else 0
def get_stats(self):
return {
"success_count": self.success_count,
"failure_count": self.failure_count,
"success_rate": f"{self.success_rate:.2%}",
"last_notification": self.last_notification
}
2. 推送延迟分析
import time
from dataclasses import dataclass
@dataclass
class PushMetrics:
start_time: float
end_time: float = 0
success: bool = False
@property
def duration(self):
return self.end_time - self.start_time if self.end_time else 0
class TimedNotifier(Notifier):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.metrics = []
def push(self, **kwargs):
metric = PushMetrics(start_time=time.time())
try:
result = super().push(**kwargs)
metric.end_time = time.time()
metric.success = result
self.metrics.append(metric)
return result
except Exception as e:
metric.end_time = time.time()
self.metrics.append(metric)
raise e
def get_performance_stats(self):
if not self.metrics:
return {}
durations = [m.duration for m in self.metrics if m.success]
return {
"total_pushes": len(self.metrics),
"successful_pushes": sum(1 for m in self.metrics if m.success),
"avg_duration": sum(durations) / len(durations) if durations else 0,
"max_duration": max(durations) if durations else 0,
"min_duration": min(durations) if durations else 0
}
安全性与可靠性保障
1. 敏感信息处理
from module.handler.sensitive_info import handle_sensitive_image, handle_sensitive_logs
def save_error_log(self):
"""保存错误日志和截图,处理敏感信息"""
if self.config.script.error.save_error:
folder = f'./log/error/{int(time.time() * 1000)}'
os.makedirs(folder, exist_ok=True)
# 处理敏感截图
for data in self.device.screenshot_deque:
image = handle_sensitive_image(data['image'])
save_image(image, f'{folder}/{data["time"].strftime("%Y-%m-%d_%H-%M-%S-%f")}.png')
# 处理敏感日志
with open(logger.log_file, 'r', encoding='utf-8') as f:
lines = handle_sensitive_logs(f.readlines())
with open(f'{folder}/log.txt', 'w', encoding='utf-8') as f:
f.writelines(lines)
2. 配置验证机制
def validate_notification_config(config_str):
"""验证通知配置有效性"""
try:
config = yaml.safe_load(config_str)
if not config:
return False, "配置为空"
provider = config.get("provider")
if not provider:
return False, "未指定推送提供商"
# 获取提供商必填参数
notifier = get_notifier(provider)
required_params = notifier.params["required"]
missing_params = []
for param in required_params:
if param not in config:
missing_params.append(param)
if missing_params:
return False, f"缺少必填参数: {', '.join(missing_params)}"
return True, "配置有效"
except Exception as e:
return False, f"配置解析失败: {str(e)}"
总结与展望
OnmyojiAutoScript的通知推送系统通过精心的架构设计和优化策略,实现了高效、可靠的消息推送功能。系统具有以下特点:
- 多提供商支持:集成多种推送服务,满足不同用户需求
- 智能错误处理:根据异常类型提供针对性的通知和处理方案
- 性能优化:懒加载、异步处理等机制确保系统高效运行
- 安全可靠:敏感信息处理和配置验证保障用户数据安全
未来可进一步优化的方向包括:
- 支持更多推送提供商和消息格式
- 实现消息优先级和去重机制
- 添加推送历史查询和统计分析功能
- 支持消息模板自定义和国际化
通过持续的优化和改进,OnmyojiAutoScript的通知推送功能将为用户提供更加完善和便捷的自动化脚本体验。
登录后查看全文
热门项目推荐
相关项目推荐
Kimi-K2.5Kimi K2.5 是一款开源的原生多模态智能体模型,它在 Kimi-K2-Base 的基础上,通过对约 15 万亿混合视觉和文本 tokens 进行持续预训练构建而成。该模型将视觉与语言理解、高级智能体能力、即时模式与思考模式,以及对话式与智能体范式无缝融合。Python00- QQwen3-Coder-Next2026年2月4日,正式发布的Qwen3-Coder-Next,一款专为编码智能体和本地开发场景设计的开源语言模型。Python00
xw-cli实现国产算力大模型零门槛部署,一键跑通 Qwen、GLM-4.7、Minimax-2.1、DeepSeek-OCR 等模型Go06
PaddleOCR-VL-1.5PaddleOCR-VL-1.5 是 PaddleOCR-VL 的新一代进阶模型,在 OmniDocBench v1.5 上实现了 94.5% 的全新 state-of-the-art 准确率。 为了严格评估模型在真实物理畸变下的鲁棒性——包括扫描伪影、倾斜、扭曲、屏幕拍摄和光照变化——我们提出了 Real5-OmniDocBench 基准测试集。实验结果表明,该增强模型在新构建的基准测试集上达到了 SOTA 性能。此外,我们通过整合印章识别和文本检测识别(text spotting)任务扩展了模型的能力,同时保持 0.9B 的超紧凑 VLM 规模,具备高效率特性。Python00
KuiklyUI基于KMP技术的高性能、全平台开发框架,具备统一代码库、极致易用性和动态灵活性。 Provide a high-performance, full-platform development framework with unified codebase, ultimate ease of use, and dynamic flexibility. 注意:本仓库为Github仓库镜像,PR或Issue请移步至Github发起,感谢支持!Kotlin08
VLOOKVLOOK™ 是优雅好用的 Typora/Markdown 主题包和增强插件。 VLOOK™ is an elegant and practical THEME PACKAGE × ENHANCEMENT PLUGIN for Typora/Markdown.Less00
热门内容推荐
最新内容推荐
Degrees of Lewdity中文汉化终极指南:零基础玩家必看的完整教程Unity游戏翻译神器:XUnity Auto Translator 完整使用指南PythonWin7终极指南:在Windows 7上轻松安装Python 3.9+终极macOS键盘定制指南:用Karabiner-Elements提升10倍效率Pandas数据分析实战指南:从零基础到数据处理高手 Qwen3-235B-FP8震撼升级:256K上下文+22B激活参数7步搞定机械键盘PCB设计:从零开始打造你的专属键盘终极WeMod专业版解锁指南:3步免费获取完整高级功能DeepSeek-R1-Distill-Qwen-32B技术揭秘:小模型如何实现大模型性能突破音频修复终极指南:让每一段受损声音重获新生
项目优选
收起
deepin linux kernel
C
27
11
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
535
3.75 K
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
12
1
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
67
20
暂无简介
Dart
773
191
Ascend Extension for PyTorch
Python
343
406
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
886
596
喝着茶写代码!最易用的自托管一站式代码托管平台,包含Git托管,代码审查,团队协作,软件包和CI/CD。
Go
23
0
React Native鸿蒙化仓库
JavaScript
303
355
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
336
178