fix message

This commit is contained in:
jxxghp 2023-07-14 07:18:28 +08:00
parent df30b71077
commit ae3d2fb7ae
7 changed files with 71 additions and 41 deletions

View File

@ -10,8 +10,8 @@ from app.core.event import EventManager
from app.core.meta import MetaBase from app.core.meta import MetaBase
from app.core.module import ModuleManager from app.core.module import ModuleManager
from app.log import logger from app.log import logger
from app.schemas import TransferInfo, TransferTorrent, ExistMediaInfo, DownloadingTorrent from app.schemas import TransferInfo, TransferTorrent, ExistMediaInfo, DownloadingTorrent, CommingMessage
from app.schemas.types import TorrentStatus, MediaType, MediaImageType from app.schemas.types import TorrentStatus, MediaType, MediaImageType, MessageChannel
from app.utils.object import ObjectUtils from app.utils.object import ObjectUtils
from app.utils.singleton import AbstractSingleton, Singleton from app.utils.singleton import AbstractSingleton, Singleton
@ -137,7 +137,8 @@ class ChainBase(AbstractSingleton, metaclass=Singleton):
""" """
return self.run_module("tmdb_info", tmdbid=tmdbid, mtype=mtype) return self.run_module("tmdb_info", tmdbid=tmdbid, mtype=mtype)
def message_parser(self, body: Any, form: Any, args: Any) -> Optional[dict]: def message_parser(self, body: Any, form: Any,
args: Any) -> Optional[CommingMessage]:
""" """
解析消息内容返回字典注意以下约定值 解析消息内容返回字典注意以下约定值
userid: 用户ID userid: 用户ID
@ -146,7 +147,7 @@ class ChainBase(AbstractSingleton, metaclass=Singleton):
:param body: 请求体 :param body: 请求体
:param form: 表单 :param form: 表单
:param args: 参数 :param args: 参数
:return: 消息内容用户ID :return: 消息渠道消息内容
""" """
return self.run_module("message_parser", body=body, form=form, args=args) return self.run_module("message_parser", body=body, form=form, args=args)

View File

@ -40,17 +40,20 @@ class MessageChain(ChainBase):
识别消息内容执行操作 识别消息内容执行操作
""" """
# 获取消息内容 # 获取消息内容
info: dict = self.message_parser(body=body, form=form, args=args) info = self.message_parser(body=body, form=form, args=args)
if not info: if not info:
return return
# 渠道
channel = info.channel
# 用户ID # 用户ID
userid = info.get('userid') userid = info.userid
username = info.get('username') # 用户名
username = info.username
if not userid: if not userid:
logger.debug(f'未识别到用户ID{body}{form}{args}') logger.debug(f'未识别到用户ID{body}{form}{args}')
return return
# 消息内容 # 消息内容
text = str(info.get('text')).strip() if info.get('text') else None text = str(info.text).strip() if info.text else None
if not text: if not text:
logger.debug(f'未识别到消息内容::{body}{form}{args}') logger.debug(f'未识别到消息内容::{body}{form}{args}')
return return

View File

