Administrator
发布于 2024-06-30 / 44 阅读 / 0 评论 / 0 点赞

利用Python实现自动监控微信消息并自动回复的脚本

背景介绍

在日常生活和工作中,我们经常需要处理大量的微信消息。如果能实现自动监控微信消息并根据特定内容自动回复,将大大提高我们的效率。本文将介绍如何使用Python和一些相关库,实现这一自动化功能。

所需工具和库

  1. pyautogui: 用于模拟键盘和鼠标操作。

  2. pyperclip: 用于剪贴板操作。

  3. time: 用于时间控制。

  4. requests: 用于发送HTTP请求。

  5. pytesseract: 用于OCR识别。

  6. PIL(Pillow):用于图像处理。

  7. osshutil: 用于文件和目录操作。

安装相关库

首先,需要安装上述库,可以通过pip进行安装:


pip install pyautogui pyperclip requests pytesseract pillow

设置Tesseract路径

在使用pytesseract进行OCR识别前,需要确保已经安装Tesseract,并配置其路径:


import pytesseract
from PIL import Image

# 手动指定 Tesseract 的路径
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'  # 替换为您的 Tesseract 安装路径

脚本实现

以下是完整的脚本实现,用于监控微信消息并根据特定内容自动回复:


import pyautogui
import pyperclip
import time
import requests
import pytesseract
from PIL import Image
import os
import shutil

# 手动指定 Tesseract 的路径
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'  # 替换为您的 Tesseract 安装路径

def send(msg):
    print(f"发送的消息: {msg}")
    pyperclip.copy(msg)
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('enter')

def call_custom_model(api_url, messages, api_key):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "model": "deepseek_chat",
        "messages": messages,
        "stream": False
    }

    try:
        response = requests.post(api_url, headers=headers, json=data)
        response.raise_for_status()
        response_json = response.json()
        message_content = response_json['choices'][0]['message']['content']
        print(f"模型回答: {message_content}")
        return message_content
    except requests.exceptions.RequestException as e:
        return f"An error occurred: {e}"

def create_temp_folder():
    temp_folder = "temp_screenshots"
    if not os.path.exists(temp_folder):
        os.makedirs(temp_folder)
    return temp_folder

def clean_temp_folder(temp_folder):
    shutil.rmtree(temp_folder)

def monitor_wechat(api_url, api_key, group_name, region):
    temp_folder = create_temp_folder()

    # 打开微信
    pyautogui.hotkey('ctrl', 'alt', 'w')
    time.sleep(1)
    # 搜索指定的群
    pyautogui.hotkey('ctrl', 'f')
    pyperclip.copy(group_name)
    pyautogui.hotkey('ctrl', 'v')
    time.sleep(1)
    pyautogui.press('enter')
    time.sleep(1)

    screenshot_counter = 0

    try:
        while True:
            screenshot_path = os.path.join(temp_folder, f"wechat_screenshot_{screenshot_counter}.png")

            # 获取当前屏幕的微信消息截图,指定区域
            screenshot = pyautogui.screenshot(region=region)
            screenshot.save(screenshot_path)
            print(f"截图已保存: {screenshot_path}")

            # 使用Pytesseract OCR识别微信截图内容
            recognized_text = pytesseract.image_to_string(Image.open(screenshot_path), lang='chi_sim')
            print(f"识别到的内容: {recognized_text}")

            if '黄有才' in recognized_text:
                full_message = recognized_text.split('黄有才')[1].strip()
                print(f"提问的内容: {full_message}")
                conversation_history = [{"role": "user", "content": full_message}]
                response = call_custom_model(api_url, conversation_history, api_key)
                send(response)

            # 删除上一个截图
            previous_screenshot = os.path.join(temp_folder, f"wechat_screenshot_{screenshot_counter - 1}.png")
            if os.path.exists(previous_screenshot):
                os.remove(previous_screenshot)

            screenshot_counter += 1
            time.sleep(5)  # 每5秒检查一次消息
    finally:
        clean_temp_folder(temp_folder)

if __name__ == "__main__":
    api_url = 'you'# 替换为您的 API 链接
    api_key = 'your_api_key_here'  # 替换为您的 API 密钥
    group_name = '文件传输助手'
    region = (267, 550, 644, 523)  # 替换为你的微信窗口区域坐标和尺寸
    monitor_wechat(api_url, api_key, group_name, region)

代码说明

  1. 打开微信和搜索群聊: 通过模拟键盘快捷键打开微信并搜索指定的群聊。

  2. 截图和OCR识别: 使用pyautogui截取微信窗口的消息区域,并通过pytesseract进行OCR识别,获取文本内容。

  3. 调用自定义模型进行回复: 根据识别到的内容,调用自定义模型API生成回复,并通过微信发送。

  4. 循环检查消息: 脚本每隔5秒检查一次新的消息,并处理相关内容。

import pyautogui
import time

def get_region():
    print("请在5秒钟内将鼠标移动到截图区域的起点...")
    time.sleep(5)
    print("开始记录起点...")
    x_start, y_start = pyautogui.position()
    print(f"起点位置:({x_start}, {y_start})")

    print("请将鼠标拖动到截图区域的终点...")
    time.sleep(5)
    print("记录终点...")
    x_end, y_end = pyautogui.position()
    print(f"终点位置:({x_end}, {y_end})")

    width = x_end - x_start
    height = y_end - y_start

    return (x_start, y_start, width, height)

if __name__ == "__main__":
    region = get_region()
    print(f"截图区域:{region}")

结语

通过上述脚本,我们可以实现自动化监控微信消息并根据特定内容自动回复的功能,这在提高效率方面具有重要作用。希望这篇博客对你有所帮助,如果有任何问题,欢迎留言讨论。


评论