from __future__ import annotations from typing import Optional from PWF.Convention.Runtime.Architecture import Architecture from Plugins.WPSAPI import GuideEntry from Plugins.WPSConfigSystem import WPSConfigAPI from .WPSRedPacketBase import WPSRedPacketBase class WPSExclusiveRedPacket(WPSRedPacketBase): """专属红包入口插件""" def get_guide_subtitle(self) -> str: return "发送给指定用户的专属红包" def collect_command_entries(self): return ( GuideEntry( title="专属红包", identifier="专属红包 <金额> ", description="只允许指定用户领取,该用户也需要使用 `抢红包` 指令领取。", ), ) def wake_up(self) -> None: self.register_plugin("专属红包") async def callback(self, message: str, chat_id: int, user_id: int) -> Optional[str]: payload = self.parse_message_after_at(message).strip() tokens = [token.strip() for token in payload.split() if token.strip()] if len(tokens) < 2: return await self.send_markdown_message( self.format_error("指令格式:`专属红包 <金额> <用户ID|用户名>`"), chat_id, user_id, ) service = self.red_packet_service() amount_token = tokens[0] target_token = tokens[1:] try: if not amount_token.isdigit(): raise ValueError("金额需要是正整数") amount = int(amount_token) target_identifier = " ".join(target_token).strip() if not target_identifier: raise ValueError("需要指定目标用户") target_user_id = self._resolve_target_user(target_identifier) if target_user_id is None: raise ValueError("未找到目标用户") target_username = self.config_api().get_user_name(target_user_id) self.validate_amount_and_slots(amount, 1) self.ensure_sufficient_points(user_id, amount) packet = service.create_exclusive_packet( chat_id, user_id, amount, target_user_id, target_username, ) hint = f"- 专属对象:{target_username}(仅该用户可抢)" return await self.send_markdown_message( self.format_packet_message(packet, hint), chat_id, user_id, ) except ValueError as exc: return await self.send_markdown_message(self.format_error(str(exc)), chat_id, user_id) def _resolve_target_user(self, identifier: str) -> Optional[int]: text = identifier.strip() if not text: return None if text.isdigit(): return int(text) config_api: WPSConfigAPI = Architecture.Get(WPSConfigAPI) return config_api.find_user_id_by_username(text) __all__ = ["WPSExclusiveRedPacket"]