@ -7,6 +7,7 @@ from app.core.config import settings
from app.log import logger from app.log import logger
from app.modules import _ModuleBase from app.modules import _ModuleBase
from app.modules.slack.slack import Slack from app.modules.slack.slack import Slack
from app.schemas import MessageChannel, CommingMessage
class SlackModule(_ModuleBase): class SlackModule(_ModuleBase):
@ -22,7 +23,8 @@ class SlackModule(_ModuleBase):
return "MESSAGER", "slack" return "MESSAGER", "slack"
@staticmethod @staticmethod
def message_parser(body: Any, form: Any, args: Any) -> Optional[dict]: def message_parser(body: Any, form: Any,
args: Any) -> Optional[CommingMessage]:
""" """
解析消息内容返回字典注意以下约定值 解析消息内容返回字典注意以下约定值
userid: 用户ID userid: 用户ID
@ -31,7 +33,7 @@ class SlackModule(_ModuleBase):
:param body: 请求体 :param body: 请求体
:param form: 表单 :param form: 表单
:param args: 参数 :param args: 参数
:return: 消息内容用户ID :return: 渠道消息体
""" """
""" """
# 消息 # 消息
@ -149,7 +151,7 @@ class SlackModule(_ModuleBase):
try: try:
msg_json: dict = json.loads(body) msg_json: dict = json.loads(body)
except Exception as err: except Exception as err:
logger.error(f"解析Slack消息失败{err}") logger.debug(f"解析Slack消息失败{err}")
return None return None
if msg_json: if msg_json:
if msg_json.get("type") == "message": if msg_json.get("type") == "message":
@ -175,11 +177,8 @@ class SlackModule(_ModuleBase):
else: else:
return None return None
logger.info(f"收到Slack消息userid={userid}, username={username}, text={text}") logger.info(f"收到Slack消息userid={userid}, username={username}, text={text}")
return { return CommingMessage(channel=MessageChannel.Slack,
"userid": userid, userid=userid, username=username, text=text)
"username": username,
"text": text
}
return None return None
def post_message(self, title: str, def post_message(self, title: str,

View File

@ -6,6 +6,7 @@ from app.core.config import settings
from app.log import logger from app.log import logger
from app.modules import _ModuleBase from app.modules import _ModuleBase
from app.modules.telegram.telegram import Telegram from app.modules.telegram.telegram import Telegram
from app.schemas import MessageChannel, CommingMessage
class TelegramModule(_ModuleBase): class TelegramModule(_ModuleBase):
@ -20,7 +21,8 @@ class TelegramModule(_ModuleBase):
def init_setting(self) -> Tuple[str, Union[str, bool]]: def init_setting(self) -> Tuple[str, Union[str, bool]]:
return "MESSAGER", "telegram" return "MESSAGER", "telegram"
def message_parser(self, body: Any, form: Any, args: Any) -> Optional[dict]: def message_parser(self, body: Any, form: Any,
args: Any) -> Optional[CommingMessage]:
""" """
解析消息内容返回字典注意以下约定值 解析消息内容返回字典注意以下约定值
userid: 用户ID userid: 用户ID
@ -29,7 +31,7 @@ class TelegramModule(_ModuleBase):
:param body: 请求体 :param body: 请求体
:param form: 表单 :param form: 表单
:param args: 参数 :param args: 参数
:return: 消息内容用户ID :return: 渠道消息体
""" """
""" """
{ {
@ -61,7 +63,7 @@ class TelegramModule(_ModuleBase):
try: try:
message: dict = json.loads(body) message: dict = json.loads(body)
except Exception as err: except Exception as err:
logger.error(f"解析Telegram消息失败{err}") logger.debug(f"解析Telegram消息失败{err}")
return None return None
if message: if message:
text = message.get("text") text = message.get("text")
@ -76,18 +78,17 @@ class TelegramModule(_ModuleBase):
and str(user_id) not in settings.TELEGRAM_ADMINS.split(',') \ and str(user_id) not in settings.TELEGRAM_ADMINS.split(',') \
and str(user_id) != settings.TELEGRAM_CHAT_ID: and str(user_id) != settings.TELEGRAM_CHAT_ID:
self.telegram.send_msg(title="只有管理员才有权限执行此命令", userid=user_id) self.telegram.send_msg(title="只有管理员才有权限执行此命令", userid=user_id)
return {} return CommingMessage(channel=MessageChannel.Wechat,
userid=user_id, username=user_id, text="")
else: else:
if settings.TELEGRAM_USERS \ if settings.TELEGRAM_USERS \
and not str(user_id) in settings.TELEGRAM_USERS.split(','): and not str(user_id) in settings.TELEGRAM_USERS.split(','):
logger.info(f"用户{user_id}不在用户白名单中,无法使用此机器人") logger.info(f"用户{user_id}不在用户白名单中,无法使用此机器人")
self.telegram.send_msg(title="你不在用户白名单中,无法使用此机器人", userid=user_id) self.telegram.send_msg(title="你不在用户白名单中,无法使用此机器人", userid=user_id)
return {} return CommingMessage(channel=MessageChannel.Wechat,
return { userid=user_id, username=user_id, text="")
"userid": user_id, return CommingMessage(channel=MessageChannel.Wechat,
"username": user_name, userid=user_id, username=user_id, text=text)
"text": text
}
return None return None
def post_message(self, title: str, def post_message(self, title: str,

View File

@ -7,11 +7,11 @@ from app.log import logger
from app.modules import _ModuleBase from app.modules import _ModuleBase
from app.modules.wechat.WXBizMsgCrypt3 import WXBizMsgCrypt from app.modules.wechat.WXBizMsgCrypt3 import WXBizMsgCrypt
from app.modules.wechat.wechat import WeChat from app.modules.wechat.wechat import WeChat
from app.schemas import MessageChannel, CommingMessage
from app.utils.dom import DomUtils from app.utils.dom import DomUtils
class WechatModule(_ModuleBase): class WechatModule(_ModuleBase):
wechat: WeChat = None wechat: WeChat = None
def init_module(self) -> None: def init_module(self) -> None:
@ -23,7 +23,8 @@ class WechatModule(_ModuleBase):
def init_setting(self) -> Tuple[str, Union[str, bool]]: def init_setting(self) -> Tuple[str, Union[str, bool]]:
return "MESSAGER", "wechat" return "MESSAGER", "wechat"
def message_parser(self, body: Any, form: Any, args: Any) -> Optional[dict]: def message_parser(self, body: Any, form: Any,
args: Any) -> Optional[CommingMessage]:
""" """
解析消息内容返回字典注意以下约定值 解析消息内容返回字典注意以下约定值
userid: 用户ID userid: 用户ID
@ -32,7 +33,7 @@ class WechatModule(_ModuleBase):
:param body: 请求体 :param body: 请求体
:param form: 表单 :param form: 表单
:param args: 参数 :param args: 参数
:return: 消息内容用户ID :return: 渠道消息体
""" """
try: try:
# URL参数 # URL参数
@ -40,7 +41,7 @@ class WechatModule(_ModuleBase):
sVerifyTimeStamp = args.get("timestamp") sVerifyTimeStamp = args.get("timestamp")
sVerifyNonce = args.get("nonce") sVerifyNonce = args.get("nonce")
if not sVerifyMsgSig or not sVerifyTimeStamp or not sVerifyNonce: if not sVerifyMsgSig or not sVerifyTimeStamp or not sVerifyNonce:
logger.error(f"微信请求参数错误:{args}") logger.debug(f"微信请求参数错误:{args}")
return None return None
# 解密模块 # 解密模块
wxcpt = WXBizMsgCrypt(sToken=settings.WECHAT_TOKEN, wxcpt = WXBizMsgCrypt(sToken=settings.WECHAT_TOKEN,
@ -48,7 +49,7 @@ class WechatModule(_ModuleBase):
sReceiveId=settings.WECHAT_CORPID) sReceiveId=settings.WECHAT_CORPID)
# 报文数据 # 报文数据
if not body: if not body:
logger.error(f"微信请求数据为空") logger.debug(f"微信请求数据为空")
return None return None
logger.debug(f"收到微信请求:{body}") logger.debug(f"收到微信请求:{body}")
ret, sMsg = wxcpt.DecryptMsg(sPostData=body, ret, sMsg = wxcpt.DecryptMsg(sPostData=body,
@ -99,18 +100,16 @@ class WechatModule(_ModuleBase):
if wechat_admins and not any( if wechat_admins and not any(
user_id == admin_user for admin_user in wechat_admins): user_id == admin_user for admin_user in wechat_admins):
self.wechat.send_msg(title="用户无权限执行菜单命令", userid=user_id) self.wechat.send_msg(title="用户无权限执行菜单命令", userid=user_id)
return {} return CommingMessage(channel=MessageChannel.Wechat,
userid=user_id, username=user_id, text="")
elif msg_type == "text": elif msg_type == "text":
# 文本消息 # 文本消息
content = DomUtils.tag_value(root_node, "Content", default="") content = DomUtils.tag_value(root_node, "Content", default="")
if content: if content:
logger.info(f"收到微信消息userid={user_id}, text={content}") logger.info(f"收到微信消息userid={user_id}, text={content}")
# 处理消息内容 # 处理消息内容
return { return CommingMessage(channel=MessageChannel.Wechat,
"userid": user_id, userid=user_id, username=user_id, text=content)
"username": user_id,
"text": content
}
except Exception as err: except Exception as err:
logger.error(f"微信消息处理发生错误:{err}") logger.error(f"微信消息处理发生错误:{err}")
return None return None

View File

@ -1,9 +1,9 @@
from pathlib import Path from pathlib import Path
from typing import Optional, Dict, List, Union from typing import Optional, Dict, List
from pydantic import BaseModel from pydantic import BaseModel
from app.schemas.types import MediaType, NotificationType from app.schemas.types import MediaType, NotificationType, MessageChannel
class MetaInfo(BaseModel): class MetaInfo(BaseModel):
@ -313,12 +313,16 @@ class Notification(BaseModel):
""" """
消息 消息
""" """
# 消息渠道
channel: Optional[MessageChannel] = None
# 消息类型 # 消息类型
mtype: Optional[NotificationType] = None mtype: Optional[NotificationType] = None
# 标题 # 标题
title: Optional[str] = None title: Optional[str] = None
# 内容 # 文本内容
content: Optional[str] = None text: Optional[str] = None
# 列表内容
items: Optional[list] = []
# 图片 # 图片
image: Optional[str] = None image: Optional[str] = None
# 链接 # 链接
@ -327,6 +331,20 @@ class Notification(BaseModel):
user_id: Optional[str] = None user_id: Optional[str] = None
class CommingMessage(BaseModel):
"""
外来消息
"""
# 用户ID
userid: Optional[str] = None
# 用户名称
username: Optional[str] = None
# 消息渠道
channel: Optional[MessageChannel] = None
# 消息体
text: Optional[str] = None
class NotificationSwitch(BaseModel): class NotificationSwitch(BaseModel):
""" """
消息开关 消息开关

View File

@ -85,3 +85,12 @@ class NotificationType(Enum):
SiteMessage = "站点消息" SiteMessage = "站点消息"
# 媒体服务器通知 # 媒体服务器通知
MediaServer = "媒体服务器通知" MediaServer = "媒体服务器通知"
class MessageChannel(Enum):
"""
消息渠道
"""
Wechat = "微信"
Telegram = "Telegram"
Slack = "Slack"