astrbot_plugin_button_gateway/qq_bridge.py

111 行
4 KiB
Python

2026-08-03 16:32:48 +08:00
"""Own the single QQ Interaction entry point on behalf of every plugin.
AstrBot builds its QQ client from botpy's `botClient`, and native (action.type=1) buttons only
arrive if the INTERACTION intent is set at construction time and `on_interaction_create` is
overridden on the class. Both are process-wide, so exactly one component may own them —
several plugins patching independently silently clobber each other.
This module is that owner. Differences from a per-plugin patch:
* install is idempotent and records the *original* attributes so uninstall genuinely restores
them (a patch that only clears an "active plugin" slot leaves wrappers stacked forever);
* unrecognised references fall through to whatever handler was installed before us, so a
plugin that still carries its own bridge keeps working while it migrates.
"""
from __future__ import annotations
import logging
from typing import Any, Awaitable, Callable
logger = logging.getLogger(__name__)
QQ_INTERACTION_INTENT = 1 << 26
_ORIG_INIT = "_btngw_original_init"
_ORIG_HANDLER = "_btngw_original_interaction_handler"
_DISPATCH = "_btngw_dispatch"
_INSTALLED = "_btngw_installed"
def _bot_client() -> Any | None:
try:
from astrbot.core.platform.sources.qqofficial.qqofficial_platform_adapter import ( # noqa: PLC0415
botClient,
)
except (ImportError, AttributeError):
return None
return botClient
def install(dispatch: Callable[[Any, Any], Awaitable[bool]]) -> bool:
"""Take over the interaction entry point.
`dispatch(client, interaction)` must return True when it handled the interaction and False
to let the previously installed handler have it.
"""
bot_client = _bot_client()
if bot_client is None:
return False
if not hasattr(bot_client, _ORIG_INIT):
setattr(bot_client, _ORIG_INIT, bot_client.__init__)
if not hasattr(bot_client, _ORIG_HANDLER):
setattr(bot_client, _ORIG_HANDLER, getattr(bot_client, "on_interaction_create", None))
setattr(bot_client, _DISPATCH, dispatch)
if getattr(bot_client, _INSTALLED, False):
# Already wrapped; swapping the dispatch above is enough.
return True
original_init = getattr(bot_client, _ORIG_INIT)
def patched_init(client: Any, *args: Any, **kwargs: Any) -> None:
original_init(client, *args, **kwargs)
client.intents = int(getattr(client, "intents", 0)) | QQ_INTERACTION_INTENT
async def on_interaction_create(client: Any, interaction: Any) -> None:
handler = getattr(bot_client, _DISPATCH, None)
if handler is not None:
try:
if await handler(client, interaction):
return
except Exception:
logger.exception("按钮网关处理 QQ Interaction 失败")
return
fallback = getattr(bot_client, _ORIG_HANDLER, None)
if fallback is not None:
await fallback(client, interaction)
bot_client.__init__ = patched_init
bot_client.on_interaction_create = on_interaction_create
setattr(bot_client, _INSTALLED, True)
return True
def uninstall() -> None:
"""Restore botpy to its pre-gateway state, unlike a slot-clearing teardown."""
bot_client = _bot_client()
if bot_client is None or not getattr(bot_client, _INSTALLED, False):
return
if hasattr(bot_client, _ORIG_INIT):
bot_client.__init__ = getattr(bot_client, _ORIG_INIT)
delattr(bot_client, _ORIG_INIT)
if hasattr(bot_client, _ORIG_HANDLER):
original = getattr(bot_client, _ORIG_HANDLER)
if original is not None:
bot_client.on_interaction_create = original
else:
try:
del bot_client.on_interaction_create
except AttributeError:
pass
delattr(bot_client, _ORIG_HANDLER)
for attr in (_DISPATCH, _INSTALLED):
if hasattr(bot_client, attr):
delattr(bot_client, attr)
def intent_enabled(client: Any) -> bool:
return bool(int(getattr(client, "intents", 0)) & QQ_INTERACTION_INTENT)