Files
abot/message_util.py

74 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
import logging
import random
import time
from typing import Optional
from wcferry import Wcf
class MessageUtil:
"""
消息发送工具类,封装了发送文本和文件的方法
"""
# 修改 MessageUtil 类的初始化方法,接受联系人管理器而不是联系人字典
def __init__(self, wcf, contact_manager):
self.wcf = wcf
self.contact_manager = contact_manager
self.LOG = logging.getLogger("MessageUtil")
def send_text_msg(self, msg: str, receiver: str, at_list: str = "") -> None:
"""
发送文本消息
:param msg: 消息字符串
:param receiver: 接收人wxid或者群id
:param at_list: 要@的wxid, @所有人的wxid为notify@all
"""
# 风控处理,随机延迟发送,解决群消息高频发送导致的微信风险
time.sleep(random.uniform(0.3, 1.0))
ats = ""
if at_list:
if at_list == "notify@all": # @所有人
ats = " @所有人"
else:
wxids = at_list.split(",")
for wxid in wxids:
# 根据 wxid 查找群昵称
ats += f" @{self.wcf.get_alias_in_chatroom(wxid, receiver)}"
# {msg}{ats} 表示要发送的消息内容后面紧跟@,例如 北京天气情况为xxx @张三
if ats == "":
self.LOG.info(f"To {receiver}: {msg}")
self.wcf.send_text(f"{msg}", receiver, at_list)
else:
self.LOG.info(f"To {receiver}: {ats}\r{msg}")
self.wcf.send_text(f"{ats}\n{msg}", receiver, at_list)
def send_file(self, file_path: str, receiver: str) -> None:
"""
发送文件消息
:param file_path: 文件路径
:param receiver: 接收人wxid或者群id
"""
# 风控处理,随机延迟发送,解决群消息高频发送导致的微信风险
time.sleep(random.uniform(0.5, 1.5))
self.LOG.info(f"Sending file to {receiver}: {file_path}")
self.wcf.send_file(file_path, receiver)
def update_contacts(self, contacts: dict) -> None:
"""
更新联系人字典
:param contacts: 联系人字典,格式为 {"wxid": "NickName"}
"""
self.contacts.update(contacts)
# 修改使用 allContacts 的地方,改为使用 contact_manager
# 例如:
# 原来的代码: nickname = self.allContacts.get(wxid, wxid)
# 修改为: nickname = self.contact_manager.get_nickname(wxid)