astrbot_plugin_button_gateway/main.py
2026-08-03 16:32:48 +08:00

398 行
16 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

"""Shared interactive-button gateway.
Any plugin that wants buttons calls this one instead of patching botpy itself:
gw = context.get_registered_star("astrbot_plugin_button_gateway").star_cls
await gw.send_buttons(
event,
"确认重启照片服务?",
[{"label": "批准", "action": "approve", "style": 1},
{"label": "取消", "action": "cancel", "style": 0}],
owner="astrbot_plugin_nas_ops",
handler="on_button",
payload={"plan_id": "..."},
allowed_user_id=event.get_sender_id(),
)
and exposes:
async def on_button(action: str, payload: dict, identity: dict) -> tuple[bool, str]
returning (ok, 回复文案). The gateway maps that onto the platform's ACK semantics and sends the
reply, so callers never touch QQ interaction codes.
Why a gateway at all: the QQ INTERACTION intent and `on_interaction_create` are process-wide
class attributes, so only one component can own them. Two plugins patching independently
silently clobber each other.
"""
from __future__ import annotations
import asyncio
import contextlib
import contextvars
import random
from typing import Any
from astrbot.api import AstrBotConfig, logger
from astrbot.api.event import AstrMessageEvent, filter
from astrbot.api.star import Context, Star, register
from . import keyboards, qq_bridge
from .registry import ButtonRegistry
# QQ interaction result codes.
ACK_OK = 0
ACK_FAILED = 1
ACK_REPEATED = 3
ACK_FORBIDDEN = 4
_REASON_ACK = {
"expired": ACK_FAILED,
"invalid_ref": ACK_FAILED,
"unknown_action": ACK_FAILED,
"forbidden": ACK_FORBIDDEN,
"already_consumed": ACK_REPEATED,
}
_REASON_TEXT = {
"expired": "这个按钮已经失效了,请重新发起。",
"invalid_ref": "按钮数据无法识别。",
"unknown_action": "按钮数据无法识别。",
"forbidden": "这个按钮不是给你的。",
"already_consumed": "这一项刚才已经处理过了。",
}
# Set for the duration of a click so a handler can answer with a *new* card without holding an
# AstrMessageEvent. QQ rejects unsolicited pushes, so the interaction's event_id has to ride
# along — that is why this is context rather than something the handler could reconstruct.
_ACTIVE_CALLBACK: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar(
"button_gateway_active_callback", default=None
)
@register(
"astrbot_plugin_button_gateway",
"local",
"跨插件共享的交互按钮网关:独占 QQ Interaction 入口,按短引用路由回调",
"0.1.0",
)
class ButtonGatewayPlugin(Star):
def __init__(self, context: Context, config: AstrBotConfig):
super().__init__(context)
self.context = context
self.registry = ButtonRegistry()
self.qq_platform_id = str(config.get("qq_platform_id") or "default_1905122299")
self.telegram_platform_id = str(config.get("telegram_platform_id") or "telegram")
self.enabled = bool(config.get("enable", True))
self._bridge_installed = False
self._telegram_application: Any = None
self._watch_task: asyncio.Task | None = None
# ──── lifecycle ────
async def initialize(self):
if not self.enabled:
logger.info("按钮网关已禁用")
return
self._bridge_installed = qq_bridge.install(self._dispatch_qq)
if self._bridge_installed:
logger.info("按钮网关:QQ Interaction 入口已接管")
else:
logger.warning("按钮网关:QQ Interaction 入口接管失败,将只能发命令型按钮")
self._watch_task = asyncio.create_task(self._watch_platforms())
async def terminate(self):
if self._watch_task:
self._watch_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._watch_task
qq_bridge.uninstall()
self._bridge_installed = False
async def _watch_platforms(self) -> None:
"""Attach the Telegram callback handler once its Application exists, and report intent."""
while True:
try:
platform = self.context.get_platform_inst(self.telegram_platform_id)
application = getattr(platform, "application", None) if platform else None
if application is not None and application is not self._telegram_application:
from telegram.ext import CallbackQueryHandler # noqa: PLC0415
application.add_handler(
CallbackQueryHandler(self._dispatch_telegram, pattern=r"^bg:"),
group=-25,
)
self._telegram_application = application
logger.info("按钮网关:Telegram 回调处理器已注册")
except Exception as exc:
logger.warning("按钮网关:Telegram 处理器注册失败 %s", type(exc).__name__)
try:
platform = self.context.get_platform_inst(self.qq_platform_id)
client = getattr(platform, "client", None) if platform else None
if client is not None and not qq_bridge.intent_enabled(client):
logger.warning("按钮网关:QQ INTERACTION intent 未启用,需重启 AstrBot 后生效")
except Exception as exc:
logger.warning("按钮网关:QQ intent 检查失败 %s", type(exc).__name__)
await asyncio.sleep(5)
# ──── public API ────
async def send_buttons(
self,
event: AstrMessageEvent,
text: str,
buttons: list[dict[str, Any]],
*,
owner: str,
handler: str,
payload: dict[str, Any] | None = None,
allowed_user_id: str | None = None,
ttl_seconds: int = 600,
single_use: bool = True,
) -> bool:
"""Send a button card. Returns False when the window cannot render buttons.
A False return is not an error — callers should fall back to their text flow.
"""
if not self.enabled:
return False
actions = tuple(str(b["action"]) for b in buttons)
ref = self.registry.issue(
owner=owner,
handler=handler,
payload=payload or {},
actions=actions,
allowed_user_id=allowed_user_id,
ttl_seconds=ttl_seconds,
single_use=single_use,
)
try:
platform = str(getattr(getattr(event, "platform_meta", None), "name", "") or "").lower()
if platform == "qq_official":
ok = await self._send_qq(event, text, buttons, ref, allowed_user_id)
elif platform == "telegram":
ok = await self._send_telegram(event, text, buttons, ref)
else:
ok = False
except Exception as exc:
logger.warning("按钮网关:发送失败 %s: %s", type(exc).__name__, exc)
ok = False
if not ok:
self.registry.revoke(ref)
return ok
async def send_buttons_to(
self,
identity: dict[str, str],
text: str,
buttons: list[dict[str, Any]],
*,
owner: str,
handler: str,
payload: dict[str, Any] | None = None,
ttl_seconds: int = 600,
single_use: bool = True,
) -> bool:
"""Send a card from inside a button callback, where there is no AstrMessageEvent.
Enables multi-step flows — check, then offer what passed; pick a target, then confirm.
Only valid while handling a click: QQ refuses unsolicited pushes, so this reuses the
interaction's event_id, which exists only for that window.
"""
if not self.enabled:
return False
ctx = _ACTIVE_CALLBACK.get()
if ctx is None:
logger.warning("按钮网关:send_buttons_to 只能在按钮回调期间调用")
return False
user_id = str(identity.get("user_id") or ctx.get("user_id") or "")
actions = tuple(str(b["action"]) for b in buttons)
ref = self.registry.issue(
owner=owner, handler=handler, payload=payload or {}, actions=actions,
allowed_user_id=user_id or None, ttl_seconds=ttl_seconds, single_use=single_use,
)
try:
if ctx["platform"] == "qq_official":
keyboard = keyboards.build_qq_keyboard(buttons, ref, allowed_user_id=user_id or None)
message = keyboards.build_qq_c2c_payload(text, keyboard)
kwargs: dict[str, Any] = {"openid": user_id, "msg_seq": random.randint(1, 10000), **message}
if ctx.get("event_id"):
kwargs["event_id"] = ctx["event_id"]
await ctx["client"].api.post_c2c_message(**kwargs)
return True
if ctx["platform"] == "telegram":
markup = keyboards.build_telegram_markup(buttons, ref)
await ctx["query"].message.reply_text(text, reply_markup=markup)
return True
except Exception as exc:
logger.warning("按钮网关:回调内发送卡片失败 %s: %s", type(exc).__name__, exc)
self.registry.revoke(ref)
return False
def revoke(self, ref: str) -> bool:
return self.registry.revoke(ref)
# ──── senders ────
async def _send_qq(self, event, text, buttons, ref, allowed_user_id) -> bool:
if not hasattr(event, "post_c2c_message"):
return False
if str(getattr(getattr(event, "message_obj", None), "group_id", "") or "").strip():
return False # group buttons need a different API surface; not supported yet
keyboard = keyboards.build_qq_keyboard(buttons, ref, allowed_user_id=allowed_user_id)
message = keyboards.build_qq_c2c_payload(text, keyboard)
source = getattr(getattr(event, "message_obj", None), "raw_message", None)
msg_id = str(getattr(source, "id", "") or getattr(getattr(event, "message_obj", None), "message_id", "") or "")
result = await event.post_c2c_message(
openid=str(event.get_sender_id()),
msg_id=msg_id or None,
msg_seq=random.randint(1, 10000),
**message,
)
return result is not None
async def _send_telegram(self, event, text, buttons, ref) -> bool:
client = getattr(event, "client", None)
if client is None:
return False
markup = keyboards.build_telegram_markup(buttons, ref)
await client.send_message(chat_id=str(event.get_sender_id()), text=text, reply_markup=markup)
return True
# ──── dispatch ────
async def _invoke_owner(self, entry, action: str, identity: dict[str, str]) -> tuple[bool, str]:
meta = self.context.get_registered_star(entry.owner)
target = getattr(meta, "star_cls", None) if meta else None
if target is None:
logger.warning("按钮网关:找不到注册插件 %s", entry.owner)
return False, "处理该按钮的插件当前不可用。"
func = getattr(target, entry.handler, None)
if func is None:
logger.warning("按钮网关:%s 缺少 handler %s", entry.owner, entry.handler)
return False, "处理该按钮的插件当前不可用。"
result = await func(action, dict(entry.payload), dict(identity))
if isinstance(result, tuple) and len(result) == 2:
return bool(result[0]), str(result[1])
return True, str(result or "处理完成")
async def _dispatch_qq(self, client: Any, interaction: Any) -> bool:
resolved = getattr(getattr(interaction, "data", None), "resolved", None)
raw = getattr(resolved, "button_data", "")
try:
action, ref = keyboards.decode(raw)
except ValueError:
return False # not ours — let the previous handler try
interaction_id = str(getattr(interaction, "id", "") or "")
user_id = str(getattr(interaction, "user_openid", "") or "")
# bot_instance is part of the identity tuple downstream controllers key on, so it must
# travel with the callback rather than be re-derived by each caller.
identity = {
"platform": "qq_official",
"bot_instance": self.qq_platform_id,
"user_id": user_id,
"chat_id": str(getattr(interaction, "group_openid", "") or "") or user_id,
}
entry, reason = self.registry.claim(ref, action, user_id)
if reason != "ok":
await self._qq_ack(client, interaction_id, _REASON_ACK.get(reason, ACK_FAILED))
await self._qq_reply(client, interaction, user_id, _REASON_TEXT.get(reason, "处理失败。"))
return True
token = _ACTIVE_CALLBACK.set({
"platform": "qq_official",
"client": client,
"user_id": user_id,
"event_id": str(getattr(interaction, "event_id", "") or ""),
})
try:
ok, reply = await self._invoke_owner(entry, action, identity)
except Exception:
logger.exception("按钮网关:插件 %s 处理按钮失败", entry.owner)
ok, reply = False, "处理时出错,请查看日志。"
finally:
_ACTIVE_CALLBACK.reset(token)
await self._qq_ack(client, interaction_id, ACK_OK if ok else ACK_FAILED)
if reply:
await self._qq_reply(client, interaction, user_id, reply)
return True
async def _dispatch_telegram(self, update, _context) -> None:
query = getattr(update, "callback_query", None)
if query is None:
return
try:
action, ref = keyboards.decode(query.data)
except ValueError:
return
user_id = str(getattr(getattr(query, "from_user", None), "id", "") or "")
identity = {
"platform": "telegram",
"bot_instance": self.telegram_platform_id,
"user_id": user_id,
"chat_id": user_id,
}
entry, reason = self.registry.claim(ref, action, user_id)
if reason != "ok":
await query.answer(_REASON_TEXT.get(reason, "处理失败。"), show_alert=True)
return
token = _ACTIVE_CALLBACK.set({"platform": "telegram", "query": query, "user_id": user_id})
try:
ok, reply = await self._invoke_owner(entry, action, identity)
except Exception:
logger.exception("按钮网关:插件 %s 处理按钮失败", entry.owner)
ok, reply = False, "处理时出错,请查看日志。"
finally:
_ACTIVE_CALLBACK.reset(token)
await query.answer("已处理" if ok else "处理失败")
if reply:
with contextlib.suppress(Exception):
await query.edit_message_text(reply[:3800])
@staticmethod
async def _qq_ack(client: Any, interaction_id: str, code: int) -> None:
if not interaction_id:
return
try:
await client.api.on_interaction_result(interaction_id, int(code))
except Exception as exc:
logger.warning("按钮网关:QQ ACK 失败 %s", type(exc).__name__)
@staticmethod
async def _qq_reply(client: Any, interaction: Any, user_id: str, text: str) -> None:
kwargs: dict[str, Any] = {
"openid": user_id,
"msg_type": 0,
"content": str(text or "处理完成")[:1800],
"msg_seq": random.randint(1, 10000),
}
event_id = str(getattr(interaction, "event_id", "") or "")
if event_id:
kwargs["event_id"] = event_id
try:
await client.api.post_c2c_message(**kwargs)
except Exception as exc:
logger.warning("按钮网关:QQ 结果消息发送失败 %s", type(exc).__name__)
# ──── diagnostics ────
@filter.command("btngw")
@filter.permission_type(filter.PermissionType.ADMIN)
async def cmd_status(self, event: AstrMessageEvent):
"""查看按钮网关状态。"""
self.registry.purge()
platform = self.context.get_platform_inst(self.qq_platform_id)
client = getattr(platform, "client", None) if platform else None
yield event.plain_result(
"按钮网关状态\n"
f"QQ 入口接管:{'是' if self._bridge_installed else '否'}\n"
f"QQ INTERACTION intent:{'已启用' if client is not None and qq_bridge.intent_enabled(client) else '未启用/未连接'}\n"
f"Telegram 处理器:{'已注册' if self._telegram_application is not None else '未注册'}\n"
f"待处理引用:{len(self.registry)}"
)