Restore proactive reminders with group permission guidance and verification

This commit is contained in:
itxiaohui committed 2026-10-05 19:58:27 +08:00
1 parent 58d6807ed0
commit 88cadbac0b
10 files changed
+679 -30

No files matched your search

+8
View File
@@ -7,6 +7,14 @@ from html import escape
OFFICIAL = {"qq_official", "qq_official_webhook"}
def proactive_denied(exc):
text = str(exc).lower()
return any(
token in text
for token in ("主动消息失败", "无权限", "permission", "not allowed", "主动消息权限")
)
def incoming_reply(event):
"""Read an inbound message ID and its original timestamp, never a sent ID."""
raw = event.message_obj.raw_message
+73
View File
@@ -0,0 +1,73 @@
"""Observe the official SDK's group lifecycle events without replacing its parsers."""
import asyncio
import inspect
from astrbot.api import logger
NOTICE = (
"⏰ 定时提醒需要主动消息权限。请群主或管理员打开本群机器人的权限设置,"
"确认已开启“允许机器人主动发送消息”(不同 QQ 版本名称可能略有不同)。"
"开启后可 @机器人 /tx permission check 验证;随后按设置时间主动提醒。"
)
EVENTS = ("group_add_robot", "group_del_robot", "group_msg_receive", "group_msg_reject")
class PermissionBridge:
def __init__(self, platform, handler):
self.platform = platform
self.client = platform.get_client()
self.handler = handler
self.closed = False
self.callbacks = {}
self.tasks = set()
def install(self):
for kind in EVENTS:
name = "on_" + kind
previous = getattr(self.client, name, None)
async def callback(event, kind=kind, previous=previous):
task = asyncio.current_task()
if not self.closed:
self.tasks.add(task)
try:
await self.handler(self.platform, kind, event)
except Exception:
logger.exception("[Reminder] 处理 QQ 群权限事件失败:%s", kind)
finally:
self.tasks.discard(task)
if previous:
result = previous(event)
if inspect.isawaitable(result):
await result
callback._reminder_bridge = self
callback._reminder_previous = previous
setattr(self.client, name, callback)
self.callbacks[name] = callback
async def close(self):
self.closed = True
# Finish any notification + persistence before the plugin is unloaded.
if self.tasks:
pending = asyncio.gather(*self.tasks, return_exceptions=True)
try:
await asyncio.shield(pending)
except asyncio.CancelledError:
await pending
raise
for name, callback in self.callbacks.items():
if getattr(self.client, name, None) is not callback:
continue
previous = callback._reminder_previous
while previous and isinstance(
getattr(previous, "_reminder_bridge", None), PermissionBridge
):
if not previous._reminder_bridge.closed:
break
previous = previous._reminder_previous
if previous is None:
delattr(self.client, name)
else:
setattr(self.client, name, previous)
+99
View File
@@ -70,6 +70,13 @@ class ReminderStore:
used INTEGER NOT NULL DEFAULT 0, blocked INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY(platform_id, scene, destination)
);
CREATE TABLE IF NOT EXISTS group_permissions (
platform_id TEXT NOT NULL, destination TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'unknown', notified INTEGER NOT NULL DEFAULT 0,
notice_until REAL NOT NULL DEFAULT 0, event_at REAL NOT NULL DEFAULT 0,
event_id TEXT NOT NULL DEFAULT '',
PRIMARY KEY(platform_id, destination)
);
""")
columns = {row[1] for row in db.execute("PRAGMA table_info(reminders)")}
if "waiting_reason" not in columns:
@@ -79,6 +86,98 @@ class ReminderStore:
await self._run(create)
async def permission(self, platform_id, destination):
return await self._run(
lambda db: dict(
db.execute(
"SELECT * FROM group_permissions WHERE platform_id=? AND destination=?",
(platform_id, destination),
).fetchone()
or {"state": "unknown", "notified": 0}
)
)
async def set_permission(
self, platform_id, destination, state, event_at=None, event_id="", reset=False
):
def write(db):
db.execute("BEGIN IMMEDIATE")
db.execute(
"INSERT OR IGNORE INTO group_permissions(platform_id,destination) VALUES (?,?)",
(platform_id, destination),
)
row = db.execute(
"SELECT * FROM group_permissions WHERE platform_id=? AND destination=?",
(platform_id, destination),
).fetchone()
if event_at is not None and (
event_at < row["event_at"] or (event_id and event_id == row["event_id"])
):
return False
reset_notice = reset and (row["state"] != state or event_at is not None)
db.execute(
"UPDATE group_permissions SET state=?,event_at=COALESCE(?,event_at),"
"event_id=CASE WHEN ?!='' THEN ? ELSE event_id END,"
"notified=CASE WHEN ? THEN 0 ELSE notified END,"
"notice_until=CASE WHEN ? THEN 0 ELSE notice_until END "
"WHERE platform_id=? AND destination=?",
(
state,
event_at,
event_id,
event_id,
reset_notice,
reset_notice,
platform_id,
destination,
),
)
if state == "granted":
db.execute(
"UPDATE reminders SET retry_at=0,waiting_reason='' WHERE platform_id=? "
"AND destination=? AND scene='group' AND status='active' "
"AND waiting_reason LIKE '主动消息权限%'",
(platform_id, destination),
)
return True
return await self._run(write)
async def claim_notice(self, platform_id, destination):
def write(db):
db.execute("BEGIN IMMEDIATE")
db.execute(
"INSERT OR IGNORE INTO group_permissions(platform_id,destination) VALUES (?,?)",
(platform_id, destination),
)
return (
db.execute(
"UPDATE group_permissions SET notice_until=? WHERE platform_id=? "
"AND destination=? AND state!='granted' AND notified=0 AND notice_until<=?",
(time.time() + 60, platform_id, destination, time.time()),
).rowcount
== 1
)
return await self._run(write)
async def finish_notice(self, platform_id, destination, sent):
await self._run(
lambda db: db.execute(
"UPDATE group_permissions SET notified=MAX(notified,?),notice_until=0 WHERE platform_id=? AND destination=?",
(int(sent), platform_id, destination),
)
)
async def wait_for_permission(self, reminder_id, owner, reason, retry_at):
await self._run(
lambda db: db.execute(
"UPDATE reminders SET waiting_reason=?,retry_at=?,lease_owner='',lease_until=0 "
"WHERE id=? AND lease_owner=? AND status='active'",
(reason[:500], retry_at, reminder_id, owner),
)
)
async def observe(self, scope, user_id, nickname=""):
await self._run(
lambda db: (