python获取微信最新消息并通过AI回复

AI处理消息

我这里使用的是阿里云通义千问qwen-long,可以自己找模型和api-key

可以在这里 阿里云百炼平台 注册并获取key,当然可以是其他大模型,百度千帆,文心一言,豆包,chatgpt等等

from openai import OpenAI

# 向AI发送消息
def request_url(nickname, message):
    client = OpenAI(
        api_key="api-key",  # 替换成真实DashScope的API_KEY
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    
    # 如果用户有历史对话,则加载历史对话,否则初始化新的对话
    if nickname not in conversation_history:
        conversation_history[nickname] = [
            {
                'role': 'system',
                'content': '你现在正在通过微信与用户交流'
            },
            {
                'role': 'system',
                'content': 'getMsgContent()方法返回的内容正是微信的文本消息最长可以支持的,即採用UTF-8编码方式时,文本消息内容最多支持2047个字节,在中文情况下,大约800-1000个字符左右,请注意你每次回答的内容长度'
            },
            {
                'role': 'system',
                'content': '你叫"你爹",一个智能助手'
            },
            {
                'role': 'system',
                'content': '默认回答,第一次要回答,现在本人不在,由我来暂时回答你的问题'
            },
            {
                'role': 'system',
                'content': '由于限制,你现在只支持处理文本消息'
            }
        ]
    
    # 追加新消息到对话历史
    conversation_history[nickname].append({
        'role': 'user',
        'content': message
    })
    
    completion = client.chat.completions.create(
        model="qwen-long",
        messages=conversation_history[nickname],
        stream=False
    )
    json_resp = completion.choices[0].message.model_dump().get('content')
    
    # 将AI回复追加到对话历史中
    conversation_history[nickname].append({
        'role': 'assistant',
        'content': json_resp
    })
    #print("对话历史:",conversation_history)
    return json_resp

获取微信窗口

from uiautomation import WindowControl

# 绑定微信主窗口
wx = WindowControl(
    Name='微信', ClassName="WeChatMainWndForPC"
    # searchDepth=1
    )
# 切换窗口
wx.SwitchToThisWindow()
    # 寻找会话控件绑定
    
hw = wx.ListControl(Name='会话')
we = hw.TextControl(searchDepth=4)

 检查微信消息

def check_wechat_messages(hw):
    bbb = hw.GetChildren()
    while not we.Exists(0):
        time.sleep(0.5)
    for chatMsg in bbb:
        if "条新消息" in chatMsg.Name:
            match = re.match(r'(.+?)(\d+)条新消息', chatMsg.Name)
            if match:
                nickname = match.group(1)
                if nickname in allowed_nicknames:  # 仅在nickname在允许列表中时才回复
                    message_count = int(match.group(2))
                    printInfo = f"来自 {nickname} 的{message_count} 条消息"
                    print(printInfo)
                    getMsg_send(nickname)

发送消息

def getMsg_send(nickname):
    if we.Name:
        we.Click(simulateMove=False)
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
        print(f"{nickname}:", last_msg)
        
        msg = request_url(nickname, last_msg)
        print("我(qwen-long):", msg)
        
        if msg:
            # 切换窗口
            wx.SwitchToThisWindow()
            wx.SendKeys(msg.replace('{br}', '{Shift}{Enter}'), waitTime=0)
            wx.SendKeys('{Enter}', waitTime=0)
            wx.TextControl(SubName=msg[:5]).RightClick()
        else:
            wx.TextControl(SubName=last_msg[:5]).RightClick()

完整示例

运行程序之前打开微信窗口。如果有新消息,它会点击并回复最新一条消息,现在支持回复指定昵称,就是备注,即对方在你通讯录中显示的名字,把这个昵称添加到allowed_nicknames中

import uiautomation as auto
from openai import OpenAI
import pandas as pd
import numpy as np
import time
import re

from uiautomation import WindowControl, MenuControl
from plyer import notification

# 存储每个用户的对话历史
conversation_history = {}

# 允许回复的nickname列表
allowed_nicknames = {"张三","李四","王五","老六"}  # 修改为你想要回复的nickname

# 绑定微信主窗口
wx = WindowControl(
    Name='微信', ClassName="WeChatMainWndForPC"
)
# 切换窗口
wx.SwitchToThisWindow()

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

# 向AI发送消息
def request_url(nickname, message):
    client = OpenAI(
        api_key="api-key",  # 替换成真实DashScope的API_KEY
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    
    # 如果用户有历史对话,则加载历史对话,否则初始化新的对话
    if nickname not in conversation_history:
        conversation_history[nickname] = [
            {
                'role': 'system',
                'content': '你现在正在通过微信与用户交流'
            },
            {
                'role': 'system',
                'content': 'getMsgContent()方法返回的内容正是微信的文本消息最长可以支持的,即採用UTF-8编码方式时,文本消息内容最多支持2047个字节,在中文情况下,大约800-1000个字符左右,请注意你每次回答的内容长度'
            },
            {
                'role': 'system',
                'content': '你叫"你爹",一个智能助手'
            },
            {
                'role': 'system',
                'content': '默认回答,第一次要回答,现在本人不在,由我来暂时回答你的问题'
            },
            {
                'role': 'system',
                'content': '由于限制,你现在只支持处理文本消息'
            }
        ]
    
    # 追加新消息到对话历史
    conversation_history[nickname].append({
        'role': 'user',
        'content': message
    })
    
    completion = client.chat.completions.create(
        model="qwen-long",
        messages=conversation_history[nickname],
        stream=False
    )
    json_resp = completion.choices[0].message.model_dump().get('content')
    
    # 将AI回复追加到对话历史中
    conversation_history[nickname].append({
        'role': 'assistant',
        'content': json_resp
    })
    #print("对话历史:",conversation_history)
    return json_resp

def check_wechat_messages(hw):
    bbb = hw.GetChildren()
    while not we.Exists(0):
        time.sleep(0.5)
    for chatMsg in bbb:
        if "条新消息" in chatMsg.Name:
            match = re.match(r'(.+?)(\d+)条新消息', chatMsg.Name)
            if match:
                nickname = match.group(1)
                if nickname in allowed_nicknames:  # 仅在nickname在允许列表中时才回复
                    message_count = int(match.group(2))
                    printInfo = f"来自 {nickname} 的{message_count} 条消息"
                    print(printInfo)
                    getMsg_send(nickname)

def getMsg_send(nickname):
    if we.Name:
        we.Click(simulateMove=False)
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
        print(f"{nickname}:", last_msg)
        
        msg = request_url(nickname, last_msg)
        print("我(qwen-long):", msg)
        
        if msg:
            # 切换窗口
            wx.SwitchToThisWindow()
            wx.SendKeys(msg.replace('{br}', '{Shift}{Enter}'), waitTime=0)
            wx.SendKeys('{Enter}', waitTime=0)
            wx.TextControl(SubName=msg[:5]).RightClick()
        else:
            wx.TextControl(SubName=last_msg[:5]).RightClick()

if __name__ == "__main__":
    i = 1
    try:
        while True:
            print(f"{i}.检测中,等待消息...")
            check_wechat_messages(hw=hw)
            time.sleep(1)
            i += 1
    except KeyboardInterrupt:
        print("程序退出~")
    except Exception as e:
        print(f"程序执行出现了问题: {str(e)}")

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值