nonebot-plugin-game-uid 0.2.0__tar.gz → 0.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nonebot-plugin-game-uid
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: 记录、汇总和定时播报群友的星布谷地、原神、崩坏:星穹铁道与绝区零 UID
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -38,7 +38,9 @@ Description-Content-Type: text/markdown
38
38
  - 在群聊中通过 `@群友` 查询对方主动绑定的 UID
39
39
  - 按“群名片:UID”列出本群已经绑定指定游戏的群友
40
40
  - SUPERUSER 可设置定时播报,周期性提示群友使用 UID 列表命令
41
+ - 播报发送失败时按递增间隔自动重试,避免每分钟刷屏
41
42
  - 删除自己的指定游戏 UID
43
+ - 一键清空自己的全部 UID,或只清空指定游戏 UID
42
44
  - 使用 SQLite 异步持久化,无需外部数据库或游戏 API
43
45
  - 兼容“星布谷底”“星铁”“铁道”“崩铁”等常用别名
44
46
 
@@ -90,12 +92,33 @@ UID 按 QQ 用户全局保存,不按群分别存储。群友只能查询用户
90
92
  | `/游戏UID [游戏] @群友` | 所有人 | 群聊 | 查看群友的指定 UID |
91
93
  | `/游戏UID @群友` | 所有人 | 群聊 | 查看群友的全部 UID |
92
94
  | `/删除UID <游戏>` | 所有人 | 群聊/私聊 | 删除自己的指定 UID |
95
+ | `/清空UID [游戏]` | 所有人 | 群聊/私聊 | 有参数时清空指定游戏;无参数时一键清空自己的全部 UID |
96
+ | `/绑定帮助` | 所有人 | 群聊/私聊 | 查看支持的游戏、绑定格式和常用操作示例 |
93
97
  | `/群UID <游戏>` | 所有人 | 群聊 | 按“群名片:UID”查看本群列表 |
94
98
  | `/设置UID提醒 <间隔> <游戏>` | SUPERUSER | 群聊 | 开启或更新定时播报 |
95
99
  | `/关闭UID提醒` | SUPERUSER | 群聊 | 关闭定时播报 |
96
100
  | `/UID提醒状态` | 所有人 | 群聊 | 查看本群提醒状态 |
97
101
  | `/UID帮助` | 所有人 | 群聊/私聊 | 查看命令帮助 |
98
102
 
103
+ ### 命令别名
104
+
105
+ 命令支持下列别名,效果与完整命令一致(别名区分大小写,`UID` 全大写和 `uid` 全小写两种写法均已注册):
106
+
107
+ | 命令 | 别名 |
108
+ |---|---|
109
+ | `/绑定UID` | `/绑定uid`、`/绑定游戏UID`、`/绑定游戏uid` |
110
+ | `/游戏UID` | `/游戏uid`、`/UID`、`/uid`、`/我的UID`、`/我的uid` |
111
+ | `/删除UID` | `/删除uid`、`/解绑UID`、`/解绑uid` |
112
+ | `/清空UID` | `/清空uid`、`/清除UID`、`/清除uid`、`/一键清除UID`、`/一键清除uid`、`/一件清除UID`、`/一件清除uid` |
113
+ | `/绑定帮助` | `/绑定UID帮助`、`/绑定uid帮助` |
114
+ | `/群UID` | `/群uid`、`/群友UID`、`/群友uid`、`/UID列表`、`/uid列表` |
115
+ | `/设置UID提醒` | `/设置uid提醒` |
116
+ | `/关闭UID提醒` | `/关闭uid提醒` |
117
+ | `/UID提醒状态` | `/uid提醒状态` |
118
+ | `/UID帮助` | `/uid帮助`、`/游戏UID帮助`、`/游戏uid帮助` |
119
+
120
+ 命令前缀默认为 `/`,可在 NoneBot 的 `COMMAND_START` 配置中修改;帮助和播报文案中的 `/` 仅作示例。
121
+
99
122
  支持的游戏名及常用别名:
100
123
 
101
124
  - 星布谷地:`星布谷地`、`星布谷底`、`星布`、`谷地`、`谷底`
@@ -106,6 +129,15 @@ UID 按 QQ 用户全局保存,不按群分别存储。群友只能查询用户
106
129
  UID 必须为 5~20 位半角数字。
107
130
 
108
131
  提醒间隔支持 `分钟`、`小时`、`天`,范围为 10 分钟到 30 天。每个群保存一条提醒设置,再次设置会覆盖旧设置。机器人重启后设置仍然有效。
132
+ 发送失败(机器人离线、被移出群等)时,插件会按 2、4、8…… 分钟的递增间隔重试,单次等待不超过提醒间隔;连续失败 5 次后改为按正常间隔重试,`/UID提醒状态` 会显示最近的失败次数。
133
+ 同一群的 `/群UID` 每 10 秒最多触发一次;列表默认最多显示 100 人,超过人数上限或消息过长时会折叠剩余人数。
134
+
135
+ ## 数据存储
136
+
137
+ - 默认数据库位于 `nonebot-plugin-localstore` 的插件数据目录,文件名为 `uid.db`:Linux 为 `~/.local/share/nonebot2/nonebot_plugin_game_uid/uid.db`,macOS 为 `~/Library/Application Support/nonebot2/nonebot_plugin_game_uid/uid.db`,Windows 为 `%LOCALAPPDATA%\nonebot2\nonebot_plugin_game_uid\uid.db`。
138
+ - 配置 `GAME_UID_DB_PATH` 可改用自定义路径,相对路径按机器人启动目录解析。
139
+ - 数据库启用 WAL 模式;从 0.3.x 升级到 0.4.0 后首次启动会自动补齐 `retry_count` 列,已有绑定和提醒不会丢失。
140
+ - 备份时请先停止机器人再复制 `uid.db`,或连同同目录的 `uid.db-wal`、`uid.db-shm` 一起复制。
109
141
 
