回退“feat: 实现KEYWORD_OR_LLM_JUDGE激活类型”

This commit is contained in:
tt-P607
2025-09-17 22:37:45 +08:00
committed by Windpicker-owo
parent 78615fc8ce
commit 65087b8c98
15 changed files with 57 additions and 3683 deletions

View File

@@ -1,20 +0,0 @@
{
"manifest_version": 1,
"name": "塔罗牌插件",
"version": "1.3.0",
"description": "提供了抽塔罗牌占卜功能具有模拟人类的调用方式和独特自定义风格的解牌回复。牌面为B站幻星集",
"author": {
"name": "A肆零西烛",
"url": "https://github.com/A0000Xz"
},
"license": "AGPL-v3.0",
"host_application": {
"min_version": "0.9.1",
"max_version": "0.10.0"
},
"keywords": ["tarot", "divination","moderation","bilibili"],
"categories": ["Moderation", "Entertainment-oriented divination"],
"repository_url": "https://github.com/A0000Xz/MaiBot-Tarots-Plugin",
"default_locale": "zh-CN",
"locales_path": "_locales"
}

View File

@@ -1,850 +0,0 @@
from src.plugin_system.base.base_plugin import BasePlugin
from src.plugin_system.apis.plugin_register_api import register_plugin
from src.plugin_system.base.base_action import BaseAction, ActionActivationType, ChatMode
from src.plugin_system.base.base_command import BaseCommand
from src.plugin_system.base.component_types import ComponentInfo
from src.plugin_system.base.config_types import ConfigField
from src.plugin_system.apis import generator_api
from src.plugin_system.apis import database_api
from src.plugin_system.apis import config_api
from src.plugin_system.apis import send_api
from src.common.database.sqlalchemy_models import Messages, PersonInfo
from src.common.data_models.database_data_model import DatabaseMessages
from src.person_info.person_info import get_person_info_manager
from src.common.logger import get_logger
from PIL import Image
from typing import Tuple, Dict, Optional, List, Any, Type
from pathlib import Path
import traceback
import tomlkit
import json
import random
import asyncio
import aiohttp
import base64
import toml
import io
import os
import re
logger = get_logger("tarots")
class TarotsAction(BaseAction):
action_name = "tarots"
# 双激活类型配置
focus_activation_type = ActionActivationType.LLM_JUDGE
normal_activation_type = ActionActivationType.ALWAYS
activation_keywords = ["抽一张塔罗牌", "抽张塔罗牌"]
keyword_case_sensitive = False
# 模式和并行控制
mode_enable = ChatMode.ALL
parallel_action = False
action_description = "执行塔罗牌占卜,支持多种抽牌方式" # action描述
action_parameters = {
"card_type": "塔罗牌的抽牌范围,必填,只能填一个参数,这里请根据用户的要求填'全部''大阿卡纳''小阿卡纳',如果用户的要求并不明确,默认填'全部'",
"formation": "塔罗牌的抽牌方式,必填,只能填一个参数,这里请根据用户的要求填'单张''圣三角''时间之流''四要素''五牌阵''吉普赛十字''马蹄''六芒星',如果用户的要求并不明确,默认填'单张'",
"target_message": "提出抽塔罗牌的对方的发言内容,格式必须为:(用户名:发言内容若不清楚是回复谁的话可以为None"
}
action_require = [
"当消息包含'抽塔罗牌''塔罗牌占卜'等关键词,且用户明确表达了要求你帮忙抽牌的意向时,你看心情调用就行(这意味着你可以拒绝抽塔罗牌,拒绝执行这个动作)。",
"用户需要明确指定抽牌范围和抽牌类型,如果用户未明确指定抽牌范围则默认为'全部',未明确指定抽牌类型则默认为'单张'",
"请仔细辨别对方到底是不是在让你抽塔罗牌!如果用户只是单独说了'抽卡''抽牌''占卜''算命'等,而且并没有上文内容验证用户是想抽塔罗牌的意思,就不要抽塔罗牌,不要执行这个动作!",
"在完成一次抽牌后,请仔细确定用户有没有明确要求再抽一次,没有再次要求就不要继续执行这个动作。"
]
associated_types = ["image", "text"] #该插件会发送的消息类型
def __init__(self,
action_data: dict,
reasoning: str,
cycle_timers: dict,
thinking_id: str,
global_config: Optional[dict] = None,
action_message: Optional[dict] = None,
**kwargs,
):
# 显式调用父类初始化
super().__init__(
action_data=action_data,
reasoning=reasoning,
cycle_timers=cycle_timers,
thinking_id=thinking_id,
global_config=global_config,
action_message=action_message,
**kwargs
)
self.action_message = action_message
# 初始化基本路径
self.base_dir = Path(__file__).parent.absolute()
# 扫描并更新可用牌组
self.config = self._load_config()
self._update_available_card_sets()
# 初始化路径
self.using_cards = self.config["cards"].get("using_cards", 'bilibili')
if not self.using_cards:
self.cache_dir = self.base_dir / "tarots_cache" / "default"
else:
self.cache_dir = self.base_dir / "tarots_cache" / self.using_cards # 定义图片缓存主文件夹为tarots_cache后面紧随牌组文件夹名
self.cache_dir.mkdir(parents=True, exist_ok=True) # 不存在该文件夹就创建
# 加载卡牌数据
self.card_map: Dict = {}
self.formation_map: Dict = {}
self._load_resources()
def _load_resources(self):
"""同步加载资源文件(显式指定UTF-8编码)"""
try:
if not self.using_cards:
logger.info("没有加载到任何可用牌组")
return
# 加载卡牌数据
with open(
self.base_dir / f"tarot_jsons/{self.using_cards}/tarots.json",
encoding="utf-8"
) as f:
self.card_map = json.load(f)
# 加载牌阵配置
with open(
self.base_dir / "tarot_jsons/formation.json",
encoding="utf-8"
) as f:
self.formation_map = json.load(f)
logger.info(f"{self.log_prefix} 已加载{self.card_map['_meta']['total_cards']}张卡牌和{len(self.formation_map)}种抽牌方式")
except UnicodeDecodeError as e:
logger.error(f"{self.log_prefix} 编码错误: 请确保JSON文件为UTF-8格式 - {str(e)}")
raise
except Exception as e:
logger.error(f"{self.log_prefix} 资源加载失败: {str(e)}")
raise
async def execute(self) -> Tuple[bool, str]:
"""实现基类要求的入口方法"""
try:
if not self.card_map:
await self.send_text("没有牌组,无法使用")
return False, "没有牌组,无法使用"
logger.info(f"{self.log_prefix} 开始执行塔罗占卜")
# 参数解析
request_type = self.action_data.get("card_type", "全部")
formation_name = self.action_data.get("formation", "单张")
card_type = self.get_available_card_type(request_type)
# 参数校验
if card_type not in ["全部", "大阿卡纳", "小阿卡纳"]:
await self.send_text("不存在这样的抽牌范围")
return False, "参数错误"
if formation_name not in self.formation_map:
await self.send_text("不存在这样的抽牌方法")
return False, "参数错误"
# 获取牌阵配置
formation = self.formation_map[formation_name] # 根据确定好的抽牌方式名称获取具体牌阵的字典
cards_num = formation["cards_num"] # 该抽牌方式要抽几张牌
is_cut = formation["is_cut"] # 该抽牌方式要不要切牌
represent_list = formation["represent"] # 该抽牌方式所包含的预言方向内容
# 获取有效卡牌范围
valid_ids = self._get_card_range(card_type)
if not valid_ids:
await self.send_text("当前牌堆不对")
return False, "参数错误"
# 抽牌逻辑
selected_ids = random.sample(valid_ids, cards_num)
if is_cut:
selected_cards = [
(cid, random.random() < 0.5) # 切牌时50%概率逆位
for cid in selected_ids
]
else:
selected_cards = [
(cid, False) # 不切牌时全部正位
for cid in selected_ids
]
# 结果处理
result_text = f"{formation_name}牌阵 - {self.using_cards}牌组】\n"
failed_images = [] # 记录获取失败的图片
# 优先使用target_message来定位精确的回复目标
target_message_str = self.action_data.get("target_message")
reply_target_message = self.action_message # 默认引用触发消息
user_nickname = self.user_nickname
if target_message_str:
try:
# 解析用户名
if ":" in target_message_str:
target_nickname = target_message_str.split(":", 1)[0].strip()
elif "" in target_message_str:
target_nickname = target_message_str.split("", 1)[0].strip()
else:
target_nickname = None
if target_nickname:
user_nickname = target_nickname # 更新为正确的用户昵称
# 在数据库中查找该用户的最近一条消息
found_message = await database_api.db_get(
Messages,
filters={"user_nickname": target_nickname},
order_by="-time",
limit=1,
single_result=True
)
if found_message:
# 将字典转换为标准的数据模型对象,再转回字典,以确保格式正确
reply_target_obj = DatabaseMessages(**found_message)
reply_target_message = reply_target_obj.to_dict()
logger.info(f"已定位到来自'{target_nickname}'的最新消息进行引用: {found_message.get('message_id')}")
else:
logger.warning(f"未能找到来自'{target_nickname}'的任何消息,将回退至默认引用")
except Exception as e:
logger.warning(f"解析target_message时出错: {e}, 将回退至默认引用")
for idx, (card_id, is_reverse) in enumerate(selected_cards):
card_data = self.card_map[card_id]
card_info = card_data["info"]
pos_name = represent_list[0][idx] if idx < len(represent_list[0]) else f"位置{idx+1}"
# 轮询发送图片
img_data = await self._get_card_image(card_id, is_reverse)
if img_data:
b64_data = base64.b64encode(img_data).decode('utf-8')
await send_api.custom_to_stream(
message_type="image",
content=b64_data,
stream_id=self.chat_id,
reply_to_message=reply_target_message,
set_reply=True
)
else:
# 记录失败的图片
failed_images.append(f"{card_data['name']}({'逆位' if is_reverse else '正位'})")
logger.warning(f"{self.log_prefix} 卡牌图片获取失败: {card_id}")
# 轮询构建文本
desc = card_info['reverseDescription'] if is_reverse else card_info['description']
result_text += (
f"\n{pos_name} - {'逆位' if is_reverse else '正位'} {card_data['name']}\n"
f"{desc[:100]}...\n"
)
await asyncio.sleep(0.3) # 防止消息频率限制
if failed_images:
error_msg = f"以下卡牌图片获取失败,占卜中断: {', '.join(failed_images)}"
await self.send_text(error_msg)
return False, ""
# 发送最终文本
await asyncio.sleep(1.5) # 权宜之计给最后一张图片1.5s的发送起跑时间,无可奈何的办法
original_text = self.config["adjustment"].get("enable_original_text", False)
self_id = config_api.get_global_config("bot.qq_account")
# 查询自己机器人本体的名字,因为可乐允许机器人自己更改自己的绰号,还一直在不断的改!
self_personinfo = await database_api.db_get(
PersonInfo,
filters={"user_id": f"{self_id}"},
limit=1,
single_result = True
)
message_text = ""
result_status, result_message, _ = await generator_api.rewrite_reply(
chat_stream=self.chat_stream,
reply_data={
"raw_reply": result_text,
"reason": "抽出了塔罗牌结果,请根据其内容为用户进行解牌"
},
reply_to=target_message_str or "",
enable_splitter=False,
enable_chinese_typo=False
) # 让你的麦麦用自己的语言风格阐释结果
# 获取数据库内最近1条记录
records = await database_api.db_get(
Messages,
filters={"user_id": f"{self_id}"},
order_by="-time",
limit=1,
single_result = True
)
# 处理records文本中的引用格式
processed_record_text = ""
if records:
processed_record_text = records['processed_plain_text']
# 处理回复格式
reply_match = re.search(r"回复<([^:<>]+):([^:<>]+)>", processed_record_text)
if reply_match:
person_id = get_person_info_manager().get_person_id("qq", reply_match.group(2))
person_name = await get_person_info_manager().get_value(person_id, "person_name") or reply_match.group(1)
processed_record_text = re.sub(r"回复<[^:<>]+:[^:<>]+>", f"回复 {person_name}", processed_record_text, count=1)
# 处理@格式
for match in re.finditer(r"@<([^:<>]+):([^:<>]+)>", processed_record_text):
person_id = get_person_info_manager().get_person_id("qq", match.group(2))
person_name = await get_person_info_manager().get_value(person_id, "person_name") or match.group(1)
processed_record_text = processed_record_text.replace(match.group(0), f"@{person_name}")
if original_text:
await self.send_text(result_text)
logger.info("原始文本已发送")
if result_status:
# 合并所有消息片段
message_text = result_message[0][1]
# 一次性发送合并的消息
if message_text:
await send_api.text_to_stream(
text=message_text,
stream_id=self.chat_id,
reply_to_message=reply_target_message
)
logger.info("合并消息已发送")
else:
return False, "消息生成错误很可能是generator炸了"
# 记录动作信息
await self.store_action_info(
action_build_into_prompt=True,
action_prompt_display=f"已为{user_nickname}抽取了塔罗牌并成功解牌。",
action_done=True
)
return True, f"已为{user_nickname}抽取了塔罗牌并成功解牌,占卜成功。"
except Exception as e:
error_msg = traceback.format_exc()
logger.error(f"{self.log_prefix} 执行失败: {error_msg}")
await self.send_text(f"占卜失败: {str(e)}")
return False, "执行错误"
def _get_card_range(self, card_type: str) -> list:
"""获取卡牌范围"""
if card_type == "大阿卡纳":
return [str(i) for i in range(22)]
elif card_type == "小阿卡纳":
return [str(i) for i in range(22, 78)]
return [str(i) for i in range(78)] # 既不是大阿卡纳也不是小阿卡纳就返回全部的
async def _get_card_image(self, card_id: str, is_reverse: bool) -> Optional[bytes]:
"""获取卡牌图片(有缓存机制)"""
try:
filename = f"{card_id}_norm.png"
cache_path = self.cache_dir / filename
# 检查缓存文件是否存在且有效
if not cache_path.exists() or not self._validate_image_integrity(cache_path):
if cache_path.exists():
logger.warning(f"{self.log_prefix} 发现损坏的缓存文件,准备重新下载: {cache_path}")
try:
cache_path.unlink()
except Exception as e:
logger.error(f"{self.log_prefix} 删除损坏文件失败: {str(e)}")
return None
# 下载图片,现在返回布尔值
success = await self._download_image(card_id, cache_path)
if not success:
return None
with open(cache_path, "rb") as f:
img_data = f.read()
if is_reverse:
img_data = self._rotate_image(img_data) # 如果是逆位牌直接把正位牌扭180度
if not img_data: # 旋转失败
return None
return img_data
except Exception as e:
logger.warning(f"{self.log_prefix} 获取图片失败: {str(e)}")
return None
def _rotate_image(self, img_data: bytes) -> Optional[bytes]:
"""将图片旋转180度生成逆位图片"""
try:
# bytes → PIL Image对象
image = Image.open(io.BytesIO(img_data))
# 旋转180度逆时针
rotated_image = image.rotate(180)
# PIL Image对象 → bytes
buffer = io.BytesIO()
rotated_image.save(buffer, format='PNG')
return buffer.getvalue()
except Exception as e:
logger.error(f"{self.log_prefix} 图片旋转失败: {str(e)}")
# 旋转失败时返回None
return None
async def _download_image(self, card_id: str, save_path: Path):
"""图片本地缓存"""
MAX_RETRIES = 3
RETRY_DELAY = 2 # 初始重试间隔(秒)
try:
# 获取卡牌数据
card_info = self.card_map[card_id]["info"]
img_path = card_info['imgUrl']
base_url = self.card_map["_meta"]["base_url"]
# 获取代理数据
enable_proxy = self.config["proxy"].get("enable_proxy", False)
if enable_proxy:
proxy_url = self.config["proxy"].get("proxy_url", "")
else:
proxy_url = None
# 构建完整的下载URL
full_url = f"{base_url}{img_path}"
# 下载尝试循环
for attempt in range(1, MAX_RETRIES + 1):
try:
logger.info(f"[图片下载] 尝试 {attempt}/{MAX_RETRIES} - {card_id} - {full_url}")
async with aiohttp.ClientSession() as session:
async with session.get(full_url, timeout=15, proxy=proxy_url) as resp:
if resp.status == 200:
# 确保目录存在
save_path.parent.mkdir(parents=True, exist_ok=True)
# 写入文件
with open(save_path, "wb") as f:
f.write(await resp.read())
# 立即进行完整性检测
if self._validate_image_integrity(save_path):
logger.info(f"[图片下载] 成功并通过完整性检测 {save_path.name} (尝试 {attempt}次)")
return True
else:
# 完整性检测失败,删除文件
logger.warning(f"[图片下载] 完整性检测失败,删除文件: {save_path}")
try:
save_path.unlink()
except Exception as delete_error:
logger.error(f"[图片下载] 删除损坏文件失败: {delete_error}")
# 如果不是最后一次尝试,继续重试
if attempt < MAX_RETRIES:
logger.info(f"[图片下载] 完整性检测失败,准备重试 (尝试 {attempt+1}/{MAX_RETRIES})")
continue
else:
logger.error(f"[图片下载] 完整性检测失败且已达最大重试次数: {save_path}")
break
else:
logger.warning(f"[图片下载] 异常状态码 {resp.status} - {full_url}")
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
logger.warning(f"[图片下载] 尝试 {attempt}/{MAX_RETRIES} 失败: {str(e)}")
# 指数退避等待
if attempt < MAX_RETRIES:
await asyncio.sleep(RETRY_DELAY ** attempt)
# 最终失败处理
logger.error(f"[图片下载] 终极失败 {full_url},已达最大重试次数 {MAX_RETRIES}")
return False
except KeyError:
logger.error(f"[图片下载] 致命错误:卡牌 {card_id} 不存在于card_map中")
return False
except Exception as e:
logger.error(f"{self.log_prefix} 图片下载失败: {str(e)}")
return False
def _load_config(self) -> Dict[str, Any]:
"""从同级目录的config.toml文件直接加载配置"""
try:
# 获取当前文件所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(script_dir, "config.toml")
# 读取并解析TOML配置文件
with open(config_path, 'r', encoding='utf-8') as f:
config_data = toml.load(f)
# 构建配置字典使用get方法安全访问嵌套值
config = {
"permissions": {
"admin_users": config_data.get("permissions", {}).get("admin_users", [])
},
"proxy": {
"enable_proxy": config_data.get("proxy", {}).get("enable_proxy", False),
"proxy_url": config_data.get("proxy", {}).get("proxy_url", "")
},
"cards": {
"using_cards": config_data.get("cards", {}).get("using_cards", 'bilibili'),
"use_cards": config_data.get("cards", {}).get("use_cards", ['bilibili','east'])
},
"adjustment": {
"enable_original_text": config_data.get("adjustment", {}).get("enable_original_text", False)
}
}
return config
except Exception as e:
logger.error(f"{self.log_prefix} 加载配置失败: {e}")
raise
def _validate_image_integrity(self, file_path: Path) -> bool:
"""检查图片文件完整性"""
try:
# 检查文件是否存在
if not file_path.exists():
logger.debug(f"{self.log_prefix} 图片文件不存在: {file_path}")
return False
# 检查文件大小至少要有内容不能是0字节
if file_path.stat().st_size == 0:
logger.warning(f"{self.log_prefix} 图片文件为空: {file_path}")
return False
# 尝试使用PIL打开图片来验证完整性
try:
with Image.open(file_path) as img:
# 验证图片基本信息
if img.size[0] <= 0 or img.size[1] <= 0:
logger.warning(f"{self.log_prefix} 图片尺寸异常: {file_path}")
return False
# 尝试加载图片数据以确保文件没有损坏
img.load()
logger.debug(f"{self.log_prefix} 图片完整性校验通过: {file_path}")
return True
except (Image.UnidentifiedImageError, OSError, IOError) as e:
logger.warning(f"{self.log_prefix} 图片损坏或格式错误: {file_path} - {str(e)}")
return False
except Exception as e:
logger.error(f"{self.log_prefix} 图片完整性校验异常: {file_path} - {str(e)}")
return False
def get_available_card_type(self, user_requested_type):
"""获取当前牌组支持的卡牌类型"""
supported_type = self.card_map.get("_meta", {}).get("card_types", "")
# 如果牌组支持全部,或者用户请求与牌组支持的一致,就用用户请求的
if supported_type == '全部' or user_requested_type == supported_type:
return user_requested_type
else:
# 否则用牌组支持的类型
return supported_type
def _update_available_card_sets(self):
"""更新配置文件中的可用牌组列表"""
try:
current_using = self.config["cards"].get("using_cards", "")
available_sets = self._scan_available_card_sets()
# 如果当前使用的牌组不存在于可用牌组中
if not current_using or current_using not in available_sets:
# 尝试从可用牌组中选择一个有效的
new_using = available_sets[0] if available_sets else ""
logger.warning(
f"当前使用牌组 '{current_using}' 不存在,已自动切换至 '{new_using}'"
)
# 更新当前使用牌组
self.set_card(new_using)
if available_sets:
self.set_cards(available_sets)
logger.info(f"已更新可用牌组配置: {available_sets}")
else:
logger.error("未发现任何可用牌组")
self.set_card("")
self.set_cards([])
self.config = self._load_config()
except Exception as e:
logger.error(f"更新牌组配置失败: {e}")
def _scan_available_card_sets(self) -> List[str]:
"""扫描tarot_jsons文件夹返回可用牌组列表"""
try:
tarot_jsons_dir = self.base_dir / "tarot_jsons"
available_sets = []
if not tarot_jsons_dir.exists():
logger.warning(f"tarot_jsons目录不存在: {tarot_jsons_dir}")
return []
for item in tarot_jsons_dir.iterdir():
if item.is_dir():
tarots_json_path = item / "tarots.json"
if tarots_json_path.exists():
available_sets.append(item.name)
logger.info(f"发现可用牌组: {item.name}")
return available_sets
except Exception as e:
logger.error(f"扫描牌组失败: {e}")
return []
def set_cards(self, cards: List):
"""使用tomlkit修改配置文件保持注释和格式"""
try:
config_path = os.path.join(self.base_dir, "config.toml")
# 使用tomlkit读取保持格式和注释
with open(config_path, 'r', encoding='utf-8') as f:
config_data = tomlkit.load(f)
# 只有在列表内容不同的情况下才写入
# 只有在列表内容不同的情况下才写入
if set(config_data.get("cards", {}).get("use_cards", [])) != set(cards):
config_data["cards"]["use_cards"] = cards
# 使用tomlkit写入保持格式和注释
with open(config_path, 'w', encoding='utf-8') as f:
tomlkit.dump(config_data, f)
except Exception as e:
logger.error(f"{self.log_prefix} 扫描牌组失败: {e}")
raise
def _check_cards(self, cards: str) -> bool:
"""权限检查逻辑"""
use_cards = self.config["cards"].get("use_cards", ['bilibili','east'])
if not use_cards:
logger.warning(f"{self.log_prefix} 未配置可使用牌组列表")
return ""
return cards in use_cards
def set_card(self, cards: str):
"""使用tomlkit修改配置文件保持注释和格式"""
try:
config_path = os.path.join(self.base_dir, "config.toml")
# 使用tomlkit读取保持格式和注释
with open(config_path, 'r', encoding='utf-8') as f:
config_data = tomlkit.load(f)
config_data["cards"]["using_cards"] = cards
# 使用tomlkit写入保持格式和注释
with open(config_path, 'w', encoding='utf-8') as f:
tomlkit.dump(config_data, f)
except Exception as e:
logger.error(f"{self.log_prefix} 更新配置文件失败: {e}")
raise
class TarotsCommand(BaseCommand, TarotsAction):
command_name = "tarots_command"
command_description = "塔罗牌命令,目前仅做缓存"
command_pattern = r"^/tarots\s+(?P<target_type>\w+)(?:\s+(?P<action_value>\w+))?\s*$"
command_help = "使用方法: /tarots cache - 缓存所有牌面;/tarots switch 牌组名称 - 切换当前使用的牌组"
command_examples = [
"/tarots cache - 开始缓存全部牌面",
"/tarots switch 牌组名称 - 切换当前使用的牌组"
]
enable_command = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 初始化 TarotsAction 的属性
self.base_dir = Path(__file__).parent.absolute()
self.config = self._load_config()
self._update_available_card_sets()
self.using_cards = self.config["cards"].get("using_cards", 'bilibili')
if not self.using_cards:
self.cache_dir = self.base_dir / "tarots_cache" / "default"
else:
self.cache_dir = self.base_dir / "tarots_cache" / self.using_cards
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.card_map = {}
self.formation_map = {}
self._load_resources()
async def execute(self) -> Tuple[bool, Optional[str]]:
try:
sender = self.message.message_info.user_info
if not self._check_person_permission(sender.user_id):
await self.send_text("权限不足,你无权使用此命令")
return False,"权限不足,无权使用此命令", True
if not self.card_map:
await self.send_text("没有牌组,无法使用")
return False, "没有牌组,无法使用", True
target_type = self.matched_groups.get("target_type")
action_value = self.matched_groups.get("action_value")
support_type = self.get_available_card_type("全部")
if support_type == '全部':
check_count=[str(i) for i in range(78)]
elif support_type == '大阿卡纳':
check_count=[str(i) for i in range(22)]
elif support_type == '小阿卡纳':
check_count=[str(i) for i in range(22,78)]
else:
await self.send_text("这不在可用牌组中")
return False, "非可用牌组", True
if target_type == "cache" and not action_value:
# 添加进度提示
await self.send_text("开始缓存全部牌面,请稍候...")
success_count = 0
redownload_count = 0 # 记录重新下载的数量
for card in check_count:
try:
filename = f"{card}_norm.png"
cache_path = self.cache_dir / filename
# 检查文件是否存在且完整
if not cache_path.exists() or not self._validate_image_integrity(cache_path):
if cache_path.exists():
# 文件存在但损坏,记录重新下载
logger.warning(f"{self.log_prefix} 发现损坏的缓存文件,准备重新下载: {cache_path}")
redownload_count += 1
try:
cache_path.unlink() # 删除损坏的文件
except Exception as e:
logger.error(f"{self.log_prefix} 删除损坏文件失败: {str(e)}")
continue
# 下载图片
download_success = await self._download_image(card, cache_path)
if download_success:
success_count += 1
else:
logger.warning(f"{self.log_prefix} 下载卡牌 {card} 失败")
else:
# 文件存在且完整
success_count += 1
except Exception as e:
logger.warning(f"{self.log_prefix} 缓存卡牌 {card} 失败: {str(e)}")
continue
# 构建结果消息
result_msg = f"缓存完成,成功缓存 {success_count}/{len(check_count)} 张牌面"
if redownload_count > 0:
result_msg += f",其中重新下载了 {redownload_count} 张损坏的图片"
await self.send_text(result_msg)
return True, result_msg, True
elif target_type == "switch" and action_value:
cards = self._check_cards(action_value)
if cards:
self.set_card(action_value)
await self.send_text(f"已更换当前牌组为{action_value}")
return True, f"成功更换使用牌组至{action_value}", True
else:
await self.send_text(f"{action_value}并不在当前可用牌组里")
return False, f"{action_value}并不在当前可用牌组里", True
else:
await self.send_text("没有这种参数只能填cache或者switch哦")
return False, "没有这种参数", True
except Exception as e:
await self.send_text(f"{self.log_prefix} 命令执行错误: {e}")
logger.error(f"{self.log_prefix} 命令执行错误: {e}")
return False, f"执行失败: {str(e)}", True
def _check_person_permission(self, user_id: str) -> bool:
"""权限检查逻辑"""
admin_users = self.config["permissions"].get("admin_users", [])
if not admin_users:
logger.warning(f"{self.log_prefix} 未配置管理员用户列表")
return False
return user_id in admin_users
@register_plugin
class TarotsPlugin(BasePlugin):
"""塔罗牌插件
- 支持多种牌阵抽取
- 支持区分大小阿卡纳抽取
- 会在本地逐步缓存牌面图片
- 拥有一键缓存所有牌面的指令
- 完整的错误处理
- 日志记录和监控
"""
# 插件基本信息
plugin_name = "tarots_plugin"
enable_plugin = True
config_file_name = "config.toml"
dependencies = []
python_dependencies = []
# 配置节描述
config_section_descriptions = {
"plugin": "插件基本配置",
"components": "组件启用控制",
"proxy": "代理设置(支持热重载)",
"cards": "牌组相关设置(支持热重载)",
"adjustment": "功能微调向(支持热重载)",
"permissions": "管理者用户配置(支持热重载)",
"logging": "日志记录配置",
}
# 配置Schema定义
config_schema = {
"plugin": {
"config_version": ConfigField(type=str, default="1.3.0", description="插件配置文件版本号"),
"enabled": ConfigField(type=bool, default=True, description="是否启用插件"),
},
"components": {
"enable_tarots": ConfigField(type=bool, default=True, description="是否启用塔罗牌插件抽牌功能"),
"enable_tarots_command": ConfigField(type=bool, default=True, description="是否启用塔罗牌指令功能")
},
"proxy":{
"enable_proxy": ConfigField(type=bool, default=False, description="是否启用代理功能"),
"proxy_url": ConfigField(type=str, default="", description="请在双引号中填入你要使用的代理地址")
},
"cards":{
"using_cards": ConfigField(type=str, default='bilibili', description="塔罗牌插件使用哪套牌组"),
"use_cards": ConfigField(type=List, default=['bilibili','east'], description="塔罗牌插件可用的牌组,目前默认有'bilibili''east'两套默认牌组可选")
},
"adjustment":{
"enable_original_text": ConfigField(type=bool, default=False, description="是否启用塔罗牌原始文本,开启该功能可以额外发出初始的解牌文本")
},
"permissions": {
"admin_users": ConfigField(type=List, default=["123456789"], description="请写入被许可用户的QQ号记得用英文单引号包裹并使用逗号分隔。这个配置会决定谁被允许使用塔罗牌指令注意这个选项支持热重载你可以不重启麦麦改动会即刻生效"),
},
"logging": {
"level": ConfigField(
type=str, default="INFO", description="日志级别", choices=["DEBUG", "INFO", "WARNING", "ERROR"]
),
"prefix": ConfigField(type=str, default="[Tarots]", description="日志前缀"),
},
}
def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]:
"""返回插件包含的组件列表"""
components = []
if self.get_config("components.enable_tarots", True):
components.append((TarotsAction.get_action_info(), TarotsAction))
if self.get_config("components.enable_tarots_command", True):
components.append((TarotsCommand.get_command_info(), TarotsCommand))
return components

