Python implements the function of WeChat to automatically reply to information (reply to the corresponding information according to different information), hand-in-hand construction and code analysis

Table of contents

1. Effect display

2. Introduction

3. Get to the point

1. Packages needed

2. Enter the code part below

2.1 Import the required packages

2.2 Define WeChat window controls 

2.3 Call the method to find the WeChat control

2.3 Bind the session list control of the window and read the data

2.4 Use while True: infinite loop monitoring information

2.5 Get the latest information

2.6 Some operations to be done in the loop

2.7 Reply to information

Four: complete code


1. Effect display

2. Introduction

The third-party package we use is: UIAutomation

Introduction to UIAutomation : UIAutomation is an automated testing framework that simulates user actions on the application's graphical user interface and provides complete access to the elements of the application's interface. The framework was originally developed by Microsoft to provide a standardized approach to automated testing of applications on the Microsoft Windows platform. The UIAutomation framework allows testers to write automated test scripts to reliably test an application across different versions and environments. This automated testing method can increase the speed and accuracy of testing and reduce the burden of manual testing.

In short, the function of UIAutomation is still very powerful. Let's use it to try it out this time.

3. Get to the point

1. Packages needed

If we want to analyze and judge the received information, we first need to store the text content locally. This time we use: csv file, which is an Excel file, so we need to install the corresponding package if we want to parse the corresponding file .

Install the UIAutomation package

pip install uiautomation

Install the pandas package to read csv data

pip install pandas

Install the numpy package, the purpose is to convert the read data into a list

pip install numpy

2. Enter the code part below

2.1 Import the required packages

import numpy as np  # 引入numpy库,目的是将读取的数据转换为列表
import pandas as pd  # 引入pandas库,用来读取csv数据
from uiautomation import WindowControl  # 引入uiautomation库中的WindowControl类,用来进行图像识别和模拟操作

2.2 Define WeChat window controls 

wx = WindowControl(
    Name='微信',
    # searchDepth=1
)

Here we define a window control WX, which represents the main window of the WeChat application. Through the constructor of the WindowControl class, pass the name of the window Name='WeChat' to it, and it will search and bind the main window of the WeChat application on the screen. Parameters can also be used  searchDepth to set the depth of the search window controls.

2.3 Call the method to find the WeChat control

wx.ListControl()
wx.SwitchToThisWindow()

The wx.ListControl() function is used here, and its function is to find the session list in the window control. Then call the wx.SwitchToThisWindow() function to switch the WeChat application to the current window, that is, display the WeChat interface to the top layer.

2.3 Bind the session list control of the window and read the data

hw = wx.ListControl(Name='会话')
df = pd.read_csv('回复数据.csv', encoding='GBK')

Here, the session list control of the bound window is obtained and assigned to it  hwfor use in subsequent codes. Then use the functions in the pandas library  read_csv() to read the csv file named "reply data.csv", set the encoding format to GBK, and store the read data in the pandas DataFrame object  df .

You can see that the data at this time is a list, just like an excel table

 The data in the file as seen by the compiler looks like this:

2.4 Use while True: infinite loop monitoring information

while True:
    # 获取未读消息控件we
    we = hw.TextControl(searchDepth=4)

    # 死循环直到获取未读消息
    while not we.Exists():
        pass

A while loop is used here to keep listening to messages in WeChat groups or private chats. When a new message appears, get the unread message control, and use a while loop to wait until the unread message is obtained. serchDepth=4 means that we only monitor the top four friends or group chats

2.5 Get the latest information

last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name

In the above while loop, if there is a new message, this line of code will be executed, and the  wx.ListControl() window control of the latest message will be obtained through the function, and its name will be stored in  last_msg a variable. Note that we will only set it here and only get the last information. If you want to modify it, just modify the subscript

2.6 Some operations to be done in the loop

  # 存在未读消息
    if we.Name:
        # 点击未读消息
        we.Click(simulateMove=False)
        # 读取最后一条消息
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
        # 判断关键字
        msg = df.apply(lambda x: x['回复内容'] if x['关键词'] in last_msg else None, axis=1)
        print(msg)
        # 数据筛选,移除空数据
        msg.dropna(axis=0, how='any', inplace=True)
        # 做成列表
        ar = np.array(msg).tolist()

