Do you want to view the message withdrawn by wechat friends? Python does it for you

~wangweijun 2020-11-13 07:21:30
want view message withdrawn wechat


The most disgusting invention of wechat , The withdrawal of the message can definitely make the list .

For example, you are chatting with your girlfriend via wechat , Or talk to your favorite girl , An indiscretion , You didn't notice the message sent by the other party and she withdrew it in time , You're curious , I wonder what happened to her ? So you're going to ask her what she sent , As a result, she replied " It's nothing ". This reply , Make your curiosity even stronger , I immediately feel that the function of message withdrawal is used to torture people .

So is there any way to know your beloved one ( He ) What on earth has been withdrawn ? Don't worry ,Python I'll fix it for you. .

Module introduction

This article will use Python Realize the anti withdrawal function of wechat , For wechat operation ,Python There is 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 :

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.

Which translates as :itchat It's an open wechat for personal account api project , It allows 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 , therefore , First download the module :

pip install itchat

You can also develop tools Pycharm Import the module directly ,Pycharm You will be prompted to download .

Module initial experience

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

1、 How to log in wechat

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

import itchat
itchat.login()

you 're right , One code can complete the login , A QR code will pop up after running , After scanning, you are authorized to log in on your mobile phone , The console will prompt if the login is successful .

Login successfully as Y

This means that the login is successful .

Here's a question to pay attention to , You will find that every time you run the program, you need to scan the QR code to log in , This is too much trouble , Is there a way to scan only once , I'll log in automatically later ? Of course it can .

import itchat
itchat.auto_login(hotReload=True)

Through the function name can also know that this method can achieve automatic login , Run the program , After the code scanning login, a itchat.pkl file , This file is used to store the login status , So don't move it , If you want to change your wechat account to login , Just delete this file first , Because this file records the status of the previous wechat , Delete and log in .

We need to pay attention to : In this way, you can only ensure that you do not need to log in repeatedly in a short period of time , After a long time , Still need to scan the code again to log in .

Go here , Some people may find that their wechat can't log in , as far as I am concerned , Some new registered wechat and long-term unused wechat can't log into the web version of wechat , So it also leads to login failure . If you can't log in , There is no way , The following is meaningless .

2、 Get a list of friends

After logging in to wechat , Let's use it itchat Module provides some api, For example, get a list of friends .

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

Use get_friends() Function to get all the friends in the friends list , Include nicknames 、 Note name 、 Address 、 Individuality signature 、 Gender and so on .

Here I randomly copied a friend's personal information , Of course, due to privacy issues , Part of the information here I use "*" Instead of , Let's focus on analyzing the content of this information . For example, the first UserName, This is the only identification of the user , Equivalent to ID number , Every friend of yours will have such a logo , There must be something different between each friend ; And then there was NickName, This is my friend's nickname ;HeadImgUrl It's a friend's Avatar address ;RemarkName It's your comment to your friend ;Province Provinces and so on , I won't introduce them here , 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 very simple :

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

At this time UserName That comes in handy , That is the only identification of a friend , such , We sent a message to the corresponding friend of the logo , therefore , We can improve the program in this way :

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

such , You can send it to any friend , Search the friends list by their nicknames , If you find it , Get the friend's UserName, And then send a message , You can also comment on a friend's name (RemarkName) lookup , You can try it yourself .

4、 Decorator

About itchat The module also has many functions , There won't be too much explanation here , We will only talk about the knowledge of this procedure , Here's the last thing , Decorator .

About ornaments , It's not clear for a while , This is just a brief introduction , The function of the decorator is to expand the function of the original function , The purpose is not to change the original function name ( Or the name of the class ) Under the circumstances , Add new functions to functions .

