Want to see the messages recalled by wechat friends? Python does it for you

 

Preface
The text and pictures of this article are from the Internet, only for learning and communication, not for any commercial purpose. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.
By ~ wangweijun

Python wechat anti recall applet,

When you chat with each other via wechat, the other party suddenly withdraws several messages. Would you be curious? Would you like to know what the other party has withdrawn? The wechat anti withdrawal applet implemented in Python makes it easy for you to get the message content withdrawn by the other party

 

To say the most disgusting invention of wechat, message withdrawal can definitely be on the list.

For example, you are chatting with your girlfriend via wechat, or with a girl you like. If you don't pay attention to her, you will be withdrawn in time. At this time, you are curious about what she has sent? So you're going to ask her what she sent, and she says, "nothing.". This reply makes your curiosity more intense, and immediately feels that the function of message withdrawal is used to torture people.

So is there any way to know what your beloved has withdrawn? Don't worry, python will do it for you. If you don't know how to write Python programs, I suggest you go to the python exchange. Skirt: after a long time, you can find the latest Python tutorial project under the conversion of streaming and thinking (homophony of numbers). If you communicate with them more, you will make rapid progress!

Module introduction

This article will use Python to implement the anti withdrawal function of wechat. For wechat operation, python has a very powerful library: itchat. I'm sure I've heard about it even though I haven't used it. The official way of describing it is as follows:

Project description
itchat is a open souce wechat api project for personal account.

It enables you to access your personal wechat account through command line.

itchat is an open wechat api project for personal accounts, which enables you to access your personal wechat account through the command line.

Since it's for the development of wechat, we can't do without the help of this module, so first download this module:

pip install itchat

You can also directly import the module in the development tool Pycharm, which will prompt you to download it.

Module initial experience

Considering that some people should never use the module, here is a simple introduction to the module.

1. How to log in wechat

Since we want to operate wechat, the question before us is how to log in to wechat. Logging in to wechat is very simple. Look at the code directly:

import itchat

itchat.login()

Yes, one code can complete the login, and a QR code will pop up after running. After scanning, you can authorize the login on the mobile phone, and the console will prompt whether the login is successful.

Login successfully as Y

This means that the login is successful.

Here we need to pay attention to the problem that you will find that every time you run a program, you have to scan the QR code to log in, which is too troublesome. Is there any way to scan only once, and then log in automatically? Of course it can.

import itchat

itchat.auto_login(hotReload=True)

Through function name, you can also know that this method can realize automatic login, run the program, scan the code to login, and then create an itchat.pkl file under the project path. This file is used to store the login status, so do not touch it. If you want to change a wechat account to login, you need to delete this file first, because this file records the status of the previous wechat, delete it Then log in.

Note: this method can only ensure that you do not need to log in repeatedly in a short period of time. If the time is long, you still need to scan the code again to log in.

In this case, some people may find that their wechat can't log in. As far as I know, some newly registered wechat and long-term unused wechat can't log in to the web version of wechat, so it will also lead to login failure here. If you can't log in, there's no way. The following is meaningless.

2. Get friends list

After logging in to wechat, let's use some APIs provided by itchat module, such as getting friends list.

import itchat

itchat.auto_login(hotReload=True)
friends = itchat.get_friends()  # Friends list
print(friends)

You can get all the friends' information in the friends list, including nickname, comment name, address, personal signature, gender, etc. by using the get_friends() function.

Here I randomly copy a friend's personal information. Of course, due to privacy issues, I use "*" instead of some of the information here. We focus on analyzing the content of these information. For example, the first UserName is the unique identification of the user, which is equivalent to the ID card number. Each of your friends will have such an identification, which must be different from each other. Then it's nick name, which is the NickName of your friend. HeadImgUrl is the address of your friend's head image. RemarkName is your comment name to your friend. Province is the province, etc., which is not introduced here Shao, if you are interested, you can find out for yourself.

3. How to send messages to friends

How to send a message to a designated friend? It's also very simple:

import itchat

itchat.auto_login(hotReload=True)
itchat.send('Hello World', toUserName='@f9e42aafa1175b38b60a0be4d651a34c77f2528d9b7784e7aaf415090eca8fa6')

 

At this time, UseName comes into use, that is, the unique ID of a friend. In this way, we send a message to the corresponding friend of the ID, so we can improve the program as follows:

import itchat

itchat.auto_login(hotReload=True)
friends = itchat.get_friends()
nickName = 'Chengchengtong authorized channel provider-Lao Zeng'
for i in friends:
    if 'Chengchengtong authorized channel provider-Lao Zeng' == i['NickName']:
        itchat.send('Hello World', toUserName=i['UserName'])
        break

In this way, you can specify to send it to any friend, retrieve it in the friend list through the nickname of the friend, if you find it, you can get the user name of the friend, and then send a message, or you can find it through the remark name of the friend, and you can try it yourself.

4. Decorator

There are many functions about itchat module, so I won't explain them too much here. We only talk about the knowledge of this program. Here is the last content, decorator.