110
142
  ## 示例
111
143
 
@@ -120,6 +152,20 @@ UID 必须为 5~20 位半角数字。
120
152
  用户:/删除UID 原神
121
153
  机器人:已删除原神 UID。
122
154
 
155
+ 用户:/清空UID
156
+ 机器人:已一键清空你的全部游戏 UID(共 2 项)。
157
+
158
+ 用户:/绑定帮助
159
+ 机器人:UID 绑定帮助
160
+ 绑定:/绑定UID <游戏> <UID>
161
+ 示例:/绑定UID 原神 100123456
162
+ 查询:/游戏UID [游戏] [@群友]
163
+ 删除指定游戏:/删除UID <游戏>
164
+ 清空指定游戏:/清空UID <游戏>
165
+ 清空全部:/清空UID
166
+ 支持游戏:星布谷地、原神、星铁、绝区零
167
+ UID 必须是 5~20 位半角数字。
168
+
123
169
  用户:/群UID 原神
124
170
  机器人:本群原神 UID 列表(2人):
125
171
  提瓦特旅行者:100123456
@@ -130,6 +176,18 @@ SUPERUSER:/设置UID提醒 6小时 原神
130
176
  提醒内容:
131
177
  想查看本群群友的原神 UID 并添加游戏好友?
132
178
  发送 /群UID 原神,即可查看群友主动绑定的 UID(群名片:UID)。
