Skip to content

Commit 497e5a9

Browse files
refactor: ⚡ 插件系统大改。
refactor: ⚡ 插件系统大改。
2 parents 40734ed + fd22f2d commit 497e5a9

13 files changed

Lines changed: 491 additions & 60 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
__pycache__/
2+
bot/

__init__.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""程序总入口"""
2+
3+
from asyncio import CancelledError
4+
import tomllib
5+
from contextlib import asynccontextmanager
6+
import importlib
7+
import logging
8+
from pathlib import Path
9+
from fastapi import FastAPI
10+
11+
log = logging.getLogger("uvicorn")
12+
13+
loaded_plugins = {}
14+
15+
# 使用绝对路径加载配置文件
16+
config_path = Path(__file__).parent / "config.toml"
17+
try:
18+
with open(config_path, "rb") as f:
19+
_config_data = tomllib.load(f)
20+
except FileNotFoundError:
21+
log.error("配置文件未找到: %s", config_path)
22+
raise
23+
24+
@asynccontextmanager
25+
async def lifespan(application: FastAPI):
26+
"""
27+
应用生命周期管理
28+
29+
:param application: FastAPI应用实例
30+
:type application: FastAPI
31+
"""
32+
try:
33+
log.info("CodeFeatrue-破晓之码 正在启动")
34+
# 存储插件事件映射
35+
event_subscriptions = {}
36+
for plugin_name in _config_data["main"]["plugins"]:
37+
# 初始化插件
38+
try:
39+
plugin = importlib.import_module("plugins." + plugin_name)
40+
loaded_plugins[plugin_name] = plugin
41+
plugin_meta = getattr(plugin, '__plugin_meta__', {})
42+
events = plugin_meta.get('events', [])
43+
# 订阅事件
44+
for event in events:
45+
if event not in event_subscriptions:
46+
event_subscriptions[event] = []
47+
event_subscriptions[event].append(plugin_name)
48+
log.info("插件 %s 加载成功", plugin_name)
49+
# 调用插件启用函数
50+
if hasattr(plugin, 'on_enable'):
51+
plugin.on_enable(application)
52+
except AttributeError as ae:
53+
log.warning("插件 %s 缺少必要的函数: %s", plugin_name, ae)
54+
# 将事件订阅信息存储到应用状态中
55+
application.state.event_subscriptions = event_subscriptions
56+
log.info("事件订阅: %s", event_subscriptions)
57+
yield
58+
log.info("CodeFeatrue-破晓之码 正在退出")
59+
except (CancelledError, KeyboardInterrupt) as e:
60+
log.error("CodeFeatrue-破晓之码 启动失败: 在启动过程中被用户手动关闭。%s", e)
61+
raise
62+
63+
app = FastAPI(lifespan=lifespan)
64+
65+
@app.post("/")
66+
def main(info: dict):
67+
"""
68+
处理接收到的消息
69+
70+
:param info: Onebot实现端传入的信息
71+
:type info: dict
72+
"""
73+
post_type = info["post_type"]
74+
# 通知订阅了该事件的所有插件
75+
event_subscriptions = app.state.event_subscriptions
76+
if post_type in event_subscriptions:
77+
for plugin_name in event_subscriptions[post_type]:
78+
plugin = loaded_plugins.get(plugin_name)
79+
if plugin and hasattr(plugin, 'on_event'):
80+
return_info = plugin.on_event(post_type, info)
81+
if return_info:
82+
return return_info
83+
else:
84+
log.info("插件 %s 未处理事件 %s", plugin_name, post_type)
85+
return { }

codefeatrue.zip

13.6 KB
Binary file not shown.

config.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[ main ]
2-
plugins = [ "oseddl" ]
2+
plugins = [ "bilibili", "github" ,"oseddl", "invite", "hust_eat" ]
33

44
# 供插件使用的配置
55
[ oseddl ]

data/user.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[
2+
{
3+
"platform": "onebot",
4+
"id": 1,
5+
"platform_id": 2812703122
6+
}
7+
]

docs/debug.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# API
2+
3+
## 1. Send Prative Message
4+
5+
``` request
6+
POST /api/v1/message/send
7+
```
8+
9+
### 请求参数
10+
11+
``` json
12+
{
13+
"self_id": 1817547029,
14+
"user_id": 2812703122,
15+
"time": 1766416525,
16+
"message_id": 1374201205,
17+
"message_seq": 59,
18+
"message_type": "private",
19+
"sender": {
20+
"user_id": 2812703122,
21+
"nickname": "夜影星辰",
22+
"card": ""
23+
},
24+
"raw_message": "测试",
25+
"font": 14,
26+
"sub_type": "friend",
27+
"message": [
28+
{
29+
"type": "text",
30+
"data": {
31+
"text": "测试"
32+
}
33+
}
34+
],
35+
"message_format": "array",
36+
"post_type": "message",
37+
"raw_pb": ""
38+
}
39+
```

main.py

Lines changed: 0 additions & 28 deletions
This file was deleted.

plugins/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""插件包"""