View File

@@ -1,632 +0,0 @@
{
"_meta": {
"card_types": "全部",
"total_cards": 78,
"description": "B站幻星集塔罗牌组 - 包含全部牌面",
"base_url": "https://raw.githubusercontent.com/FloatTech/zbpdata/main/Tarot/"
},
"0": {
"name": "愚者",
"info": {
"description": "新的开始、冒险、自信、乐观、好的时机",
"reverseDescription": "时机不对、鲁莽、轻信、承担风险",
"imgUrl": "MajorArcana/0.png"
}
},
"1": {
"name": "魔术师",
"info": {
"description": "创造力、主见、激情、发展潜力",
"reverseDescription": "缺乏创造力、优柔寡断、才能平庸、计划不周",
"imgUrl": "MajorArcana/1.png"
}
},
"2": {
"name": "女祭司",
"info": {
"description": "潜意识、洞察力、知性、研究精神",
"reverseDescription": "自我封闭、内向、神经质、缺乏理性",
"imgUrl": "MajorArcana/2.png"
}
},
"3": {
"name": "皇后",
"info": {
"description": "母性、女性特质、生命力、接纳",
"reverseDescription": "生育问题、不安全感、敏感、困扰于细枝末节",
"imgUrl": "MajorArcana/3.png"
}
},
"4": {
"name": "皇帝",
"info": {
"description": "控制、意志、领导力、权力、影响力",
"reverseDescription": "混乱、固执、暴政、管理不善、不务实",
"imgUrl": "MajorArcana/4.png"
}
},
"5": {
"name": "教皇",
"info": {
"description": "值得信赖的、顺从、遵守规则",
"reverseDescription": "失去信赖、固步自封、质疑权威、恶意的规劝",
"imgUrl": "MajorArcana/5.png"
}
},
"6": {
"name": "恋人",
"info": {
"description": "爱、肉体的连接、新的关系、美好时光、互相支持",
"reverseDescription": "纵欲过度、不忠、违背诺言、情感的抉择",
"imgUrl": "MajorArcana/6.png"
}
},
"7": {
"name": "战车",
"info": {
"description": "高效率、把握先机、坚韧、决心、力量、克服障碍",
"reverseDescription": "失控、挫折、诉诸暴力、冲动",
"imgUrl": "MajorArcana/7.png"
}
},
"8": {
"name": "力量",
"info": {
"description": "勇气、决断、克服阻碍、胆识过人",
"reverseDescription": "恐惧、精力不足、自我怀疑、懦弱",
"imgUrl": "MajorArcana/8.png"
}
},
"9": {
"name": "隐士",
"info": {
"description": "内省、审视自我、探索内心、平静",
"reverseDescription": "孤独、孤立、过分慎重、逃避",
"imgUrl": "MajorArcana/9.png"
}
},
"10": {
"name": "命运之轮",
"info": {
"description": "把握时机、新的机会、幸运降临、即将迎来改变",
"reverseDescription": "厄运、时机未到、计划泡汤",
"imgUrl": "MajorArcana/10.png"
}
},
"11": {
"name": "正义",
"info": {
"description": "公平、正直、诚实、正义、表里如一",
"reverseDescription": "失衡、偏见、不诚实、表里不一",
"imgUrl": "MajorArcana/11.png"
}
},
"12": {
"name": "倒吊人",
"info": {
"description": "进退两难、接受考验、因祸得福、舍弃行动追求顿悟",
"reverseDescription": "无畏的牺牲、利己主义、内心抗拒、缺乏远见",
"imgUrl": "MajorArcana/12.png"
}
},
"13": {
"name": "死神",
"info": {
"description": "失去、舍弃、离别、死亡、新生事物的来临",
"reverseDescription": "起死回生、回心转意、逃避现实",
"imgUrl": "MajorArcana/13.png"
}
},
"14": {
"name": "节制",
"info": {
"description": "平衡、和谐、治愈、节制",
"reverseDescription": "失衡、失谐、沉溺愉悦、过度放纵",
"imgUrl": "MajorArcana/14.png"
}
},
"15": {
"name": "恶魔",
"info": {
"description": "负面影响、贪婪的欲望、物质主义、固执己见",
"reverseDescription": "逃离束缚、拒绝诱惑、治愈病痛、直面现实",
"imgUrl": "MajorArcana/15.png"
}
},
"16": {
"name": "塔",
"info": {
"description": "急剧的转变、突然的动荡、毁灭后的重生、政权更迭",
"reverseDescription": "悬崖勒马、害怕转变、发生内讧、风暴前的寂静",
"imgUrl": "MajorArcana/16.png"
}
},
"17": {
"name": "星辰",
"info": {
"description": "希望、前途光明、曙光出现",
"reverseDescription": "好高骛远、异想天开、事与愿违、失去目标",
"imgUrl": "MajorArcana/17.png"
}
},
"18": {
"name": "月亮",
"info": {
"description": "虚幻、不安与动摇、迷惘、欺骗",
"reverseDescription": "状况逐渐好转、疑虑渐消、排解恐惧",
"imgUrl": "MajorArcana/18.png"
}
},
"19": {
"name": "太阳",
"info": {
"description": "活力充沛、生机、远景明朗、积极",
"reverseDescription": "意志消沉、情绪低落、无助、消极",
"imgUrl": "MajorArcana/19.png"
}
},
"20": {
"name": "审判",
"info": {
"description": "命运好转、复活的喜悦、恢复健康",
"reverseDescription": "一蹶不振、尚未开始便已结束、自我怀疑、不予理睬",
"imgUrl": "MajorArcana/20.png"
}
},
"21": {
"name": "世界",
"info": {
"description": "愿望达成、获得成功、到达目的地",
"reverseDescription": "无法投入、不安现状、半途而废、盲目接受",
"imgUrl": "MajorArcana/21.png"
}
},
"22": {
"name": "圣杯ACE",
"info": {
"description": "新恋情或新友情、精神愉悦、心灵满足",
"reverseDescription": "情感缺失、缺乏交流、虚情假意",
"imgUrl": "MinorArcana/Cups/圣杯-01.png"
}
},
"23": {
"name": "圣杯2",
"info": {
"description": "和谐对等的关系、情侣间的相互喜爱、合作顺利",
"reverseDescription": "两性关系趋于极端、情感的割裂、双方不平等、冲突",
"imgUrl": "MinorArcana/Cups/圣杯-02.png"
}
},
"24": {
"name": "圣杯3",
"info": {
"description": "达成合作、努力取得成果",
"reverseDescription": "乐极生悲、无法达成共识、团队不和",
"imgUrl": "MinorArcana/Cups/圣杯-03.png"
}
},
"25": {
"name": "圣杯4",
"info": {
"description": "身心俱疲、缺乏动力、对事物缺乏兴趣、情绪低潮",
"reverseDescription": "新的人际关系、有所行动、脱离低潮期",
"imgUrl": "MinorArcana/Cups/圣杯-04.png"
}
},
"26": {
"name": "圣杯5",
"info": {
"description": "过度注意失去的事物、自责、自我怀疑、因孤傲而拒绝外界帮助",
"reverseDescription": "走出悲伤、破釜沉舟、东山再起",
"imgUrl": "MinorArcana/Cups/圣杯-05.png"
}
},
"27": {
"name": "圣杯6",
"info": {
"description": "思乡、美好的回忆、纯真的情感、简单的快乐、安全感",
"reverseDescription": "沉溺于过去、不美好的回忆、不甘受束缚",
"imgUrl": "MinorArcana/Cups/圣杯-06.png"
}
},
"28": {
"name": "圣杯7",
"info": {
"description": "不切实际的幻想、不踏实的人际关系、虚幻的情感、生活混乱",
"reverseDescription": "看清现实、对物质的不满足、做出明智的选择",
"imgUrl": "MinorArcana/Cups/圣杯-07.png"
}
},
"29": {
"name": "圣杯8",
"info": {
"description": "离开熟悉的人事物、不沉醉于目前的成果、经考虑后的行动",
"reverseDescription": "犹豫不决、失去未来的规划、维持现状",
"imgUrl": "MinorArcana/Cups/圣杯-08.png"
}
},
"30": {
"name": "圣杯9",
"info": {
"description": "愿望极有可能实现、满足现状、物质与精神富足",
"reverseDescription": "物质受损失、不懂节制、寻求更高层次的快乐",
"imgUrl": "MinorArcana/Cups/圣杯-09.png"
}
},
"31": {
"name": "圣杯10",
"info": {
"description": "团队和谐、人际关系融洽、家庭和睦",
"reverseDescription": "团队不和、人际关系不和、冲突",
"imgUrl": "MinorArcana/Cups/圣杯-10.png"
}
},
"32": {
"name": "圣杯侍从",
"info": {
"description": "情感的表达与奉献、积极的消息即将传来、情感的追求但不成熟",
"reverseDescription": "情感的追求但错误、感情暧昧、过度执着于情感或问题",
"imgUrl": "MinorArcana/Cups/圣杯侍从.png"
}
},
"33": {
"name": "圣杯国王",
"info": {
"description": "创造力、决策力、某方面的专家、有条件的分享或交换",
"reverseDescription": "表里不一、行为另有所图、对自我创造力的不信任",
"imgUrl": "MinorArcana/Cups/圣杯国王.png"
}
},
"34": {
"name": "圣杯王后",
"info": {
"description": "感情丰富而细腻、重视直觉、感性的思考",
"reverseDescription": "过度情绪化、用情不专、心灵的孤立",
"imgUrl": "MinorArcana/Cups/圣杯皇后.png"
}
},
"35": {
"name": "圣杯骑士",
"info": {
"description": "在等待与行动之间做出决定、新的机会即将到来",
"reverseDescription": "用情不专、消极的等待、对于情感的行动错误",
"imgUrl": "MinorArcana/Cups/圣杯骑士.png"
}
},
"36": {
"name": "星币ACE",
"info": {
"description": "新的机遇、顺利发展、物质回报",
"reverseDescription": "金钱上的损失、发展不顺、物质丰富但精神虚空",
"imgUrl": "MinorArcana/Pentacles/星币-01.png"
}
},
"37": {
"name": "星币2",
"info": {
"description": "收支平衡、财富的流通、生活的波动与平衡",
"reverseDescription": "用钱过度、难以维持平衡、面临物质的损失",
"imgUrl": "MinorArcana/Pentacles/星币-02.png"
}
},
"38": {
"name": "星币3",
"info": {
"description": "团队合作、沟通顺畅、工作熟练、关系稳定",
"reverseDescription": "分工不明确、人际关系不和、专业技能不足",
"imgUrl": "MinorArcana/Pentacles/星币-03.png"
}
},
"39": {
"name": "星币4",
"info": {
"description": "安于现状、吝啬、守财奴、财富停滞、精神匮乏",
"reverseDescription": "入不敷出、奢侈无度、挥霍",
"imgUrl": "MinorArcana/Pentacles/星币-04.png"
}
},
"40": {
"name": "星币5",
"info": {
"description": "经济危机、同甘共苦、艰难时刻",
"reverseDescription": "居住问题、生活混乱、劳燕分飞",
"imgUrl": "MinorArcana/Pentacles/星币-05.png"
}
},
"41": {
"name": "星币6",
"info": {
"description": "慷慨、给予、礼尚往来、财务稳定且乐观",
"reverseDescription": "自私、暗藏心机、负债或在情义上亏欠于人",
"imgUrl": "MinorArcana/Pentacles/星币-06.png"
}
},
"42": {
"name": "星币7",
"info": {
"description": "等待时机成熟、取得阶段性成果、思考计划",
"reverseDescription": "事倍功半、投资失利、踟蹰不决",
"imgUrl": "MinorArcana/Pentacles/星币-07.png"
}
},
"43": {
"name": "星币8",
"info": {
"description": "工作专注、技能娴熟、进取心、做事有条理",
"reverseDescription": "精力分散、工作乏味、工作产出不佳",
"imgUrl": "MinorArcana/Pentacles/星币-08.png"
}
},
"44": {
"name": "星币9",
"info": {
"description": "事业收获、持续为自己创造有利条件、懂得理财储蓄",
"reverseDescription": "失去财富、舍弃金钱追求生活、管理能力欠缺",
"imgUrl": "MinorArcana/Pentacles/星币-09.png"
}
},
"45": {
"name": "星币10",
"info": {
"description": "团队和谐、成功的事业伙伴、家族和谐",
"reverseDescription": "团队不和、投资合伙暂缓、家庭陷入不和",
"imgUrl": "MinorArcana/Pentacles/星币-10.png"
}
},
"46": {
"name": "星币侍从",
"info": {
"description": "善于思考和学习、求知欲旺盛、与知识或者研究工作有关的好消息",
"reverseDescription": "知识贫乏、自我认知不足、金钱上面临损失、视野狭窄",
"imgUrl": "MinorArcana/Pentacles/星币侍从.png"
}
},
"47": {
"name": "星币国王",
"info": {
"description": "成功人士、追求物质、善于经营、值得信赖、成熟务实",
"reverseDescription": "缺乏经济头脑、缺乏信任、管理不善、失去信赖",
"imgUrl": "MinorArcana/Pentacles/星币国王.png"
}
},
"48": {
"name": "星币王后",
"info": {
"description": "成熟、繁荣、值得信赖、温暖、安宁",
"reverseDescription": "爱慕虚荣、生活浮华、态度恶劣",
"imgUrl": "MinorArcana/Pentacles/星币皇后.png"
}
},
"49": {
"name": "星币骑士",
"info": {
"description": "讲究效率、责任感赖、稳重、有计划",
"reverseDescription": "懈怠、思想保守、发展停滞不前",
"imgUrl": "MinorArcana/Pentacles/星币骑士.png"
}
},
"50": {
"name": "宝剑ACE",
"info": {
"description": "有进取心和攻击性、敏锐、理性、成功的开始",
"reverseDescription": "易引起争端、逞强而招致灾难、偏激专横、不公正的想法",
"imgUrl": "MinorArcana/Swords/宝剑-01.png"
}
},
"51": {
"name": "宝剑2",
"info": {
"description": "想法的对立、选择的时机、意见不合且暗流汹涌",
"reverseDescription": "做出选择但流言与欺诈会浮出水面、犹豫不决导致错失机会",
"imgUrl": "MinorArcana/Swords/宝剑-02.png"
}
},
"52": {
"name": "宝剑3",
"info": {
"description": "感情受到伤害、生活中出现麻烦、自怜自哀",
"reverseDescription": "心理封闭、情绪不安、逃避、伤害周边的人",
"imgUrl": "MinorArcana/Swords/宝剑-03.png"
}
},
"53": {
"name": "宝剑4",
"info": {
"description": "养精蓄锐、以退为进、放缓行动、留意总结",
"reverseDescription": "即刻行动、投入生活、未充分准备却慌忙应对",
"imgUrl": "MinorArcana/Swords/宝剑-04.png"
}
},
"54": {
"name": "宝剑5",
"info": {
"description": "矛盾冲突、不择手段伤害对方、赢得比赛却失去关系",
"reverseDescription": "找到应对方法、冲突有解决的可能性、双方愿意放下武器",
"imgUrl": "MinorArcana/Swords/宝剑-05.png"
}
},
"55": {
"name": "宝剑6",
"info": {
"description": "伤口迟迟没能痊愈、现在没有很好的对策、未来存在更多的艰难",
"reverseDescription": "深陷于困难、鲁莽地解决却忽视背后更大的问题、需要其他人的帮助或救援",
"imgUrl": "MinorArcana/Swords/宝剑-06.png"
}
},
"56": {
"name": "宝剑7",
"info": {
"description": "疏忽大意、有隐藏很深的敌人、泄密、非常手段或小伎俩无法久用",
"reverseDescription": "意想不到的好运、计划不周全、掩耳盗铃",
"imgUrl": "MinorArcana/Swords/宝剑-07.png"
}
},
"57": {
"name": "宝剑8",
"info": {
"description": "孤立无助、陷入艰难处境、受困于想法导致行动受阻",
"reverseDescription": "摆脱束缚、脱离危机、重新起步",
"imgUrl": "MinorArcana/Swords/宝剑-08.png"
}
},
"58": {
"name": "宝剑9",
"info": {
"description": "精神上的恐惧、害怕、焦虑、前路不顺的预兆",
"reverseDescription": "事情出现转机、逐渐摆脱困境、沉溺于过去、正视现实",
"imgUrl": "MinorArcana/Swords/宝剑-09.png"
}
},
"59": {
"name": "宝剑10",
"info": {
"description": "进展严重受阻、无路可走、面临绝境、重新归零的机会",
"reverseDescription": "绝处逢生、东山再起的希望、物极必反",
"imgUrl": "MinorArcana/Swords/宝剑-10.png"
}
},
"60": {
"name": "宝剑侍从",
"info": {
"description": "思维发散、洞察力、谨慎的判断",
"reverseDescription": "短见、做事虎头蛇尾、对信息不加以过滤分析",
"imgUrl": "MinorArcana/Swords/宝剑侍从.png"
}
},
"61": {
"name": "宝剑国王",
"info": {
"description": "公正、权威、领导力、冷静",
"reverseDescription": "思想偏颇、强加观念、极端、不择手段",
"imgUrl": "MinorArcana/Swords/宝剑国王.png"
}
},
"62": {
"name": "宝剑王后",
"info": {
"description": "理性、思考敏捷、有距离感、公正不阿",
"reverseDescription": "固执、想法偏激、高傲、盛气凌人",
"imgUrl": "MinorArcana/Swords/宝剑皇后.png"
}
},
"63": {
"name": "宝剑骑士",
"info": {
"description": "勇往直前的行动力、充满激情",
"reverseDescription": "计划不周、天马行空、缺乏耐心、做事轻率、自负",
"imgUrl": "MinorArcana/Swords/宝剑骑士.png"
}
},
"64": {
"name": "权杖4",
"info": {
"description": "和平繁荣、关系稳固、学业或事业发展稳定",
"reverseDescription": "局势失衡、稳固的基础被打破、人际关系不佳、收成不佳",
"imgUrl": "MinorArcana/Wands/权杖-04.png"
}
},
"65": {
"name": "权杖ACE",
"info": {
"description": "新的开端、新的机遇、燃烧的激情、创造力",
"reverseDescription": "新行动失败的可能性比较大、开端不佳、意志力薄弱",
"imgUrl": "MinorArcana/Wands/权杖-01.png"
}
},
"66": {
"name": "权杖2",
"info": {
"description": "高瞻远瞩、规划未来、在习惯与希望间做选择",
"reverseDescription": "犹豫不决、行动受阻、花费太多时间在选择上",
"imgUrl": "MinorArcana/Wands/权杖-02.png"
}
},
"67": {
"name": "权杖3",
"info": {
"description": "探索的好时机、身心灵的契合、领导能力、主导地位",
"reverseDescription": "合作不顺、欠缺领导能力、团队不和谐",
"imgUrl": "MinorArcana/Wands/权杖-03.png"
}
},
"68": {
"name": "权杖5",
"info": {
"description": "竞争、冲突、内心的矛盾、缺乏共识",
"reverseDescription": "不公平的竞争、达成共识",
"imgUrl": "MinorArcana/Wands/权杖-05.png"
}
},
"69": {
"name": "权杖6",
"info": {
"description": "获得胜利、成功得到回报、进展顺利、有望水到渠成",
"reverseDescription": "短暂的成功、骄傲自满、失去自信",
"imgUrl": "MinorArcana/Wands/权杖-06.png"
}
},
"70": {
"name": "权杖7",
"info": {
"description": "坚定信念、态度坚定、内芯的权衡与决断、相信自己的观点与能力",
"reverseDescription": "对自己的能力产生怀疑、缺乏自信与动力、缺乏意志力",
"imgUrl": "MinorArcana/Wands/权杖-07.png"
}
},
"71": {
"name": "权杖8",
"info": {
"description": "目标明确、一鼓作气、进展神速、趁热打铁、旅行",
"reverseDescription": "方向错误、行动不一致、急躁冲动、计划延误",
"imgUrl": "MinorArcana/Wands/权杖-08.png"
}
},
"72": {
"name": "权杖9",
"info": {
"description": "做好准备以应对困难、自我防御、蓄势待发、力量的对立",
"reverseDescription": "遭遇逆境、失去自信、士气低落",
"imgUrl": "MinorArcana/Wands/权杖-09.png"
}
},
"73": {
"name": "权杖10",
"info": {
"description": "责任感、内芯的热忱、过重的负担、过度劳累",
"reverseDescription": "难以承受的压力、高估自身的能力、调整自己的步调、逃避责任",
"imgUrl": "MinorArcana/Wands/权杖-10.png"
}
},
"74": {
"name": "权杖侍从",
"info": {
"description": "新计划的开始、尝试新事物、好消息传来",
"reverseDescription": "三分钟热度、规划太久导致进展不顺、坏消息传来",
"imgUrl": "MinorArcana/Wands/权杖侍从.png"
}
},
"75": {
"name": "权杖国王",
"info": {
"description": "行动力强、态度明确、运筹帷幄、领袖魅力",
"reverseDescription": "独断专行、严苛、态度傲慢",
"imgUrl": "MinorArcana/Wands/权杖国王.png"
}
},
"76": {
"name": "权杖王后",
"info": {
"description": "刚柔并济、热情而温和、乐观而活泼",
"reverseDescription": "情绪化、信心不足、热情消退、孤独",
"imgUrl": "MinorArcana/Wands/权杖皇后.png"
}
},
"77": {
"name": "权杖骑士",
"info": {
"description": "行动力、精力充沛、新的旅程、对现状不满足的改变",
"reverseDescription": "有勇无谋、鲁莽、行动延迟、计划不周、急躁",
"imgUrl": "MinorArcana/Wands/权杖骑士.png"
}
}
}