179
+
180
+ 全部命令:
181
+ /绑定UID <游戏> <UID> — 绑定或更新自己的 UID
182
+ /游戏UID [游戏] [@群友] — 查询自己或群友的 UID
183
+ /删除UID <游戏> — 删除自己的指定游戏 UID
184
+ /清空UID [游戏] — 清空自己的指定游戏或全部 UID
185
+ /绑定帮助 — 查看 UID 绑定说明和示例
186
+ /群UID <游戏> — 查看本群“群名片:UID”列表
187
+ /设置UID提醒 <间隔> <游戏> — SUPERUSER 开启或更新定时提醒
188
+ /关闭UID提醒 — SUPERUSER 关闭定时提醒
189
+ /UID提醒状态 — 查看本群提醒设置
190
+ /UID帮助 — 查看完整帮助
133
191
  ```
134
192
 
135
193
  ## 开发
@@ -10,7 +10,9 @@
10
10
  - 在群聊中通过 `@群友` 查询对方主动绑定的 UID
11
11
  - 按“群名片:UID”列出本群已经绑定指定游戏的群友
12
12
  - SUPERUSER 可设置定时播报,周期性提示群友使用 UID 列表命令
13
+ - 播报发送失败时按递增间隔自动重试,避免每分钟刷屏
13
14
  - 删除自己的指定游戏 UID
15
+ - 一键清空自己的全部 UID,或只清空指定游戏 UID
14
16
  - 使用 SQLite 异步持久化,无需外部数据库或游戏 API
15
17
  - 兼容“星布谷底”“星铁”“铁道”“崩铁”等常用别名
16
18
 
@@ -62,12 +64,33 @@ UID 按 QQ 用户全局保存,不按群分别存储。群友只能查询用户
62
64
  | `/游戏UID [游戏] @群友` | 所有人 | 群聊 | 查看群友的指定 UID |
63
65
  | `/游戏UID @群友` | 所有人 | 群聊 | 查看群友的全部 UID |
64
66
  | `/删除UID <游戏>` | 所有人 | 群聊/私聊 | 删除自己的指定 UID |
67
+ | `/清空UID [游戏]` | 所有人 | 群聊/私聊 | 有参数时清空指定游戏;无参数时一键清空自己的全部 UID |
68
+ | `/绑定帮助` | 所有人 | 群聊/私聊 | 查看支持的游戏、绑定格式和常用操作示例 |
65
69
  | `/群UID <游戏>` | 所有人 | 群聊 | 按“群名片:UID”查看本群列表 |
66
70
  | `/设置UID提醒 <间隔> <游戏>` | SUPERUSER | 群聊 | 开启或更新定时播报 |
67
71
  | `/关闭UID提醒` | SUPERUSER | 群聊 | 关闭定时播报 |
68
72
  | `/UID提醒状态` | 所有人 | 群聊 | 查看本群提醒状态 |
69
73
  | `/UID帮助` | 所有人 | 群聊/私聊 | 查看命令帮助 |
70
74
 
75
+ ### 命令别名
76
+
77
+ 命令支持下列别名,效果与完整命令一致(别名区分大小写,`UID` 全大写和 `uid` 全小写两种写法均已注册):
78
+
79
+ | 命令 | 别名 |
80
+ |---|---|
81
+ | `/绑定UID` | `/绑定uid`、`/绑定游戏UID`、`/绑定游戏uid` |
82
+ | `/游戏UID` | `/游戏uid`、`/UID`、`/uid`、`/我的UID`、`/我的uid` |
83
+ | `/删除UID` | `/删除uid`、`/解绑UID`、`/解绑uid` |
84
+ | `/清空UID` | `/清空uid`、`/清除UID`、`/清除uid`、`/一键清除UID`、`/一键清除uid`、`/一件清除UID`、`/一件清除uid` |
85
+ | `/绑定帮助` | `/绑定UID帮助`、`/绑定uid帮助` |
86
+ | `/群UID` | `/群uid`、`/群友UID`、`/群友uid`、`/UID列表`、`/uid列表` |
87
+ | `/设置UID提醒` | `/设置uid提醒` |
88
+ | `/关闭UID提醒` | `/关闭uid提醒` |
89
+ | `/UID提醒状态` | `/uid提醒状态` |
90
+ | `/UID帮助` | `/uid帮助`、`/游戏UID帮助`、`/游戏uid帮助` |
91
+
92
+ 命令前缀默认为 `/`,可在 NoneBot 的 `COMMAND_START` 配置中修改;帮助和播报文案中的 `/` 仅作示例。
93
+
71
94
  支持的游戏名及常用别名:
72
95
 
73
96
  - 星布谷地:`星布谷地`、`星布谷底`、`星布`、`谷地`、`谷底`
@@ -78,6 +101,15 @@ UID 按 QQ 用户全局保存,不按群分别存储。群友只能查询用户
78
101
  UID 必须为 5~20 位半角数字。
79
102
 
80
103
  提醒间隔支持 `分钟`、`小时`、`天`,范围为 10 分钟到 30 天。每个群保存一条提醒设置,再次设置会覆盖旧设置。机器人重启后设置仍然有效。
104
+ 发送失败(机器人离线、被移出群等)时,插件会按 2、4、8…… 分钟的递增间隔重试,单次等待不超过提醒间隔;连续失败 5 次后改为按正常间隔重试,`/UID提醒状态` 会显示最近的失败次数。
105
+ 同一群的 `/群UID` 每 10 秒最多触发一次;列表默认最多显示 100 人,超过人数上限或消息过长时会折叠剩余人数。
106
+
107
+ ## 数据存储
108
+
109
+ - 默认数据库位于 `nonebot-plugin-localstore` 的插件数据目录,文件名为 `uid.db`:Linux 为 `~/.local/share/nonebot2/nonebot_plugin_game_uid/uid.db`,macOS 为 `~/Library/Application Support/nonebot2/nonebot_plugin_game_uid/uid.db`,Windows 为 `%LOCALAPPDATA%\nonebot2\nonebot_plugin_game_uid\uid.db`。
110
+ - 配置 `GAME_UID_DB_PATH` 可改用自定义路径,相对路径按机器人启动目录解析。
111
+ - 数据库启用 WAL 模式;从 0.3.x 升级到 0.4.0 后首次启动会自动补齐 `retry_count` 列,已有绑定和提醒不会丢失。
112
+ - 备份时请先停止机器人再复制 `uid.db`,或连同同目录的 `uid.db-wal`、`uid.db-shm` 一起复制。
81
113
 
82
114
  ## 示例
83
115
 
@@ -92,6 +124,20 @@ UID 必须为 5~20 位半角数字。
92
124
  用户:/删除UID 原神
93
125
  机器人:已删除原神 UID。
94
126
 
127
+ 用户:/清空UID
128
+ 机器人:已一键清空你的全部游戏 UID(共 2 项)。
129
+
130
+ 用户:/绑定帮助
131
+ 机器人:UID 绑定帮助
132
+ 绑定:/绑定UID <游戏> <UID>
133
+ 示例:/绑定UID 原神 100123456
134
+ 查询:/游戏UID [游戏] [@群友]
135
+ 删除指定游戏:/删除UID <游戏>
136
+ 清空指定游戏:/清空UID <游戏>
137
+ 清空全部:/清空UID
138
+ 支持游戏:星布谷地、原神、星铁、绝区零
139
+ UID 必须是 5~20 位半角数字。
140
+
95
141
  用户:/群UID 原神
96
142
  机器人:本群原神 UID 列表(2人):
97
143
  提瓦特旅行者:100123456
@@ -102,6 +148,18 @@ SUPERUSER:/设置UID提醒 6小时 原神
102
148
  提醒内容:
103
149
  想查看本群群友的原神 UID 并添加游戏好友?
104
150
  发送 /群UID 原神,即可查看群友主动绑定的 UID(群名片:UID)。
151
+
152
+ 全部命令:
153
+ /绑定UID <游戏> <UID> — 绑定或更新自己的 UID
154
+ /游戏UID [游戏] [@群友] — 查询自己或群友的 UID
155
+ /删除UID <游戏> — 删除自己的指定游戏 UID
156
+ /清空UID [游戏] — 清空自己的指定游戏或全部 UID
157
+ /绑定帮助 — 查看 UID 绑定说明和示例
158
+ /群UID <游戏> — 查看本群“群名片:UID”列表
159
+ /设置UID提醒 <间隔> <游戏> — SUPERUSER 开启或更新定时提醒
160
+ /关闭UID提醒 — SUPERUSER 关闭定时提醒
161
+ /UID提醒状态 — 查看本群提醒设置
162
+ /UID帮助 — 查看完整帮助
105
163
  ```
106
164
 
107
165
  ## 开发
@@ -10,8 +10,12 @@ __plugin_meta__ = PluginMetadata(
10
10
  "/绑定UID <游戏> <UID>\n"
11
11
  "/游戏UID [游戏] [@群友]\n"
12
12
  "/删除UID <游戏>\n"
13
+ "/清空UID [游戏]\n"
14
+ "/绑定帮助\n"
13
15
  "/群UID <游戏>\n"
14
16
  "/设置UID提醒 <间隔> <游戏>\n"
17
+ "/关闭UID提醒\n"
18
+ "/UID提醒状态\n"
15
19
  "/UID帮助"
16
20
  ),
17
21
  type="application",
@@ -1,5 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import math
4
+ import time
3
5
  from pathlib import Path
4
6
  from typing import Optional
5
7
 
@@ -17,8 +19,22 @@ from .repository import UIDRepository
17
19
  BIND_USAGE = "用法:/绑定UID <游戏> <UID>\n例如:/绑定UID 原神 100123456"
