执行条件:ptyhone3环境
安装库命令:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy pandas uiautomation
文件名:wechat_auto_reply.py
import pandas as pd
import numpy as np
import uiautomation as auto
import time
def find_wechat_window():
try:
# 尝试找到微信窗口,这里可能需要根据实际情况调整参数
wx_window = auto.WindowControl(searchDepth=3, Name='微信')
if wx_window.Exists(0):
wx_window.SwitchToThisWindow()
return wx_window
else:
print("未找到微信窗口")
return None
except Exception as e:
print(f"查找微信窗口出错: {e}")
return None
def get_last_message(wx):
try:
# 获取消息列表
message_list = wx.ListControl(Name='消息').GetChildren()
if message_list:
# 读取最后一条消息
last_msg = message_list[-1].Name
return last_msg
else:
print("消息列表为空")
return None
except Exception as e:
print(f"获取最后一条消息出错: {e}")
return None
wx = find_wechat_window()
if not wx:
exit()
# 通过pd读取数据
df = pd.read_csv(r'C:\Users\Administrator\Documents\weChatRobot\AutoBack.csv', encoding='gb18030')
print(df)
# 寻找特定联系人的对话
contact_name = '21day'
conversations = wx.ListControl()
for conversation in conversations.GetChildren():
if conversation.Name == contact_name:
conversation.Click(simulateMove=False)
break
# 死循环接收消息
while True:
time.sleep(1) # 避免过于频繁的循环
last_msg = get_last_message(wx)
if last_msg:
# print(f"收到新消息: {last_msg}")
# 判断关键字
msg = df.apply(lambda x: x['回复内容'] if x['关键词'] in last_msg else None, axis=1)
# 数据筛选,移除空数据
msg.dropna(axis=0, how='any', inplace=True)
# 做成列表
ar = np.array(msg).tolist()
# 能够匹配到数据时
if ar:
try:
# 将数据输入
# 替换换行符号
reply = ar[0].replace('{br}', '\n')
wx.SendKeys(reply, waitTime=0)
# 发送消息,回车键
wx.SendKeys('{Enter}', waitTime=1)
print(f"回复内容是: {ar[0]}")
except Exception as e:
print(f"发送消息出错: {e}")
# 没有匹配到数据时
# else:
# try:
# wx.SendKeys('不知道你在说什么', waitTime=0)
# wx.SendKeys('{Enter}', waitTime=0)
# except Exception as e:
# print(f"发送默认回复出错: {e}")
else:
print("没有新消息")
文件名:AutoBack.csv 文本打开编辑就行
内容如下:
序号,关键词,回复内容
1,吃的,猪脚饭
2,哈哈,我的
注: 微信窗口得一直打开