plugins/bilibili/__init__.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,15 @@
44
import json
55
import requests
66

7-
8-
def on_command(message_type: str, info: dict):
7+
__plugin_meta__ = {
8+
"name": "Github 信息监控",
9+
"description": "Github 信息监控",
10+
"author": "yeying-xingchen",
11+
"version": "0.0.1",
12+
"events": ["message"] # 添加需要订阅的事件
13+
}
14+
15+
def on_event(_message_type: str, info: dict):
916
"""
1017
处理接收到的命令
1118
@@ -14,8 +21,7 @@ def on_command(message_type: str, info: dict):
1421
:param info: 信息
1522
:type info: dict
1623
"""
17-
18-
if message_type == "json":
24+
if info["message"][0]["type"] == "json":
1925
try:
2026
card_info = json.loads(str(info["message"][0]["data"]["data"]))
2127
meta = card_info.get("meta", {})

plugins/github/__init__.py

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,25 @@
11
"""Github 信息监控插件"""
22

3+
import logging
34

4-
def on_command(message_type: str, info: dict):
5+
log = logging.getLogger("uvicorn")
6+
7+
__plugin_meta__ = {
8+
"name": "Github 信息监控",
9+
"description": "Github 信息监控",
10+
"author": "yeying-xingchen",
11+
"version": "0.0.1",
12+
"events": ["message", "request"] # 添加需要订阅的事件
13+
}
14+
15+
def on_enable(_app):
16+
"""
17+
插件启用时调用
18+
19+
:param app: FastAPI应用实例
20+
"""
21+
22+
def on_event(_event_type: str, info: dict):
523
"""
624
处理接收到的命令
725
@@ -10,17 +28,20 @@ def on_command(message_type: str, info: dict):
1028
:param info: 信息
1129
:type info: dict
1230
"""
13-
if message_type == "text":
14-
raw = info.get("raw_message", "")
15-
if raw.startswith("/github "):
16-
sub_command = raw[len("/github "):]
17-
if sub_command.startswith("add "):
18-
repo = sub_command[len("add "):]
19-
group_name = info.get("group_name", "未知群")
20-
group_id = info.get("group_id", "未知ID")
21-
reply = (
22-
f"已绑定仓库 {repo}{group_name} "
23-
f"群号 {group_id}"
24-
)
25-
return {"reply": reply}
26-
return {}
31+
32+
raw = info.get("raw_message", "")
33+
raw_message = raw.strip()
34+
parts = raw_message.split()
35+
if parts[0] == "/github":
36+
sub_command = raw[len("/github "):]
37+
if sub_command.startswith("add "):
38+
repo = sub_command[len("add "):]
39+
group_name = info.get("group_name", "未知群")
40+
group_id = info.get("group_id", "未知ID")
41+
reply = (
42+
f"已绑定仓库 {repo}{group_name} "
43+
f"群号 {group_id}"
44+
)
45+
return {"reply": reply}
46+
else:
47+
pass

0 commit comments

Comments
 (0)