About decorators, it will not be clear for a while. Here is just a brief introduction. The function of decorators is a function used to expand the original function. The purpose is to add new functions to the function without changing the original function name (or class name).

For example, now there is a function called fun(). You don't know the implementation principle of the function, and you can't modify the code of the function, but you need to add a function to output the start time and end time of the function. How to implement it? You can use decorators at this time.

import time
 
def show_time(fun):
    def inner():
        print(time.time())
        fun()
        print(time.time())
    return inner   
 
@show_time
def fun():
    pass
 
fun()

How to understand this procedure? First, @show_time is to use a decorator show_time, which will pass the decorating function, that is, fun(), as the parameter to the decorator show_time(). We know that the function as the return value is actually executing the function, so the program executes the internal function inner(), when the output starts running time, and then calls the fun() function (the original function can not be lost), and finally, the output will start. Output end run time. In this way, the function extension of a function is realized through the decorator, which is also a typical aspect oriented programming idea.

How to get messages sent by friends

After the preparation, we will get to the main point. For the above knowledge points, you must master them. If you don't understand them, you may be confused about the next code.

First, let's see how to get messages sent by friends.

import itchat

itchat.auto_login(hotReload=True)


@itchat.msg_register(itchat.content.TEXT)
def resever_info(msg):
    print(msg)


itchat.run() #keep

The itchat module provides the @ itchat.msg_register decorator to listen to messages. For example, here we customize a function of reset_info() and use the decorator to listen to messages. In the decorator, the type of itchat.content.TEXT is passed in, so what we listen to is the text message. After listening to the input, the decorator will pass the text message into the parameter of reset_info(). Therefore, msg is the content of the message.

For @ itchat.msg_register decorator, it can not only listen to text, but also listen to voice, picture, map, business card, video, etc. for convenience, here we import all the content in the content module under the itchat module, because these message types are declared under the module.

TEXT       = 'Text'
MAP        = 'Map'
CARD       = 'Card'
NOTE       = 'Note'
SHARING    = 'Sharing'
PICTURE    = 'Picture'
RECORDING  = VOICE = 'Recording'
ATTACHMENT = 'Attachment'
VIDEO      = 'Video'
FRIENDS    = 'Friends'
SYSTEM     = 'System'

INCOME_MSG = [TEXT, MAP, CARD, NOTE, SHARING, PICTURE,
    RECORDING, VOICE, ATTACHMENT, VIDEO, FRIENDS, SYSTEM]

What's more, remember to call itchat's run() function to keep the program running, otherwise the program will end directly.

Next, we can test it. I asked my friend to send me a message, and the console output the following:

There are a lot of contents, we only choose the important ones. For example, FromUserName, which is the sender's ID; ToUserName, which is the receiver's ID; Content, which is the text Content of course; CreateTime, which is the sending time; note the last two values: Type, which is the message Type, which is the text Type, and then text is the text Content, so if you want to get the message Content sent by your friends, use Content and Text. After the analysis, it's easy to extract the Content:

import itchat
import time
from itchat.content import *  # Import content module under itchat

itchat.auto_login(hotReload=True)


@itchat.msg_register(TEXT)
def resever_info(msg):
    info = msg['Text']  # Get text message
    info_type = msg['Type']  # Get message type
    fromUser = itchat.search_friends(userName=msg['FromUserName'])['NickName']
    ticks = msg['CreateTime']  # Time to get information sent
    time_local = time.localtime(ticks)
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)  # format date
    print("Give a person:" + fromUser + '\n Message type:' + info_type + '\n Sending time:' + dt + '\n Message content:' + info)


