由于微信没有自动回复功能,加上自己最近再看autowx相关的东西,故开发此工具
实现功能:
1.设置监听用户 (由于编码问题,暂不支持用户名中带有表情,此处的用户名就是微信窗口上显示的那个,所以改备注也可以)
2.支持根据用户设置不同的回复内容和超时时间(分钟)
超时时间:最后一次本人回复后的时间截至现在的时间 防止连续聊天的时候自动回复
ps:
1.由于使用到window相关api,所以需要已管理员方式运行
2.只支持到3.9.x 版本(3.9.12.55) 不支持4.x
关键代码:
from datetime import datetime
import time
from wxauto import WeChat
import win32gui
import json
import sysdef load_config():"""读取当前目录下的config.json文件,返回json对象"""script_path = sys.argv[0]print("当前执行脚本的位置:", script_path)with open('config.json', 'r', encoding='utf-8') as f:return json.load(f)def hide_window(who):"""最小化窗口"""hwnd = win32gui.FindWindow(None, who)if hwnd:win32gui.ShowWindow(hwnd, 6) # 最小化窗口def get_reply_msg(user_name) -> str:"""根据消息内容获取回复内容"""exists = [x for x in listen_list if x['user_name'] == user_name]if exists:return exists[0]['reply_msg']else:return Nonedef refresh_reply(user_name, reply_msg):"""刷新回复列表"""exist_configs = [x for x in listen_list if x['user_name'] == user_name]if not exist_configs:returnconfig = exist_configs[0]if config['reply_msg'] == reply_msg:returnexists = [x for x in message_list if x['user_name'] == user_name]if not exists:message_list.append({'user_name': user_name, 'last_time': datetime.now(), 'reply_msg': reply_msg})else:exists[0]['last_time'] = datetime.now()exists[0]['reply_msg'] = reply_msgdef check_need_reply(user_name) -> bool:"""判断是否需要回复"""exists_configs = [x for x in listen_list if x['user_name'] == user_name]if not exists_configs:return Falseconfig = exists_configs[0]time_out = float(config['time_out'])exists = [msg for msg in message_list if msg['user_name'] == user_name]if not exists:return Trueelse:last_time = exists[0]['last_time']if (datetime.now() - last_time).seconds > time_out * 60:return Trueelse:return Falsedef send_and_hide(sender, reply_msg, wx):"""发送消息并最小化窗口"""if reply_msg:wx.SendMsg(reply_msg, sender)hide_window(sender)def process_message(chat, one_msgs, wx):"""处理收到的消息"""for msg in one_msgs:sender = msg.sendercontent = msg.contentreciver = 'self'if msg.type == 'self':chatbox = msg.chatboxreciver = chatbox.Namerefresh_reply(reciver, content)print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] {sender} -> {reciver}: {content}')if msg.type == 'friend':if check_need_reply(sender):reply_msg = get_reply_msg(sender)send_and_hide(sender, reply_msg, wx)def main():global listen_list, message_listconfig = load_config()listen_list = config.get('listen_list', [])message_list = []wx = WeChat()for item in listen_list:user_name = item['user_name']try:wx.AddListenChat(who=user_name)hide_window(user_name)except Exception as e:print(f'添加{user_name}失败: {str(e)}')while True:time.sleep(2)msgs = wx.GetListenMessage()for chat, one_msgs in msgs.items():process_message(chat, one_msgs, wx)if __name__ == '__main__':try:main()except Exception as e:print(f'程序出错:{str(e)}')input('按任意键退出')
点击下载下载地址