For example, now there is a function fun(), You don't know how functions work , You can't change the code of this function , And you need to add a function that outputs the start and end run times , How to achieve 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 program ? First @show_time It's using a decorator show_time, This will decorate the function , That is to say fun() Pass it as a parameter to the decorator show_time(), If we know the function as a return value , This function is actually executed , So the program will execute internal functions inner(), At this time, the output starts to run , And then call fun() function ( The original function cannot be lost ), Last output end run time . In this way, the function extension is realized through the decorator , This is also a typical aspect oriented programming idea .

How to get messages sent by friends

The preparatory work is done , Next, I'll get to the point , For the above knowledge points , You must master , If you don't understand , You may be confused about the next code .

First , Let's see how to get messages from friends .

import itchat
itchat.auto_login(hotReload=True)
@itchat.msg_register(itchat.content.TEXT)
def resever_info(msg):
print(msg)
itchat.run() # Keep running 

itchat The module provides @itchat.msg_register Decorators to listen for messages , For example, here we have a custom resever_info() function , And use the decorator to monitor the message , In the decorator came itchat.content.TEXT type , So what we're listening to is text messages , After listening to the input , The decorator will pass the text message in resever_info() The parameters of the . therefore ,msg It's the content of the message you're listening to .

about @itchat.msg_register Decorator , It can not only listen to text , It can also monitor voice 、 picture 、 Map 、 Business card 、 Video and so on , For convenience , Here we import itchat Under the module of content Everything in the module , Because these message types are declared under this 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]

There's something else to pay attention to , Finally remember to call itchat Of run() function , Keep the program running , Otherwise, the program will end directly .

Next we can test , I asked my friend to send me a message , The console outputs the following :
 Insert picture description here

It's a lot of content , Let's just look at the important . for example FromUserName, This is the identity of the sender ;ToUserName, This is the receiver's logo ;Content, This, of course, is the text ;CreateTime, This is the sending time ; Notice the last two values :Type, This is the message type , Here is the text type Text, then Text It's also the content of the text , So if you want to take out the message sent by your friends , use Content and Text Fine . After the analysis , It's easy to take out the content :

import itchat
import time
from itchat.content import * # Import itchat Under the content modular 
itchat.auto_login(hotReload=True)
@itchat.msg_register(TEXT)
def resever_info(msg):
info = msg['Text'] # Take out the text message 
info_type = msg['Type'] # Take out the 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 Send time :' + dt + '\n The message content :' + info)
itchat.run()

It's used here time modular , Used to format dates .

For testing convenience , I just sent a message to others , Messages sent by oneself will also be monitored , Look at the results :

 Give a person :Y
Message type :Text
Send time :2019-11-28 16:19:13
The message content : Woodlouse

Let's try voice and pictures again ? Let's go back to the code :

import itchat
from itchat.content import * # Import itchat Under the content modular 
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 , The console just doesn't respond , This is of course , We haven't monitored voice and pictures yet , Modify the code :

import itchat
from itchat.content import * # Import itchat Under the content modular 
itchat.auto_login(hotReload=True)
@itchat.msg_register([TEXT, PICTURE, RECORDING]) # Added monitoring of images and voice 
def resever_info(msg):
print(msg)
itchat.run()

Try again , Send a picture first , Send another voice , The console output two paragraphs , Because the length is too long , I won't post it , It's just that information , sender , The receiver , date , Message content and so on , Just pay attention to the content of pictures 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 it 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 itchat Under the content modular 
itchat.auto_login(hotReload=True)
temp = 'C:/Users/Administrator/Desktop/CrawlerDemo' + '/' + ' The message of withdrawal '
# 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'] # Take out the text message 
info_type = msg['Type'] # Take out the message type 
name = msg['FileName'] # Take out the voice ( picture ) file name 
if info_type == 'Recording':
# Save the voice 
info(temp + '/' + name)
elif info_type == 'Picture':
# Save the picture 
info(temp + '/' + name)
itchat.run()

Run up , Then send a picture and a voice , Two files will be generated in the specified directory :
 Insert picture description here

How to monitor a friend's recall

