nonebot-plugin-spg 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nonebot_plugin_spg/__init__.py +41 -0
- nonebot_plugin_spg/commands_spec.py +241 -0
- nonebot_plugin_spg/config.py +37 -0
- nonebot_plugin_spg/group_guard.py +86 -0
- nonebot_plugin_spg/handlers.py +592 -0
- nonebot_plugin_spg/invite.py +90 -0
- nonebot_plugin_spg/jobs.py +24 -0
- nonebot_plugin_spg/model.py +223 -0
- nonebot_plugin_spg/privacy.py +41 -0
- nonebot_plugin_spg/runtime.py +97 -0
- nonebot_plugin_spg/service.py +358 -0
- nonebot_plugin_spg/store.py +546 -0
- nonebot_plugin_spg-0.1.0.dist-info/METADATA +149 -0
- nonebot_plugin_spg-0.1.0.dist-info/RECORD +16 -0
- nonebot_plugin_spg-0.1.0.dist-info/WHEEL +4 -0
- nonebot_plugin_spg-0.1.0.dist-info/licenses/LICENSE +235 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from nonebot import logger, require, get_driver
|
|
2
|
+
from nonebot.plugin import PluginMetadata, inherit_supported_adapters
|
|
3
|
+
|
|
4
|
+
require("nonebot_plugin_uninfo")
|
|
5
|
+
require("nonebot_plugin_alconna")
|
|
6
|
+
require("nonebot_plugin_localstore")
|
|
7
|
+
require("nonebot_plugin_apscheduler")
|
|
8
|
+
|
|
9
|
+
from .config import Config
|
|
10
|
+
|
|
11
|
+
__plugin_meta__ = PluginMetadata(
|
|
12
|
+
name="卫戍协议找队友",
|
|
13
|
+
description="私聊匹配官服「卫戍协议」联合模拟队友,交换联系方式",
|
|
14
|
+
usage="私聊发送「卫戍 帮助」查看用法",
|
|
15
|
+
type="application",
|
|
16
|
+
homepage="https://github.com/aknyzsd/nonebot-plugin-SPG",
|
|
17
|
+
config=Config,
|
|
18
|
+
supported_adapters=inherit_supported_adapters(
|
|
19
|
+
"nonebot_plugin_alconna", "nonebot_plugin_uninfo"
|
|
20
|
+
),
|
|
21
|
+
extra={"author": "aknyzsd <aknyzsd@outlook.com>"},
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from .runtime import service
|
|
25
|
+
|
|
26
|
+
_driver = get_driver()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@_driver.on_startup
|
|
30
|
+
async def _startup() -> None:
|
|
31
|
+
await service.store.connect()
|
|
32
|
+
logger.info("spg: 匹配服务已启动")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@_driver.on_shutdown
|
|
36
|
+
async def _shutdown() -> None:
|
|
37
|
+
await service.store.close()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
from . import jobs as _jobs # noqa: F401 (导入即注册定时任务)
|
|
41
|
+
from . import handlers as _handlers # noqa: F401 (导入即注册响应器)
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""命令表:动作 id、默认词、作用域校验,以及**不做正则猜测**的消息解析。
|
|
2
|
+
|
|
3
|
+
设计约束(对应文档 §5.6):
|
|
4
|
+
|
|
5
|
+
1. 按空白切词,第一段必须**完全等于**某个根词;
|
|
6
|
+
2. 第二段必须**完全等于**某个动作词;
|
|
7
|
+
3. 命中后剩下的词原样交给 handler,参数校验发生在 service 层;
|
|
8
|
+
4. 任何一步不满足都返回 ``None``,调用方必须当作「这不是命令」处理——
|
|
9
|
+
不撤回、不回复、不记录。
|
|
10
|
+
|
|
11
|
+
这里刻意不使用「包含关键词」或模糊匹配:群里有人问「有人打卫戍吗」、
|
|
12
|
+
贴一条 `https://...?room=XXXX`,都不应该被当成命令。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import Literal
|
|
18
|
+
from dataclasses import field, dataclass
|
|
19
|
+
|
|
20
|
+
Scope = Literal["dm", "group", "both"]
|
|
21
|
+
Role = Literal["user", "admin", "superuser"]
|
|
22
|
+
|
|
23
|
+
MAX_MESSAGE_LEN = 200
|
|
24
|
+
MAX_WORD_LEN = 8
|
|
25
|
+
|
|
26
|
+
# 无论配置怎么改,这些动作必须存在,否则插件无法工作。
|
|
27
|
+
# 开房不走 token 命令,只接受整条邀请文案(见 ``invite.py``)。
|
|
28
|
+
REQUIRED_ACTIONS: tuple[str, ...] = ("join", "cancel", "status", "help")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class ActionSpec:
|
|
33
|
+
id: str
|
|
34
|
+
words: tuple[str, ...]
|
|
35
|
+
scope: Scope = "dm"
|
|
36
|
+
role: Role = "user"
|
|
37
|
+
help: str = ""
|
|
38
|
+
usage: str = ""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
DEFAULT_ACTIONS: dict[str, ActionSpec] = {
|
|
42
|
+
"join": ActionSpec("join", ("报名", "join"), "dm", "user", "加入房间", "<房间号>"),
|
|
43
|
+
"match": ActionSpec(
|
|
44
|
+
"match", ("匹配", "match"), "dm", "user", "自动匹配有空位的房间", "[难度]"
|
|
45
|
+
),
|
|
46
|
+
"cancel": ActionSpec(
|
|
47
|
+
"cancel", ("取消", "cancel"), "dm", "user", "取消待确认的开房或退出房间", ""
|
|
48
|
+
),
|
|
49
|
+
"status": ActionSpec(
|
|
50
|
+
"status", ("状态", "status"), "dm", "user", "我的房间与配额", ""
|
|
51
|
+
),
|
|
52
|
+
"close": ActionSpec("close", ("关闭", "close"), "dm", "user", "关闭自己的房间", ""),
|
|
53
|
+
"report": ActionSpec(
|
|
54
|
+
"report", ("上报", "report"), "dm", "user", "上报异常房间", "<房间号> <原因>"
|
|
55
|
+
),
|
|
56
|
+
"privacy": ActionSpec("privacy", ("隐私", "privacy"), "dm", "user", "隐私说明", ""),
|
|
57
|
+
"forget": ActionSpec(
|
|
58
|
+
"forget", ("删除我的数据", "forget"), "dm", "user", "删除我的联系方式", ""
|
|
59
|
+
),
|
|
60
|
+
"board": ActionSpec(
|
|
61
|
+
"board", ("公告", "board"), "group", "admin", "发布本群公告", "[on|off]"
|
|
62
|
+
),
|
|
63
|
+
"switch": ActionSpec(
|
|
64
|
+
"switch", ("开关", "switch"), "group", "admin", "开关本群入口", "on|off"
|
|
65
|
+
),
|
|
66
|
+
"help": ActionSpec("help", ("帮助", "help"), "both", "user", "用法", ""),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
DEFAULT_ROOTS: tuple[str, ...] = ("卫戍", "spg")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class CommandSpec:
|
|
74
|
+
roots: tuple[str, ...]
|
|
75
|
+
actions: dict[str, ActionSpec]
|
|
76
|
+
_by_word: dict[str, str] = field(default_factory=dict, repr=False)
|
|
77
|
+
|
|
78
|
+
def action_for(self, word: str) -> ActionSpec | None:
|
|
79
|
+
action_id = self._by_word.get(word.casefold())
|
|
80
|
+
if action_id is None:
|
|
81
|
+
return None
|
|
82
|
+
return self.actions[action_id]
|
|
83
|
+
|
|
84
|
+
def is_root(self, word: str) -> bool:
|
|
85
|
+
return word.casefold() in {root.casefold() for root in self.roots}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class ParsedCommand:
|
|
90
|
+
action: str
|
|
91
|
+
args: tuple[str, ...]
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def action_spec(self) -> ActionSpec:
|
|
95
|
+
raise AttributeError("请通过 CommandSpec 取 ActionSpec")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _validate_word(word: str, *, where: str) -> None:
|
|
99
|
+
if not word:
|
|
100
|
+
raise ValueError(f"{where}: 命令词不能为空")
|
|
101
|
+
if len(word) > MAX_WORD_LEN:
|
|
102
|
+
raise ValueError(f"{where}: 命令词 {word!r} 超过 {MAX_WORD_LEN} 字")
|
|
103
|
+
if any(char.isspace() for char in word):
|
|
104
|
+
raise ValueError(f"{where}: 命令词 {word!r} 不能包含空白")
|
|
105
|
+
if word.startswith(("-", "#", "/")):
|
|
106
|
+
raise ValueError(f"{where}: 命令词 {word!r} 不能以 - # / 开头")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _patch_words(
|
|
110
|
+
action_id: str, patch: dict[str, object], fallback: tuple[str, ...]
|
|
111
|
+
) -> tuple[str, ...]:
|
|
112
|
+
raw = patch.get("words", fallback)
|
|
113
|
+
if isinstance(raw, str) or not isinstance(raw, (list, tuple)):
|
|
114
|
+
raise ValueError(f"{action_id}: 命令词必须是字符串列表")
|
|
115
|
+
words = tuple(word for word in raw if isinstance(word, str))
|
|
116
|
+
if len(words) != len(raw):
|
|
117
|
+
raise ValueError(f"{action_id}: 命令词只能是字符串")
|
|
118
|
+
return words
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _patch_scope(action_id: str, patch: dict[str, object], fallback: Scope) -> Scope:
|
|
122
|
+
raw = patch.get("scope", fallback)
|
|
123
|
+
if raw == "dm":
|
|
124
|
+
return "dm"
|
|
125
|
+
if raw == "group":
|
|
126
|
+
return "group"
|
|
127
|
+
if raw == "both":
|
|
128
|
+
return "both"
|
|
129
|
+
raise ValueError(f"{action_id}: 非法作用域 {raw!r}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _patch_role(action_id: str, patch: dict[str, object], fallback: Role) -> Role:
|
|
133
|
+
raw = patch.get("role", fallback)
|
|
134
|
+
if raw == "user":
|
|
135
|
+
return "user"
|
|
136
|
+
if raw == "admin":
|
|
137
|
+
return "admin"
|
|
138
|
+
if raw == "superuser":
|
|
139
|
+
return "superuser"
|
|
140
|
+
raise ValueError(f"{action_id}: 非法角色 {raw!r}")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def build_spec(
|
|
144
|
+
roots: list[str] | tuple[str, ...],
|
|
145
|
+
overrides: dict[str, dict[str, object]] | None = None,
|
|
146
|
+
) -> CommandSpec:
|
|
147
|
+
"""按默认表合并配置,校验冲突后返回不可变的 CommandSpec。"""
|
|
148
|
+
if not roots:
|
|
149
|
+
raise ValueError("根命令不能为空")
|
|
150
|
+
|
|
151
|
+
actions: dict[str, ActionSpec] = dict(DEFAULT_ACTIONS)
|
|
152
|
+
if overrides:
|
|
153
|
+
for action_id, patch in overrides.items():
|
|
154
|
+
if action_id not in DEFAULT_ACTIONS:
|
|
155
|
+
raise ValueError(f"未知命令动作: {action_id}")
|
|
156
|
+
base = DEFAULT_ACTIONS[action_id]
|
|
157
|
+
actions[action_id] = ActionSpec(
|
|
158
|
+
id=base.id,
|
|
159
|
+
words=_patch_words(action_id, patch, base.words),
|
|
160
|
+
scope=_patch_scope(action_id, patch, base.scope),
|
|
161
|
+
role=_patch_role(action_id, patch, base.role),
|
|
162
|
+
help=str(patch.get("help", base.help)),
|
|
163
|
+
usage=str(patch.get("usage", base.usage)),
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
for action_id in REQUIRED_ACTIONS:
|
|
167
|
+
if action_id not in actions:
|
|
168
|
+
raise ValueError(f"缺少必需命令动作: {action_id}")
|
|
169
|
+
|
|
170
|
+
roots = tuple(root.strip() for root in roots)
|
|
171
|
+
for root in roots:
|
|
172
|
+
_validate_word(root, where="根命令")
|
|
173
|
+
|
|
174
|
+
seen: dict[str, str] = {}
|
|
175
|
+
for root in roots:
|
|
176
|
+
key = root.casefold()
|
|
177
|
+
if key in seen:
|
|
178
|
+
raise ValueError(f"根命令重复: {root!r}")
|
|
179
|
+
seen[key] = "__root__"
|
|
180
|
+
|
|
181
|
+
by_word: dict[str, str] = {}
|
|
182
|
+
for action_id, spec in actions.items():
|
|
183
|
+
if spec.scope not in ("dm", "group", "both"):
|
|
184
|
+
raise ValueError(f"{action_id}: 非法作用域 {spec.scope}")
|
|
185
|
+
if spec.role not in ("user", "admin", "superuser"):
|
|
186
|
+
raise ValueError(f"{action_id}: 非法角色 {spec.role}")
|
|
187
|
+
if not spec.words:
|
|
188
|
+
raise ValueError(f"{action_id}: 至少需要一个命令词")
|
|
189
|
+
for word in spec.words:
|
|
190
|
+
_validate_word(word, where=action_id)
|
|
191
|
+
key = word.casefold()
|
|
192
|
+
if key in seen:
|
|
193
|
+
raise ValueError(
|
|
194
|
+
f"命令词冲突: {word!r} 同时属于 {seen[key]} 与 {action_id}"
|
|
195
|
+
)
|
|
196
|
+
seen[key] = action_id
|
|
197
|
+
by_word[key] = action_id
|
|
198
|
+
|
|
199
|
+
return CommandSpec(roots=roots, actions=actions, _by_word=by_word)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def parse_message(text: str, spec: CommandSpec) -> ParsedCommand | None:
|
|
203
|
+
"""解析一条消息;``None`` 表示「不是命令」,调用方必须完全静默。"""
|
|
204
|
+
if not text or len(text) > MAX_MESSAGE_LEN:
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
stripped = text.strip()
|
|
208
|
+
if not stripped:
|
|
209
|
+
return None
|
|
210
|
+
# 带链接的消息一律不处理:哪怕它以根词开头,也多半是在分享而不是下命令。
|
|
211
|
+
lowered = stripped.casefold()
|
|
212
|
+
if any(token in lowered for token in ("http://", "https://", "www.", "?room=")):
|
|
213
|
+
return None
|
|
214
|
+
# 含换行的消息视为多段文本 / 转发内容。
|
|
215
|
+
if "\n" in stripped or "\r" in stripped:
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
parts = stripped.split()
|
|
219
|
+
if len(parts) < 2:
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
if not spec.is_root(parts[0]):
|
|
223
|
+
return None
|
|
224
|
+
|
|
225
|
+
action = spec.action_for(parts[1])
|
|
226
|
+
if action is None:
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
return ParsedCommand(action=action.id, args=tuple(parts[2:]))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
__all__ = [
|
|
233
|
+
"DEFAULT_ACTIONS",
|
|
234
|
+
"DEFAULT_ROOTS",
|
|
235
|
+
"REQUIRED_ACTIONS",
|
|
236
|
+
"ActionSpec",
|
|
237
|
+
"CommandSpec",
|
|
238
|
+
"ParsedCommand",
|
|
239
|
+
"build_spec",
|
|
240
|
+
"parse_message",
|
|
241
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from nonebot import get_driver, get_plugin_config
|
|
6
|
+
from pydantic import Field, BaseModel
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Config(BaseModel):
|
|
10
|
+
# 命令表:根词 + 每个动作的词/作用域/角色
|
|
11
|
+
spg_roots: list[str] = Field(default_factory=lambda: ["卫戍", "spg"])
|
|
12
|
+
spg_actions: dict[str, Any] = Field(default_factory=dict)
|
|
13
|
+
|
|
14
|
+
# 房号:官方邀请链接里是 14 位字母数字,这里放宽到 4-32 位
|
|
15
|
+
spg_room_code_regex: str = r"^[0-9A-Za-z]{4,32}$"
|
|
16
|
+
spg_note_max_len: int = 40
|
|
17
|
+
|
|
18
|
+
# 生命周期
|
|
19
|
+
spg_room_ttl_minutes: int = 30
|
|
20
|
+
spg_pending_ttl_minutes: int = 5
|
|
21
|
+
spg_retain_hours: int = 24
|
|
22
|
+
|
|
23
|
+
# 配额
|
|
24
|
+
spg_quota_per_hour: int = 3
|
|
25
|
+
|
|
26
|
+
# 群内行为
|
|
27
|
+
spg_recall: bool = True
|
|
28
|
+
spg_board_interval_minutes: int = 30
|
|
29
|
+
|
|
30
|
+
# 业务开关
|
|
31
|
+
spg_lianji_open: bool = True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
plugin_config: Config = get_plugin_config(Config)
|
|
35
|
+
global_config = get_driver().config
|
|
36
|
+
|
|
37
|
+
NICKNAME: str = next(iter(global_config.nickname), "")
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""群内行为:撤回、提示、管理员公告。
|
|
2
|
+
|
|
3
|
+
原则:群里能看见的只有「这不是命令」的静默、管理员公告和帮助;
|
|
4
|
+
房号、QQ、谁在玩什么,一律不出现在群消息里。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from nonebot import logger
|
|
10
|
+
from nonebot.adapters import Bot, Event
|
|
11
|
+
|
|
12
|
+
from .config import plugin_config
|
|
13
|
+
from .runtime import mask
|
|
14
|
+
from .commands_spec import ActionSpec
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def recall_message(bot: Bot, event: Event) -> bool:
|
|
18
|
+
"""尽力撤回触发消息;失败就放弃,绝不打扰用户。"""
|
|
19
|
+
message_id = getattr(event, "message_id", None)
|
|
20
|
+
if message_id is None:
|
|
21
|
+
return False
|
|
22
|
+
try:
|
|
23
|
+
await bot.delete_msg(message_id=message_id)
|
|
24
|
+
return True
|
|
25
|
+
except Exception as error:
|
|
26
|
+
logger.debug(f"spg: 撤回失败 {mask(str(message_id))}: {error!r}")
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def send_private(bot: Bot, user_id: int, text: str) -> bool:
|
|
31
|
+
try:
|
|
32
|
+
await bot.call_api("send_private_msg", user_id=user_id, message=text)
|
|
33
|
+
return True
|
|
34
|
+
except Exception as error:
|
|
35
|
+
logger.debug(f"spg: 私聊失败 {mask(str(user_id))}: {error!r}")
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def handle_misplaced(bot: Bot, event: Event, action: ActionSpec) -> None:
|
|
40
|
+
"""私聊命令在群里被触发:撤回 + 私聊引导,群里不留可用信息。"""
|
|
41
|
+
user_id = int(event.get_user_id())
|
|
42
|
+
recalled = False
|
|
43
|
+
if plugin_config.spg_recall:
|
|
44
|
+
recalled = await recall_message(bot, event)
|
|
45
|
+
|
|
46
|
+
hint = (
|
|
47
|
+
"找卫戍协议队友请私聊我,群里不显示房号和联系方式。\n私聊发送「帮助」查看用法。"
|
|
48
|
+
)
|
|
49
|
+
sent = await send_private(bot, user_id, hint)
|
|
50
|
+
if not recalled and not sent:
|
|
51
|
+
# 两件事都没成,才在群里留一句自删提示,且不含任何房号。
|
|
52
|
+
logger.debug("spg: 撤回与私聊均失败,放弃群内提示")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def is_group_admin(bot: Bot, event: Event) -> bool:
|
|
56
|
+
user_id = int(event.get_user_id())
|
|
57
|
+
superusers = getattr(bot.config, "superusers", set())
|
|
58
|
+
if str(user_id) in superusers or user_id in superusers:
|
|
59
|
+
return True
|
|
60
|
+
group_id = getattr(event, "group_id", None)
|
|
61
|
+
if group_id is None:
|
|
62
|
+
return False
|
|
63
|
+
try:
|
|
64
|
+
info = await bot.call_api(
|
|
65
|
+
"get_group_member_info", group_id=int(group_id), user_id=user_id
|
|
66
|
+
)
|
|
67
|
+
except Exception:
|
|
68
|
+
return False
|
|
69
|
+
return info.get("role") in ("admin", "owner")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def board_text(open_count: int) -> str:
|
|
73
|
+
"""管理员公告:只有聚合数字。"""
|
|
74
|
+
return (
|
|
75
|
+
"要找卫戍协议队友?私聊我发送「帮助」。\n"
|
|
76
|
+
f"当前有 {open_count} 个房间有空位可加入。"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
__all__ = [
|
|
81
|
+
"board_text",
|
|
82
|
+
"handle_misplaced",
|
|
83
|
+
"is_group_admin",
|
|
84
|
+
"recall_message",
|
|
85
|
+
"send_private",
|
|
86
|
+
]
|