Files
NeoBot/docs/plugin-development/best-practices.md
K2cr2O1 24af862924 feat: 添加性能优化和架构文档,更新依赖和核心模块
refactor(browser_manager): 实现页面池机制以提升性能
refactor(image_manager): 添加模板缓存并集成页面池
refactor(bili_parser): 迁移到异步HTTP请求并实现会话复用
docs: 新增性能优化、架构设计和最佳实践文档
chore: 更新requirements.txt添加新依赖
2026-01-13 03:56:31 +08:00

68 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 插件开发最佳实践
写插件很简单,但写出**高性能、不炸裂**的插件需要遵守规矩。
## 1. 绝对不要阻塞事件循环 (Don't Block the Loop!)
这是死罪。NEO Bot 是单线程异步架构,如果你在主线程里 `time.sleep(5)`,整个机器人就会卡死 5 秒,谁都别想说话。
* **错误**: `time.sleep(1)`, `requests.get(...)`, 大量 CPU 计算。
* **正确**: `await asyncio.sleep(1)`, `await session.get(...)`
如果你必须运行同步代码(比如图像处理、复杂计算):
```python
from core.utils.executor import run_in_thread_pool
# 扔到线程池里去跑,别占着主线程
result = await run_in_thread_pool(heavy_function, arg1, arg2)
```
## 2. 复用资源
别每次都创建新的连接。
* **HTTP 请求**: 使用插件内提供的 `get_session()` 或全局 `aiohttp` session。
* **浏览器**: 必须使用 `browser_manager.get_page()`,严禁自己 `playwright.chromium.launch()`
## 3. 善用缓存
如果你的插件需要查外部 API比如查天气、查 B 站),记得加缓存。
Redis 就在那里,不用白不用。
```python
from core.managers.redis_manager import redis_manager
# 存
await redis_manager.set("weather:beijing", "sunny", ex=3600)
# 取
weather = await redis_manager.get("weather:beijing")
```
## 4. 类型提示 (Type Hinting)
我们开启了 Mypyc 编译,这意味着你的代码最好有规范的类型提示。
这不仅是为了编译,也是为了让你自己少写 Bug。
```python
# 好的写法
async def handle(event: MessageEvent, args: list[str]) -> None:
...
# 烂写法
async def handle(event, args):
...
```
## 5. 异常处理
别让你的插件因为一个报错就搞崩整个机器人。
虽然框架层有捕获机制,但你自己处理好异常是基本素养。
```python
try:
await do_something()
except Exception as e:
logger.error(f"插件炸了: {e}")
await event.reply("出错了,请稍后再试。")
```