The above code first uses the wc.Click() click event , clicks to the user dialog box of unread information, and uses  apply() the function to find whether last_msg the keyword in the read csv file is included  . This function uses the given lambda function to  df traverse each row in the DataFrame table and returns the qualified rows, then filters out the data, uses  the function to delete invalid data (that is, rows with a value of None), and uses   the function to convert the DataFrame The object is converted to a numpy array , and then   a function is used to convert it to a Python list. Store the processed list in   a variable named . dropna()np.array()tolist()ar

2.7 Reply to information

    # 能够匹配到数据时
        if ar:
            # 将数据输入
            # 替换换行符号
            wx.SendKeys(ar[0].replace('{br}', '{Shift}{Enter}'), waitTime=1)
            # 发送消息 回车键
            wx.SendKeys('{Enter}', waitTime=0)

            # 通过消息匹配检索会话栏的联系人
            wx.TextControl(SubName=ar[0][:5]).RightClick()
        # 没有匹配到数据时
        else:
            wx.SendKeys('我不理解你什么意思', waitTime=1)
            wx.SendKeys('{Enter}', waitTime=0)
            wx.TextControl(SubName=last_msg[:5]).RightClick(10)

 The above is the reply message, wx.SendKeys('{Shift}{Enter}') is to input the data in the ar list into the dialog box, waitTime is to set its waiting time, wx.SendKeys'{Enter}' is the response Enter key to send the information, waitTime is also the waiting time, the function of wx.TextControl(SubName=ar[0][:5]).RightClick() is to retrieve the contacts in the conversation bar through message matching, that is, to realize a Right mouse click function:

  • wx.TextControl() The function is used to find the text box control in the WeChat window;
  • SubName The parameter is used to specify the subname of the control, that is, the label name of the control;
  • ar[0][:5] is a string, obtained somehow, that specifies the position of the text to be right-clicked in the text box;
  • RightClick() The method simulates a right-click event of the mouse, that is, clicking the right mouse button on the specified text location.

Four: complete code

#!/usr/bin/python3
# -*- coding: utf-8 -*-


import numpy as np  # 引入numpy库,目的是将读取的数据转换为列表
import pandas as pd  # 引入pandas库,用来读取csv数据
from uiautomation import WindowControl  # 引入uiautomation库中的WindowControl类,用来进行图像识别和模拟操作

# 绑定微信主窗口
wx = WindowControl(
    Name='微信',
    searchDepth=1
)
# 切换窗口
wx.ListControl()
wx.SwitchToThisWindow()
# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')
# 通过pd读取数据
df = pd.read_csv('回复数据.csv', encoding='GBK')
print(df)
# 死循环接收消息
while True:
    # 从查找未读消息
    we = hw.TextControl(searchDepth=4)

    # 死循环维持,没有超时报错
    while not we.Exists():
        pass

    # 存在未读消息
    if we.Name:
        # 点击未读消息
        we.Click(simulateMove=False)
        # 读取最后一条消息
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
        # 判断关键字
        msg = df.apply(lambda x: x['回复内容'] if x['关键词'] in last_msg else None, axis=1)
        print(msg)
        # 数据筛选,移除空数据
        msg.dropna(axis=0, how='any', inplace=True)
        # 做成列表
        ar = np.array(msg).tolist()
        # 能够匹配到数据时
        if ar:
            # 将数据输入
            # 替换换行符号
            wx.SendKeys(ar[0].replace('{br}', '{Shift}{Enter}'), waitTime=1)
            # 发送消息 回车键
            wx.SendKeys('{Enter}', waitTime=1)

            # 通过消息匹配检索会话栏的联系人
            wx.TextControl(SubName=ar[0][:5]).RightClick()
        # 没有匹配到数据时
        else:
            wx.SendKeys('我不理解你什么意思', waitTime=1)
            wx.SendKeys('{Enter}', waitTime=1)
            wx.TextControl(SubName=last_msg[:5]).RightClick()

Can you give me three consecutive supports if you think it is helpful?

Guess you like

Origin blog.csdn.net/m0_64642443/article/details/131260518