18
20
  QUERY_USAGE = "用法:/游戏UID [游戏] [@群友]\n例如:/游戏UID 星铁 @某位群友"
19
21
  DELETE_USAGE = "用法:/删除UID <游戏>\n例如:/删除UID 绝区零"
22
+ CLEAR_USAGE = "用法:/清空UID [游戏]\n不填游戏时清空自己的全部 UID\n例如:/清空UID 或 /清空UID 原神"
20
23
  GROUP_LIST_USAGE = "用法:/群UID <游戏>\n例如:/群UID 星布谷地"
21
24
  REMINDER_USAGE = "用法:/设置UID提醒 <间隔> <游戏>\n例如:/设置UID提醒 6小时 原神\n间隔范围:10分钟~30天"
25
+ GROUP_LIST_MAX_CHARS = 1500
26
+ GROUP_LIST_COOLDOWN_SECONDS = 10
27
+ BIND_HELP_TEXT = (
28
+ "UID 绑定帮助\n"
29
+ "绑定:/绑定UID <游戏> <UID>\n"
30
+ "示例:/绑定UID 原神 100123456\n"
31
+ "查询:/游戏UID [游戏] [@群友]\n"
32
+ "删除指定游戏:/删除UID <游戏>\n"
33
+ "清空指定游戏:/清空UID <游戏>\n"
34
+ "清空全部:/清空UID\n"
35
+ "支持游戏:星布谷地、原神、星铁、绝区零\n"
36
+ "UID 必须是 5~20 位半角数字。"
37
+ )
22
38
 