View File

@@ -1,632 +0,0 @@
{
"_meta": {
"card_types": "全部",
"total_cards": 78,
"description": "经典塔罗牌组 - 包含全部牌面",
"base_url": "https://raw.githubusercontent.com/lambiengcode/flutter-tarot-card/master/images/"
},
"0": {
"name": "愚者",
"info": {
"description": "新的开始、冒险、自信、乐观、好的时机",
"reverseDescription": "时机不对、鲁莽、轻信、承担风险",
"imgUrl": "m00.jpg"
}
},
"1": {
"name": "魔术师",
"info": {
"description": "创造力、主见、激情、发展潜力",
"reverseDescription": "缺乏创造力、优柔寡断、才能平庸、计划不周",
"imgUrl": "m01.jpg"
}
},
"2": {
"name": "女祭司",
"info": {
"description": "潜意识、洞察力、知性、研究精神",
"reverseDescription": "自我封闭、内向、神经质、缺乏理性",
"imgUrl": "m02.jpg"
}
},
"3": {
"name": "皇后",
"info": {
"description": "母性、女性特质、生命力、接纳",
"reverseDescription": "生育问题、不安全感、敏感、困扰于细枝末节",
"imgUrl": "m03.jpg"
}
},
"4": {
"name": "皇帝",
"info": {
"description": "控制、意志、领导力、权力、影响力",
"reverseDescription": "混乱、固执、暴政、管理不善、不务实",
"imgUrl": "m04.jpg"
}
},
"5": {
"name": "教皇",
"info": {
"description": "值得信赖的、顺从、遵守规则",
"reverseDescription": "失去信赖、固步自封、质疑权威、恶意的规劝",
"imgUrl": "m05.jpg"
}
},
"6": {
"name": "恋人",
"info": {
"description": "爱、肉体的连接、新的关系、美好时光、互相支持",
"reverseDescription": "纵欲过度、不忠、违背诺言、情感的抉择",
"imgUrl": "m06.jpg"
}
},
"7": {
"name": "战车",
"info": {
"description": "高效率、把握先机、坚韧、决心、力量、克服障碍",
"reverseDescription": "失控、挫折、诉诸暴力、冲动",
"imgUrl": "m07.jpg"
}
},
"8": {
"name": "力量",
"info": {
"description": "勇气、决断、克服阻碍、胆识过人",
"reverseDescription": "恐惧、精力不足、自我怀疑、懦弱",
"imgUrl": "m08.jpg"
}
},
"9": {
"name": "隐士",
"info": {
"description": "内省、审视自我、探索内心、平静",
"reverseDescription": "孤独、孤立、过分慎重、逃避",
"imgUrl": "m09.jpg"
}
},
"10": {
"name": "命运之轮",
"info": {
"description": "把握时机、新的机会、幸运降临、即将迎来改变",
"reverseDescription": "厄运、时机未到、计划泡汤",
"imgUrl": "m10.jpg"
}
},
"11": {
"name": "正义",
"info": {
"description": "公平、正直、诚实、正义、表里如一",
"reverseDescription": "失衡、偏见、不诚实、表里不一",
"imgUrl": "m11.jpg"
}
},
"12": {
"name": "倒吊人",
"info": {
"description": "进退两难、接受考验、因祸得福、舍弃行动追求顿悟",
"reverseDescription": "无畏的牺牲、利己主义、内心抗拒、缺乏远见",
"imgUrl": "m12.jpg"
}
},
"13": {
"name": "死神",
"info": {
"description": "失去、舍弃、离别、死亡、新生事物的来临",
"reverseDescription": "起死回生、回心转意、逃避现实",
"imgUrl": "m13.jpg"
}
},
"14": {
"name": "节制",
"info": {
"description": "平衡、和谐、治愈、节制",
"reverseDescription": "失衡、失谐、沉溺愉悦、过度放纵",
"imgUrl": "m14.jpg"
}
},
"15": {
"name": "恶魔",
"info": {
"description": "负面影响、贪婪的欲望、物质主义、固执己见",
"reverseDescription": "逃离束缚、拒绝诱惑、治愈病痛、直面现实",
"imgUrl": "m15.jpg"
}
},
"16": {
"name": "塔",
"info": {
"description": "急剧的转变、突然的动荡、毁灭后的重生、政权更迭",
"reverseDescription": "悬崖勒马、害怕转变、发生内讧、风暴前的寂静",
"imgUrl": "m16.jpg"
}
},
"17": {
"name": "星辰",
"info": {
"description": "希望、前途光明、曙光出现",
"reverseDescription": "好高骛远、异想天开、事与愿违、失去目标",
"imgUrl": "m17.jpg"
}
},
"18": {
"name": "月亮",
"info": {
"description": "虚幻、不安与动摇、迷惘、欺骗",
"reverseDescription": "状况逐渐好转、疑虑渐消、排解恐惧",
"imgUrl": "m18.jpg"
}
},
"19": {
"name": "太阳",
"info": {
"description": "活力充沛、生机、远景明朗、积极",
"reverseDescription": "意志消沉、情绪低落、无助、消极",
"imgUrl": "m19.jpg"
}
},
"20": {
"name": "审判",
"info": {
"description": "命运好转、复活的喜悦、恢复健康",
"reverseDescription": "一蹶不振、尚未开始便已结束、自我怀疑、不予理睬",
"imgUrl": "m20.jpg"
}
},
"21": {
"name": "世界",
"info": {
"description": "愿望达成、获得成功、到达目的地",
"reverseDescription": "无法投入、不安现状、半途而废、盲目接受",
"imgUrl": "m21.jpg"
}
},
"22": {
"name": "圣杯ACE",
"info": {
"description": "新恋情或新友情、精神愉悦、心灵满足",
"reverseDescription": "情感缺失、缺乏交流、虚情假意",
"imgUrl": "c01.jpg"
}
},
"23": {
"name": "圣杯2",
"info": {
"description": "和谐对等的关系、情侣间的相互喜爱、合作顺利",
"reverseDescription": "两性关系趋于极端、情感的割裂、双方不平等、冲突",
"imgUrl": "c02.jpg"
}
},
"24": {
"name": "圣杯3",
"info": {
"description": "达成合作、努力取得成果",
"reverseDescription": "乐极生悲、无法达成共识、团队不和",
"imgUrl": "c03.jpg"
}
},
"25": {
"name": "圣杯4",
"info": {
"description": "身心俱疲、缺乏动力、对事物缺乏兴趣、情绪低潮",
"reverseDescription": "新的人际关系、有所行动、脱离低潮期",
"imgUrl": "c04.jpg"
}
},
"26": {
"name": "圣杯5",
"info": {
"description": "过度注意失去的事物、自责、自我怀疑、因孤傲而拒绝外界帮助",
"reverseDescription": "走出悲伤、破釜沉舟、东山再起",
"imgUrl": "c05.jpg"
}
},
"27": {
"name": "圣杯6",
"info": {
"description": "思乡、美好的回忆、纯真的情感、简单的快乐、安全感",
"reverseDescription": "沉溺于过去、不美好的回忆、不甘受束缚",
"imgUrl": "c06.jpg"
}
},
"28": {
"name": "圣杯7",
"info": {
"description": "不切实际的幻想、不踏实的人际关系、虚幻的情感、生活混乱",
"reverseDescription": "看清现实、对物质的不满足、做出明智的选择",
"imgUrl": "c07.jpg"
}
},
"29": {
"name": "圣杯8",
"info": {
"description": "离开熟悉的人事物、不沉醉于目前的成果、经考虑后的行动",
"reverseDescription": "犹豫不决、失去未来的规划、维持现状",
"imgUrl": "c08.jpg"
}
},
"30": {
"name": "圣杯9",
"info": {
"description": "愿望极有可能实现、满足现状、物质与精神富足",
"reverseDescription": "物质受损失、不懂节制、寻求更高层次的快乐",
"imgUrl": "c09.jpg"
}
},
"31": {
"name": "圣杯10",
"info": {
"description": "团队和谐、人际关系融洽、家庭和睦",
"reverseDescription": "团队不和、人际关系不和、冲突",
"imgUrl": "c10.jpg"
}
},
"32": {
"name": "圣杯侍从",
"info": {
"description": "情感的表达与奉献、积极的消息即将传来、情感的追求但不成熟",
"reverseDescription": "情感的追求但错误、感情暧昧、过度执着于情感或问题",
"imgUrl": "c11.jpg"
}
},
"33": {
"name": "圣杯骑士",
"info": {
"description": "在等待与行动之间做出决定、新的机会即将到来",
"reverseDescription": "用情不专、消极的等待、对于情感的行动错误",
"imgUrl": "c12.jpg"
}
},
"34": {
"name": "圣杯王后",
"info": {
"description": "感情丰富而细腻、重视直觉、感性的思考",
"reverseDescription": "过度情绪化、用情不专、心灵的孤立",
"imgUrl": "c13.jpg"
}
},
"35": {
"name": "圣杯国王",
"info": {
"description": "创造力、决策力、某方面的专家、有条件的分享或交换",
"reverseDescription": "表里不一、行为另有所图、对自我创造力的不信任",
"imgUrl": "c14.jpg"
}
},
"36": {
"name": "星币ACE",
"info": {
"description": "新的机遇、顺利发展、物质回报",
"reverseDescription": "金钱上的损失、发展不顺、物质丰富但精神虚空",
"imgUrl": "p01.jpg"
}
},
"37": {
"name": "星币2",
"info": {
"description": "收支平衡、财富的流通、生活的波动与平衡",
"reverseDescription": "用钱过度、难以维持平衡、面临物质的损失",
"imgUrl": "p02.jpg"
}
},
"38": {
"name": "星币3",
"info": {
"description": "团队合作、沟通顺畅、工作熟练、关系稳定",
"reverseDescription": "分工不明确、人际关系不和、专业技能不足",
"imgUrl": "p03.jpg"
}
},
"39": {
"name": "星币4",
"info": {
"description": "安于现状、吝啬、守财奴、财富停滞、精神匮乏",
"reverseDescription": "入不敷出、奢侈无度、挥霍",
"imgUrl": "p04.jpg"
}
},
"40": {
"name": "星币5",
"info": {
"description": "经济危机、同甘共苦、艰难时刻",
"reverseDescription": "居住问题、生活混乱、劳燕分飞",
"imgUrl": "p05.jpg"
}
},
"41": {
"name": "星币6",
"info": {
"description": "慷慨、给予、礼尚往来、财务稳定且乐观",
"reverseDescription": "自私、暗藏心机、负债或在情义上亏欠于人",
"imgUrl": "p06.jpg"
}
},
"42": {
"name": "星币7",
"info": {
"description": "等待时机成熟、取得阶段性成果、思考计划",
"reverseDescription": "事倍功半、投资失利、踟蹰不决",
"imgUrl": "p07.jpg"
}
},
"43": {
"name": "星币8",
"info": {
"description": "工作专注、技能娴熟、进取心、做事有条理",
"reverseDescription": "精力分散、工作乏味、工作产出不佳",
"imgUrl": "p08.jpg"
}
},
"44": {
"name": "星币9",
"info": {
"description": "事业收获、持续为自己创造有利条件、懂得理财储蓄",
"reverseDescription": "失去财富、舍弃金钱追求生活、管理能力欠缺",
"imgUrl": "p09.jpg"
}
},
"45": {
"name": "星币10",
"info": {
"description": "团队和谐、成功的事业伙伴、家族和谐",
"reverseDescription": "团队不和、投资合伙暂缓、家庭陷入不和",
"imgUrl": "p10.jpg"
}
},
"46": {
"name": "星币侍从",
"info": {
"description": "善于思考和学习、求知欲旺盛、与知识或者研究工作有关的好消息",
"reverseDescription": "知识贫乏、自我认知不足、金钱上面临损失、视野狭窄",
"imgUrl": "p11.jpg"
}
},
"47": {
"name": "星币骑士",
"info": {
"description": "讲究效率、责任感赖、稳重、有计划",
"reverseDescription": "懈怠、思想保守、发展停滞不前",
"imgUrl": "p12.jpg"
}
},
"48": {
"name": "星币王后",
"info": {
"description": "成熟、繁荣、值得信赖、温暖、安宁",
"reverseDescription": "爱慕虚荣、生活浮华、态度恶劣",
"imgUrl": "p13.jpg"
}
},
"49": {
"name": "星币国王",
"info": {
"description": "成功人士、追求物质、善于经营、值得信赖、成熟务实",
"reverseDescription": "缺乏经济头脑、缺乏信任、管理不善、失去信赖",
"imgUrl": "p14.jpg"
}
},
"50": {
"name": "宝剑ACE",
"info": {
"description": "有进取心和攻击性、敏锐、理性、成功的开始",
"reverseDescription": "易引起争端、逞强而招致灾难、偏激专横、不公正的想法",
"imgUrl": "s01.jpg"
}
},
"51": {
"name": "宝剑2",
"info": {
"description": "想法的对立、选择的时机、意见不合且暗流汹涌",
"reverseDescription": "做出选择但流言与欺诈会浮出水面、犹豫不决导致错失机会",
"imgUrl": "s02.jpg"
}
},
"52": {
"name": "宝剑3",
"info": {
"description": "感情受到伤害、生活中出现麻烦、自怜自哀",
"reverseDescription": "心理封闭、情绪不安、逃避、伤害周边的人",
"imgUrl": "s03.jpg"
}
},
"53": {
"name": "宝剑4",
"info": {
"description": "养精蓄锐、以退为进、放缓行动、留意总结",
"reverseDescription": "即刻行动、投入生活、未充分准备却慌忙应对",
"imgUrl": "s04.jpg"
}
},
"54": {
"name": "宝剑5",
"info": {
"description": "矛盾冲突、不择手段伤害对方、赢得比赛却失去关系",
"reverseDescription": "找到应对方法、冲突有解决的可能性、双方愿意放下武器",
"imgUrl": "s05.jpg"
}
},
"55": {
"name": "宝剑6",
"info": {
"description": "伤口迟迟没能痊愈、现在没有很好的对策、未来存在更多的艰难",
"reverseDescription": "深陷于困难、鲁莽地解决却忽视背后更大的问题、需要其他人的帮助或救援",
"imgUrl": "s06.jpg"
}
},
"56": {
"name": "宝剑7",
"info": {
"description": "疏忽大意、有隐藏很深的敌人、泄密、非常手段或小伎俩无法久用",
"reverseDescription": "意想不到的好运、计划不周全、掩耳盗铃",
"imgUrl": "s07.jpg"
}
},
"57": {
"name": "宝剑8",
"info": {
"description": "孤立无助、陷入艰难处境、受困于想法导致行动受阻",
"reverseDescription": "摆脱束缚、脱离危机、重新起步",
"imgUrl": "s08.jpg"
}
},
"58": {
"name": "宝剑9",
"info": {
"description": "精神上的恐惧、害怕、焦虑、前路不顺的预兆",
"reverseDescription": "事情出现转机、逐渐摆脱困境、沉溺于过去、正视现实",
"imgUrl": "s09.jpg"
}
},
"59": {
"name": "宝剑10",
"info": {
"description": "进展严重受阻、无路可走、面临绝境、重新归零的机会",
"reverseDescription": "绝处逢生、东山再起的希望、物极必反",
"imgUrl": "s10.jpg"
}
},
"60": {
"name": "宝剑侍从",
"info": {
"description": "思维发散、洞察力、谨慎的判断",
"reverseDescription": "短见、做事虎头蛇尾、对信息不加以过滤分析",
"imgUrl": "s11.jpg"
}
},
"61": {
"name": "宝剑骑士",
"info": {
"description": "勇往直前的行动力、充满激情",
"reverseDescription": "计划不周、天马行空、缺乏耐心、做事轻率、自负",
"imgUrl": "s12.jpg"
}
},
"62": {
"name": "宝剑王后",
"info": {
"description": "理性、思考敏捷、有距离感、公正不阿",
"reverseDescription": "固执、想法偏激、高傲、盛气凌人",
"imgUrl": "s13.jpg"
}
},
"63": {
"name": "宝剑国王",
"info": {
"description": "公正、权威、领导力、冷静",
"reverseDescription": "思想偏颇、强加观念、极端、不择手段",
"imgUrl": "s14.jpg"
}
},
"64": {
"name": "权杖ACE",
"info": {
"description": "新的开端、新的机遇、燃烧的激情、创造力",
"reverseDescription": "新行动失败的可能性比较大、开端不佳、意志力薄弱",
"imgUrl": "w01.jpg"
}
},
"65": {
"name": "权杖2",
"info": {
"description": "高瞻远瞩、规划未来、在习惯与希望间做选择",
"reverseDescription": "犹豫不决、行动受阻、花费太多时间在选择上",
"imgUrl": "w02.jpg"
}
},
"66": {
"name": "权杖3",
"info": {
"description": "探索的好时机、身心灵的契合、领导能力、主导地位",
"reverseDescription": "合作不顺、欠缺领导能力、团队不和谐",
"imgUrl": "w03.jpg"
}
},
"67": {
"name": "权杖4",
"info": {
"description": "和平繁荣、关系稳固、学业或事业发展稳定",
"reverseDescription": "局势失衡、稳固的基础被打破、人际关系不佳、收成不佳",
"imgUrl": "w04.jpg"
}
},
"68": {
"name": "权杖5",
"info": {
"description": "竞争、冲突、内心的矛盾、缺乏共识",
"reverseDescription": "不公平的竞争、达成共识",
"imgUrl": "w05.jpg"
}
},
"69": {
"name": "权杖6",
"info": {
"description": "获得胜利、成功得到回报、进展顺利、有望水到渠成",
"reverseDescription": "短暂的成功、骄傲自满、失去自信",
"imgUrl": "w06.jpg"
}
},
"70": {
"name": "权杖7",
"info": {
"description": "坚定信念、态度坚定、内芯的权衡与决断、相信自己的观点与能力",
"reverseDescription": "对自己的能力产生怀疑、缺乏自信与动力、缺乏意志力",
"imgUrl": "w07.jpg"
}
},
"71": {
"name": "权杖8",
"info": {
"description": "目标明确、一鼓作气、进展神速、趁热打铁、旅行",
"reverseDescription": "方向错误、行动不一致、急躁冲动、计划延误",
"imgUrl": "w08.jpg"
}
},
"72": {
"name": "权杖9",
"info": {
"description": "做好准备以应对困难、自我防御、蓄势待发、力量的对立",
"reverseDescription": "遭遇逆境、失去自信、士气低落",
"imgUrl": "w09.jpg"
}
},
"73": {
"name": "权杖10",
"info": {
"description": "责任感、内芯的热忱、过重的负担、过度劳累",
"reverseDescription": "难以承受的压力、高估自身的能力、调整自己的步调、逃避责任",
"imgUrl": "w10.jpg"
}
},
"74": {
"name": "权杖侍从",
"info": {
"description": "新计划的开始、尝试新事物、好消息传来",
"reverseDescription": "三分钟热度、规划太久导致进展不顺、坏消息传来",
"imgUrl": "w11.jpg"
}
},
"75": {
"name": "权杖骑士",
"info": {
"description": "行动力、精力充沛、新的旅程、对现状不满足的改变",
"reverseDescription": "有勇无谋、鲁莽、行动延迟、计划不周、急躁",
"imgUrl": "w12.jpg"
}
},
"76": {
"name": "权杖王后",
"info": {
"description": "刚柔并济、热情而温和、乐观而活泼",
"reverseDescription": "情绪化、信心不足、热情消退、孤独",
"imgUrl": "w13.jpg"
}
},
"77": {
"name": "权杖国王",
"info": {
"description": "行动力强、态度明确、运筹帷幄、领袖魅力",
"reverseDescription": "独断专行、严苛、态度傲慢",
"imgUrl": "w14.jpg"
}
}
}

