利用Python库wxauto实现(抄)智能微信聊天机器人实现的步骤

292 阅读2分钟

参考文章1 | 参考文章2

抄?那是叫抄吗,年轻人那不叫抄,是借鉴

image.png

回归正题,还是好好的说咋写的吧

前期准备

  1. 需要有 python 环境(照着百度上的教程咔咔一顿装) 有需要可以自取我用的python3.10.11 或者也可以官网下载需要的版本

  2. python 的编译器(vscode、PyCharm...),当然如果你强的可怕也可以直接用文本编辑器写

  3. 照着参考文章1的第4章咔咔一顿操作获取百度大模型的 APIKeySecretKey

  4. 好像没了吧

整活

  1. pythonWorkSpace 下新建一个文件夹,命名为 robotDemo 然后右键点击用vscode(或者其他编译器)打开

  2. vscode 双击或者右键新建文件 wxautochat.py(其他编译器应该右键吧)

  3. 上代码

import time
from wxauto import WeChat
import requests
import json
import re

def get_access_token():
    # """
    # 使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    # """

    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=API Key&client_secret=Secret Key"

    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def get_baidubce_rpc(content):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + get_access_token()

    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": content
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    json_result = json.loads(response.text)
    print("json_result",json_result)
    return json_result['result']

def remove_at_user(content):
    return re.sub(r"@机器人\s+", "", content)

if __name__ == '__main__':
    # 获取微信窗口对象
    wx = WeChat()
    # 输出 > 初始化成功,获取到已登录窗口:xxxx
    # 设置监听列表(可以是好友名,也可以是群名)
    listen_list = [
        'Sy', 
        '机器学习交流群1'
    ]
    # 循环添加监听对象
    for i in listen_list:
        wx.AddListenChat(who=i, savepic=True)
    # 持续监听消息,并且收到消息后回复“收到”
    wait = 1  # 设置1秒查看一次是否有新消息
    while True:
        msgs = wx.GetListenMessage()
        for chat in msgs:
            who = chat.who              # 获取聊天窗口名(人或群名)
            one_msgs = msgs.get(chat)   # 获取消息内容
            # 回复收到
            for msg in one_msgs:
                msgtype = msg.type       # 获取消息类型
                content = msg.content    # 获取消息内容,字符串类型的消息内容
                print(f'【{who}】:{content}')
                
                # 如果是好友发来的消息(即非系统消息等),则回复收到
                if msgtype == 'friend':
                    # 调用函数并传入消息内容
                    # 如果信息为空 或者 content不包含'@机器人' 的信息则等待
                    if not content or "@机器人" not in content:
                        continue
                    # 使用正则表达式替换 "@机器人 " 为空字符串
                    # 获取 百度 大模型的数据
                    result = get_baidubce_rpc(remove_at_user(content))
                    print("get_baidubce_rpc",result)
                    chat.SendMsg(result)
        time.sleep(wait)

最后感谢两位作者大大的文章给予借鉴

image.png