855 协议版本-调整完毕内容
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
@@ -47,7 +45,6 @@ class BeautyLegPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
|
||||
@@ -6,6 +6,7 @@ import time
|
||||
import re # 添加re模块导入
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
@@ -15,6 +16,7 @@ from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotMan
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from utils.media_downloader import MediaDownloader
|
||||
from utils.string_utils import remove_trailing_content
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class DifyPlugin(MessagePluginInterface):
|
||||
@@ -58,7 +60,6 @@ class DifyPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -114,7 +115,7 @@ class DifyPlugin(MessagePluginInterface):
|
||||
|
||||
@plugin_stats_decorator(plugin_name="Dify聊天")
|
||||
@plugin_points_cost(2, "AI聊天消耗积分", Feature.AI_CAPABILITY)
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
@@ -122,6 +123,7 @@ class DifyPlugin(MessagePluginInterface):
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
|
||||
bot: WechatAPIClient = message.get("bot")
|
||||
# 处理被@的消息
|
||||
if message.get("is_at", False) and roomid:
|
||||
# 检查权限
|
||||
@@ -132,14 +134,14 @@ class DifyPlugin(MessagePluginInterface):
|
||||
query = re.sub(r"@.*?[\u2005|\s]", "", content).strip()
|
||||
|
||||
if not query:
|
||||
self.message_util.send_text("请在@我的同时提供问题内容", roomid, sender)
|
||||
await bot.send_text_message(roomid, "请在@我的同时提供问题内容", sender)
|
||||
return False, "没有提供问题内容"
|
||||
|
||||
# self.message_util.send_text_msg("⏳AI 正在加油,请稍候… 😊", roomid, sender)
|
||||
|
||||
try:
|
||||
# 调用Dify API获取回复
|
||||
response = self._chat_with_dify(roomid, sender, query)
|
||||
response = self._chat_with_dify((roomid if roomid else sender), sender, query)
|
||||
# 去除广告内容
|
||||
response = remove_trailing_content(response)
|
||||
|
||||
@@ -151,15 +153,15 @@ class DifyPlugin(MessagePluginInterface):
|
||||
self.message_util.send_file(response, roomid)
|
||||
else:
|
||||
# 如果是普通文本,使用发送文本方法
|
||||
self.message_util.send_text(response, roomid, sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), response, sender)
|
||||
return True, "发送成功"
|
||||
else:
|
||||
self.message_util.send_text("❌未能获取到回复,请稍后再试", roomid, sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), "❌未能获取到回复,请稍后再试", sender)
|
||||
return False, "未获取到回复"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理Dify聊天请求出错: {e}")
|
||||
self.message_util.send_text(f"❌请求出错:{str(e)}", roomid, sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), "❌未能获取到回复,请稍后再试", sender)
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
# 原有的命令处理逻辑
|
||||
@@ -168,8 +170,7 @@ class DifyPlugin(MessagePluginInterface):
|
||||
|
||||
# 检查命令格式
|
||||
if len(parts) < 2 or not parts[1].strip():
|
||||
self.message_util.send_text(f"{self.command_format}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), f"{self.command_format}", sender)
|
||||
return False, "命令格式错误"
|
||||
|
||||
# 检查权限
|
||||
@@ -199,16 +200,17 @@ class DifyPlugin(MessagePluginInterface):
|
||||
self.message_util.send_file(response, (roomid if roomid else sender))
|
||||
else:
|
||||
# 如果是普通文本,使用发送文本方法
|
||||
self.message_util.send_text(response, (roomid if roomid else sender), sender if roomid else "")
|
||||
await bot.send_text_message((roomid if roomid else sender), response,
|
||||
sender if roomid else "")
|
||||
return True, "发送成功"
|
||||
else:
|
||||
self.message_util.send_text("❌未能获取到回复,请稍后再试", (roomid if roomid else sender),
|
||||
await bot.send_text_message((roomid if roomid else sender), "❌未能获取到回复,请稍后再试",
|
||||
sender if roomid else "")
|
||||
return False, "未获取到回复"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理Dify聊天请求出错: {e}")
|
||||
self.message_util.send_text(f"❌请求出错:{str(e)}", (roomid if roomid else sender),
|
||||
await bot.send_text_message((roomid if roomid else sender), f"❌请求出错:{str(e)}",
|
||||
sender if roomid else "")
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
@@ -6,6 +5,8 @@ import traceback
|
||||
import requests
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
@@ -47,6 +48,7 @@ class DouyinParserPlugin(MessagePluginInterface):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.LOG = logger
|
||||
self.url_pattern = re.compile(r'https?://v\.douyin\.com/\w+/?')
|
||||
# 修改为使用插件目录下的down_load_dir文件夹
|
||||
self.download_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "down_load_dir")
|
||||
@@ -56,7 +58,6 @@ class DouyinParserPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import random
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
@@ -12,6 +13,7 @@ from utils.decorator.points_decorator import points_reward_decorator
|
||||
from utils.ai.game_chatgpt_qa import game_question_json, game_answer_json
|
||||
from db.connection import DBConnectionManager
|
||||
from db.encyclopedia import EncyclopediaDB
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class GameTaskPlugin(MessagePluginInterface):
|
||||
@@ -43,10 +45,11 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.LOG = logger
|
||||
self.bot: WechatAPIClient = None
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -70,7 +73,6 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
# 初始化数据库连接
|
||||
self.db_manager = DBConnectionManager.get_instance()
|
||||
self.encyclopedia_db = EncyclopediaDB(self.db_manager)
|
||||
|
||||
self.LOG.info(f"[{self.name}] 插件初始化完成,指令:{self._commands}")
|
||||
return True
|
||||
|
||||
@@ -106,7 +108,7 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
return 0
|
||||
|
||||
@plugin_stats_decorator(plugin_name="百科问答")
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
command = content.split(" ")[0].lower()
|
||||
@@ -115,6 +117,7 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
all_contacts = message.get("all_contacts", {})
|
||||
|
||||
self.bot = message.get("bot")
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
|
||||
# 检查权限
|
||||
@@ -126,22 +129,22 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
wx_nick_name = all_contacts.get(sender, sender)
|
||||
|
||||
if command == "/s":
|
||||
self._handle_join_game(sender, roomid, wx_nick_name)
|
||||
await self._handle_join_game(sender, roomid, wx_nick_name)
|
||||
return True, "加入游戏成功"
|
||||
elif command == "/t":
|
||||
self._handle_get_task(sender, roomid)
|
||||
await self._handle_get_task(sender, roomid)
|
||||
return True, "获取任务成功"
|
||||
elif command == "/a":
|
||||
# 这里传递整个消息对象给处理方法
|
||||
return self._handle_submit_answer(message)
|
||||
return await self._handle_submit_answer(message)
|
||||
elif command == "/r":
|
||||
self._handle_show_rank(sender, roomid)
|
||||
await self._handle_show_rank(sender, roomid)
|
||||
return True, "显示排行榜成功"
|
||||
elif command == "/l":
|
||||
self._handle_show_active_tasks(sender, roomid)
|
||||
await self._handle_show_active_tasks(sender, roomid)
|
||||
return True, "显示活跃任务成功"
|
||||
elif command == "/h":
|
||||
self._handle_list_uncompleted_tasks(sender, roomid)
|
||||
await self._handle_list_uncompleted_tasks(sender, roomid)
|
||||
return True, "列举未完成任务成功"
|
||||
else:
|
||||
self.message_util.send_text(f"❌未知命令!\n{self.command_format}",
|
||||
@@ -152,15 +155,15 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
self.LOG.error(f"处理消息出错: {e}")
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
def _handle_join_game(self, sender: str, roomid: str, wx_nick_name: str) -> None:
|
||||
async def _handle_join_game(self, sender: str, roomid: str, wx_nick_name: str) -> None:
|
||||
"""处理加入游戏请求"""
|
||||
try:
|
||||
# 检查并添加群聊
|
||||
if not self.encyclopedia_db.check_group_exists(roomid):
|
||||
self.encyclopedia_db.add_group(roomid)
|
||||
self.message_util.send_text(
|
||||
f"🎉 群 {roomid} 已就位,准备开燥!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎉 群 {roomid} 已就位,准备开燥!",
|
||||
sender
|
||||
)
|
||||
|
||||
@@ -168,22 +171,22 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
player = self.encyclopedia_db.get_player(sender, roomid)
|
||||
if not player:
|
||||
self.encyclopedia_db.add_player(sender, roomid, wx_nick_name)
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎉 哇塞,{wx_nick_name} 你来啦!\n"
|
||||
f"🌟 群 {roomid} 瞬间燃爆!\n"
|
||||
f"🎈 快来接任务,秀翻全场!指令: /t",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"加入游戏出错: {e}")
|
||||
self.message_util.send_text(
|
||||
f"😔 加入游戏出错,请稍后再试!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 加入游戏出错,请稍后再试!",
|
||||
sender
|
||||
)
|
||||
|
||||
def _handle_get_task(self, sender: str, roomid: str) -> None:
|
||||
async def _handle_get_task(self, sender: str, roomid: str) -> None:
|
||||
"""处理获取任务请求"""
|
||||
try:
|
||||
# 获取群内所有玩家
|
||||
@@ -194,35 +197,35 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
# 检查并添加群聊
|
||||
if not self.encyclopedia_db.check_group_exists(roomid):
|
||||
self.encyclopedia_db.add_group(roomid)
|
||||
self.message_util.send_text(
|
||||
f"🎉 群 {roomid} 已就位,准备开燥!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎉 群 {roomid} 已就位,准备开燥!",
|
||||
sender
|
||||
)
|
||||
|
||||
|
||||
# 获取用户昵称 (从all_contacts中获取可能不可行,因为这里没有all_contacts参数)
|
||||
# 使用sender作为临时昵称
|
||||
wx_nick_name = sender
|
||||
|
||||
|
||||
# 添加当前用户为玩家
|
||||
self.encyclopedia_db.add_player(sender, roomid, wx_nick_name)
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎉 哇塞,{wx_nick_name} 你是第一个玩家!\n"
|
||||
f"🌟 已自动为你加入游戏!\n"
|
||||
f"🎈 现在就为你准备题目...",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
|
||||
|
||||
# 更新玩家列表
|
||||
players = self.encyclopedia_db.get_all_players_in_group(roomid)
|
||||
|
||||
|
||||
player_dict = {p['player_id']: p['player_name'] for p in players}
|
||||
if sender not in player_dict:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😅 嘿,你谁啊?\n"
|
||||
f"🌟 先用 /s 报名,不然没法玩哦!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return
|
||||
@@ -241,32 +244,32 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
)
|
||||
|
||||
if not active_task_id:
|
||||
self.message_util.send_text(
|
||||
f"😔 任务创建失败,请稍后再试!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 任务创建失败,请稍后再试!",
|
||||
sender
|
||||
)
|
||||
return
|
||||
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎁 {player_dict[sender]},你的专属任务闪亮登场!\n"
|
||||
f"🎀 任务ID: {active_task_id}\n"
|
||||
f"🎈 问题:[{category}]{question}\n"
|
||||
f"🌼 积分:{score}\n"
|
||||
f"🌈 快上答案:/a {active_task_id} 答案",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"获取任务出错: {e}")
|
||||
self.message_util.send_text(
|
||||
f"😔 获取任务出错,请稍后再试!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 获取任务出错,请稍后再试!",
|
||||
sender
|
||||
)
|
||||
|
||||
@points_reward_decorator(calculate_game_points, "game", "百科答题奖励", Feature.TASK_GAME)
|
||||
def _handle_submit_answer(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_submit_answer(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理提交答案请求"""
|
||||
try:
|
||||
content = str(message.get("content", "")).strip()
|
||||
@@ -274,11 +277,11 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
roomid = message.get("roomid", "")
|
||||
parts = content.split(" ", 2)
|
||||
if len(parts) < 3:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😅 喂,格式不对啊!\n"
|
||||
f"🌟 正确姿势:/a [任务ID] [答案]\n"
|
||||
f"🎈 比如:/a 1 钒",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return False, "0"
|
||||
@@ -289,10 +292,10 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
# 获取玩家信息
|
||||
player = self.encyclopedia_db.get_player(sender, roomid)
|
||||
if not player:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😅 嘿,你是路人甲吗?\n"
|
||||
f"🌟 用 /s 先加入群 {roomid} 吧!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return False, "0"
|
||||
@@ -300,11 +303,11 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
player_name = player['player_name']
|
||||
|
||||
if not task_id.isdigit():
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😅 喂,任务ID得是数字好吗?\n"
|
||||
f"🌟 比如:1\n"
|
||||
f"🎈 别瞎搞,重新来!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return False, "0"
|
||||
@@ -315,20 +318,20 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
task_data = self.encyclopedia_db.get_task_by_id(roomid, active_task_id)
|
||||
|
||||
if not task_data:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 哎哟,任务 task_{active_task_id} 不翼而飞啦!\n"
|
||||
f"🌼 可能被别人抢先一步咯!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return False, "0"
|
||||
|
||||
if task_data['status'] == 'completed':
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😄 哈哈,你慢了一步!\n"
|
||||
f"🌟 任务 task_{active_task_id} 已经完结\n"
|
||||
f"🎈 快去抢新任务吧!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return False, "0"
|
||||
@@ -358,30 +361,31 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
self.encyclopedia_db.complete_task(active_task_id)
|
||||
|
||||
if sender == holder_id:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎉 {player_name} 你是天才吗?\n"
|
||||
f"🌟 任务:{question}\n"
|
||||
f"🎈 答对啦,简直无敌!\n"
|
||||
f"🌈 奖励:{points} 分\n"
|
||||
f"🎀 彩蛋:{description}",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
else:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"🎉 {player_name} 抢答王上线!\n"
|
||||
f"🌟 任务:{question}\n"
|
||||
f"🎈 原主:{holder_name} 被你截胡啦!\n"
|
||||
f"🌈 狂揽 {points} 分,太骚了!\n"
|
||||
f"🎀 彩蛋:{description}",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
else:
|
||||
# 扣除积分
|
||||
self.encyclopedia_db.update_player_points(sender, roomid, -1)
|
||||
points = -1
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😅 {player_name} 你这是要笑死我吗?\n"
|
||||
f"🌼 任务:{question}\n"
|
||||
f"🎈 你答:{answer}\n"
|
||||
@@ -389,7 +393,6 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
f"🌈 扣 1 分,别哭哦!\n"
|
||||
f"🎀 提示:{description}\n"
|
||||
f"🌟 任务ID: {active_task_id} 还能抢救一下!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
|
||||
@@ -398,17 +401,17 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
self.LOG.error(f"提交答案出错: {e}")
|
||||
return False, "0"
|
||||
|
||||
def _handle_show_rank(self, sender: str, roomid: str) -> None:
|
||||
async def _handle_show_rank(self, sender: str, roomid: str) -> None:
|
||||
"""处理显示排行榜请求"""
|
||||
try:
|
||||
# 获取排行榜
|
||||
ranks = self.encyclopedia_db.get_player_ranking(roomid, 10)
|
||||
|
||||
if not ranks:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 群 {roomid} 冷冷清清\n"
|
||||
f"🌟 快来一起燥起来吧!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return
|
||||
@@ -424,23 +427,23 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"显示排行榜出错: {e}")
|
||||
self.message_util.send_text(
|
||||
f"😔 获取排行榜出错,请稍后再试!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 获取排行榜出错,请稍后再试!",
|
||||
sender
|
||||
)
|
||||
|
||||
def _handle_show_active_tasks(self, sender: str, roomid: str) -> None:
|
||||
async def _handle_show_active_tasks(self, sender: str, roomid: str) -> None:
|
||||
"""处理显示活跃任务请求"""
|
||||
try:
|
||||
# 获取活跃任务
|
||||
tasks = self.encyclopedia_db.get_active_tasks_in_group(roomid)
|
||||
|
||||
if not tasks:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😄 群 {roomid} 现在一片祥和\n"
|
||||
f"🌟 没任务?快用 /t 搞一个!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return
|
||||
@@ -453,30 +456,30 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
f"🌼 大佬:{task['player_name']}\n"
|
||||
)
|
||||
|
||||
self.message_util.send_text(
|
||||
task_text,
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
task_text,
|
||||
sender
|
||||
)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"显示活跃任务出错: {e}")
|
||||
self.message_util.send_text(
|
||||
f"😔 获取活跃任务出错,请稍后再试!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 获取活跃任务出错,请稍后再试!",
|
||||
sender
|
||||
)
|
||||
|
||||
def _handle_list_uncompleted_tasks(self, sender: str, roomid: str) -> None:
|
||||
async def _handle_list_uncompleted_tasks(self, sender: str, roomid: str) -> None:
|
||||
"""处理列举未完成任务请求"""
|
||||
try:
|
||||
# 获取未完成任务
|
||||
tasks = self.encyclopedia_db.get_active_tasks_in_group(roomid)
|
||||
|
||||
if not tasks:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😄 群 {roomid} 全员开挂?\n"
|
||||
f"🌟 没未完成任务,快用 /t 再战!",
|
||||
(roomid if roomid else sender),
|
||||
sender
|
||||
)
|
||||
return
|
||||
@@ -489,20 +492,20 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
f"🌼 主人:{task['player_name']}\n"
|
||||
)
|
||||
|
||||
self.message_util.send_text(
|
||||
task_text,
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
task_text,
|
||||
sender
|
||||
)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"列举未完成任务出错: {e}")
|
||||
self.message_util.send_text(
|
||||
f"😔 获取未完成任务出错,请稍后再试!",
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"😔 获取未完成任务出错,请稍后再试!",
|
||||
sender
|
||||
)
|
||||
|
||||
def run_random_task_assignment(self) -> None:
|
||||
async def run_random_task_assignment(self) -> None:
|
||||
"""定时任务:整点触发,排除23:00-08:00"""
|
||||
current_hour = datetime.now().hour
|
||||
if current_hour >= 23 or current_hour < 9:
|
||||
@@ -538,14 +541,14 @@ class GameTaskPlugin(MessagePluginInterface):
|
||||
)
|
||||
|
||||
if active_task_id:
|
||||
self.message_util.send_text(
|
||||
await self.bot.send_text_message(
|
||||
group_id,
|
||||
f"🎁 新任务来袭,够不够刺激?\n"
|
||||
f"🎀 任务ID: {active_task_id}\n"
|
||||
f"🌟 幸运鹅:{holder_name}\n"
|
||||
f"🎈 问题:[{category}]{question}\n"
|
||||
f"🌼 积分:{score}\n"
|
||||
f"🌈 抢答格式:/a {active_task_id} 答案",
|
||||
group_id
|
||||
f"🌈 抢答格式:/a {active_task_id} 答案"
|
||||
)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"定时任务出错: {e}")
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import asyncio
|
||||
import threading
|
||||
import time # 添加这一行
|
||||
@@ -12,6 +11,7 @@ from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotMan
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from utils.ai.dify_news_analyze import dify_news_title_analyze
|
||||
from utils.markdown_to_image import convert_md_str_to_image
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
# 导入新闻抓取函数
|
||||
from .news_crawler import nbc, cnn, abc, fox, bbc
|
||||
@@ -46,11 +46,12 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.bot: WechatAPIClient = None
|
||||
self._news_tasks = {} # 存储正在进行的新闻抓取任务
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -90,13 +91,14 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
|
||||
@plugin_stats_decorator(plugin_name="全球政治经济新闻")
|
||||
@plugin_points_cost(5, "全球新闻消耗积分", Feature.NEWS)
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
self.bot: WechatAPIClient = message.get("bot")
|
||||
|
||||
# 检查权限
|
||||
if roomid and gbm.get_group_permission(roomid, Feature.NEWS) == PermissionStatus.DISABLED:
|
||||
@@ -106,8 +108,8 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
task_id = f"{sender}_{roomid}_{int(time.time())}"
|
||||
|
||||
# 发送等待消息
|
||||
self.message_util.send_text("🌍正在获取全球新闻,请稍候...",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender), "🌍正在获取全球新闻,请稍候...", sender)
|
||||
|
||||
# 启动异步任务
|
||||
self._start_news_task(task_id, sender, roomid)
|
||||
@@ -125,7 +127,7 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
self._news_tasks[task_id] = thread
|
||||
self.LOG.info(f"启动新闻获取任务: {task_id}")
|
||||
|
||||
def _fetch_news_thread(self, task_id: str, sender: str, roomid: str):
|
||||
async def _fetch_news_thread(self, task_id: str, sender: str, roomid: str):
|
||||
"""在单独的线程中运行异步新闻获取任务"""
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
@@ -137,15 +139,15 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
if news_result:
|
||||
# 发送新闻图片
|
||||
receiver = roomid if roomid else sender
|
||||
self.message_util.send_image(news_result, receiver)
|
||||
self.message_util.send_text("🌍全球新闻获取完成!", receiver, sender)
|
||||
await self.bot.send_image_message(receiver, news_result)
|
||||
await self.bot.send_text_message("🌍全球新闻获取完成!", receiver, sender)
|
||||
else:
|
||||
self.message_util.send_text("❌获取新闻失败,请稍后再试",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender), "❌获取新闻失败,请稍后再试", sender)
|
||||
except Exception as e:
|
||||
self.LOG.error(f"新闻获取任务出错: {e}")
|
||||
self.message_util.send_text(f"❌获取新闻出错: {str(e)}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"❌获取新闻出错: {str(e)}",
|
||||
sender)
|
||||
finally:
|
||||
# 清理任务
|
||||
if task_id in self._news_tasks:
|
||||
|
||||
@@ -7,20 +7,10 @@ Created Date: 2024-05-01
|
||||
import requests
|
||||
from time import localtime, sleep
|
||||
from lxml import etree
|
||||
import logging
|
||||
from loguru import logger
|
||||
from datetime import datetime
|
||||
import time
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s',
|
||||
handlers=[
|
||||
logging.FileHandler(f'global_news_{datetime.now().strftime("%Y%m%d")}.log'),
|
||||
logging.StreamHandler()
|
||||
]
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 请求配置
|
||||
HEADERS = {
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import redis
|
||||
import re
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from gewechat_client import GewechatClient
|
||||
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.robot_cmd.robot_command import GroupBotManager
|
||||
from utils.wechat.contact_manager import ContactManager
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
@@ -45,10 +43,10 @@ class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
# Redis 中存储群组映射的前缀
|
||||
self.mapping_prefix = "group:group_mapping:"
|
||||
self._commands = []
|
||||
self.bot: WechatAPIClient = None
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 获取群管理器
|
||||
@@ -56,8 +54,6 @@ class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
# 获取Redis连接池
|
||||
self.redis_pool = context.get("redis_pool")
|
||||
|
||||
self.clent:GewechatClient = context.get("clent")
|
||||
self.message_util: MessageUtil = context.get("message_util")
|
||||
# 从配置中获取命令和启用状态
|
||||
plugin_config = self._config.get("GroupAutoInvite", {})
|
||||
self._commands = plugin_config.get("command", ["#加群配置"])
|
||||
@@ -105,7 +101,7 @@ class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
return False
|
||||
|
||||
@plugin_stats_decorator(plugin_name="自动加群功能")
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
@@ -114,25 +110,26 @@ class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
|
||||
self.bot: WechatAPIClient = message.get("bot")
|
||||
# 处理加群配置命令
|
||||
if content.startswith("#加群配置|"):
|
||||
return self._handle_config_command(content, sender, roomid, gbm)
|
||||
return await self._handle_config_command(content, sender, roomid, gbm)
|
||||
|
||||
# 处理加群请求
|
||||
match = re.search(r"^#加群\s+(\w+)$", content)
|
||||
if match:
|
||||
return self._handle_join_request(match.group(1), sender, roomid, gbm)
|
||||
return await self._handle_join_request(match.group(1), sender, roomid, gbm)
|
||||
|
||||
return False, "无法处理的消息"
|
||||
|
||||
def _handle_config_command(self, content: str, sender: str, roomid: str, gbm: GroupBotManager) -> Tuple[
|
||||
async def _handle_config_command(self, content: str, sender: str, roomid: str, gbm: GroupBotManager) -> Tuple[
|
||||
bool, Optional[str]]:
|
||||
"""处理配置命令"""
|
||||
# 检查是否为管理员
|
||||
admin_list = self.gbm.get_admin_list()
|
||||
if sender not in admin_list:
|
||||
self.message_util.send_text("⚠️ 权限不足,只有管理员才能配置群邀请功能",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), "⚠️ 权限不足,只有管理员才能配置群邀请功能",
|
||||
sender)
|
||||
return True, "权限不足"
|
||||
|
||||
# 解析命令
|
||||
@@ -140,10 +137,10 @@ class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
result = self.process_command(command)
|
||||
|
||||
# 发送结果
|
||||
self.message_util.send_text(result, (roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), result, sender)
|
||||
return True, "配置命令处理成功"
|
||||
|
||||
def _handle_join_request(self, key: str, sender: str, roomid: str, gbm: GroupBotManager) -> Tuple[
|
||||
async def _handle_join_request(self, key: str, sender: str, roomid: str, gbm: GroupBotManager) -> Tuple[
|
||||
bool, Optional[str]]:
|
||||
"""处理加群请求"""
|
||||
try:
|
||||
@@ -152,29 +149,29 @@ class GroupAutoInvitePlugin(MessagePluginInterface):
|
||||
|
||||
# 检查是否找到群ID
|
||||
if isinstance(group_id, str) and "没有关联的群ID" in group_id:
|
||||
self.message_util.send_text(f"⚠️ 未找到关键词 '{key}' 对应的群聊", sender)
|
||||
await self.bot.send_text_message(sender, f"⚠️ 未找到关键词 '{key}' 对应的群聊")
|
||||
return True, "未找到群聊"
|
||||
# 判断是否在群里面,如果在,则不添加
|
||||
con = ContactManager.get_instance()
|
||||
members = con.get_group_members(group_id)
|
||||
# 如果在群里面,则不添加
|
||||
if sender in members:
|
||||
self.message_util.send_text(f"⚠️ 你已经在群聊中了,无需重复添加", sender)
|
||||
await self.bot.send_text_message(sender, f"⚠️ 你已经在群聊中了,无需重复添加")
|
||||
return True, "你已经在群聊中了"
|
||||
# 发送邀请
|
||||
self.LOG.info(f"邀请用户 {sender} 加入群 {group_id}")
|
||||
result = self.message_util.invite_member(group_id, sender)
|
||||
result = await self.bot.invite_chatroom_member(sender, group_id)
|
||||
|
||||
if result:
|
||||
self.message_util.send_text(f"✅ 已发送邀请,请查看群聊邀请通知", sender)
|
||||
await self.bot.send_text_message(sender, f"✅ 已发送邀请,请查看群聊邀请通知")
|
||||
return True, "邀请发送成功"
|
||||
else:
|
||||
self.message_util.send_text(f"❌ 邀请发送失败,请稍后再试", sender)
|
||||
await self.bot.send_text_message(sender, f"❌ 邀请发送失败,请稍后再试")
|
||||
return False, "邀请发送失败"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理加群请求出错: {e}")
|
||||
self.message_util.send_text(f"❌ 处理加群请求出错: {e}", sender)
|
||||
await self.bot.send_text_message(sender, f"❌ 处理加群请求出错: {e}")
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
def add_mapping(self, key, group_id):
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
@@ -6,16 +5,16 @@ import xml.etree.ElementTree as ET
|
||||
|
||||
import dacite
|
||||
|
||||
from gewechat.client import gewe_client
|
||||
from gewechat.response.model.group.chatroom_member_detail import ChatroomMemberDetail
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager
|
||||
from message_util import MessageUtil # 导入消息工具类
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class GroupMemberChangePlugin(MessagePluginInterface):
|
||||
"""群成员变更监控插件"""
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "群成员变更监控"
|
||||
@@ -46,7 +45,6 @@ class GroupMemberChangePlugin(MessagePluginInterface):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
@@ -58,7 +56,11 @@ class GroupMemberChangePlugin(MessagePluginInterface):
|
||||
self.LOG.info(f"{self.name} 插件初始化完成")
|
||||
return True
|
||||
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
def can_process(self, message: Dict[str, Any]) -> bool:
|
||||
"""检查是否可以处理该消息"""
|
||||
return True
|
||||
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理接收到的消息"""
|
||||
|
||||
content = str(message.get("content", "")).strip()
|
||||
@@ -67,6 +69,7 @@ class GroupMemberChangePlugin(MessagePluginInterface):
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
|
||||
bot: WechatAPIClient = message.get("bot")
|
||||
# 检查权限
|
||||
if roomid and gbm.get_group_permission(roomid, Feature.GROUP_MEMBER_CHANGE) == PermissionStatus.DISABLED:
|
||||
return False, "没有权限"
|
||||
@@ -114,18 +117,18 @@ class GroupMemberChangePlugin(MessagePluginInterface):
|
||||
wxid = member["wxid"]
|
||||
nickname = member["nickname"]
|
||||
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
# now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
member_wxids = [wxid]
|
||||
profile: ChatroomMemberDetail = dacite.from_dict(ChatroomMemberDetail,
|
||||
gewe_client.client.get_chatroom_member_detail(
|
||||
gewe_client.client.app_id,
|
||||
member_wxids))
|
||||
if profile.ret == 200:
|
||||
gewe_client.client.post_link(gewe_client.client.app_id, sender,
|
||||
title=f"👏欢迎 {nickname} 加入群聊!🎉",
|
||||
description=f"⌚时间:{now}\n",
|
||||
url="https://hot.imsyy.top/#/",
|
||||
thumb_url=profile.data[0].big_head_img_url)
|
||||
|
||||
await bot.send_at_message(roomid, f"👏欢迎 {nickname} 加入群聊!🎉", member_wxids)
|
||||
# members = await bot.get_contract_detail(member_wxids, roomid)
|
||||
|
||||
# if members:
|
||||
# gewe_client.client.post_link(gewe_client.client.app_id, sender,
|
||||
# title=f"👏欢迎 {nickname} 加入群聊!🎉",
|
||||
# description=f"⌚时间:{now}\n",
|
||||
# url="https://hot.imsyy.top/#/",
|
||||
# thumb_url=profile.data[0].big_head_img_url)
|
||||
return True, "已发送进群欢迎语"
|
||||
return False, "无需执行"
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import logging
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from gewechat.call_back_message.message import WxMessage
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
@@ -9,6 +7,7 @@ from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.wechat.contact_manager import ContactManager
|
||||
from db.connection import DBConnectionManager
|
||||
from db.group_virtual_redis import GroupVirtualRedisDB
|
||||
from wechat_ipad.models.message import WxMessage
|
||||
|
||||
|
||||
class GroupVirtualPlugin(MessagePluginInterface):
|
||||
@@ -46,7 +45,6 @@ class GroupVirtualPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -97,7 +95,7 @@ class GroupVirtualPlugin(MessagePluginInterface):
|
||||
"""处理消息"""
|
||||
roomid = message.get("roomid", "")
|
||||
sender = message.get("sender", "")
|
||||
full_wx_msg: WxMessage = message.get("full_wx_msg", "")
|
||||
full_wx_msg: WxMessage = message.get("full_wx_msg")
|
||||
# 检查是否是机器人自己发送的消息
|
||||
if full_wx_msg.from_self():
|
||||
return False, "不转发自己的消息"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
from typing import Dict, Any, List, Tuple, Optional
|
||||
|
||||
from message_util import MessageUtil
|
||||
@@ -40,7 +40,7 @@ class MessageRecallPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
self.event_system = context.get("event_system")
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
from loguru import logger
|
||||
import pytz
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
|
||||
from db.connection import DBConnectionManager
|
||||
from message_util import MessageUtil
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
@@ -16,6 +14,7 @@ import random
|
||||
import os
|
||||
|
||||
from utils.decorator.points_decorator import points_reward_decorator
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class MessageSignPlugin(MessagePluginInterface):
|
||||
@@ -56,15 +55,15 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
self.vocab_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
||||
"resource", "6 托福-乱序.txt")
|
||||
self.vocab_list = []
|
||||
self.bot: WechatAPIClient = None
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
self.event_system = context.get("event_system")
|
||||
self.message_util: MessageUtil = context.get("message_util")
|
||||
self.gbm = context.get("gbm")
|
||||
self.all_contacts = context.get("all_contacts", {})
|
||||
|
||||
@@ -178,15 +177,15 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
# 使用数据库中已更新的连签天数
|
||||
streak = user_record.get('signin_streak', 1)
|
||||
# 如果今天刚签到,连签天数已经+1,所以这里不需要再加1
|
||||
|
||||
|
||||
# 计算积分
|
||||
points = self.calculate_points(streak)
|
||||
|
||||
|
||||
return points
|
||||
|
||||
# 修改 process_message 方法,作为路由分发
|
||||
@plugin_stats_decorator(plugin_name="签到系统")
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
@@ -194,6 +193,7 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
self.bot = message.get("bot")
|
||||
|
||||
# 检查权限
|
||||
if roomid and gbm.get_group_permission(roomid, Feature.SIGNIN) == PermissionStatus.DISABLED:
|
||||
@@ -201,17 +201,17 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
|
||||
# 处理补签命令
|
||||
if command in self._makeup_commands:
|
||||
return self._handle_makeup_sign(message)
|
||||
return await self._handle_makeup_sign(message)
|
||||
|
||||
# 处理正常签到命令
|
||||
if command in self._commands:
|
||||
return self._handle_sign_in(message)
|
||||
return await self._handle_sign_in(message)
|
||||
|
||||
return False, "不支持的命令"
|
||||
|
||||
# 添加签到处理方法,应用积分奖励装饰器
|
||||
@points_reward_decorator(calculate_sign_in_points, "checkin", "每日签到奖励", Feature.SIGNIN)
|
||||
def _handle_sign_in(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_sign_in(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理签到请求"""
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
@@ -237,8 +237,8 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
|
||||
# 如果 sign_stat 已经大于或等于今天的零点,则认为用户已经签到过了
|
||||
if sign_stat >= today_start:
|
||||
self.message_util.send_text(f"您今天已经签到过了!",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender), f"您今天已经签到过了!", sender)
|
||||
return False, "已签到"
|
||||
|
||||
# 在_handle_sign_in方法中,修改断签处理逻辑
|
||||
@@ -313,13 +313,13 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
daily_vocab = self.get_random_vocabulary()
|
||||
output += f"\n今日词汇:{daily_vocab}"
|
||||
|
||||
self.message_util.send_text(output, (roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), output, sender)
|
||||
return True, "签到成功"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理签到请求出错: {e}")
|
||||
self.message_util.send_text(f"签到出错:{e}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"签到出错:{e}",
|
||||
sender)
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
def reset_today_count_if_needed(self):
|
||||
@@ -350,7 +350,7 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
|
||||
# 修改_handle_makeup_sign方法,实现连签恢复功能
|
||||
|
||||
def _handle_makeup_sign(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_makeup_sign(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理补签请求"""
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
@@ -370,9 +370,9 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
|
||||
# 检查用户是否有签到记录
|
||||
if not user_record:
|
||||
self.message_util.send_text(
|
||||
"❌ 您还没有签到记录,请先进行签到!",
|
||||
(roomid if roomid else sender), sender
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
"❌ 您还没有签到记录,请先进行签到!", sender
|
||||
)
|
||||
return True, "无签到记录"
|
||||
|
||||
@@ -403,27 +403,26 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
else:
|
||||
# 昨天已经签到了或者断签超过一天,不需要补签
|
||||
self.LOG.info(f"不符合补签条件,last_sign_date: {last_sign_date}, sign_stat: {sign_stat}")
|
||||
self.message_util.send_text(
|
||||
"❌ 您昨天已经签到过了或断签超过一天,不符合补签条件!",
|
||||
(roomid if roomid else sender), sender
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender), "❌ 您昨天已经签到过了或断签超过一天,不符合补签条件!", sender
|
||||
)
|
||||
return True, "不符合补签条件"
|
||||
else:
|
||||
# 今天未签到,检查是否符合补签条件(只能补签昨天)
|
||||
if not last_sign_date or last_sign_date < day_before_yesterday:
|
||||
self.LOG.info(f"断签超过一天,last_sign_date: {last_sign_date}")
|
||||
self.message_util.send_text(
|
||||
"❌ 只能补签断签一天的情况!您已断签超过一天或没有签到记录。",
|
||||
(roomid if roomid else sender), sender
|
||||
)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
"❌ 只能补签断签一天的情况!您已断签超过一天或没有签到记录。",
|
||||
sender
|
||||
)
|
||||
return True, "不符合补签条件"
|
||||
|
||||
if last_sign_date >= yesterday:
|
||||
self.LOG.info(f"昨天已签到,last_sign_date: {last_sign_date}")
|
||||
self.message_util.send_text(
|
||||
"❌ 您昨天已经签到过了,不需要补签!",
|
||||
(roomid if roomid else sender), sender
|
||||
)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
"❌ 您昨天已经签到过了,不需要补签!",
|
||||
sender
|
||||
)
|
||||
return True, "无需补签"
|
||||
|
||||
# 检查用户积分是否足够
|
||||
@@ -432,10 +431,10 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
user_points = points_db.get_user_points(sender, roomid)
|
||||
|
||||
if not user_points or user_points["total_points"] < self.makeup_cost:
|
||||
self.message_util.send_text(
|
||||
f"❌ 积分不足!补签需要 {self.makeup_cost} 积分,您当前只有 {user_points.get('total_points', 0)} 积分。",
|
||||
(roomid if roomid else sender), sender
|
||||
)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"❌ 积分不足!补签需要 {self.makeup_cost} 积分,您当前只有 {user_points.get('total_points', 0)} 积分。",
|
||||
sender
|
||||
)
|
||||
return True, "积分不足"
|
||||
|
||||
# 扣除积分
|
||||
@@ -445,10 +444,10 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
)
|
||||
|
||||
if not deduct_success:
|
||||
self.message_util.send_text(
|
||||
f"❌ 扣除积分失败:{deduct_result.get('error', '未知错误')}",
|
||||
(roomid if roomid else sender), sender
|
||||
)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"❌ 扣除积分失败:{deduct_result.get('error', '未知错误')}",
|
||||
sender
|
||||
)
|
||||
return True, "扣除积分失败"
|
||||
|
||||
# 在_handle_makeup_sign方法中,修改计算新连签天数的逻辑
|
||||
@@ -504,17 +503,17 @@ class MessageSignPlugin(MessagePluginInterface):
|
||||
|
||||
success_message += f"💰 当前积分:{user_points['total_points'] - self.makeup_cost}"
|
||||
|
||||
self.message_util.send_text(
|
||||
success_message,
|
||||
(roomid if roomid else sender), sender
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
success_message, sender
|
||||
)
|
||||
|
||||
return True, "补签成功"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理补签请求出错: {e}")
|
||||
self.message_util.send_text(
|
||||
f"❌ 补签出错:{e}",
|
||||
(roomid if roomid else sender), sender
|
||||
await self.bot.send_text_message(
|
||||
(roomid if roomid else sender),
|
||||
f"❌ 补签出错:{e}", sender
|
||||
)
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import requests
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from gewechat.client import gewe_client
|
||||
from gewechat.response.gewe_resp import GeweResponse
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class MusicPlugin(MessagePluginInterface):
|
||||
@@ -43,7 +42,7 @@ class MusicPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -81,7 +80,7 @@ class MusicPlugin(MessagePluginInterface):
|
||||
|
||||
@plugin_stats_decorator(plugin_name="音乐点播")
|
||||
@plugin_points_cost(2, "音乐点播消耗积分", Feature.MUSIC)
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
@@ -89,11 +88,12 @@ class MusicPlugin(MessagePluginInterface):
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
bot: WechatAPIClient = message.get("bot")
|
||||
|
||||
# 检查命令格式
|
||||
if len(content.split(" ")) == 1:
|
||||
self.message_util.send_text(f"❌命令格式错误!\n{self.command_format}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), f"❌命令格式错误!\n{self.command_format}"
|
||||
, sender)
|
||||
return False, "命令格式错误"
|
||||
|
||||
# 检查权限
|
||||
@@ -107,12 +107,11 @@ class MusicPlugin(MessagePluginInterface):
|
||||
# 搜索歌曲
|
||||
song_info = self._search_song(user_song_name)
|
||||
if not song_info or not song_info.get("play_url"):
|
||||
self.message_util.send_text(f"❌未找到歌曲:{user_song_name}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), f"❌未找到歌曲:{user_song_name}", sender)
|
||||
return False, "未找到歌曲"
|
||||
|
||||
# 发送音乐
|
||||
self._send_music_message(song_info, roomid or sender)
|
||||
await self._send_music_message(bot, song_info, roomid or sender)
|
||||
return True, "发送成功"
|
||||
|
||||
except Exception as e:
|
||||
@@ -143,7 +142,7 @@ class MusicPlugin(MessagePluginInterface):
|
||||
self.LOG.error(f"搜索歌曲出错: {e}")
|
||||
return {}
|
||||
|
||||
def _send_music_message(self, song_info: Dict[str, Any], receiver: str) -> bool:
|
||||
async def _send_music_message(self, bot: WechatAPIClient, song_info: Dict[str, Any], receiver: str) -> bool:
|
||||
"""发送音乐消息"""
|
||||
try:
|
||||
song_name = song_info.get("song_name", "")
|
||||
@@ -201,11 +200,11 @@ class MusicPlugin(MessagePluginInterface):
|
||||
</appinfo>
|
||||
<commenturl />
|
||||
</msg>"""
|
||||
resp = gewe_client.client.post_app_msg(gewe_client.client.app_id, receiver, xml_message)
|
||||
data = GeweResponse(resp)
|
||||
self.LOG.info(f"发送音乐消息:{data}")
|
||||
if data.is_success:
|
||||
return True
|
||||
|
||||
self.LOG.info(f"发送音乐消息:{xml_message}")
|
||||
res = await bot.send_app_message(wxid=receiver, xml=xml_message, type=0)
|
||||
self.LOG.info(f"发送音乐消息 res:{res}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"发送音乐消息出错: {e}")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import os
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
@@ -53,7 +53,7 @@ class PluginManagerPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
from db.connection import DBConnectionManager
|
||||
from db.points_db import PointsDBOperator, PointSource
|
||||
from message_util import MessageUtil
|
||||
@@ -15,6 +14,8 @@ from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotMan
|
||||
|
||||
import mysql.connector.pooling
|
||||
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class PointTradePlugin(MessagePluginInterface):
|
||||
"""积分交易插件"""
|
||||
@@ -46,15 +47,15 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.db_pool = None
|
||||
self.bot: WechatAPIClient = None
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
self.event_system = context.get("event_system")
|
||||
self.message_util: MessageUtil = context.get("message_util")
|
||||
self.gbm = context.get("gbm")
|
||||
self.db_manager = DBConnectionManager.get_instance()
|
||||
|
||||
@@ -120,7 +121,7 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
return command in self._commands
|
||||
|
||||
@plugin_stats_decorator(plugin_name="积分交易")
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
@@ -129,6 +130,7 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
xml = message.get("xml", "")
|
||||
self.bot: WechatAPIClient = message.get("bot")
|
||||
|
||||
# 检查权限
|
||||
if roomid and gbm.get_group_permission(roomid, Feature.POINT_TRADE) == PermissionStatus.DISABLED:
|
||||
@@ -136,21 +138,21 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 处理不同的命令
|
||||
if command[0] == "我的积分":
|
||||
return self._handle_my_points(message)
|
||||
return await self._handle_my_points(message)
|
||||
elif command[0] == "积分排行":
|
||||
return self._handle_points_ranking(message)
|
||||
return await self._handle_points_ranking(message)
|
||||
elif command[0] == "打劫":
|
||||
return self._handle_rob_points(message)
|
||||
return await self._handle_rob_points(message)
|
||||
elif command[0] == "保释":
|
||||
return self._handle_bailout(message)
|
||||
return await self._handle_bailout(message)
|
||||
elif command[0] in self._commands:
|
||||
return self._handle_transfer_points(message)
|
||||
return await self._handle_transfer_points(message)
|
||||
else:
|
||||
self.message_util.send_text(f"❌未知命令!{self.command_format}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"❌未知命令!{self.command_format}",
|
||||
sender)
|
||||
return True, "未知命令"
|
||||
|
||||
def _handle_transfer_points(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_transfer_points(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理积分转账命令"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
command = content.split(" ")
|
||||
@@ -160,21 +162,23 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 检查命令格式
|
||||
if len(command) < 3:
|
||||
self.message_util.send_text(f"❌命令格式错误!积分转账 积分数 @用户",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"❌命令格式错误!积分转账 积分数 @用户",
|
||||
sender)
|
||||
return True, "命令格式错误"
|
||||
|
||||
# 检查积分数是否为正整数
|
||||
if not command[1].isdigit():
|
||||
self.message_util.send_text(f"🈚️转账积分无效(必须为正整数!) \n积分转账 积分数 @用户",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"🈚️转账积分无效(必须为正整数!) \n积分转账 积分数 @用户",
|
||||
sender)
|
||||
return True, "积分无效"
|
||||
|
||||
# 检查@用户是否有效
|
||||
at_users = self.at_list(xml)
|
||||
if len(at_users) != 1:
|
||||
self.message_util.send_text(f"转账失败❌\n🈚️转账人无效! \n积分转账 积分数 @用户",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"转账失败❌\n🈚️转账人无效! \n积分转账 积分数 @用户",
|
||||
sender)
|
||||
return True, "转账人无效"
|
||||
|
||||
reward_points = int(command[1])
|
||||
@@ -193,13 +197,13 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
error_msg = result.get("error", "未知错误")
|
||||
if "积分不足" in error_msg:
|
||||
current_points = result.get("current_points", 0)
|
||||
self.message_util.send_text(
|
||||
f"❌转账失败!\n你的积分不足以进行转账!当前积分:{current_points},你需要 {reward_points} 积分。",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"❌转账失败!\n你的积分不足以进行转账!当前积分:{current_points},你需要 {reward_points} 积分。",
|
||||
sender)
|
||||
else:
|
||||
self.message_util.send_text(
|
||||
f"❌转账失败!\n{error_msg}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"❌转账失败!\n{error_msg}",
|
||||
sender)
|
||||
return True, f"转账失败: {error_msg}"
|
||||
|
||||
# 获取转账后的积分信息
|
||||
@@ -220,16 +224,16 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
f"👤{to_user_name} 当前积分: {to_user.get('total_points', 0)}"
|
||||
)
|
||||
|
||||
self.message_util.send_text(output, (roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), output, sender)
|
||||
return True, "转账成功"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"积分交易出错: {e}")
|
||||
self.message_util.send_text(f"❌积分交易失败!请稍后重试。错误: {str(e)}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"❌积分交易失败!请稍后重试。错误: {str(e)}",
|
||||
sender)
|
||||
return True, f"处理出错: {str(e)}"
|
||||
|
||||
def _handle_my_points(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_my_points(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理查询个人积分命令"""
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
@@ -239,8 +243,9 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
user_points = self.points_db.get_user_points(sender, roomid)
|
||||
|
||||
if not user_points:
|
||||
self.message_util.send_text(f"❌未找到你的积分记录!请先参与积分活动[签到,答题/t]。",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender),
|
||||
f"❌未找到你的积分记录!请先参与积分活动[签到,答题/t]。",
|
||||
sender)
|
||||
return False, "未找到积分记录"
|
||||
|
||||
# 获取用户昵称
|
||||
@@ -295,22 +300,22 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
f"{recent_txs}"
|
||||
)
|
||||
|
||||
self.message_util.send_text(output, (roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), output, sender)
|
||||
return True, "查询积分成功"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"查询积分出错: {e}")
|
||||
self.message_util.send_text(f"❌查询积分失败!请稍后重试。错误: {str(e)}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"❌查询积分失败!请稍后重试。错误: {str(e)}",
|
||||
sender)
|
||||
return True, f"处理出错: {str(e)}"
|
||||
|
||||
def _handle_points_ranking(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_points_ranking(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理积分排行榜命令"""
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
|
||||
if not roomid:
|
||||
self.message_util.send_text("❌积分排行榜仅在群聊中可用!", sender, "")
|
||||
await self.bot.send_text_message(sender, "❌积分排行榜仅在群聊中可用!", "")
|
||||
return True, "非群聊环境"
|
||||
|
||||
try:
|
||||
@@ -318,7 +323,7 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
ranking = self.points_db.get_points_ranking(roomid, 10)
|
||||
|
||||
if not ranking:
|
||||
self.message_util.send_text("❌暂无积分排行数据!请先参与积分活动。", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, "❌暂无积分排行数据!请先参与积分活动。", sender)
|
||||
return True, "无排行数据"
|
||||
|
||||
# 构建排行榜消息
|
||||
@@ -343,12 +348,12 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
f"更新时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
)
|
||||
|
||||
self.message_util.send_text(output, roomid, sender)
|
||||
await self.bot.send_text_message(roomid, output, sender)
|
||||
return True, "查询排行榜成功"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"查询积分排行榜出错: {e}")
|
||||
self.message_util.send_text(f"❌查询积分排行榜失败!请稍后重试。错误: {str(e)}", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌查询积分排行榜失败!请稍后重试。错误: {str(e)}", sender)
|
||||
return True, f"处理出错: {str(e)}"
|
||||
|
||||
def at_list(self, xml):
|
||||
@@ -438,7 +443,7 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
self.LOG.error(f"更新用户积分失败: {e}")
|
||||
raise
|
||||
|
||||
def _handle_rob_points(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_rob_points(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理打劫积分命令"""
|
||||
import random
|
||||
import time
|
||||
@@ -451,13 +456,13 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 检查是否在群聊中
|
||||
if not roomid:
|
||||
self.message_util.send_text("❌打劫功能仅在群聊中可用!", sender, "")
|
||||
await self.bot.send_text_message(sender, "❌打劫功能仅在群聊中可用!", "")
|
||||
return True, "非群聊环境"
|
||||
|
||||
# 检查时间限制 - 只允许在18:00-21:00之间打劫
|
||||
current_hour = datetime.now().hour
|
||||
if current_hour < 18 or current_hour >= 21:
|
||||
self.message_util.send_text("❌打劫功能仅在晚上18:00-21:00之间开放!请在开放时间再来。", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, "❌打劫功能仅在晚上18:00-21:00之间开放!请在开放时间再来。", sender)
|
||||
return True, "时间限制"
|
||||
|
||||
# 检查是否在押
|
||||
@@ -466,8 +471,10 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
remaining_time = prison_status['end_time'] - datetime.now()
|
||||
hours = int(remaining_time.total_seconds() / 3600)
|
||||
minutes = int((remaining_time.total_seconds() % 3600) / 60)
|
||||
self.message_util.send_text(f"❌你正在服刑!\n剩余时间: {hours}小时{minutes}分钟\n可请求他人花费30积分保释。", roomid,
|
||||
sender)
|
||||
await self.bot.send_text_message(
|
||||
f"❌你正在服刑!\n剩余时间: {hours}小时{minutes}分钟\n可请求他人花费30积分保释。",
|
||||
roomid,
|
||||
sender)
|
||||
return True, "在押状态"
|
||||
|
||||
# 检查冷却时间
|
||||
@@ -478,15 +485,16 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
if time_passed < self.rob_cooldown:
|
||||
remaining_time = int(self.rob_cooldown - time_passed)
|
||||
minutes, seconds = divmod(remaining_time, 60)
|
||||
self.message_util.send_text(f"❌你最近已经打劫过了,需要冷却 {minutes}分{seconds}秒 后才能再次打劫!",
|
||||
roomid, sender)
|
||||
await self.bot.send_text_message(roomid,
|
||||
f"❌你最近已经打劫过了,需要冷却 {minutes}分{seconds}秒 后才能再次打劫!",
|
||||
sender)
|
||||
return True, "冷却中"
|
||||
|
||||
# 检查@用户是否有效
|
||||
at_users = self.at_list(xml)
|
||||
if len(at_users) != 1:
|
||||
self.message_util.send_text(f"打劫失败❌\n请指定一个打劫目标!\n打劫 @用户",
|
||||
roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"打劫失败❌\n请指定一个打劫目标!\n打劫 @用户",
|
||||
sender)
|
||||
return True, "目标无效"
|
||||
|
||||
target_wxid = next(iter(at_users))
|
||||
@@ -494,7 +502,7 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 不能打劫自己
|
||||
if target_wxid == robber_wxid:
|
||||
self.message_util.send_text("❌你不能打劫自己!", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, "❌你不能打劫自己!", sender)
|
||||
return True, "不能打劫自己"
|
||||
|
||||
try:
|
||||
@@ -503,11 +511,11 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
target_points = self.points_db.get_user_points(target_wxid, roomid)
|
||||
|
||||
if not robber_points:
|
||||
self.message_util.send_text("❌你没有积分记录,无法进行打劫!请先参与积分活动。", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, "❌你没有积分记录,无法进行打劫!请先参与积分活动。", sender)
|
||||
return True, "打劫者无积分"
|
||||
|
||||
if not target_points:
|
||||
self.message_util.send_text("❌目标没有积分记录,无法进行打劫!", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, "❌目标没有积分记录,无法进行打劫!", sender)
|
||||
return True, "目标无积分"
|
||||
|
||||
robber_total = robber_points.get('total_points', 0)
|
||||
@@ -515,11 +523,12 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 检查最低积分要求
|
||||
if robber_total < self.rob_min_points:
|
||||
self.message_util.send_text(f"❌你的积分不足 {self.rob_min_points} 点,无法进行打劫!", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌你的积分不足 {self.rob_min_points} 点,无法进行打劫!",
|
||||
sender)
|
||||
return True, "打劫者积分不足"
|
||||
|
||||
if target_total < self.rob_min_points:
|
||||
self.message_util.send_text(f"❌目标积分不足 {self.rob_min_points} 点,不值得打劫!", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌目标积分不足 {self.rob_min_points} 点,不值得打劫!", sender)
|
||||
return True, "目标积分不足"
|
||||
|
||||
# 获取用户昵称
|
||||
@@ -575,10 +584,11 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
f"👤{target_name} 当前积分: {from_user.get('total_points', 0)}"
|
||||
)
|
||||
|
||||
self.message_util.send_text(output, roomid, sender)
|
||||
await self.bot.send_text_message(output, roomid, sender)
|
||||
return True, "打劫成功"
|
||||
else:
|
||||
self.message_util.send_text(f"❌打劫过程中出现问题:{result.get('error', '未知错误')}", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌打劫过程中出现问题:{result.get('error', '未知错误')}",
|
||||
sender)
|
||||
return True, "打劫失败"
|
||||
else:
|
||||
|
||||
@@ -612,18 +622,20 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
f"👤{robber_name} 当前积分: {from_user.get('total_points', 0)}"
|
||||
)
|
||||
|
||||
self.message_util.send_text(output, roomid, sender)
|
||||
await self.bot.send_text_message(roomid, output, sender)
|
||||
return True, "打劫失败"
|
||||
else:
|
||||
self.message_util.send_text(f"❌处理打劫惩罚时出现问题:{result.get('error', '未知错误')}", roomid, sender)
|
||||
await self.bot.send_text_message(roomid,
|
||||
f"❌处理打劫惩罚时出现问题:{result.get('error', '未知错误')}",
|
||||
sender)
|
||||
return True, "处理惩罚失败"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理打劫请求出错: {e}")
|
||||
self.message_util.send_text(f"❌打劫过程中出现意外:{str(e)}", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌打劫过程中出现意外:{str(e)}", sender)
|
||||
return True, f"处理出错: {str(e)}"
|
||||
|
||||
def _handle_bailout(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def _handle_bailout(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理保释命令"""
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
@@ -631,14 +643,14 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 检查是否在群聊中
|
||||
if not roomid:
|
||||
self.message_util.send_text("❌保释功能仅在群聊中可用!", sender, "")
|
||||
await self.bot.send_text_message(sender, "❌保释功能仅在群聊中可用!", "")
|
||||
return True, "非群聊环境"
|
||||
|
||||
# 检查@用户是否有效
|
||||
at_users = self.at_list(xml)
|
||||
if len(at_users) != 1:
|
||||
self.message_util.send_text(f"保释失败❌\n请指定一个保释目标!\n保释 @用户",
|
||||
roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"保释失败❌\n请指定一个保释目标!\n保释 @用户",
|
||||
sender)
|
||||
return True, "目标无效"
|
||||
|
||||
prisoner_wxid = next(iter(at_users))
|
||||
@@ -646,7 +658,7 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
|
||||
# 不能保释自己
|
||||
if prisoner_wxid == bailout_wxid:
|
||||
self.message_util.send_text("❌你不能保释自己!", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, "❌你不能保释自己!", sender)
|
||||
return True, "不能保释自己"
|
||||
|
||||
try:
|
||||
@@ -665,13 +677,13 @@ class PointTradePlugin(MessagePluginInterface):
|
||||
f"✅ 保释成功!\n"
|
||||
f"👤{bailout_name} 花费30积分保释了 👤{prisoner_name}"
|
||||
)
|
||||
self.message_util.send_text(output, roomid, sender)
|
||||
await self.bot.send_text_message(roomid, output, sender)
|
||||
return True, "保释成功"
|
||||
else:
|
||||
self.message_util.send_text(f"❌保释失败: {message}", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌保释失败: {message}", sender)
|
||||
return True, "保释失败"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理保释请求出错: {e}")
|
||||
self.message_util.send_text(f"❌保释过程中出现意外:{str(e)}", roomid, sender)
|
||||
await self.bot.send_text_message(roomid, f"❌保释过程中出现意外:{str(e)}", sender)
|
||||
return True, f"处理出错: {str(e)}"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import time
|
||||
from typing import Dict, Any, Tuple, Optional, List
|
||||
from datetime import datetime
|
||||
@@ -42,7 +42,7 @@ class StatsCollectorPlugin(PluginInterface):
|
||||
def __init__(self):
|
||||
|
||||
super().__init__()
|
||||
self.logger = logging.getLogger("StatsCollector")
|
||||
self.LOG = logger
|
||||
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
# 默认配置
|
||||
@@ -62,7 +62,7 @@ class StatsCollectorPlugin(PluginInterface):
|
||||
self.config.update(config)
|
||||
|
||||
if not self.config["enable"]:
|
||||
self.logger.info("统计收集插件已禁用")
|
||||
self.LOG.info("统计收集插件已禁用")
|
||||
return False
|
||||
|
||||
# 注册事件处理器
|
||||
@@ -79,7 +79,7 @@ class StatsCollectorPlugin(PluginInterface):
|
||||
return
|
||||
|
||||
# 记录开始时间和相关信息
|
||||
self.logger.debug(f"记录插件调用开始: {event.plugin_name} - {event.command}")
|
||||
self.LOG.debug(f"记录插件调用开始: {event.plugin_name} - {event.command}")
|
||||
|
||||
def handle_plugin_call_end(self, event: PluginCallEndEvent) -> None:
|
||||
"""处理插件调用结束事件"""
|
||||
@@ -98,10 +98,10 @@ class StatsCollectorPlugin(PluginInterface):
|
||||
success=event.process_result,
|
||||
process_time_ms=event.process_time
|
||||
)
|
||||
self.logger.debug(
|
||||
self.LOG.debug(
|
||||
f"记录插件调用结束: {event.plugin_name} - {event.command} - 成功: {event.process_result} - 处理时间: {event.process_time}ms")
|
||||
except Exception as e:
|
||||
self.logger.error(f"记录插件调用统计数据出错: {e}")
|
||||
self.LOG.error(f"记录插件调用统计数据出错: {e}")
|
||||
|
||||
def handle_plugin_error(self, event: PluginCallErrorEvent) -> None:
|
||||
"""处理插件调用错误事件"""
|
||||
@@ -119,9 +119,9 @@ class StatsCollectorPlugin(PluginInterface):
|
||||
error_message=event.error_message,
|
||||
stack_trace=event.stack_trace
|
||||
)
|
||||
self.logger.debug(f"记录插件调用错误: {event.plugin_name} - {event.command} - {event.error_message}")
|
||||
self.LOG.debug(f"记录插件调用错误: {event.plugin_name} - {event.command} - {event.error_message}")
|
||||
except Exception as e:
|
||||
self.logger.error(f"记录插件错误信息出错: {e}")
|
||||
self.LOG.error(f"记录插件错误信息出错: {e}")
|
||||
|
||||
def _should_record_plugin(self, plugin_name: str) -> bool:
|
||||
"""检查是否应该记录该插件的调用"""
|
||||
@@ -154,7 +154,7 @@ class StatsCollectorPlugin(PluginInterface):
|
||||
self.event_manager.unregister(PluginCallEndEvent, self.handle_plugin_call_end)
|
||||
self.event_manager.unregister(PluginCallErrorEvent, self.handle_plugin_error)
|
||||
|
||||
self.logger.info("统计收集插件已关闭")
|
||||
self.LOG.info("统计收集插件已关闭")
|
||||
|
||||
def start(self) -> bool:
|
||||
"""启动插件"""
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
from loguru import logger
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
@@ -42,7 +42,7 @@ class SystemUpdaterPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import os
|
||||
import requests
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
|
||||
from plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from plugin_common.plugin_interface import PluginStatus
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class VideoPlugin(MessagePluginInterface):
|
||||
@@ -40,12 +40,13 @@ class VideoPlugin(MessagePluginInterface):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.bot: WechatAPIClient = None
|
||||
# 修改为使用插件目录下的down_load_dir文件夹
|
||||
self.download_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "down_load_dir")
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -56,7 +57,7 @@ class VideoPlugin(MessagePluginInterface):
|
||||
self._commands = self._config.get("Video", {}).get("command", ["黑丝视频", "黑丝", "来个黑丝", "搞个黑丝"])
|
||||
self.command_format = self._config.get("Video", {}).get("command-format", "黑丝")
|
||||
self.enable = self._config.get("Video", {}).get("enable", True)
|
||||
|
||||
|
||||
# 确保下载目录存在
|
||||
if not os.path.exists(self.download_dir):
|
||||
os.makedirs(self.download_dir, exist_ok=True)
|
||||
@@ -88,13 +89,14 @@ class VideoPlugin(MessagePluginInterface):
|
||||
|
||||
@plugin_stats_decorator(plugin_name="视频插件")
|
||||
@plugin_points_cost(2, "视频插件消耗积分", Feature.VIDEO)
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
self.bot: WechatAPIClient = message.get("bot")
|
||||
|
||||
# 检查权限
|
||||
if roomid and gbm.get_group_permission(roomid, Feature.VIDEO) == PermissionStatus.DISABLED:
|
||||
@@ -104,21 +106,21 @@ class VideoPlugin(MessagePluginInterface):
|
||||
# 下载视频
|
||||
save_path = os.path.join(self.download_dir, "video.mp4")
|
||||
file_abspath = self._download_stream("https://api.guiguiya.com/api/hook/heisis", save_path)
|
||||
|
||||
|
||||
if not file_abspath or not file_abspath.endswith("mp4"):
|
||||
self.message_util.send_text(f"\n❌视频下载失败,请稍后再试",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"\n❌视频下载失败,请稍后再试",
|
||||
sender)
|
||||
return False, "视频下载失败"
|
||||
|
||||
# 发送视频
|
||||
result = self.message_util.send_file(file_abspath, (roomid if roomid else sender))
|
||||
result = await self.bot.send_video_message((roomid if roomid else sender), file_abspath)
|
||||
self.LOG.info(f"发送视频结果: {result}")
|
||||
return True, "发送成功"
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理视频请求出错: {e}")
|
||||
self.message_util.send_text(f"\n❌请求出错:{e}",
|
||||
(roomid if roomid else sender), sender)
|
||||
await self.bot.send_text_message((roomid if roomid else sender), f"\n❌请求出错:{e}",
|
||||
sender)
|
||||
return False, f"处理出错: {e}"
|
||||
|
||||
def _download_stream(self, url, save_path):
|
||||
@@ -157,4 +159,4 @@ class VideoPlugin(MessagePluginInterface):
|
||||
self.LOG.error(f"文件写入失败: {e}")
|
||||
except Exception as e:
|
||||
self.LOG.error(f"发生未知错误: {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import logging
|
||||
from loguru import logger
|
||||
import os
|
||||
import requests
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
@@ -45,7 +45,7 @@ class VideoManPlugin(MessagePluginInterface):
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from loguru import logger
|
||||
import os
|
||||
import random
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
@@ -8,6 +10,7 @@ from plugin_common.plugin_interface import PluginStatus
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
|
||||
class XiurenImagePlugin(MessagePluginInterface):
|
||||
@@ -39,11 +42,12 @@ class XiurenImagePlugin(MessagePluginInterface):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.image_folder = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "xiuren")
|
||||
self.image_folder = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
"xiuren")
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
self.LOG = logging.getLogger(f"Plugin.{self.name}")
|
||||
self.LOG = logger
|
||||
self.LOG.info(f"正在初始化 {self.name} 插件...")
|
||||
|
||||
# 保存上下文对象
|
||||
@@ -86,13 +90,14 @@ class XiurenImagePlugin(MessagePluginInterface):
|
||||
|
||||
@plugin_stats_decorator(plugin_name="秀人图片")
|
||||
@plugin_points_cost(2, "秀人图片消耗积分", Feature.PIC)
|
||||
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
async def process_message(self, message: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
||||
"""处理消息"""
|
||||
content = str(message.get("content", "")).strip()
|
||||
self.LOG.info(f"插件执行: {self.name}:{content}")
|
||||
sender = message.get("sender")
|
||||
roomid = message.get("roomid", "")
|
||||
gbm: GroupBotManager = message.get("gbm")
|
||||
bot: WechatAPIClient = message.get("bot")
|
||||
|
||||
# 检查权限
|
||||
if roomid and gbm.get_group_permission(roomid, Feature.PIC) == PermissionStatus.DISABLED:
|
||||
@@ -102,12 +107,13 @@ class XiurenImagePlugin(MessagePluginInterface):
|
||||
# 获取随机图片
|
||||
pic_path = self._get_random_pic()
|
||||
if not pic_path:
|
||||
self.message_util.send_text(f"❌未找到图片资源",
|
||||
(roomid if roomid else sender), sender)
|
||||
await bot.send_text_message((roomid if roomid else sender), f"❌未找到图片资源",
|
||||
sender)
|
||||
return False, "未找到图片资源"
|
||||
|
||||
# 发送图片
|
||||
result = self.message_util.send_file(pic_path, (roomid if roomid else sender))
|
||||
|
||||
result = await bot.send_image_message((roomid if roomid else sender), Path(pic_path))
|
||||
self.LOG.info(f"发送图片结果: {result}")
|
||||
return True, "发送成功"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user