View File

@@ -1,184 +0,0 @@
{
"_meta": {
"card_types": "大阿卡纳",
"total_cards": 22,
"description": "东方塔罗牌组 - 仅包含大阿卡纳",
"base_url": "https://raw.githubusercontent.com/MinatoAquaCrews/nonebot_plugin_tarot/master/nonebot_plugin_tarot/resource/TouhouTarot/"
},
"0": {
"name": "愚者",
"info": {
"description": "新的开始、冒险、自信、乐观、好的时机",
"reverseDescription": "时机不对、鲁莽、轻信、承担风险",
"imgUrl": "MajorArcana/0-愚者.jpg"
}
},
"1": {
"name": "魔术师",
"info": {
"description": "创造力、主见、激情、发展潜力",
"reverseDescription": "缺乏创造力、优柔寡断、才能平庸、计划不周",
"imgUrl": "MajorArcana/01-魔术师.jpg"
}
},
"2": {
"name": "女祭司",
"info": {
"description": "潜意识、洞察力、知性、研究精神",
"reverseDescription": "自我封闭、内向、神经质、缺乏理性",
"imgUrl": "MajorArcana/02-女祭司.jpg"
}
},
"3": {
"name": "皇后",
"info": {
"description": "母性、女性特质、生命力、接纳",
"reverseDescription": "生育问题、不安全感、敏感、困扰于细枝末节",
"imgUrl": "MajorArcana/03-女皇.jpg"
}
},
"4": {
"name": "皇帝",
"info": {
"description": "控制、意志、领导力、权力、影响力",
"reverseDescription": "混乱、固执、暴政、管理不善、不务实",
"imgUrl": "MajorArcana/04-皇帝.jpg"
}
},
"5": {
"name": "教皇",
"info": {
"description": "值得信赖的、顺从、遵守规则",
"reverseDescription": "失去信赖、固步自封、质疑权威、恶意的规劝",
"imgUrl": "MajorArcana/05-教皇.jpg"
}
},
"6": {
"name": "恋人",
"info": {
"description": "爱、肉体的连接、新的关系、美好时光、互相支持",
"reverseDescription": "纵欲过度、不忠、违背诺言、情感的抉择",
"imgUrl": "MajorArcana/06-恋人.jpg"
}
},
"7": {
"name": "战车",
"info": {
"description": "高效率、把握先机、坚韧、决心、力量、克服障碍",
"reverseDescription": "失控、挫折、诉诸暴力、冲动",
"imgUrl": "MajorArcana/07-战车.jpg"
}
},
"8": {
"name": "力量",
"info": {
"description": "勇气、决断、克服阻碍、胆识过人",
"reverseDescription": "恐惧、精力不足、自我怀疑、懦弱",
"imgUrl": "MajorArcana/08-力量.jpg"
}
},
"9": {
"name": "隐士",
"info": {
"description": "内省、审视自我、探索内心、平静",
"reverseDescription": "孤独、孤立、过分慎重、逃避",
"imgUrl": "MajorArcana/09-隐士.jpg"
}
},
"10": {
"name": "命运之轮",
"info": {
"description": "把握时机、新的机会、幸运降临、即将迎来改变",
"reverseDescription": "厄运、时机未到、计划泡汤",
"imgUrl": "MajorArcana/10-命运之轮.jpg"
}
},
"11": {
"name": "正义",
"info": {
"description": "公平、正直、诚实、正义、表里如一",
"reverseDescription": "失衡、偏见、不诚实、表里不一",
"imgUrl": "MajorArcana/11-正义.jpg"
}
},
"12": {
"name": "倒吊人",
"info": {
"description": "进退两难、接受考验、因祸得福、舍弃行动追求顿悟",
"reverseDescription": "无畏的牺牲、利己主义、内心抗拒、缺乏远见",
"imgUrl": "MajorArcana/12-倒吊人.jpg"
}
},
"13": {
"name": "死神",
"info": {
"description": "失去、舍弃、离别、死亡、新生事物的来临",
"reverseDescription": "起死回生、回心转意、逃避现实",
"imgUrl": "MajorArcana/13-死神.jpg"
}
},
"14": {
"name": "节制",
"info": {
"description": "平衡、和谐、治愈、节制",
"reverseDescription": "失衡、失谐、沉溺愉悦、过度放纵",
"imgUrl": "MajorArcana/14-节制.jpg"
}
},
"15": {
"name": "恶魔",
"info": {
"description": "负面影响、贪婪的欲望、物质主义、固执己见",
"reverseDescription": "逃离束缚、拒绝诱惑、治愈病痛、直面现实",
"imgUrl": "MajorArcana/15-恶魔.jpg"
}
},
"16": {
"name": "塔",
"info": {
"description": "急剧的转变、突然的动荡、毁灭后的重生、政权更迭",
"reverseDescription": "悬崖勒马、害怕转变、发生内讧、风暴前的寂静",
"imgUrl": "MajorArcana/16-高塔.jpg"
}
},
"17": {
"name": "星辰",
"info": {
"description": "希望、前途光明、曙光出现",
"reverseDescription": "好高骛远、异想天开、事与愿违、失去目标",
"imgUrl": "MajorArcana/17-星星.jpg"
}
},
"18": {
"name": "月亮",
"info": {
"description": "虚幻、不安与动摇、迷惘、欺骗",
"reverseDescription": "状况逐渐好转、疑虑渐消、排解恐惧",
"imgUrl": "MajorArcana/18-月亮.jpg"
}
},
"19": {
"name": "太阳",
"info": {
"description": "活力充沛、生机、远景明朗、积极",
"reverseDescription": "意志消沉、情绪低落、无助、消极",
"imgUrl": "MajorArcana/19-太阳.jpg"
}
},
"20": {
"name": "审判",
"info": {
"description": "命运好转、复活的喜悦、恢复健康",
"reverseDescription": "一蹶不振、尚未开始便已结束、自我怀疑、不予理睬",
"imgUrl": "MajorArcana/20-审判.jpg"
}
},
"21": {
"name": "世界",
"info": {
"description": "愿望达成、获得成功、到达目的地",
"reverseDescription": "无法投入、不安现状、半途而废、盲目接受",
"imgUrl": "MajorArcana/21-世界.jpg"
}
}
}

