From 0d6fb99e286a8f59be628a6f4a8d8c5f06552602 Mon Sep 17 00:00:00 2001 From: liuwei Date: Mon, 24 Mar 2025 13:27:34 +0800 Subject: [PATCH] =?UTF-8?q?=E7=9C=8B=E6=9D=BF=E5=86=85=E5=AE=B9=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E4=BC=98=E5=8C=96=EF=BC=8C=E5=90=8C=E6=97=B6=E5=8A=A0?= =?UTF-8?q?=E5=85=A5=E4=BA=86=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=EF=BC=8C=E5=B0=86=E7=94=A8=E6=88=B7=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E5=85=A8=E5=B1=80=E5=BC=80=E6=94=BE=EF=BC=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/wechat/contact_manager.py | 79 +++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 utils/wechat/contact_manager.py diff --git a/utils/wechat/contact_manager.py b/utils/wechat/contact_manager.py new file mode 100644 index 0000000..7994e61 --- /dev/null +++ b/utils/wechat/contact_manager.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +""" +联系人管理器 - 提供全局访问联系人信息的单例类 +""" +import logging +from typing import Dict, Optional + + +class ContactManager: + """联系人管理器单例类""" + _instance = None + _contacts: Dict[str, str] = {} + _initialized = False + _logger = logging.getLogger("ContactManager") + + def __new__(cls): + if cls._instance is None: + cls._instance = super(ContactManager, cls).__new__(cls) + return cls._instance + + def __init__(self): + # 确保初始化代码只执行一次 + if not ContactManager._initialized: + self._logger.info("初始化联系人管理器") + ContactManager._initialized = True + + @classmethod + def get_instance(cls): + """获取单例实例""" + if cls._instance is None: + cls._instance = ContactManager() + return cls._instance + + def set_contacts(self, contacts: Dict[str, str]) -> None: + """设置联系人字典 + + Args: + contacts: 联系人字典,格式为 {"wxid": "NickName"} + """ + self._contacts = contacts + self._logger.info(f"联系人信息已更新,共 {len(contacts)} 个联系人") + + def get_contacts(self) -> Dict[str, str]: + """获取所有联系人 + + Returns: + 联系人字典,格式为 {"wxid": "NickName"} + """ + return self._contacts + + def get_nickname(self, wxid: str) -> str: + """根据微信ID获取昵称 + + Args: + wxid: 微信ID + + Returns: + 对应的昵称,如果不存在则返回wxid本身 + """ + return self._contacts.get(wxid, wxid) + + def update_contact(self, wxid: str, nickname: str) -> None: + """更新单个联系人信息 + + Args: + wxid: 微信ID + nickname: 昵称 + """ + self._contacts[wxid] = nickname + self._logger.debug(f"已更新联系人: {wxid} -> {nickname}") + + def refresh_contacts(self, new_contacts: Dict[str, str]) -> None: + """刷新联系人信息 + + Args: + new_contacts: 新的联系人字典 + """ + self._contacts = new_contacts + self._logger.info(f"联系人信息已刷新,共 {len(new_contacts)} 个联系人") \ No newline at end of file