Using python to realize wechat automatic reply, group sending and other operations (no need to log in to wechat on the web)

At present, wechat web version restricts login, and the means of operating wechat by wxpy and other modules can not be used. WechatPCAPI module was found a while ago. Wechat is operated by means of dll injection. Here is how to use this module.

Operating environment

The WechatPCAPI module still has strict requirements for the running environment. It needs to use the old version of wechat and python 3 seven
Module download address:
https://github.com/terrywangt/WeChatBot
The module downloaded from github contains the old version of wechat. The path is as follows:

WeChatBot-master.zip\WeChatBot-master\botWeb\bot\Wechat-V2.7.1.82.exe

Log in to wechat

Run the following code to pop up the wechat login interface, on_ The message function is used to process the received message.

from WechatPCAPI import WechatPCAPI
import time
import logging
from datetime import date
from queue import Queue
import threading

logging.basicConfig(level=logging.INFO)

def on_message(message):
	# Print received messages
    print("message->:",message)
    
def main():
	wx_inst = WechatPCAPI(on_message=on_message, log=logging)
    wx_inst.start_wechat(block=True)
    while not wx_inst.get_myself():
        time.sleep(5)
    threading.Thread(target=thread_handle_message, args=(wx_inst,)).start()

if __name__ == '__main__':
    main()

Processing messages using Queue()

This step is not necessary

Insert here from WechatPCAPI import WechatPCAPI
import time
import logging
from datetime import date
from queue import Queue
import threading
from queue import Queue

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

def on_message(message):
    queue_recved_message.put(message)

def thread_handle_message(wx_inst):
    """
    Message processing shunting
    """
    while True:
        message = queue_recved_message.get()
        print(message)
        # Add your message processing code down
    
def main():
	wx_inst = WechatPCAPI(on_message=on_message, log=logging)
    wx_inst.start_wechat(block=True)
    while not wx_inst.get_myself():
        time.sleep(5)
    threading.Thread(target=thread_handle_message, args=(wx_inst,)).start()

if __name__ == '__main__':
    main()

Received message structure

To process messages, you must first understand the structure of the received data. There are four main structures

The structure of the received friend chat message is as follows. The type is msg::single

        {
            'user': 'The default micro signal will not be changed after modification', 
            'type': 'msg::single', 
            'data': {
                'data_type': '1', 
                'send_or_recv': '0+[received]', 
                'from_wxid': 'The default wechat will not change after modification', 
                'time': '2022-01-21 15:11:04', 
                'msg': 'Messages sent by friends', 
                'from_nickname': 'Friend nickname, not note'
            }
        }

The structure of the received group chat message is as follows. The type is msg::chatroom

       {'user': 'The default micro signal will not be changed after modification', 
            'type': 'msg::chatroom', 
            'data': {'data_type': '1', 
                'send_or_recv': '0+[received]', 
                'from_chatroom_wxid': 'Group chat id,Shape: 12756220923@chatroom', 
                'from_member_wxid': 'Sending messages to group members',
                'time': '2022-01-26 15:30:03', 
                'msg': 'Messages received', 
                'from_chatroom_nickname': 'Group chat name'
            }
        }

There are also two types of data, friend::person and friend::chatroom, which are the basic information of friends and group chat respectively. After logging in to wechat, you will first obtain these two kinds of data. You can obtain the relevant information of all friends and group chat by processing these two kinds of data

all_users = {}      # All friends of wechat
all_chatroom = {}   # Wechat all group chat
# Capture friend::person and friend::chatroom, and get all wechat friends and group chat
if message['type'] == 'friend::person':
	all_users[message['data']['wx_nickname']] = message['data']['wx_id']
if message['type'] == 'friend::chatroom':
	all_chatroom[message['data']['chatroom_name']] = message['data']['chatroom_id']

send message

Send to individuals or group chat through the following forms

wx_inst.send_text(to_user=Micro signal or group chat number, msg=What to send)

Call Tianxing robot to reply information automatically

First register Skywalker robot interface from the following website
https://www.tianapi.com/apiview/47
After registering the interface, get a key, copy the key and fill in the following code

tx_url = 'http://api.tianapi.com/txapi/robot/index?key={}&question={}'
tx_key = 'You registered to get key'

def tx_robot(msg):
    """Send the received message to Tianxing robot and return the content"""
    r = requests.get(tx_url.format(tx_key, msg)).json()
    code = int(r['code'])
    msg = r['msg']
    if code != 200:
        print(f'[Error code{code}: {msg},Please check the configuration item"tx_key". ')
    return r["newslist"][0]["reply"]
 
def on_message(message):
	if message['type'] == 'msg::single':
		wxid = message['data']['from_wxid']	# Friend wechat
		msg = message['data']['msg']		# Messages received
		name = message['data']['from_nickname']
		send_or_recv = message['data']['send_or_recv']
	# If you don't judge send_or_recv will send unlimited messages and talk to itself
	if send_or_recv == '0+[received]':
		wx_inst.send_text(to_user=wxid, msg=tx_robot(msg))

ending

These are the basic operations of WechatPCAPI module. The rest is to add your message processing code to realize the functions of mass sending and automatic reply. You can also control the switch of these functions by sending specific information to your file transmission assistant.
The author has written a program including Turing / Skywalker robot automatic reply, template automatic reply and group sending function through WechatPCAPI. Interested readers can download it through the following link.
Wechat automatic reply and group sending program

Keywords: Python wechat

Added by Hatdrawn on Tue, 08 Feb 2022 06:55:34 +0200