微信自動回覆如何實現?用 Python 就能夠!

在以前的文章 Python遇到微信 中,咱們使用 WechatPCAPI 作了獲取微信好友信息以及查看撤回消息,本文咱們再使用 WechatPCAPI 來實現微信自動回覆的功能。python

實現自動回覆的功能,咱們須要用到圖靈機器人,網址爲:http://www.turingapi.com,咱們在瀏覽器中輸入上述網址打開,以後點擊註冊/登陸按鈕,以下圖所示:json

打開後以下圖所示:api

咱們接着點擊當即註冊,就跳轉到了註冊頁,以下圖所示:瀏覽器

咱們先填寫必填信息,填寫完以後點擊註冊按鈕便可,註冊成功以後便跳到了機器人管理頁面,以下所示:微信

咱們點擊建立機器人按鈕跳轉到以下頁面:dom

咱們填寫完相應信息以後點建立按鈕,以後會跳轉到機器人設置頁面,以下圖所示:url

咱們須要記錄下 apikeyspa

有了 apikey,咱們就能夠實現自動回覆功能了,實現代碼以下所示:code

import time, logging, random, requests
from queue import Queue
from WechatPCAPI import WechatPCAPI

logging.basicConfig(level=logging.INFO)
queue_recved_event = Queue()

def on_message(msg):
    queue_recved_event.put(msg)

# 機器人返回消息
def reply_msg(receive_msg):
    apikey = '本身的apikey'
    apiurl = 'http://www.tuling123.com/openapi/api?key=%s&info=%s' % (apikey, receive_msg)
    result = requests.get(apiurl)
    result.encoding = 'utf-8'
    data = result.json()
    return data['text']

def login():
    pre_msg = ''
    # 初始化微信實例
    wx_inst = WechatPCAPI(on_message=on_message, log=logging)
    # 啓動微信
    wx_inst.start_wechat(block=True)
    # 等待登錄成功,此時須要人爲掃碼登陸微信
    while not wx_inst.get_myself():
        time.sleep(5)
    print('登錄成功')
    while True:
        msg = queue_recved_event.get()
        if 'msg::single' in msg.get('type'):
            data = msg.get('data')
            if data.get('is_recv', False):
                msgfrominfo = data.get('msgfrominfo')
                if msgfrominfo is not None:
                    wx_id = msgfrominfo.get('wx_id')
                    if wx_id != 'weixin':
                        receive_msg =str(data.get('msgcontent'))
                        reply = reply_msg(receive_msg)
                        wx_inst.send_text(to_user=wx_id, msg=reply)

看一下實現效果:utf-8

完整代碼在下方公衆號後臺回覆 200523 獲取。

qrcode1.PNG

相關文章
相關標籤/搜索