23
39
  uid_bind = on_command(
24
40
  "绑定UID",
@@ -38,6 +54,18 @@ uid_delete = on_command(
38
54
  priority=10,
39
55
  block=True,
40
56
  )
57
+ uid_clear = on_command(
58
+ "清空UID",
59
+ aliases={"清空uid", "清除UID", "清除uid", "一键清除UID", "一键清除uid", "一件清除UID", "一件清除uid"},
60
+ priority=10,
61
+ block=True,
62
+ )
63
+ bind_help = on_command(
64
+ "绑定帮助",
65
+ aliases={"绑定UID帮助", "绑定uid帮助"},
66
+ priority=10,
67
+ block=True,
68
+ )
41
69
  uid_help = on_command(
42
70
  "UID帮助",
43
71
  aliases={"uid帮助", "游戏UID帮助", "游戏uid帮助"},
@@ -72,20 +100,31 @@ reminder_status = on_command(
72
100
  )
73
101
 
74
102
  _repository: Optional[UIDRepository] = None
75
- _repository_path: Optional[Path] = None
103
+ _group_list_cooldowns: dict[str, float] = {}
76
104
 
77
105
 
78
106
  def get_repository() -> UIDRepository:
79
- global _repository, _repository_path
107
+ global _repository
80
108
 
81
- configured_path = get_plugin_config(Config).game_uid_db_path
82
- path = Path(configured_path).expanduser() if configured_path else localstore.get_plugin_data_file("uid.db")
83
- if _repository is None or _repository_path != path:
109
+ if _repository is None:
110
+ configured_path = get_plugin_config(Config).game_uid_db_path
111
+ path = Path(configured_path).expanduser() if configured_path else localstore.get_plugin_data_file("uid.db")
84
112
  _repository = UIDRepository(path)
85
- _repository_path = path
86
113
  return _repository
87
114
 
88
115
 
116
+ def group_list_cooldown_remaining(group_id: str) -> int:
117
+ """返回本群 `/群UID` 的剩余冷却秒数,0 表示可以立即使用。"""
118
+
119
+ last_used = _group_list_cooldowns.get(group_id)
120
+ if last_used is None:
121
+ return 0
122
+ remaining = GROUP_LIST_COOLDOWN_SECONDS - (time.monotonic() - last_used)
123
+ if remaining <= 0:
124
+ return 0
125
+ return math.ceil(remaining)
126
+
127
+
89
128
  def get_mentioned_user(message: Message) -> Optional[str]:
90
129
  """提取消息中的第一个 QQ @,忽略 @全体成员。"""
91
130
 
@@ -126,6 +165,7 @@ def format_group_uid_list(
126
165
  bindings: dict[str, str],
127
166
  *,
128
167
  limit: int,
168
+ max_chars: int = GROUP_LIST_MAX_CHARS,
129
169
  ) -> str:
130
170
  lines: list[str] = []
131
171
  for member in members:
@@ -138,10 +178,24 @@ def format_group_uid_list(
138
178
 
139
179
  if not lines:
140
180
  return f"本群还没有群友绑定{game.name} UID。"
141
- shown = lines[:limit]
142
181
  header = f"本群{game.name} UID 列表({len(lines)}人):"
143
- if len(lines) > limit:
144
- shown.append(f"……另有 {len(lines) - limit} 人未显示,请提高 game_uid_list_limit 配置。")
182
+
183
+ shown: list[str] = []
184
+ used_chars = len(header)
185
+ for line in lines[:limit]:
186
+ cost = len(line) + 1
187
+ # 至少保留一行,避免超长群名片把整条消息吞掉
188
+ if shown and used_chars + cost > max_chars:
189
+ break
190
+ shown.append(line)
191
+ used_chars += cost
192
+
193
+ hidden = len(lines) - len(shown)
194
+ if hidden:
195
+ if len(lines) > limit:
196
+ shown.append(f"……另有 {hidden} 人未显示,请提高 game_uid_list_limit 配置。")
197
+ else:
198
+ shown.append(f"……另有 {hidden} 人未显示(消息长度限制)。")
145
199
  return "\n".join([header, *shown])
146
200
 
147
201
 
@@ -198,6 +252,34 @@ async def handle_delete(event: MessageEvent, args: Message = CommandArg()) -> No
198
252
  await uid_delete.finish(f"已删除{game.name} UID。")
199
253
 
200
254
 
255
+ @uid_clear.handle()
256
+ async def handle_clear(event: MessageEvent, args: Message = CommandArg()) -> None:
257
+ parts = args.extract_plain_text().strip().split()
258
+ if len(parts) > 1:
259
+ await uid_clear.finish(CLEAR_USAGE)
260
+
261
+ repository = get_repository()
262
+ user_id = event.get_user_id()
263
+ if parts:
264
+ game = resolve_game(parts[0])
265
+ if game is None:
266
+ await uid_clear.finish(f"不支持游戏“{parts[0]}”。\n支持:星布谷地、原神、星铁、绝区零")
267
+ deleted = await repository.delete_uid(user_id, game.key)
268
+ if not deleted:
269
+ await uid_clear.finish(f"你还没有绑定{game.name} UID。")
270
+ await uid_clear.finish(f"已清空你的{game.name} UID。")
271
+
272
+ deleted_count = await repository.delete_all_uids(user_id)
273
+ if deleted_count == 0:
274
+ await uid_clear.finish("你还没有绑定任何游戏 UID。")
275
+ await uid_clear.finish(f"已一键清空你的全部游戏 UID(共 {deleted_count} 项)。")
276
+
277
+
278
+ @bind_help.handle()
279
+ async def handle_bind_help() -> None:
280
+ await bind_help.finish(BIND_HELP_TEXT)
281
+
282
+
201
283
  @group_uid_list.handle()
202
284
  async def handle_group_uid_list(bot: Bot, event: MessageEvent, args: Message = CommandArg()) -> None:
203
285
  if not isinstance(event, GroupMessageEvent):
@@ -210,6 +292,12 @@ async def handle_group_uid_list(bot: Bot, event: MessageEvent, args: Message = C
210
292
  if game is None:
211
293
  await group_uid_list.finish(f"不支持游戏“{parts[0]}”。\n支持:星布谷地、原神、星铁、绝区零")
212
294
 
295
+ group_id = str(event.group_id)
296
+ remaining = group_list_cooldown_remaining(group_id)
297
+ if remaining:
298
+ await group_uid_list.finish(f"查询太频繁,请 {remaining} 秒后再试。")
299
+ _group_list_cooldowns[group_id] = time.monotonic()
300
+
213
301
  try:
214
302
  members = await bot.get_group_member_list(group_id=event.group_id)
215
303
  except Exception as error:
@@ -266,10 +354,16 @@ async def handle_reminder_status(event: MessageEvent) -> None:
266
354
  reminder = await get_repository().get_reminder(str(event.group_id))
267
355
  if reminder is None:
268
356
  await reminder_status.finish("本群尚未开启 UID 定时提醒。")
269
- game = GAME_BY_KEY[reminder.game]
270
- await reminder_status.finish(
271
- f"本群 UID 提醒:已开启\n游戏:{game.name}\n间隔:{format_duration(reminder.interval_minutes)}"
272
- )
357
+ game = GAME_BY_KEY.get(reminder.game)
358
+ game_name = game.name if game else reminder.game
359
+ lines = [
360
+ "本群 UID 提醒:已开启",
361
+ f"游戏:{game_name}",
362
+ f"间隔:{format_duration(reminder.interval_minutes)}",
363
+ ]
364
+ if reminder.retry_count:
365
+ lines.append(f"最近发送失败 {reminder.retry_count} 次,将自动重试。")
366
+ await reminder_status.finish("\n".join(lines))
273
367
 
274
368
 
275
369
  @uid_help.handle()
@@ -279,6 +373,8 @@ async def handle_help() -> None:
279
373
  "/绑定UID <游戏> <UID> — 绑定或更新自己的 UID\n"
280
374
  "/游戏UID [游戏] [@群友] — 查询 UID\n"
281
375
  "/删除UID <游戏> — 删除自己的绑定\n"
376
+ "/清空UID [游戏] — 清空自己的指定游戏或全部 UID\n"
377
+ "/绑定帮助 — 查看 UID 绑定说明和示例\n"
282
378
  "/群UID <游戏> — 按“群名片:UID”查看本群列表\n"
283
379
  "/设置UID提醒 <间隔> <游戏> — SUPERUSER 开启定时提醒\n"
284
380
  "/关闭UID提醒 — SUPERUSER 关闭定时提醒\n"
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import time
5
+ from typing import Optional
6
+
7
+ from nonebot import get_bots, logger
8
+
9
+ from .games import GAME_BY_KEY
10
+ from .repository import GroupReminder, UIDRepository
11
+
12
+ DURATION_PATTERN = re.compile(r"^(\d+)(分钟|分|小时|时|天)$")
13
+ MIN_INTERVAL_MINUTES = 10
14
+ MAX_INTERVAL_MINUTES = 30 * 24 * 60
15
+ MAX_REMINDER_RETRIES = 5
16
+
17
+
18
+ def parse_duration(value: str) -> Optional[int]:
19
+ """解析 10分钟、6小时、1天一类的时间间隔。"""
20
+
21
+ match = DURATION_PATTERN.fullmatch(value.strip())
22
+ if not match:
23
+ return None
24
+ amount = int(match.group(1))
25
+ unit = match.group(2)
26
+ multiplier = 1 if unit in {"分钟", "分"} else 60 if unit in {"小时", "时"} else 24 * 60
27
+ minutes = amount * multiplier
28
+ if not MIN_INTERVAL_MINUTES <= minutes <= MAX_INTERVAL_MINUTES:
29
+ return None
30
+ return minutes
31
+
32
+
33
+ def format_duration(minutes: int) -> str:
34
+ if minutes % (24 * 60) == 0:
35
+ return f"{minutes // (24 * 60)}天"
36
+ if minutes % 60 == 0:
37
+ return f"{minutes // 60}小时"
38
+ return f"{minutes}分钟"
39
+
40
+
41
+ def build_reminder_message(game_key: str) -> str:
42
+ game = GAME_BY_KEY.get(game_key)
43
+ game_name = game.name if game else game_key
44
+ return (
45
+ f"想查看本群群友的{game_name} UID 并添加游戏好友?\n"
46
+ f"发送 /群UID {game_name},即可查看群友主动绑定的 UID(群名片:UID)。\n\n"
47
+ "全部命令:\n"
48
+ "/绑定UID <游戏> <UID> — 绑定或更新自己的 UID\n"
49
+ "/游戏UID [游戏] [@群友] — 查询自己或群友的 UID\n"
50
+ "/删除UID <游戏> — 删除自己的指定游戏 UID\n"
51
+ "/清空UID [游戏] — 清空自己的指定游戏或全部 UID\n"
52
+ "/绑定帮助 — 查看 UID 绑定说明和示例\n"
53
+ "/群UID <游戏> — 查看本群“群名片:UID”列表\n"
54
+ "/设置UID提醒 <间隔> <游戏> — SUPERUSER 开启或更新定时提醒\n"
55
+ "/关闭UID提醒 — SUPERUSER 关闭定时提醒\n"
56
+ "/UID提醒状态 — 查看本群提醒设置\n"
57
+ "/UID帮助 — 查看完整帮助"
58
+ )
59
+
60
+
61
+ def retry_delay_minutes(interval_minutes: int, failures: int) -> int:
62
+ """发送失败后按 2、4、8… 分钟退避,最长不超过正常提醒间隔。"""
63
+
64
+ return max(1, min(2**min(failures, 10), interval_minutes))
65
+
66
+
67
+ async def _record_failure(
68
+ repository: UIDRepository,
69
+ reminder: GroupReminder,
70
+ *,
71
+ now: float,
72
+ reason: str,
73
+ ) -> None:
74
+ """记录一次发送失败并安排下一次尝试,避免每分钟无限重试。"""
75
+
76
+ failures = reminder.retry_count + 1
77
+ if reminder.retry_count >= MAX_REMINDER_RETRIES:
78
+ # 退避次数已用尽,之后按正常提醒间隔继续尝试
79
+ delay = reminder.interval_minutes
80
+ logger.debug(f"[game_uid] 群 {reminder.group_id} UID 提醒仍无法发送({reason})")
81
+ else:
82
+ delay = retry_delay_minutes(reminder.interval_minutes, failures)
83
+ if failures < MAX_REMINDER_RETRIES:
84
+ logger.warning(
85
+ f"[game_uid] 群 {reminder.group_id} UID 提醒发送失败({reason}),"
86
+ f"{delay} 分钟后重试(第 {failures} 次)"
87
+ )
88
+ else:
89
+ logger.warning(
90
+ f"[game_uid] 群 {reminder.group_id} UID 提醒已连续失败 {failures} 次({reason}),"
91
+ f"后续改为按正常间隔 {format_duration(reminder.interval_minutes)} 重试"
92
+ )
93
+
94
+ await repository.update_reminder_attempt(
95
+ reminder.group_id,
96
+ next_run_at=now + delay * 60,
97
+ retry_count=min(failures, MAX_REMINDER_RETRIES),
98
+ )
99
+
100
+
101
+ async def dispatch_due_reminders(*, now: Optional[float] = None) -> int:
102
+ """发送已到期提醒,返回成功发送数量。"""
103
+
104
+ from .commands import get_repository
105
+
106
+ repository = get_repository()
107
+ current_time = time.time() if now is None else now
108
+ bots = get_bots()
109
+ sent = 0
110
+ for reminder in await repository.get_due_reminders(now=current_time):
111
+ bot = bots.get(reminder.bot_id)
112
+ if bot is None:
113
+ await _record_failure(
114
+ repository,
115
+ reminder,
116
+ now=current_time,
117
+ reason=f"机器人 {reminder.bot_id} 不在线",
118
+ )
119
+ continue
120
+ try:
121
+ await bot.call_api(
122
+ "send_group_msg",
123
+ group_id=int(reminder.group_id),
124
+ message=build_reminder_message(reminder.game),
125
+ )
126
+ except Exception as error:
127
+ await _record_failure(
128
+ repository,
129
+ reminder,
130
+ now=current_time,
131
+ reason=str(error) or type(error).__name__,
132
+ )
133
+ continue
134
+ await repository.mark_reminder_sent(reminder.group_id, now=current_time)
135
+ sent += 1
136
+ return sent
@@ -8,6 +8,8 @@ from typing import Optional, Union
8
8
 
9
9
  import aiosqlite
10
10
 
11
+ SQLITE_BUSY_TIMEOUT_SECONDS = 5.0
12
+
11
13
 
12
14
  @dataclass(frozen=True)
13
15
  class GroupReminder:
@@ -16,6 +18,7 @@ class GroupReminder:
16
18
  game: str
17
19
  interval_minutes: int
18
20
  next_run_at: float
21
+ retry_count: int = 0
19
22
 
20
23
 
21
24
  class UIDRepository:
@@ -26,6 +29,11 @@ class UIDRepository:
26
29
  self._initialized = False
27
30
  self._init_lock = asyncio.Lock()
28
31
 
32
+ def _connect(self) -> aiosqlite.Connection:
33
+ """连接数据库;busy timeout 让并发写入排队而不是立刻报锁。"""
34
+
35
+ return aiosqlite.connect(self.db_path, timeout=SQLITE_BUSY_TIMEOUT_SECONDS)
36
+
29
37
  async def initialize(self) -> None:
30
38
  if self._initialized:
31
39
  return
@@ -34,7 +42,8 @@ class UIDRepository:
34
42
  if self._initialized:
35
43
  return
36
44
  await asyncio.to_thread(self.db_path.parent.mkdir, parents=True, exist_ok=True)
37
- async with aiosqlite.connect(self.db_path) as db:
45
+ async with self._connect() as db:
46
+ await db.execute("PRAGMA journal_mode=WAL")
38
47
  await db.execute(
39
48
  """
40
49
  CREATE TABLE IF NOT EXISTS uid_bindings (
@@ -53,18 +62,32 @@ class UIDRepository:
53
62
  bot_id TEXT NOT NULL,
54
63
  game TEXT NOT NULL,
55
64
  interval_minutes INTEGER NOT NULL,
56
- next_run_at REAL NOT NULL
65
+ next_run_at REAL NOT NULL,
66
+ retry_count INTEGER NOT NULL DEFAULT 0
57
67
  )
58
68
  """
59
69
  )
70
+ await self._migrate(db)
60
71
  await db.commit()
61
72
  self._initialized = True
62
73
 
74
+ @staticmethod
75
+ async def _migrate(db: aiosqlite.Connection) -> None:
76
+ """为旧版本建的表补齐新增列。"""
77
+
78
+ cursor = await db.execute("PRAGMA table_info(group_reminders)")
79
+ columns = {str(row[1]) for row in await cursor.fetchall()}
80
+ await cursor.close()
81
+ if "retry_count" not in columns:
82
+ await db.execute(
83
+ "ALTER TABLE group_reminders ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0"
84
+ )
85
+
63
86
  async def set_uid(self, platform_user_id: str, game: str, uid: str) -> bool:
64
87
  """新增或更新 UID;返回 True 表示替换了旧绑定。"""
65
88
 
66
89
  await self.initialize()
67
- async with aiosqlite.connect(self.db_path) as db:
90
+ async with self._connect() as db:
68
91
  cursor = await db.execute(
69
92
  "SELECT 1 FROM uid_bindings WHERE platform_user_id = ? AND game = ?",
70
93
  (platform_user_id, game),
@@ -86,7 +109,7 @@ class UIDRepository:
86
109
 
87
110
  async def get_uid(self, platform_user_id: str, game: str) -> Optional[str]:
88
111
  await self.initialize()
89
- async with aiosqlite.connect(self.db_path) as db:
112
+ async with self._connect() as db:
90
113
  cursor = await db.execute(
91
114
  "SELECT uid FROM uid_bindings WHERE platform_user_id = ? AND game = ?",
92
115
  (platform_user_id, game),
@@ -97,7 +120,7 @@ class UIDRepository:
97
120
 
98
121
  async def get_all(self, platform_user_id: str) -> dict[str, str]:
99
122
  await self.initialize()
100
- async with aiosqlite.connect(self.db_path) as db:
123
+ async with self._connect() as db:
101
124
  cursor = await db.execute(
102
125
  "SELECT game, uid FROM uid_bindings WHERE platform_user_id = ?",
103
126
  (platform_user_id,),
@@ -114,7 +137,7 @@ class UIDRepository:
114
137
  return {}
115
138
 
116
139
  result: dict[str, str] = {}
117
- async with aiosqlite.connect(self.db_path) as db:
140
+ async with self._connect() as db:
118
141
  for start in range(0, len(platform_user_ids), 900):
119
142
  chunk = platform_user_ids[start : start + 900]
120
143
  placeholders = ",".join("?" for _ in chunk)
@@ -133,7 +156,7 @@ class UIDRepository:
133
156
 
134
157
  async def delete_uid(self, platform_user_id: str, game: str) -> bool:
135
158
  await self.initialize()
136
- async with aiosqlite.connect(self.db_path) as db:
159
+ async with self._connect() as db:
137
160
  cursor = await db.execute(
138
161
  "DELETE FROM uid_bindings WHERE platform_user_id = ? AND game = ?",
139
162
  (platform_user_id, game),
@@ -143,6 +166,20 @@ class UIDRepository:
143
166
  await db.commit()
144
167
  return deleted
145
168
 
169
+ async def delete_all_uids(self, platform_user_id: str) -> int:
170
+ """删除用户的全部 UID;返回实际删除数量。"""
171
+
172
+ await self.initialize()
173
+ async with self._connect() as db:
174
+ cursor = await db.execute(
175
+ "DELETE FROM uid_bindings WHERE platform_user_id = ?",
176
+ (platform_user_id,),
177
+ )
178
+ deleted = max(cursor.rowcount, 0)
179
+ await cursor.close()
180
+ await db.commit()
181
+ return deleted
182
+
146
183
  async def set_reminder(
147
184
  self,
148
185
  group_id: str,
@@ -154,7 +191,7 @@ class UIDRepository:
154
191
  ) -> None:
155
192
  await self.initialize()
156
193
  current_time = time.time() if now is None else now
157
- async with aiosqlite.connect(self.db_path) as db:
194
+ async with self._connect() as db:
158
195
  await db.execute(
159
196
  """
160
197
  INSERT INTO group_reminders (group_id, bot_id, game, interval_minutes, next_run_at)
@@ -171,10 +208,10 @@ class UIDRepository:
171
208
 
172
209
  async def get_reminder(self, group_id: str) -> Optional[GroupReminder]:
173
210
  await self.initialize()
174
- async with aiosqlite.connect(self.db_path) as db:
211
+ async with self._connect() as db:
175
212
  cursor = await db.execute(
176
213
  """
177
- SELECT group_id, bot_id, game, interval_minutes, next_run_at
214
+ SELECT group_id, bot_id, game, interval_minutes, next_run_at, retry_count
178
215
  FROM group_reminders
179
216
  WHERE group_id = ?
180
217
  """,
@@ -187,10 +224,10 @@ class UIDRepository:
187
224
  async def get_due_reminders(self, *, now: Optional[float] = None) -> list[GroupReminder]:
188
225
  await self.initialize()
189
226
  current_time = time.time() if now is None else now
190
- async with aiosqlite.connect(self.db_path) as db:
227
+ async with self._connect() as db:
191
228
  cursor = await db.execute(
192
229
  """
193
- SELECT group_id, bot_id, game, interval_minutes, next_run_at
230
+ SELECT group_id, bot_id, game, interval_minutes, next_run_at, retry_count
194
231
  FROM group_reminders
195
232
  WHERE next_run_at <= ?
196
233
  ORDER BY next_run_at
@@ -204,20 +241,42 @@ class UIDRepository:
204
241
  async def mark_reminder_sent(self, group_id: str, *, now: Optional[float] = None) -> None:
205
242
  await self.initialize()
206
243
  current_time = time.time() if now is None else now
207
- async with aiosqlite.connect(self.db_path) as db:
244
+ async with self._connect() as db:
208
245
  await db.execute(
209
246
  """
210
247
  UPDATE group_reminders
211
- SET next_run_at = ? + interval_minutes * 60
248
+ SET next_run_at = ? + interval_minutes * 60,
249
+ retry_count = 0
212
250
  WHERE group_id = ?
213
251
  """,
214
252
  (current_time, group_id),
215
253
  )
216
254
  await db.commit()
217
255
 
256
+ async def update_reminder_attempt(
257
+ self,
258
+ group_id: str,
259
+ *,
260
+ next_run_at: float,
261
+ retry_count: int,
262
+ ) -> None:
263
+ """记录一次发送失败后的重试状态。"""
264
+
265
+ await self.initialize()
266
+ async with self._connect() as db:
267
+ await db.execute(
268
+ """
269
+ UPDATE group_reminders
270
+ SET next_run_at = ?, retry_count = ?
271
+ WHERE group_id = ?
272
+ """,
273
+ (next_run_at, retry_count, group_id),
274
+ )
275
+ await db.commit()
276
+
218
277
  async def delete_reminder(self, group_id: str) -> bool:
219
278
  await self.initialize()
220
- async with aiosqlite.connect(self.db_path) as db:
279
+ async with self._connect() as db:
221
280
  cursor = await db.execute("DELETE FROM group_reminders WHERE group_id = ?", (group_id,))
222
281
  deleted = cursor.rowcount > 0
223
282
  await cursor.close()
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "nonebot-plugin-game-uid"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "记录、汇总和定时播报群友的星布谷地、原神、崩坏:星穹铁道与绝区零 UID"
5
5
  authors = [{ name = "TonyLiangP2010405" }]
6
6
  license = "MIT"
@@ -1,70 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- from typing import Optional
5
-
6
- from nonebot import get_bots, logger
7
-
8
- from .games import GAME_BY_KEY
9
-
10
- DURATION_PATTERN = re.compile(r"^(\d+)(分钟|分|小时|时|天)$")
11
- MIN_INTERVAL_MINUTES = 10
12
- MAX_INTERVAL_MINUTES = 30 * 24 * 60
13
-
14
-
15
- def parse_duration(value: str) -> Optional[int]:
16
- """解析 10分钟、6小时、1天一类的时间间隔。"""
17
-
18
- match = DURATION_PATTERN.fullmatch(value.strip())
19
- if not match:
20
- return None
21
- amount = int(match.group(1))
22
- unit = match.group(2)
23
- multiplier = 1 if unit in {"分钟", "分"} else 60 if unit in {"小时", "时"} else 24 * 60
24
- minutes = amount * multiplier
25
- if not MIN_INTERVAL_MINUTES <= minutes <= MAX_INTERVAL_MINUTES:
26
- return None
27
- return minutes
28
-
29
-
30
- def format_duration(minutes: int) -> str:
31
- if minutes % (24 * 60) == 0:
32
- return f"{minutes // (24 * 60)}天"
33
- if minutes % 60 == 0:
34
- return f"{minutes // 60}小时"
35
- return f"{minutes}分钟"
36
-
37
-
38
- def build_reminder_message(game_key: str) -> str:
39
- game = GAME_BY_KEY[game_key]
40
- return (
41
- f"想查看本群群友的{game.name} UID 并添加游戏好友?\n"
42
- f"发送 /群UID {game.name},即可查看群友主动绑定的 UID(群名片:UID)。"
43
- )
44
-
45
-
46
- async def dispatch_due_reminders(*, now: Optional[float] = None) -> int:
47
- """发送已到期提醒,返回成功发送数量。"""
48
-
49
- from .commands import get_repository
50
-
51
- repository = get_repository()
52
- bots = get_bots()
53
- sent = 0
54
- for reminder in await repository.get_due_reminders(now=now):
55
- bot = bots.get(reminder.bot_id)
56
- if bot is None:
57
- logger.warning(f"[game_uid] 提醒群 {reminder.group_id} 时机器人 {reminder.bot_id} 不在线")
58
- continue
59
- try:
60
- await bot.call_api(
61
- "send_group_msg",
62
- group_id=int(reminder.group_id),
63
- message=build_reminder_message(reminder.game),
64
- )
65
- except Exception as error:
66
- logger.warning(f"[game_uid] 群 {reminder.group_id} UID 提醒发送失败:{error}")
67
- continue
68
- await repository.mark_reminder_sent(reminder.group_id, now=now)
69
- sent += 1
70
- return sent