itchat.run(

The time module is used to format the date.

For the convenience of testing, I sent a message to others by myself. The message I sent will also be monitored. See the operation result:

Give the person: Y
 Message type: Text
 Sending time: November 28, 2019 16:19:13
 Message content: woodlouse

Try voice and picture again. Can you get it? Let's go back to the code:

import itchat
from itchat.content import *  # Import content module under itchat

itchat.auto_login(hotReload=True)


@itchat.msg_register(TEXT)
def resever_info(msg):
    print(msg)


itchat.run()

After running, try sending voice and pictures. No matter how you send them, the console just doesn't respond. Of course, we haven't monitored the voice and pictures yet. Modify the code:

import itchat
from itchat.content import *  # Import content module under itchat

itchat.auto_login(hotReload=True)


@itchat.msg_register([TEXT, PICTURE, RECORDING])	#Added monitoring for pictures and voice
def resever_info(msg):
    print(msg)


itchat.run()

Try again. First send a picture, then a voice. The console outputs two paragraphs of content. Because the length is too long, it won't be pasted out. It's just the information, sender, receiver, date, message content, etc. here, just pay attention to the content of the picture and voice:

'Type': 'Picture', 'Text': <function get_download_fn.<locals>.download_fn at 0x0000000003574158>
'Type': 'Recording', 'Text': <function get_download_fn.<locals>.download_fn at 0x0000000002CFED08>

This is an address, through which we can save pictures and voice.

How to save pictures and voice sent by friends

Next, we will save the pictures and voice sent by our friends.

import itchat
import os
from itchat.content import *  # Import content module under itchat

itchat.auto_login(hotReload=True)
temp = 'C:/Users/Administrator/Desktop/CrawlerDemo' + '/' + 'Recalled message'
# If the folder does not exist, create
if not os.path.exists(temp):
    os.mkdir(temp)


@itchat.msg_register([TEXT, PICTURE, RECORDING])
def resever_info(msg):
    info = msg['Text']  # Get text message
    info_type = msg['Type']  # Get message type
    name = msg['FileName']  # Take out the voice (picture) file name

    if info_type == 'Recording':
        # Voice preservation
        info(temp + '/' + name)
    elif info_type == 'Picture':
        # Save pictures
        info(temp + '/' + name)


itchat.run()

Run it, then send a picture and a voice, and two files will be generated in the specified directory:

How to listen to a friend withdraw a message

So far, we have finished message monitoring, just need to modify it a little, but this program is flawed, because not all messages need to be saved. We can directly see the messages sent by friends normally. Isn't it unnecessary to save them? Our goal is to know what our friends have withdrawn, which involves how to monitor whether our friends have withdrawn their messages. In fact, it is also very simple. The Content module provides us with the NOTE type, which refers to the system message.

So we can customize a function to listen to system messages:

import itchat
from itchat.content import *  # Import content module under itchat


itchat.auto_login(hotReload=True)

@itchat.msg_register(NOTE)
def note_info(msg): # Monitor system messages
    print(msg)


itchat.run()

Run the program, we withdraw a message to test, and the output is as follows:

......
'DisplayName': '', 'ChatRoomId': 0, 'KeyWord': '', 'EncryChatRoomId': '', 'IsOwner': 0}>, 'Type': 'Note', 'Text': 'You withdrew a message'}
......

If you intercept part of the content here, you will find that the text content of the recall message is "you have recalled a message", so it's very simple to know whether your friend has recalled the message. Judge msg['Text '] = =' you have recalled a message '.

Implement wechat anti withdrawal program

The code of each step of the program is analyzed here. Next is the summary of all the codes and the complete code of the whole program:

import itchat
from itchat.content import *
import os
import time
import xml.dom.minidom	# Parsing xml module

# This is the file directory (such as picture, voice, etc.) where the recall message is saved. It has been written down. You can modify it yourself
temp = 'C:/Users/Administrator/Desktop/CrawlerDemo' + '/' + 'Recalled message'
if not os.path.exists(temp):
    os.mkdir(temp)

itchat.auto_login(True)	# automatic logon

dict = {}	# Define a dictionary


# This is a decorator, adding new functions to the following functions
# Can capture messages sent by friends and pass them to the function parameter msg
@itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO])  # Text, voice, picture
def resever_info(msg):
    global dict	# Declare global variables

    info = msg['Text']  # Get message content
    msgId = msg['MsgId']  # Get message ID
    info_type = msg['Type']  # Get message type
    name = msg['FileName']  # Get message file name
    # Get the message sender ID and retrieve it from the friends list
    fromUser = itchat.search_friends(userName=msg['FromUserName'])['NickName']
    ticks = msg['CreateTime']  # Time to get information sent
    time_local = time.localtime(ticks)
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)  # format date
    # Add message ID and message content to dictionary
    # The unique identifier of each message is the key, and the specific information of the message is the value. It is also a dictionary
    dict[msgId] = {"info": info, "info_type": info_type, "name": name, "fromUser": fromUser, "dt": dt}
    

@itchat.msg_register(NOTE)  # Monitor system prompt
def note_info(msg):
    # Listening to a message recalled by a friend
    if 'Recalled a message' in msg['Text']:
        # Get the Content node value in the system message
        content = msg['Content']
        # Content value is xml, parsing xml
        doc = xml.dom.minidom.parseString(content)
        # Take out the value of msgid tag
        result = doc.getElementsByTagName("msgid")
        # The msgId is the message ID of the recall, through which the message information of the recall can be found in the dictionary
        msgId = result[0].childNodes[0].nodeValue
        # Get the message type of the corresponding message ID from the dictionary
        msg_type = dict[msgId]['info_type']
        if msg_type == 'Recording':	# The recalled message is voice
            recording_info = dict[msgId]['info']  # Retrieve the message content corresponding to the message ID
            info_name = dict[msgId]['name'] # Get message file name
            fromUser = dict[msgId]['fromUser'] # Take out sender
            dt = dict[msgId]['dt'] # Take out send time
            recording_info(temp + '/' + info_name) # Voice preservation
            # Splicing prompt message
            send_msg = '[Give a person:]' + fromUser + '\n' + 'Sending time:' + dt + '\n' + 'Withdrawn a voice'
            itchat.send

Tags: Python xml pip Pycharm

Posted on Fri, 17 Apr 2020 06:00:59 -0700 by MadTechie