微信pc端接入图灵机器人,实现自动回复

微信pc端接入图灵机器人,实现自动回复

前言

以前微信的个人账号的机器人开发基本都基于itchat等这些针对网页版微信的库进行开发的。微信禁用网页版后,itchat等针对网页版微信开发的库全部失效。现在基于pc版微信使用新库wxauto进行将图灵机器人与微信对接,实现微信的机器人自动回复。

原理步骤

1、通过python的wxauto库获取微信的会话列表,聊天记录等信息。
2、将我们需要的微信记录传输到图灵机器人接口,让图灵机器人对消息做出回应。
3、将图灵机器人的回应返回给微信消息发送人。

实现方法

搭建环境

安装wxauto

方式一:可以在cmd通过pip进行安装:

pip install wxauto

方式二:pycharm中"setting"中通过搜索框安装:

微信登陆

登录pc端微信,并使微信在聊天会话框界面,并最小化微信。(注意:这两步操作非常关键,否则wxauto无法获取微信信息。

代码实现

导入需要的库
from wxauto import *
import threading
import urllib.request
import json

建立微信与python联系

wx = WeChat()

创建元组,将需要自动回复的微信好友微信名列入其中

auto_relpy_list = [] #列表中列入需要自动回复的微信好友的微信聊天框称呼

搭建爬虫,将图灵机器人接入python

def get_response(msgtext):
    try:
        api_url = "http://openapi.tuling123.com/openapi/api/v2"
        text_input = msgtext
        req = {
            "reqType": 0,  # 输入类型 0-文本, 1-图片, 2-音频
            "perception":  # 信息参数
                {
                    "inputText":  # 文本信息
                        {
                            "text": text_input
                        },

                    "selfInfo":  # 用户参数
                        {
                            "location":
                                {
                                    "city": "深圳",  # 所在城市
                                    "province": "广东",  # 省份
                                    "street": "红花岭路"  # 街道
                                }
                        }
                },
            "userInfo":
                {
                    "apiKey": " ",  # 填写自己在图灵官网申请的key
                    "userId": "0001"  # 用户唯一标识(随便填, 非密钥)
                }
        }
        # print(req)
        # 将字典格式的req编码为utf8
        req = json.dumps(req).encode('utf8')
        # print(req)
        http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
        response = urllib.request.urlopen(http_post)
        response_str = response.read().decode('utf8')
        # print(response_str)
        response_dic = json.loads(response_str)
        # print(response_dic)
        #intent_code = response_dic['intent']['code']
        results_text = response_dic['results'][0]['values']['text']
        #print('机器人1号:', results_text)
        # print('code:' + str(intent_code))
        return results_text
    except KeyError:
        print('出错啦~~, 下次别问这样的问题了')

微信消息处理

def run():
       list = wx.GetSessionList()  #获取会话框列表
       #print(list)
       who = str(list[0])  #获取会话框列表首位联系人
       sum = auto_relpy_list.count(who)#将首位与前面建立的自动回复联系人列表进行对比
      #建立判断:如果首位联系人在自动回复列表中,则继续判断是不是自己,不是就把最后一条消息内容传到图灵机器人接口,返回消息,再传给该联系人。
       if  sum==1:
           print(who)
           wx.ChatWith(who)
           msg_0 = wx.GetLastMessage
           if msg_0[0] != '麟':
             print(msg_0[1])
             ms = get_response(msg_0[1])
             print(ms)
             wx.ChatWith(who)
             wx.SendMsg(ms)
       else:
           pass

       timer = threading.Timer(1,run)
       timer.start()

完整代码

from wxauto import *
import threading
import urllib.request
import json
wx = WeChat()
auto_relpy_list = []#列表中填入要自动回复的联系人称呼
# 获取会话列表
def get_response(msgtext):
    try:
        api_url = "http://openapi.tuling123.com/openapi/api/v2"
        text_input = msgtext
        req = {
            "reqType": 0,  # 输入类型 0-文本, 1-图片, 2-音频
            "perception":  # 信息参数
                {
                    "inputText":  # 文本信息
                        {
                            "text": text_input
                        },

                    "selfInfo":  # 用户参数
                        {
                            "location":
                                {
                                    "city": "深圳",  # 所在城市
                                    "province": "广东",  # 省份
                                    "street": "红花岭路"  # 街道
                                }
                        }
                },
            "userInfo":
                {
                    "apiKey": " ",  # 改为自己申请的key
                    "userId": "0001"  # 用户唯一标识(随便填, 非密钥)
                }
        }
        # print(req)
        # 将字典格式的req编码为utf8
        req = json.dumps(req).encode('utf8')
        # print(req)
        http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
        response = urllib.request.urlopen(http_post)
        response_str = response.read().decode('utf8')
        # print(response_str)
        response_dic = json.loads(response_str)
        # print(response_dic)
        #intent_code = response_dic['intent']['code']
        results_text = response_dic['results'][0]['values']['text']
        #print('机器人1号:', results_text)
        # print('code:' + str(intent_code))
        return results_text
    except KeyError:
        print('出错啦~~, 下次别问这样的问题了')
def run():
       list = wx.GetSessionList()
       print(list)
       who = str(list[0])
       sum = auto_relpy_list.count(who)
       if  sum==1:
           print(who)
           wx.ChatWith(who)
           msg_0 = wx.GetLastMessage
           if msg_0[0] != '麟':
             print(msg_0[1])
             ms = get_response(msg_0[1])
             print(ms)
             wx.ChatWith(who)
             wx.SendMsg(ms)
       else:
           pass

       timer = threading.Timer(1,run)
       timer.start()
if __name__ == '__main__':
    run()

总结

注意:wxauto对实现环境的要求比较苛刻,要耐心去尝试;上述代码只实现了对文本内容的识别如回复,若好友发送的是文本以外的内容就会报错。

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值