Come here , We've actually completed the message monitoring , It just needs a little modification , But the program is flawed , Because not all the information we need to keep , We can see the messages sent by friends directly , Isn't it unnecessary to save it ? Our goal is to know what our friends have withdrawn , This involves how to monitor whether a friend has withdrawn a message . In fact, it's very simple ,Content Module provides us with NOTE type , This type refers to system messages .

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

import itchat
from itchat.content import * # Import itchat Under the content modular 
itchat.auto_login(hotReload=True)
@itchat.msg_register(NOTE)
def note_info(msg): # Monitor system messages 
print(msg)
itchat.run()

Run the program , Let's withdraw a message to test , The output is as follows :

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

Part of the content is intercepted here , Will find , The text of the withdrawal message is " You withdrew a message ", So it's very easy to know if a friend has withdrawn a message , Judge msg['Text'] == ' You withdrew a message ' that will do .

Implement wechat anti withdrawal procedure

The code of each step of the program is analyzed here , Next is a summary of all the code , It is also the complete code of the whole program :

import itchat
from itchat.content import *
import os
import time
import xml.dom.minidom # analysis xml modular 
# This is the directory where the recall message is stored ( Such as : picture 、 Voice etc. ), It's dead here , You can modify it yourself 
temp = 'C:/Users/Administrator/Desktop/CrawlerDemo' + '/' + ' The message of withdrawal '
if not os.path.exists(temp):
os.mkdir(temp)
itchat.auto_login(True) # automatic logon 
dict = {
} # Define a dictionary 
# This is a decorator , Add new features to the following functions 
# Ability to capture messages sent by friends , And pass it 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'] # Take out the message content 
msgId = msg['MsgId'] # Take out the message ID 
info_type = msg['Type'] # Take out the message type 
name = msg['FileName'] # Take out the message file name 
# Retrieve 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 the message ID and message content to the dictionary 
# The unique identifier of each message is used as the key , The specific information of the message as the value , It's also a dictionary 
dict[msgId] = {
"info": info, "info_type": info_type, "name": name, "fromUser": fromUser, "dt": dt}
@itchat.msg_register(NOTE) # Monitor system prompts 
def note_info(msg):
# Listening to a message from a friend who has withdrawn 
if ' Recalled a message ' in msg['Text']:
# Get... In the system message Content Node values 
content = msg['Content']
# Content The value is xml, analysis xml
doc = xml.dom.minidom.parseString(content)
# Take out msgid Value of label 
result = doc.getElementsByTagName("msgid")
# The msgId Is the message ID of the recall , It can find the recalled message information in the dictionary 
msgId = result[0].childNodes[0].nodeValue
# Take the message type corresponding to the message ID from the dictionary 
msg_type = dict[msgId]['info_type']
if msg_type == 'Recording': # The withdrawn message is voice 
recording_info = dict[msgId]['info'] # Take out the message content corresponding to the message ID 
info_name = dict[msgId]['name'] # Take out the message file name 
fromUser = dict[msgId]['fromUser'] # Take out the sender 
dt = dict[msgId]['dt'] # Take out the sending time 
recording_info(temp + '/' + info_name) # Save the voice 
# Splicing message 
send_msg = '【 Give a person :】' + fromUser + '\n' + ' Send time :' + dt + '\n' + ' Withdraw a voice '
itchat.send(send_msg, 'filehelper') # Send the prompt message to the file assistant 
# Send saved voice 
itchat.send_file(temp + '/' + info_name, 'filehelper')
del dict[msgId] # Delete the corresponding message in the dictionary 
print(" Save the voice ")
elif msg_type == 'Text':
text_info = dict[msgId]['info'] # Take out the message content corresponding to the message ID 
fromUser = dict[msgId]['fromUser'] # Take out the sender 
dt = dict[msgId]['dt'] # Take out the sending time 
# Splicing message 
send_msg = '【 Give a person :】' + fromUser + '\n' + ' Send time :' + dt + '\n' + ' Withdraw content :' + text_info
# Send the prompt message to the file assistant 
itchat.send(send_msg, 'filehelper')
del dict[msgId] # Delete the corresponding message in the dictionary 
print(" Save text ")
elif msg_type == 'Picture':
picture_info = dict[msgId]['info'] # Take out the message content corresponding to the message ID 
fromUser = dict[msgId]['fromUser'] # Take out the sender 
dt = dict[msgId]['dt'] # Take out the sending time 
info_name = dict[msgId]['name'] # Get file name 
picture_info(temp + '/' + info_name) # Save the picture 
# Splicing message 
send_msg = '【 Give a person :】' + fromUser + '\n' + ' Send time :' + dt + '\n' + ' Pulled back a picture '
itchat.send(send_msg, 'filehelper') # Send picture to file assistant 
# Send saved voice 
itchat.send_file(temp + '/' + info_name, 'filehelper')
del dict[msgId] # Delete the corresponding message in the dictionary 
print(" Save the picture ")
itchat.run()