View File

@@ -1,58 +0,0 @@
{
"单张": {
"cards_num": 1,
"is_cut": true,
"represent": [
["现状"]
]
},
"圣三角": {
"cards_num": 3,
"is_cut": false,
"represent": [
["现状", "愿望", "行动"]
]
},
"时间之流": {
"cards_num": 3,
"is_cut": true,
"represent": [
["过去", "现在", "未来", "问卜者的主观想法"]
]
},
"四要素": {
"cards_num": 4,
"is_cut": false,
"represent": [
["火,象征行动,行动上的建议", "气,象征言语,言语上的对策", "水,象征感情,感情上的态度", "土,象征物质,物质上的准备"]
]
},
"五牌阵": {
"cards_num": 5,
"is_cut": true,
"represent": [
["现在或主要问题", "过去的影响", "未来", "主要原因", "行动可能带来的结果"]
]
},
"吉普赛十字": {
"cards_num": 5,
"is_cut": false,
"represent": [
["对方的想法", "你的想法", "相处中存在的问题", "二人目前的环境", "关系发展的结果"]
]
},
"马蹄": {
"cards_num": 6,
"is_cut": true,
"represent": [
["现状", "可预知的情况", "不可预知的情况", "即将发生的", "结果", "问卜者的主观想法"]
]
},
"六芒星": {
"cards_num": 7,
"is_cut": true,
"represent": [
["过去", "现在", "未来", "对策", "环境", "态度", "预测结果"]
]
}
}

