PC端微信 机器人智能自动回复实现 全攻略

程序介绍

2021/06/05 更新

这个程序最大的优点就是免费,而且效果很好,环境要求不高。

该自动智能回复机器人基于python编写,笔者使用的版本是python3.7。

智能回复部分采用百度AI提供的智能回复API。

WechatPCAPI

百度UNIT

智能回复部分调用百度UNIT,这个是百度开发的智能回复API,目前免费开放但调用次数有限,不过用于自己玩玩的机器人还是很方便的。如果有更高需求,可以加钱嘛。 具体的调用过程包括: 1.注册UNIT账号 2.注册机器人 3.添加技能并进行排序:这里推荐将智能问答模块的优先级放在后面,因为所有的话它都接管了,导致天气、垃圾分类等功能始终没办法激活。 4.获取API密匙

实现代码

该代码保存在WechatPCAPI默认目录下才可运行,与自带的demo.py放在一个目录下

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import wechat
import json
import time
from bs4 import BeautifulSoup
from queue import Queue
import time
import logging
import threading
import requests
import urllib
import urllib.request
import sys
import ssl
import json
import ast
from wechat import WeChatManager, MessageType

wechat_manager = WeChatManager(libs_path=../../libs)

list_name=[]
open_key=[打开,开启,打开机器人,开启机器人,启动]
close_key=[关闭,关闭机器人]
image_path=D:\20210507195208.jpg

# 这里测试函数回调
@wechat.CONNECT_CALLBACK(in_class=False)
def on_connect(client_id):
    print([on_connect] client_id: {0}.format(client_id))


@wechat.RECV_CALLBACK(in_class=False)
def on_recv(client_id, message_type, message_data):
    print([on_recv] client_id: {0}, message_type: {1}, message:{2}.format(client_id,
                                                                            message_type, json.dumps(message_data)))
    message_dict=json.loads(json.dumps(message_data))

    if message_type==11046:
        try:
            if message_dict[msg] in open_key:
                list_name.append(message_dict[from_wxid])
                reply=open success!
                wechat_manager.send_text(1, message_dict[from_wxid], reply)
            elif message_dict[msg] in close_key:
                list_name.remove(message_dict[from_wxid])
                reply=close success!
                wechat_manager.send_text(1, message_dict[from_wxid], reply)
            elif message_dict[from_wxid] in list_name:
                if message_dict[from_wxid] == "wxid_wbpgt35yeika22":
                    message_dict[from_wxid] = filehelper
                if msg in message_dict.keys():
                    reply = reply_msg(message_dict[msg])
                    wechat_manager.send_text(1, message_dict[from_wxid], reply)
                elif raw_msg in message_dict.keys():
                    wechat_manager.send_image(1,message_dict[from_wxid],image_path)
                elif image in message_dict.keys():
                    wechat_manager.send_image(1,message_dict[from_wxid],image_path)
        except:
            print(error!)


@wechat.CLOSE_CALLBACK(in_class=False)
def on_close(client_id):
    print([on_close] client_id: {0}.format(client_id))


# 这里测试类回调, 函数回调与类回调可以混合使用
class LoginTipBot(wechat.CallbackHandler):

    @wechat.RECV_CALLBACK(in_class=True)
    def on_message(self, client_id, message_type, message_data):
        # 判断登录成功后,就向文件助手发条消息
        if message_type == MessageType.MT_USER_LOGIN:
            time.sleep(2)
            wechat_manager.send_text(client_id, filehelper, 😂😂😂uE052该消息通过wechat_pc_api项目接口发送)

            
            wechat_manager.send_link(client_id, 
            filehelper, 
            wechat_pc_api项目, 
            WeChatPc机器人项目, 
            https://github.com/smallevilbeast/wechat_pc_api, 
            https://www.showdoc.com.cn/server/api/attachment/visitfile/sign/0203e82433363e5ff9c6aa88aa9f1bbe?showdoc=.jpg))
            

def reply_msg(receive_msg):
    # API ID密码
    client_id = 
    client_secret = 
    host = https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id= + client_id + &client_secret= + client_secret
    request = urllib.request.Request(host)
    request.add_header(Content-Type, application/json; charset=UTF-8)
    response = urllib.request.urlopen(request)
    resp_taken = response.read()

    text = json.loads(resp_taken)

    headers = {
          
   Content-Type: application/json}
    access_token = text["access_token"]
    url = https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token= + access_token
    # 这里有一些参数,包括机器人编号之类的(S00000就是,修改成自己的);具体使用方法参照百度UNIT使用手册
    post_data = "{"log_id":"UNITTEST_10000","version":"2.0","service_id":"S31079","session_id":"JA001","request":{"query":"" + receive_msg + "","user_id":"1314520"},"dialog_state":{"contexts":{"SYS_REMEMBERED_SKILLS":["1032946"]}}}"
    request = urllib.request.Request(url, data=post_data.encode(utf-8), headers=headers)
    response = urllib.request.urlopen(request)
    content = response.read().decode("utf-8")

    # if content:
    #    print(content)

    text1 = json.loads(content)
    answer = text1[result][response_list][0][action_list][0][say]
    return answer

if __name__ == "__main__":
    bot = LoginTipBot()

    # 添加回调实例对象
    wechat_manager.add_callback_handler(bot)
    wechat_manager.manager_wechat(smart=True)

    # 阻塞主线程
    while True:
        time.sleep(0.5)

结语

经验分享 程序员 微信小程序 职场和发展