import os import random from typing import Dict, Any, List, Optional, Tuple from pathlib import Path from base.plugin_common.message_plugin_interface import MessagePluginInterface from base.plugin_common.plugin_interface import PluginStatus from utils.decorator.plugin_decorators import plugin_stats_decorator from utils.decorator.rate_limit_decorator import group_feature_rate_limit from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager from utils.decorator.points_decorator import plugin_points_cost from wechat_ipad import WechatAPIClient class BeautyLegPlugin(MessagePluginInterface): """美腿图片插件""" # 功能权限常量 FEATURE_KEY = "BEAUTY_LEG" FEATURE_DESCRIPTION = "🦵 腿来能力 [美腿, 腿来]" @property def name(self) -> str: return "美腿图片" @property def version(self) -> str: return "1.0.0" @property def description(self) -> str: return "提供随机美腿图片功能" @property def author(self) -> str: return "liu.wei" @property def command_prefix(self) -> Optional[str]: return "" # 不需要前缀,直接匹配命令 @property def commands(self) -> List[str]: return self._commands @property def feature_key(self) -> Optional[str]: return self.FEATURE_KEY @property def feature_description(self) -> Optional[str]: return self.FEATURE_DESCRIPTION def __init__(self): super().__init__() # 注册功能权限 self.feature = self.register_feature() # 修改图片目录路径指向 resource/beauty_leg self.image_folder = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "resource", "beauty_leg") def initialize(self, context: Dict[str, Any]) -> bool: """初始化插件""" self.LOG.debug(f"正在初始化 {self.name} 插件...") # 保存上下文对象 self.event_system = context.get("event_system") self.gbm = context.get("gbm") self._commands = self._config.get("Beautyleg", {}).get("command", ["美腿", "腿来"]) self.command_format = self._config.get("Beautyleg", {}).get("command-format", "美腿") self.enable = self._config.get("Beautyleg", {}).get("enable", True) config_image_folder = self._config.get("Beautyleg", {}).get("image_folder") if config_image_folder: self.image_folder = config_image_folder # 检查图片文件夹是否存在 if not os.path.exists(self.image_folder): self.LOG.warning(f"图片文件夹不存在: {self.image_folder}") os.makedirs(self.image_folder, exist_ok=True) self.LOG.debug(f"[{self.name}] 插件初始化完成,指令:{self._commands}") return True def start(self) -> bool: """启动插件""" self.LOG.debug(f"[{self.name}] 插件已启动") self.status = PluginStatus.RUNNING return True def stop(self) -> bool: """停止插件""" self.LOG.info(f"[{self.name}] 插件已停止") self.status = PluginStatus.STOPPED return True def can_process(self, message: Dict[str, Any]) -> bool: """检查是否可以处理该消息""" if not self.enable: return False content = str(message.get("content", "")).strip() command = content.split(" ")[0] return command in self._commands @plugin_stats_decorator(plugin_name="美腿图片") @plugin_points_cost(2, "美腿图片消耗积分", FEATURE_KEY) @group_feature_rate_limit(max_per_minute=1, feature_key=FEATURE_KEY) async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]: """处理消息""" content = str(message.get("content", "")).strip() self.LOG.debug(f"插件执行: {self.name}:{content}") sender = message.get("sender") roomid = message.get("roomid", "") gbm: GroupBotManager = message.get("gbm") bot: WechatAPIClient = message.get("bot") # 检查权限 if roomid and gbm.get_group_permission(roomid, self.feature) == PermissionStatus.DISABLED: return False, "没有权限" try: # 获取随机图片 random_file_path = self._get_random_file_from_dir(self.image_folder) if not random_file_path: await bot.send_text_message((roomid if roomid else sender), f"\n❌未找到美腿图片资源") return True, "未找到图片资源" # 发送图片 random_file_path = os.path.abspath(random_file_path) self.LOG.info(f"BeautyLeg.random_file_path: {random_file_path}") result = await bot.send_image_message((roomid if roomid else sender), Path(random_file_path)) self.LOG.info(f"发送图片结果: {result}") return True, "发送成功" except Exception as e: self.LOG.error(f"处理美腿图片请求出错: {e}") return True, f"处理出错: {e}" def _get_random_file_from_dir(self, directory): """获取随机图片路径""" image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'} image_files = [] if not os.path.exists(directory): self.LOG.error(f"Error: Directory '{directory}' does not exist.") return None if not os.access(directory, os.R_OK): self.LOG.error(f"Error: No read access to directory '{directory}'.") return None self.LOG.info(f"Scanning directory: {directory} (including subdirectories)") # 使用 os.walk() 递归遍历所有子目录 for root, _, files in os.walk(directory): for file in files: _, ext = os.path.splitext(file) if ext.lower() in image_extensions: full_path = os.path.join(root, file) image_files.append(full_path) if not image_files: self.LOG.error("No image files found in the directory (including subdirectories).") return None return random.choice(image_files)