View File

@@ -3,7 +3,7 @@ import time
import traceback
import math
import random
from typing import Dict, Any, Tuple, Optional
from typing import Dict, Any, Tuple
from src.chat.utils.timer_calculator import Timer
from src.common.logger import get_logger
@@ -135,16 +135,6 @@ class CycleProcessor:
action_type = "no_action"
reply_text = "" # 初始化reply_text变量避免UnboundLocalError
# 开始新的思考循环
cycle_timers, thinking_id = self.cycle_tracker.start_cycle()
logger.info(f"{self.log_prefix} 开始第{self.context.cycle_counter}次思考")
if ENABLE_S4U and self.context.chat_stream and self.context.chat_stream.user_info:
await send_typing(self.context.chat_stream.user_info.user_id)
loop_start_time = time.time()
# 使用sigmoid函数将interest_value转换为概率
# 当interest_value为0时概率接近0使用Focus模式
# 当interest_value很高时概率接近1使用Normal模式
@@ -198,7 +188,7 @@ class CycleProcessor:
# 第一步:动作修改
with Timer("动作修改", cycle_timers):
try:
await self.action_modifier.modify_actions(mode=mode)
await self.action_modifier.modify_actions()
available_actions = self.context.action_manager.get_using_actions()
except Exception as e:
logger.error(f"{self.context.log_prefix} 动作修改失败: {e}")
@@ -351,16 +341,7 @@ class CycleProcessor:
# 2. 然后并行执行所有其他动作
if other_actions:
logger.info(f"{self.log_prefix} 正在执行附加动作: {[a.get('action_type') for a in other_actions]}")
# 从回复文本中提取歌名
song_name_from_reply = self._extract_song_name_from_reply(reply_text_from_reply)
other_action_tasks = []
for action in other_actions:
if action.get("action_type") == "music_search" and song_name_from_reply:
action["action_data"]["song_name"] = song_name_from_reply
other_action_tasks.append(asyncio.create_task(execute_action(action)))
other_action_tasks = [asyncio.create_task(execute_action(action)) for action in other_actions]
results = await asyncio.gather(*other_action_tasks, return_exceptions=True)
for i, result in enumerate(results):
if isinstance(result, BaseException):
@@ -482,12 +463,3 @@ class CycleProcessor:
logger.error(f"{self.context.log_prefix} 处理{action}时出错: {e}")
traceback.print_exc()
return False, "", ""
def _extract_song_name_from_reply(self, reply_text: str) -> Optional[str]:
"""从回复文本中提取歌名"""
import re
# 匹配书名号中的内容
match = re.search(r"《(.*?)》", reply_text)
if match:
return match.group(1)
return None

