2.5 pyautogui 实现微信自动回复

第四节:实战微信自动回复

课程目标

  • 学习如何通过pyautogui完成微信自动回复

课程内容

编码实现
import pyautogui as pg
import time
from pyautogui import ImageNotFoundException
import pyperclip
from cnocr import CnOcr
import random
ocr = CnOcr()
msg_strs = [
    "嗯",
    "挺好的",
    "好",
    "是的",
    "看起来很不错!",
]
emotion_dict = {
    "你好":"你也好好呀",
    "吃了吗":"吃了,你呢",
    "今天天气怎么样":"我这边今天天气很好",
    "天气怎么样":"我这边今天天气很好",
}
emojis = [
    r"image\emoji1.png",
    r"image\emoji2.png",
    r"image\emoji3.png",
    r"image\emoji4.png",
]
def check_new_msg_last():
    """检查有没有新消息"""
    try:
        new_msg_item = pg.locateOnScreen(r"image\new_msg_img.png")
        x,y = pg.center(new_msg_item)
        pg.click(x,y)
        print("发现新消息,进入")
        return True
    except ImageNotFoundException:
        
        return False
def check_new_msg_first():
    """检查有没有新消息"""
    try:
        new_msg_item = pg.locateOnScreen(r"image\new_msg2_img.png")
        x,y = pg.center(new_msg_item)
        pg.click(x,y)
        print("发现新消息,进入")
        return True
    except ImageNotFoundException:
        
        return False
def set_my_msg(msg):
    """输入"""
    if msg in list(emotion_dict.keys()):
        msg_str = emotion_dict[msg]
    else:
        msg_str = random.choice(msg_strs)
    pyperclip.copy(msg_str)
    pg.hotkey("ctrl","v")
    pass
def send():
    """发送"""
    send_item = pg.locateOnScreen(r"image\send_img.png")
    x,y = pg.center(send_item)
    pg.click(x,y)
    pg.press("enter")
    pg.hotkey("alt","s")
def set_emoji():
    emoji_item = pg.locateOnScreen(r"image\emoji_img.png")
    x,y = pg.center(emoji_item)
    pg.click(x,y)
    emoji1 = random.choice(emojis)
    emoji1_item = pg.locateOnScreen(emoji1)
    x,y = pg.center(emoji1_item)
    pg.click(x,y)
def get_txt():
    rs = ocr.ocr(r"msg.png")
    msggs = []

    for r in rs:
        msggs.append(r['text'])
    msgg = "\n".join(msggs)
    return msgg
def get_msg():
    head_items = pg.locateAllOnScreen(r"image\head.png")
    # 头
    head_item = None
    for item in head_items:
        head_item = item
    emoji_item = pg.locateOnScreen(r"image\emoji_img.png")
    height = emoji_item.top - head_item.top
    pg.screenshot("msg.png",(int(head_item.left),int(head_item.top),200,int(height)))
    msgg = get_txt()
    return msgg
while True:
    time.sleep(0.5)
    # print("未发现新消息")
    if check_new_msg_first() or check_new_msg_last():
        # 回消息
        msg = get_msg()
        print(msg)
        set_my_msg(msg)
        set_emoji()
        send()

测试与调试
  • 测试
    • 测试程序的各个功能是否正常工作。
  • 调试
    • 根据测试结果,调整和优化代码。

你可能感兴趣的:(微信,python,开发语言)