Implement a WeChat message withdrawal capture function with Python 80 lines of code

Implement a WeChat message withdrawal capture function with Python 80 lines of code

Ever since WeChat released this message recall function, I have been tortured to death. I am a curious person. After WeChat released this function, I feel that my health is getting worse day by day. Every time I see the message sent by the goddess and then withdraw it, I feel itchy. So I wrote a WeChat message recall catcher. Now let me teach you how to get rid of being single and become a rich and beautiful woman.

1. Module Introduction

First of all, to realize message withdrawal and capture, we need to use a very powerful library on Python: itchat. If you have not used it, I will introduce it to you:

  1. Project description
  2. itchat is an open souce wechat api project for personal account.
  3. It enables you to access your personal wechat account through command line.

The above means: itchat is an open source WeChat API project for personal accounts. You can access your personal WeChat account through the command line. So we are going to use this library today. First we have to:

  1. pip install itchat

2. Familiarity with module functions

The editor here takes into account that some friends have never used this module, so the following will give a brief explanation of this module.

2.1 How to log in to WeChat

Since we want to capture WeChat's withdrawal information, the first step must be to log in to WeChat. Logging in to WeChat is very simple and only requires two lines of code:

  1. import itchat​itchat.login()

That's it, isn't it very simple? Then after running it, a QR code will appear. After scanning it, authorize the login on your mobile phone, and the console will show whether you have logged in successfully.

  1. •Login successfully as .

This means that you have logged in successfully. However, if you have newly created WeChat or have not used WeChat for a long time, you will not be able to log in to the web version of WeChat, so this will also cause you to fail to log in. If you cannot log in, there is nothing you can do.

2.2 Get the friend list

  1. import itchat
  2. itchat.auto_login(hotReload= True )
  3. friends = itchat.get_friends() #Friends list
  4. print(friends)

Use the get_friends() function to get all the friend information in the friend list, including nickname, note name, address, personality tag, gender, etc.

  1. [{ 'UserName' :
  2. '@7c2215e17edf4b193f125d6ecf944abcaf19ba72e3eb24b8442d5e32d4a8be92' ,
  3. 'City' : '' , 'DisplayName' : '' , 'PYQuanPin' : '' , 'RemarkPYInitial' :
  4. '' , 'Province' : '' , 'KeyWord' : '' , 'RemarkName' : '' , 'PYInitial' : '' ,
  5. 'EncryChatRoomId' : '' , '**' : '' , 'Signature' : '' , 'NickName' : '**' ,
  6. 'RemarkPYQuanPin' : '' , 'HeadImgUrl' : '**'  

Here I just copied a friend's information. Regarding the privacy issue, I replaced all the information with **. Our focus is to analyze the content of this information. For example, the first UserName is the user's unique identifier, which is equivalent to the ID number. All friends' UserNames are different. Then there is NickName: This is the friend's nickname, HeadImgUrl: This is the friend's avatar address, and there are some others that I will not introduce one by one. If you are interested, you can learn about them yourself.

2.3 Send messages to friends

We are now ready to send a message to a friend. How do we do this? See the following code

  1. import itchat
  2. itchat.auto_login(hotReload= True )
  3. itchat.send( "Life is short, I learn python" , toUserName = "@c4326bda513bf7cdd19f1fa03dbf7e7bc3bbc57e5abb71fd580b2c3c32cddd99" )

The itchat.send() function can take two parameters, the first one is the information you want to send to your friend, and the second one is the specified friend, that is, toUserName = the unique identifier UserName mentioned above. However, I think the above method is still a bit inappropriate, so I improved it.

  1. import itchat
  2. itchat.auto_login(hotReload= True )friends = itchat.get_friends()nickName = 'You are bald but I am not'  
  3. for i in friends:
  4. if 'You are bald and I am not' == i[ 'NickName' ]:
  5. itchat.send( 'Life is short, I learn python' , toUserName=i[ 'UserName' ])
  6. break

In this way, I can send a message to any friend by searching in the friend list by the friend's nickname. If I find it, I will get the friend's UserName and send a message. I can also search by the friend's RemarkName. You can choose according to your preferences.

2.4 Decorators

There are many functions in the itchat module, so I won't explain them here. We just need to understand the knowledge points needed for message withdrawal. Then we will move on to the last content, the decorator. I will briefly introduce the decorator. The decorator is a function that is brave enough to expand the original function. The purpose is to add new functions to the function without changing the original function name. For example, I have another function foo(). You don't know the implementation principle of the function, and you certainly can't modify the code of this function. But you need to add a function to output the start and end running time to this function. How to achieve it? At this time, you can use the decorator:

  1. import time  
  2. def show_time(foo):
  3. def inner ():
  4. print( time . time ()) foo() print( time . time ()) return   inner     
  5. @show_timedef foo(): passfoo()

The meaning of the above code is: first, @show_time uses a decorator show_time. At this time, the decorator function, that is, foo(), will be passed as a parameter to the decorator show_time(). We know that if the function is used as the return value, it is actually the function that is executed, so the program will execute the internal function inner(), which outputs the start running time, then calls the foo() function, and finally outputs the end running time. In this way, a function extension is realized, which is also a typical aspect-oriented programming idea.

3. How to monitor the information withdrawn by friends

In fact, we have completed the message monitoring here and only need to make a slight modification. However, there is still a problem with this program, that is, we need to save all the messages. We can directly see the messages sent by friends normally. Isn’t it redundant to save them? Our goal is to know what content our friends have withdrawn. Here we need to know how to monitor whether friends have withdrawn information. In fact, it is not difficult. The Content module provides us with the NOTE type, which refers to the system message, so we can customize a function to monitor the system message:

  1. import itchat
  2. from itchat.content import * # Import the content module under itchat
  3. itchat.auto_login(hotReload= True )
  4. @itchat.msg_register(NOTE)
  5. def note_info(msg): #Monitor system messages
  6. print(msg)
  7. ​​itchat.run()

Run the program and withdraw a message to test it. The output is as follows:

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

The intercepted part of the content will send the text content of the withdrawn message "You withdrew a message". If you want to know whether your friend has withdrawn the message, it is very simple. Just judge, msg['Text'] == 'You withdrew a message'

4. Implement WeChat message recall and capture function

Now that the code for each step of the program has been analyzed here, the next step is to summarize all the codes. The following is a summary of all the codes:

Now let's test it. First, I asked two of my friends to send me a message:

The result is:

<<:  WeChat's thrilling 48 hours! From a complete ban to an emergency suspension, the Trump administration's operations are "breaking the waist"

>>:  Build a trustworthy, fair and open HMS ecosystem to bring high-quality applications and services to global consumers

Recommend

Tencent X5 and Egret Runtime jointly promote HTML5 game development

As early as September 23 last year, at the X5 bro...

Soul advertising, Soul advertising billing model

Soul is a new generation social APP whose audienc...

World Hand Hygiene Day丨Teach you the correct hand washing posture

To prevent COVID-19, good hand hygiene is a key p...

The transmission and response mechanism of touch events in iOS

All inherited responder objects UIResponder can r...

Huang Daozhu's sharing session, Huang Daozhu's virtual project 3.0 course

The copyright-free virtual course project worth 9...

There are so many banks, why can't they merge into one?

Mixed knowledge, Specially designed to cure confu...

How to optimize advertising creatives? 3 analysis methods

The impact of advertising materials on advertisin...

What is a clear process for setting up a Toutiao account?

The Bytedance advertising platform, also known as...

What is the use of the hammer head of the hammerhead shark?

Recently, the world-renowned magazine Science pub...