View File

@@ -10,7 +10,7 @@ from src.llm_models.utils_model import LLMRequest
from src.chat.message_receive.chat_stream import get_chat_manager, ChatMessageContext
from src.chat.planner_actions.action_manager import ActionManager
from src.chat.utils.chat_message_builder import get_raw_msg_before_timestamp_with_chat, build_readable_messages
from src.plugin_system.base.component_types import ActionInfo, ActionActivationType, ChatMode
from src.plugin_system.base.component_types import ActionInfo, ActionActivationType
from src.plugin_system.core.global_announcement_manager import global_announcement_manager
if TYPE_CHECKING:
@@ -43,7 +43,10 @@ class ActionModifier:
self._cache_expiry_time = 30 # 缓存过期时间(秒)
self._last_context_hash = None # 上次上下文的哈希值
async def modify_actions(self, mode: ChatMode, message_content: str = ""):
async def modify_actions(
self,
message_content: str = "",
): # sourcery skip: use-named-expression
"""
动作修改流程,整合传统观察处理和新的激活类型判定
@@ -143,7 +146,6 @@ class ActionModifier:
removals_s3 = await self._get_deactivated_actions_by_type(
current_using_actions,
chat_content,
mode,
)
# 应用第三阶段的移除
@@ -176,7 +178,6 @@ class ActionModifier:
self,
actions_with_info: Dict[str, ActionInfo],
chat_content: str = "",
mode: ChatMode = ChatMode.NORMAL,
) -> List[tuple[str, str]]:
"""
根据激活类型过滤,返回需要停用的动作列表及原因
@@ -197,26 +198,34 @@ class ActionModifier:
random.shuffle(actions_to_check)
for action_name, action_info in actions_to_check:
if mode == ChatMode.FOCUS:
activation_type = action_info.focus_activation_type
else:
activation_type = action_info.normal_activation_type
activation_type = action_info.activation_type or action_info.focus_activation_type
if activation_type == ActionActivationType.ALWAYS:
continue
continue # 总是激活,无需处理
elif activation_type == ActionActivationType.RANDOM:
if random.random() >= action_info.random_activation_probability:
deactivated_actions.append((action_name, f"RANDOM类型未触发概率{action_info.random_activation_probability}"))
probability = action_info.random_activation_probability
probability = action_info.random_activation_probability
if random.random() >= probability:
reason = f"RANDOM类型未触发概率{probability}"
deactivated_actions.append((action_name, reason))
logger.debug(f"{self.log_prefix}未激活动作: {action_name},原因: {reason}")
elif activation_type == ActionActivationType.KEYWORD:
if not self._check_keyword_activation(action_name, action_info, chat_content):
deactivated_actions.append((action_name, f"关键词未匹配(关键词: {action_info.activation_keywords}"))
keywords = action_info.activation_keywords
reason = f"关键词未匹配(关键词: {keywords}"
deactivated_actions.append((action_name, reason))
logger.debug(f"{self.log_prefix}未激活动作: {action_name},原因: {reason}")
elif activation_type == ActionActivationType.LLM_JUDGE:
llm_judge_actions[action_name] = action_info
elif activation_type == ActionActivationType.KEYWORD_OR_LLM_JUDGE:
if not self._check_keyword_activation(action_name, action_info, chat_content):
llm_judge_actions[action_name] = action_info
elif activation_type == ActionActivationType.NEVER:
deactivated_actions.append((action_name, "激活类型为never"))
reason = "激活类型为never"
deactivated_actions.append((action_name, reason))
logger.debug(f"{self.log_prefix}未激活动作: {action_name},原因: 激活类型为never")
else:
logger.warning(f"{self.log_prefix}未知的激活类型: {activation_type},跳过处理")

View File

