Python 实现微信自动通过好友申请,并发送一条欢迎语

基于Python  uiautomation操作PC端微信

# 自动通过好友
# 读取命令行参数
import sys
import time

import pyperclip
import uiautomation as uia

replyContent = "你好"
# 打开微信
uia.SendKeys('{Ctrl}{Alt}{W}', waitTime=1)
wechatName = "微信"
if len(sys.argv) >= 2:
    wechatName = sys.argv[1]

# 初始化微信窗口控件
wechat_window = uia.WindowControl(Name=wechatName)
wechat_window.SwitchToThisWindow()
wechat_window.MoveToCenter()

# 点击通讯里
tongxunBtn = wechat_window.ButtonControl(Name="通讯录")
if tongxunBtn.Exists(0.01):
    tongxunBtn.Click()

# 点击新的朋友
newFirend = wechat_window.ListItemControl(Name='新的朋友')
if newFirend.Exists(0.01):
    newFirend.Click()

# 点击接受
newFirends = wechat_window.ListControl(Name='新的朋友').GetChildren()
for newFirend in newFirends:
    yesButton = newFirend.ButtonControl(Name="接受")
    if yesButton.Exists(0.01):
        nickname = newFirend.Name
        print("新的朋友:", nickname)
        yesButton.Click()
        wechat_window.CheckBoxControl(Name="聊天、朋友圈、微信运动等").Click()
        confirmBtn=wechat_window.ButtonControl(Name="确定")
        if not confirmBtn.Exists(1):
            continue
        confirmBtn.Click()
        time.sleep(2)

        # 发送一句话
        wechat_window.ButtonControl(Name="聊天").Click()

        # 搜索昵称
        uia.SendKeys('{Ctrl}f', waitTime=0)
        uia.SendKeys('{Ctrl}a', waitTime=0)
        searchBox = uia.EditControl(Name='搜索')
        pyperclip.copy(nickname)
        searchBox.SendKeys('{Ctrl}a', waitTime=0)
        searchBox.SendKeys('{Ctrl}v', waitTime=0)
        time.sleep(3)
        isExits = False
        searchItems = uia.ListControl(Name="@str:IDS_FAV_SEARCH_RESULT:3780").GetChildren()
        for item in searchItems:
            if item is None or item.Name == "":
                continue
            if "显示全部" in item.Name:
                break
            if item.Name == nickname:
                print("找到昵称:", nickname)
                isExits = True
                item.Click()
                break
        if not isExits:
            tongxunBtn.Click()
            continue

        # 发送一句话
        inputBox = wechat_window.EditControl(Name=nickname)
        inputBox.Click()
        pyperclip.copy(replyContent)
        inputBox.SendKeys('{Ctrl}a', waitTime=1)
        inputBox.SendKeys('{Ctrl}v', waitTime=1)
        inputBox.SendKeys('{Enter}', waitTime=0)