such , A complete anti withdrawal procedure is completed , If you can master the foreshadowing very well , This program is a piece of cake for you , I write every comment of the code , It should be easy to understand .

The test program

It's the exciting part of the test , Let's test whether the program has been written successfully .

 Insert picture description here

I sent three messages to my friends , They are the text 、 Pictures and voice , Then I withdraw one by one , then , The wechat program automatically sends three messages to the file transfer assistant :
 Insert picture description here

Come here , This program is basically completed . You can also call your friends when testing 、 Students send you a few messages , Then recall to see if the recalled message can be successfully obtained .

It's not good to send the withdrawn message to others , It's not just a breach of privacy , They will also harass others , So here I choose to send the recall message to the file transfer assistant , It's also easy to send messages to the file transfer assistant :

itchat.send(send_msg, toUserName='filehelper')

toUserName Pass in filehelper that will do , such , If the other party withdraws the message , You can go to the file transfer assistant to see what the other party has withdrawn .

Talk about some of the pits I met

This program says it's hard , It's not hard , But I also encountered some holes in the process of writing , At the beginning, I was testing message by message , The discovery process is normal , But I withdrew several messages in a row , But I found that the program appeared Bug. For example, I sent a picture and a paragraph of text at the beginning , As a result, I withdrew these two messages , What we get is two paragraphs of text . I just woke up later , It's the latter message that covers the former one , It led to the result , So in the process , I defined a dictionary , Used to store messages entered by friends , When the supervisor heard that the news was withdrawn , In the content generated by the withdrawal message msgId To match the dictionary , What matches is the recalled message , Then we can operate it .

Use the tutorial

It's very easy to use this program , Implement wechat anti withdrawal procedure Node has the complete code of the program , Copy and paste directly into your own python file , Then run the file , After running, a QR code will be generated , Login with mobile phone authentication .
Of course , You can also choose to package the program as executable exe file , It's more convenient to run , packaging :
Start by opening cmd window , download pyinstaller modular , You don't have to download if you have , Download instructions :pip insall pyinstaller, At this point we pass through cmd The window goes to python File directory , So here I am
 Insert picture description here
Then go to the directory :
 Insert picture description here
Then execute the following command :

pyinstaller -F wechat.py

The following is the name of the file to be packaged , After executing the command , It will generate a file in the same level directory dist Folder .
 Insert picture description here
Go to this folder , You can see us .exe The file , Then double click to execute .

Last

At present, this program only monitors the text of friends 、 picture 、 Voice type messages , For other types of messages , There are also group chat messages that can't be monitored , If you are interested, you can try to realize it yourself .

Because I just touched this module , The program in this article may have some unexpected Bug, But at present, I have no problem in testing , If there is a problem , Leave a comment in the comments section .

版权声明
本文为[~wangweijun]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database