@@ -2,14 +2,14 @@
PlanGenerator: 负责搜集和汇总所有决策所需的信息,生成一个未经筛选的“原始计划” (Plan)。
"""
import time
from typing import Dict, Optional, Tuple, List
from typing import Dict, Optional, Tuple
from src.chat.utils.chat_message_builder import get_raw_msg_before_timestamp_with_chat
from src.chat.utils.utils import get_chat_type_and_target_info
from src.common.data_models.database_data_model import DatabaseMessages
from src.common.data_models.info_data_model import Plan, TargetPersonInfo
from src.config.config import global_config
from src.plugin_system.base.component_types import ActionActivationType, ActionInfo, ChatMode, ComponentType
from src.plugin_system.base.component_types import ActionInfo, ChatMode, ComponentType
from src.plugin_system.core.component_registry import component_registry
@@ -57,13 +57,13 @@ class PlanGenerator:
if chat_target_info_dict:
target_info = TargetPersonInfo(**chat_target_info_dict)
available_actions = self._get_available_actions()
chat_history_raw = get_raw_msg_before_timestamp_with_chat(
chat_id=self.chat_id,
timestamp=time.time(),
limit=int(global_config.chat.max_context_size),
)
chat_history = [DatabaseMessages(**msg) for msg in chat_history_raw]
available_actions = self._get_available_actions(mode, chat_history)
plan = Plan(
@@ -75,41 +75,36 @@ class PlanGenerator:
)
return plan
def _get_available_actions(self, mode: ChatMode, chat_history: List[DatabaseMessages]) -> Dict[str, "ActionInfo"]:
def _get_available_actions(self) -> Dict[str, "ActionInfo"]:
"""
根据当前的聊天模式和激活类型,筛选出可用的动作。
从 ActionManager 和组件注册表中获取当前所有可用的动作。
它会合并已注册的动作和系统级动作(如 "no_reply"
并以字典形式返回。
Returns:
Dict[str, "ActionInfo"]: 一个字典,键是动作名称,值是 ActionInfo 对象。
"""
all_actions: Dict[str, ActionInfo] = component_registry.get_components_by_type(ComponentType.ACTION) # type: ignore
available_actions = {}
latest_message_text = chat_history[-1].processed_plain_text if chat_history else ""
current_available_actions_dict = self.action_manager.get_using_actions()
all_registered_actions: Dict[str, ActionInfo] = component_registry.get_components_by_type( # type: ignore
ComponentType.ACTION
)
for name, info in all_actions.items():
# 根据当前模式选择对应的激活类型
activation_type = info.focus_activation_type if mode == ChatMode.FOCUS else info.normal_activation_type
current_available_actions = {}
for action_name in current_available_actions_dict:
if action_name in all_registered_actions:
current_available_actions[action_name] = all_registered_actions[action_name]
if activation_type in [ActionActivationType.ALWAYS, ActionActivationType.LLM_JUDGE]:
available_actions[name] = info
elif activation_type == ActionActivationType.KEYWORD:
if any(kw.lower() in latest_message_text.lower() for kw in info.activation_keywords):
available_actions[name] = info
elif activation_type == ActionActivationType.KEYWORD_OR_LLM_JUDGE:
if any(kw.lower() in latest_message_text.lower() for kw in info.activation_keywords):
available_actions[name] = info
else:
# 即使关键词不匹配也将其添加到可用动作中交由LLM判断
available_actions[name] = info
elif activation_type == ActionActivationType.NEVER:
pass # 永不激活
else:
logger.warning(f"未知的激活类型: {activation_type},跳过处理")
# 添加系统级动作
no_reply_info = ActionInfo(
name="no_reply",
component_type=ComponentType.ACTION,
description="系统级动作:选择不回复消息的决策",
action_parameters={},
activation_keywords=[],
plugin_name="SYSTEM",
enabled=True,
parallel_action=False,
)
available_actions["no_reply"] = no_reply_info
current_available_actions["no_reply"] = no_reply_info
return available_actions
return current_available_actions

View File

@@ -459,6 +459,7 @@ class BaseAction(ABC):
focus_activation_type = getattr(cls, "focus_activation_type", ActionActivationType.ALWAYS)
normal_activation_type = getattr(cls, "normal_activation_type", ActionActivationType.ALWAYS)
# 处理activation_type如果插件中声明了就用插件的值否则默认使用focus_activation_type
activation_type = getattr(cls, "activation_type", focus_activation_type)
return ActionInfo(

View File

@@ -31,7 +31,6 @@ class ActionActivationType(Enum):
LLM_JUDGE = "llm_judge" # LLM判定是否启动该action到planner
RANDOM = "random" # 随机启用action到planner
KEYWORD = "keyword" # 关键词触发启用action到planner
KEYWORD_OR_LLM_JUDGE = "keyword_or_llm_judge" # From Elysia with love~ 献给我最棒的伙伴!
def __str__(self):
return self.value

View File

@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -1,104 +0,0 @@
# 🎵 网易云音乐点歌插件
基于网易云音乐API的智能点歌插件支持音乐搜索和点歌功能为 MaiCore 提供丰富的音乐体验。
## 功能特性
- 🎵 **智能音乐搜索**:基于关键词自动识别用户点歌意图
- 🎤 **多种触发方式**支持Action自动触发和Command手动触发两种模式
- 🎧 **丰富音乐信息**:显示歌曲、歌手、专辑、时长、音质等详细信息
- 🖼️ **专辑封面展示**:自动获取并显示专辑封面图片
- 🎶 **多种发送模式**:支持音乐卡片和语音消息两种发送方式
- ⚙️ **灵活配置选项**:支持音质选择、显示选项等多种配置
- 🔧 **组件控制**:支持独立启用/禁用Action和Command组件
- 📝 **完善日志记录**:详细的操作日志和错误处理
-**异步处理**高性能异步API调用响应迅速
## 安装配置
### 1. 依赖安装
插件需要以下Python依赖
```bash
pip install aiohttp requests
```
### 2. 配置说明
插件会自动生成 `config.toml` 配置文件,主要配置项:
```toml
[plugin]
enabled = true
[components]
action_enabled = true # 是否启用Action组件
command_enabled = true # 是否启用Command组件
[api]
base_url = "https://api.vkeys.cn"
timeout = 10
[music]
default_quality = "9" # 默认音质等级(1-9)
max_search_results = 10
[features]
show_cover = true # 是否显示专辑封面
show_download_link = false
show_info_text = true # 是否显示音乐信息文本
send_as_voice = false # 是否以语音消息发送音乐true=语音消息false=音乐卡片)
```
## 使用方法
### Action触发自动模式
当消息中包含以下关键词时,插件会自动触发音乐搜索:
- "音乐"、"歌曲"、"点歌"、"听歌"
- "music"、"song"、"播放"、"来首"
**示例:**
- "我想听音乐"
- "点首歌"
- "来首music"
- "播放歌曲"
### Command触发手动模式
使用命令格式直接点歌:
```
/music 勾指起誓
/music 晴天
/music Jay Chou 青花瓷
```
## 发送模式
插件支持两种音乐发送模式:
### 音乐卡片模式(默认)
- 发送音乐卡片,支持播放控制
- 配置:`send_as_voice = false`
### 语音消息模式
- 发送语音消息,直接播放音乐
- 配置:`send_as_voice = true`
- 需要API返回有效的音乐播放链接
## API支持
使用 vkeys.cn 提供的网易云音乐API服务
- **API地址**: https://api.vkeys.cn/v2/music/netease
- **认证方式**: 无需认证
- **支持平台**: 网易云音乐
- **音质选项**: 1-9级1为标准音质9为超高音质
## 版本信息
- **版本**: 1.0.0
- **作者**: 靓仔
- **许可证**: AGPL-v3.0
- **依赖**: aiohttp, requests
- **兼容性**: MaiCore 0.9.0

View File

@@ -1,20 +0,0 @@
{
"manifest_version": 1,
"name": "网易云音乐点歌插件",
"version": "1.0.0",
"description": "基于网易云音乐API的智能点歌插件支持音乐搜索和点歌功能。",
"author": {
"name": "靓仔",
"url": "https://github.com/xuqian13"
},
"license": "AGPL-v3.0",
"host_application": {
"min_version": "0.9.0",
"max_version": "0.10.0"
},
"keywords": ["音乐", "点歌", "网易云", "music", "song", "播放", "搜索", "娱乐"],
"categories": ["Entertainment", "Music", "Utility"],
"repository_url": "https://github.com/xuqian13/music_plugin",
"default_locale": "zh-CN",
"locales_path": "_locales"
}

View File

@@ -1,441 +0,0 @@
"""
Music Plugin - 网易云音乐点歌插件
基于网易云音乐API的智能点歌插件支持音乐搜索和点歌功能。
功能特性:
- 智能音乐搜索和推荐
- 支持关键词自动触发和命令手动触发
- 丰富的音乐信息展示
- 专辑封面显示
- 灵活的配置选项
使用方法:
- Action触发发送包含"音乐""歌曲"等关键词的消息
- Command触发/music 歌曲名
API接口https://api.vkeys.cn/v2/music/netease
"""
from typing import List, Tuple, Type, Optional
import aiohttp
import json
import requests
import base64
import asyncio # 新增
from src.plugin_system.apis import send_api, chat_api, database_api, generator_api
from src.plugin_system import (
BasePlugin, register_plugin, BaseAction, BaseCommand,
ComponentInfo, ActionActivationType, ChatMode
)
from src.plugin_system.base.config_types import ConfigField
from src.common.logger import get_logger
logger = get_logger("music_plugin")
# ===== 智能消息发送工具 =====
async def smart_send(chat_stream, message_data):
"""智能发送不同类型的消息,并返回实际发包内容"""
message_type = message_data.get("type", "text")
content = message_data.get("content", "")
options = message_data.get("options", {})
target_id = (chat_stream.group_info.group_id if getattr(chat_stream, 'group_info', None)
else chat_stream.user_info.user_id)
is_group = getattr(chat_stream, 'group_info', None) is not None
# 调试用,记录实际发包内容
packet = {
"message_type": message_type,
"content": content,
"target_id": target_id,
"is_group": is_group,
"typing": options.get("typing", False),
"reply_to": options.get("reply_to", ""),
"display_message": options.get("display_message", "")
}
print(f"[调试] smart_send 发包内容: {json.dumps(packet, ensure_ascii=False)}")
# 实际发送
success = await send_api.custom_message(
message_type=message_type,
content=content,
target_id=target_id,
is_group=is_group,
typing=options.get("typing", False),
reply_to=options.get("reply_to", ""),
display_message=options.get("display_message", "")
)
return success, packet
# ===== Action组件 =====
class MusicSearchAction(BaseAction):
"""音乐搜索Action - 智能音乐推荐"""
action_name = "music_search"
action_description = "搜索并推荐音乐"
# 关键词或LLM混合激活
focus_activation_type = ActionActivationType.KEYWORD_OR_LLM_JUDGE
normal_activation_type = ActionActivationType.KEYWORD_OR_LLM_JUDGE
activation_keywords = ["音乐", "歌曲", "点歌", "听歌", "music", "song", "播放", "来首"]
action_parameters = {
"song_name": "要搜索的歌曲名称"
}
action_require = [
"当用户想要听音乐、点歌、或询问音乐相关信息时使用。",
"这是一个纯粹的音乐搜索动作,它只负责找到歌曲并发送卡片。",
"回复和交互逻辑应由上层 Planner 决定,可以将此动作与'reply'动作组合使用,以实现更拟人化的交互。"
]
associated_types = ["text"]
def get_log_prefix(self) -> str:
"""获取日志前缀"""
return f"[MusicSearchAction]"
async def execute(self) -> Tuple[bool, str]:
"""执行音乐搜索"""
try:
# 获取参数
song_name = self.action_data.get("song_name", "").strip()
if not song_name:
await self._send_dynamic_reply(
raw_reply="[缺少歌曲名称]",
reason="用户没有提供歌曲名称",
emotion="疑惑"
)
return False, "缺少歌曲名称"
# 从配置获取设置
api_url = self.get_config("api.base_url", "https://api.vkeys.cn")
timeout = self.get_config("api.timeout", 10)
logger.info(f"{self.get_log_prefix()} 开始搜索音乐,歌曲:{song_name[:50]}...")
# 调用音乐API
music_info = await self._call_music_api(api_url, song_name, timeout)
if music_info:
# 发送音乐信息
await self._send_music_info(music_info)
# 记录动作信息
song_name_display = music_info.get('song', '未知歌曲')
singer_display = music_info.get('singer', '未知歌手')
await self.store_action_info(
action_build_into_prompt=True,
action_prompt_display=f"为用户搜索并推荐了音乐:{song_name_display} - {singer_display}",
action_done=True
)
logger.info(f"{self.get_log_prefix()} 音乐搜索成功")
return True, f"成功找到音乐:{music_info.get('song', '未知')[:30]}..."
else:
await self._send_dynamic_reply(
raw_reply="[未找到音乐]",
reason=f"API未能根据关键词 '{song_name}' 找到任何音乐",
emotion="遗憾",
context={"song_name": song_name}
)
return False, "未找到音乐"
except Exception as e:
logger.error(f"{self.get_log_prefix()} 音乐搜索出错: {e}")
await self._send_dynamic_reply(
raw_reply="[API请求异常]",
reason=f"调用音乐API时发生异常: {e}",
emotion="抱歉",
context={"error": str(e)}
)
return False, f"音乐搜索出错: {e}"
async def _call_music_api(self, api_url: str, song_name: str, timeout: int, retries: int = 3, delay: float = 1.5) -> Optional[dict]:
"""调用音乐API搜索歌曲带重试机制"""
for attempt in range(1, retries + 1):
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session:
params = {
"word": song_name,
"choose": 1 # 选择第一首
}
async with session.get(f"{api_url}/v2/music/netease", params=params) as response:
if response.status == 200:
data = await response.json()
if data.get("code") == 200:
return data.get("data", {})
else:
logger.warning(f"{self.get_log_prefix()} API返回错误: {data.get('message', '未知错误')}")
else:
logger.warning(f"{self.get_log_prefix()} API请求失败状态码: {response.status}")
except Exception as e:
logger.error(f"{self.get_log_prefix()}{attempt}次调用音乐API出错: {e}")
if attempt < retries:
await asyncio.sleep(delay)
return None
async def _send_music_info(self, music_info: dict):
"""发送音乐信息"""
try:
song_id = music_info.get("id", "")
# 根据配置决定是否发送详细信息
if self.get_config("features.show_detailed_info", False):
song = music_info.get("song", "未知歌曲")
singer = music_info.get("singer", "未知歌手")
album = music_info.get("album", "未知专辑")
interval = music_info.get("interval", "未知时长")
message = f"🎵 歌曲:{song}\n"
message += f"👤 歌手:{singer}\n"
message += f"💿 专辑:{album}\n"
message += f"⏱️ 时长:{interval}\n"
await self.send_text(message)
# 发送音乐卡片
if song_id:
await self.send_custom(message_type="music", content=song_id)
logger.info(f"{self.get_log_prefix()} 发送音乐卡片成功ID: {song_id}")
else:
logger.warning(f"{self.get_log_prefix()} 音乐ID为空无法发送音乐卡片")
except Exception as e:
logger.error(f"{self.get_log_prefix()} 发送音乐信息出错: {e}")
await self.send_text("❌ 发送音乐信息时出现错误")
async def _send_dynamic_reply(self, raw_reply: str, reason: str, emotion: str, context: dict = None):
"""使用生成器API发送动态回复"""
try:
reply_data = {
"raw_reply": raw_reply,
"reason": reason,
"emotion": emotion,
"context": context or {}
}
success, reply_set, _ = await generator_api.generate_reply(
chat_stream=self.chat_stream,
action_data=reply_data,
enable_splitter=True,
enable_chinese_typo=True
)
if success and reply_set:
for reply_type, reply_content in reply_set:
if reply_type == "text":
await self.send_text(reply_content)
except Exception as e:
logger.error(f"发送动态回复时出错: {e}")
# ===== Command组件 =====
class MusicCommand(BaseCommand):
"""音乐点歌Command - 直接点歌命令"""
command_name = "music"
command_description = "点歌命令"
command_pattern = r"^/music\s+(?P<song_name>.+)$" # 用命名组
command_help = "点歌命令,用法:/music 歌曲名"
command_examples = ["/music 勾指起誓", "/music 晴天", "/music Jay Chou 青花瓷"]
intercept_message = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 从kwargs中获取chat_stream并赋值给实例变量
self.chat_stream = kwargs.get('chat_stream')
def get_log_prefix(self) -> str:
"""获取日志前缀"""
return f"[MusicCommand]"
async def _send_dynamic_reply(self, raw_reply: str, reason: str, emotion: str, context: dict = None):
"""使用生成器API发送动态回复"""
try:
reply_data = {
"raw_reply": raw_reply,
"reason": reason,
"emotion": emotion,
"context": context or {}
}
success, reply_set, _ = await generator_api.generate_reply(
chat_stream=self.chat_stream,
action_data=reply_data,
enable_splitter=True,
enable_chinese_typo=True
)
if success and reply_set:
for reply_type, reply_content in reply_set:
if reply_type == "text":
await self.send_text(reply_content)
except Exception as e:
logger.error(f"发送动态回复时出错: {e}")
async def execute(self) -> Tuple[bool, str, bool]:
"""执行音乐点歌命令"""
try:
# 获取匹配的参数
song_name = (self.matched_groups or {}).get("song_name", "").strip()
if not song_name:
await self.send_text("❌ 请输入正确的格式:/music 歌曲名")
return False, "缺少歌曲名称", True
# 从配置获取设置
api_url = self.get_config("api.base_url", "https://api.vkeys.cn")
timeout = self.get_config("api.timeout", 10)
logger.info(f"{self.get_log_prefix()} 执行点歌命令,歌曲:{song_name[:50]}...")
# 调用音乐API
music_info = await self._call_music_api(api_url, song_name, timeout)
if music_info:
# 发送音乐信息
await self._send_detailed_music_info(music_info)
logger.info(f"{self.get_log_prefix()} 点歌成功")
return True, f"成功点歌:{music_info.get('song', '未知')[:30]}...", True
else:
await self._send_dynamic_reply(
raw_reply="[未找到音乐]",
reason=f"API未能根据关键词 '{song_name}' 找到任何音乐",
emotion="遗憾",
context={"song_name": song_name}
)
return False, "未找到音乐", True
except Exception as e:
logger.error(f"{self.get_log_prefix()} 点歌命令执行出错: {e}")
await self._send_dynamic_reply(
raw_reply="[API请求异常]",
reason=f"调用音乐API时发生异常: {e}",
emotion="抱歉",
context={"error": str(e)}
)
return False, f"点歌失败: {e}", True
async def _call_music_api(self, api_url: str, song_name: str, timeout: int, retries: int = 3, delay: float = 1.5) -> Optional[dict]:
"""调用音乐API搜索歌曲带重试机制"""
for attempt in range(1, retries + 1):
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session:
params = {
"word": song_name,
"choose": 1 # 选择第一首
}
async with session.get(f"{api_url}/v2/music/netease", params=params) as response:
if response.status == 200:
data = await response.json()
if data.get("code") == 200:
return data.get("data", {})
else:
logger.warning(f"{self.get_log_prefix()} API返回错误: {data.get('message', '未知错误')}")
else:
logger.warning(f"{self.get_log_prefix()} API请求失败状态码: {response.status}")
except Exception as e:
logger.error(f"{self.get_log_prefix()}{attempt}次调用音乐API出错: {e}")
if attempt < retries:
await asyncio.sleep(delay)
return None
async def _send_detailed_music_info(self, music_info: dict):
"""发送详细音乐信息Command用"""
try:
song_id = music_info.get("id", "")
# 根据配置决定是否发送详细信息
if self.get_config("features.show_detailed_info", False):
song = music_info.get("song", "未知歌曲")
singer = music_info.get("singer", "未知歌手")
album = music_info.get("album", "未知专辑")
interval = music_info.get("interval", "未知时长")
message = f"🎵 歌曲:{song}\n"
message += f"👤 歌手:{singer}\n"
message += f"💿 专辑:{album}\n"
message += f"⏱️ 时长:{interval}\n"
await self.send_text(message)
# 发送音乐卡片
if song_id:
await self.send_type(message_type="music", content=song_id)
logger.info(f"{self.get_log_prefix()} 发送音乐卡片成功ID: {song_id}")
else:
logger.warning(f"{self.get_log_prefix()} 音乐ID为空无法发送音乐卡片")
except Exception as e:
logger.error(f"{self.get_log_prefix()} 发送详细音乐信息出错: {e}")
await self.send_text("❌ 发送音乐信息时出现错误")
# ===== 插件注册 =====
@register_plugin
class MusicPlugin(BasePlugin):
"""音乐点歌插件 - 基于网易云音乐API的智能点歌插件"""
plugin_name = "music_plugin"
plugin_description = "网易云音乐点歌插件,支持音乐搜索和点歌功能"
plugin_version = "1.0.0"
plugin_author = "Augment Agent"
enable_plugin = True
config_file_name = "config.toml"
dependencies = [] # 插件依赖列表
python_dependencies = ["aiohttp", "requests"] # Python包依赖列表
# 配置节描述
config_section_descriptions = {
"plugin": "插件基本配置",
"components": "组件启用控制",
"api": "API接口配置",
"music": "音乐功能配置",
"features": "功能开关配置"
}
# 配置Schema
config_schema = {
"plugin": {
"enabled": ConfigField(type=bool, default=True, description="是否启用插件")
},
"components": {
"action_enabled": ConfigField(type=bool, default=True, description="是否启用Action组件"),
"command_enabled": ConfigField(type=bool, default=True, description="是否启用Command组件")
},
"api": {
"base_url": ConfigField(
type=str,
default="https://api.vkeys.cn",
description="音乐API基础URL"
),
"timeout": ConfigField(type=int, default=10, description="API请求超时时间(秒)")
},
"music": {
"default_quality": ConfigField(
type=str,
default="9",
description="默认音质等级(1-9)"
),
"max_search_results": ConfigField(
type=int,
default=10,
description="最大搜索结果数"
)
},
"features": {
"show_cover": ConfigField(type=bool, default=True, description="是否显示专辑封面"),
"show_download_link": ConfigField(
type=bool,
default=False,
description="是否显示下载链接"
),
"show_detailed_info": ConfigField(type=bool, default=False, description="是否显示详细的音乐信息文本"),
"send_as_voice": ConfigField(type=bool, default=False, description="是否以语音消息发送音乐true=语音消息false=音乐卡片)")
}
}
def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]:
"""返回插件组件列表"""
components = []
# 根据配置决定是否启用组件
if self.get_config("components.action_enabled", True):
components.append((MusicSearchAction.get_action_info(), MusicSearchAction))
if self.get_config("components.command_enabled", True):
components.append((MusicCommand.get_command_info(), MusicCommand))
return components