在本文中,我将向大家介绍如何使用Python脚本实现微信自动回复,并通过调用DeepSeek API来生成智能回复。这个脚本可以帮助你自动化处理微信消息,节省时间并提高效率。

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

import requests
import json
from uiautomation import WindowControl, MenuControl

# DeepSeek API配置
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
API_KEY = "sk-1c882760f0f8"  # 替换为实际API密钥
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def get_deepseek_response(prompt):
    """
    调用DeepSeek API获取回复
    """
    payload = {
        "model": "deepseek-chat",  # 根据实际模型调整
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7,
        "max_tokens": 150
    }
    
    try:
        response = requests.post(DEEPSEEK_API_URL, headers=HEADERS, json=payload, timeout=10)
        response.raise_for_status()
        result = response.json()
        return result['choices'][0]['message']['content'].strip()
    except Exception as e:
        print(f"API调用失败: {str(e)}")
        return "当前无法回复,请稍后再试。"

# 绑定微信主窗口
wx = WindowControl(Name='微信')
wx.SwitchToThisWindow()

# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')

while True:
    we = hw.TextControl(searchDepth=4)
    
    while not we.Exists(0):
        pass

    if we.Name:
        we.Click(simulateMove=False)
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
        
        # 调用DeepSeek获取回复
        reply_content = get_deepseek_response(last_msg)
        
        # 处理换行符
        formatted_reply = reply_content.replace('\n', '{Shift}{Enter}')
        
        # 发送回复
        wx.SendKeys(formatted_reply, waitTime=0)
        wx.SendKeys('{Enter}', waitTime=0)
        
        # 标记为已读
        wx.TextControl(SubName=last_msg[:5]).RightClick()

脚本功能概述
该脚本的主要功能包括:
自动检测微信新消息。
将新消息发送到DeepSeek API以生成智能回复。
自动将生成的回复发送回微信。
准备工作
在运行脚本之前,请确保完成以下准备工作:
安装Python:确保你的系统已安装Python 3.x版本。
安装依赖库:
requests:用于发送HTTP请求。
uiautomation:用于操作Windows上的UI元素。
你可以通过以下命令安装这些库:
bash
复制
pip install requests uiautomation
获取DeepSeek API密钥:
注册并登录DeepSeek API平台,获取API密钥。
替换脚本中的API_KEY为你的实际密钥。
脚本解析
以下是脚本的详细解析:

  1. 导入必要的库
    Python
    复制
    import requests
    import json
    from uiautomation import WindowControl, MenuControl
    requests:用于发送HTTP请求到DeepSeek API。
    json:用于处理JSON数据。
    uiautomation:用于操作微信窗口的UI元素。

  2. 配置DeepSeek API
    Python
    复制
    DEEPSEEK_API_URL = “https://api.deepseek.com/v1/chat/completions”
    API_KEY = “sk-1c8894600e9f4d259edc9da62760f0f8” # 替换为实际API密钥
    HEADERS = {
    “Authorization”: f"Bearer {API_KEY}",
    “Content-Type”: “application/json”
    }
    DEEPSEEK_API_URL:DeepSeek API的URL。
    API_KEY:你的DeepSeek API密钥。
    HEADERS:用于API请求的HTTP头,包含认证信息和内容类型。

  3. 调用DeepSeek API获取回复
    Python
    复制
    def get_deepseek_response(prompt):
    “”"
    调用DeepSeek API获取回复
    “”"
    payload = {
    “model”: “deepseek-chat”, # 根据实际模型调整
    “messages”: [
    {“role”: “user”, “content”: prompt}
    ],
    “temperature”: 0.7,
    “max_tokens”: 150
    }

    try:
    response = requests.post(DEEPSEEK_API_URL, headers=HEADERS, json=payload, timeout=10)
    response.raise_for_status()
    result = response.json()
    return result[‘choices’][0][‘message’][‘content’].strip()
    except Exception as e:
    print(f"API调用失败: {str(e)}")
    return “当前无法回复,请稍后再试。”
    payload:包含发送给API的请求数据,包括模型名称、消息内容、温度参数和最大令牌数。
    requests.post:发送POST请求到DeepSeek API。
    response.raise_for_status():检查API请求是否成功。
    如果请求成功,解析返回的JSON数据并提取回复内容。
    如果请求失败,捕获异常并返回默认错误消息。

  4. 绑定微信窗口
    Python
    复制

绑定微信主窗口

wx = WindowControl(Name=‘微信’)
wx.SwitchToThisWindow()
WindowControl:用于操作窗口控件。
Name=‘微信’:指定要操作的窗口名称为“微信”。
SwitchToThisWindow():切换到微信窗口。
5. 自动检测和回复消息
Python
复制

寻找会话控件绑定

hw = wx.ListControl(Name=‘会话’)

while True:
we = hw.TextControl(searchDepth=4)

while not we.Exists(0):
    pass

if we.Name:
    we.Click(simulateMove=False)
    last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
    
    # 调用DeepSeek获取回复
    reply_content = get_deepseek_response(last_msg)
    
    # 处理换行符
    formatted_reply = reply_content.replace('\n', '{Shift}{Enter}')
    
    # 发送回复
    wx.SendKeys(formatted_reply, waitTime=0)
    wx.SendKeys('{Enter}', waitTime=0)
    
    # 标记为已读
    wx.TextControl(SubName=last_msg[:5]).RightClick()

ListControl(Name=‘会话’):绑定微信的会话列表。
TextControl(searchDepth=4):查找会话中的文本控件。
Exists(0):检查控件是否存在。
Click():模拟点击操作。
GetChildren()[-1].Name:获取最新的消息内容。
SendKeys():模拟键盘输入,发送回复。
RightClick():右键点击消息,标记为已读。
注意事项
DeepSeek API的URL问题:
如果脚本无法成功调用DeepSeek API,请检查DEEPSEEK_API_URL是否正确。
如果遇到网络问题,尝试更换网络环境或稍后重试。
微信窗口操作:
确保微信窗口的名称为“微信”,如果名称不同,请修改脚本中的Name参数。
如果微信窗口未置顶,脚本可能无法正常操作。
API密钥安全性:
不要在公共代码库中暴露你的API密钥。
使用环境变量或配置文件来存储敏感信息。
总结
通过以上脚本,你可以轻松实现微信自动回复功能,并利用DeepSeek API生成智能回复。这不仅可以提高你的工作效率,还能为你的聊天增添更多乐趣。如果你在使用过程中遇到任何问题,欢迎随时与我交流!

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