Using itchat in Python to Capture and Save Recalled WeChat Messages
This tutorial demonstrates how to install the itchat library, log in to WeChat, send messages, register message listeners, handle recall notifications, and store recalled text, images, and voice messages by parsing XML and saving files with a complete Python script.
This guide walks through building a Python tool that monitors WeChat conversations using the itchat library and automatically saves any recalled messages, including text, pictures, and voice recordings.
Step 1: Install itchat Run pip install itchat to obtain the library.
Step 2: Log in Use itchat.auto_login(True) to log in to the web version of WeChat. Because the official web API is restricted, the tutorial explains a workaround that allows the script to authenticate.
Step 3: Send a test message After logging in, you can send a message to a friend with itchat.send('test', toUserName) to verify the connection.
Step 4: Register message listeners Define a decorator @itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO]) and a function resever_info(msg) that extracts the message content, type, sender, timestamp, and stores these details in a global dictionary.
Step 5: Handle recall notifications Register another listener for system messages with @itchat.msg_register(NOTE) . When a recall notice (containing the phrase "撤回了一条消息") arrives, parse the XML payload to obtain the original msgid . Use this ID to retrieve the original message from the dictionary, then:
If the recalled message is a voice recording, save the file, compose a notification, and forward both the text and the audio file to the file helper.
If it is text, compose a notification with the original text and send it to the file helper.
If it is a picture, save the image, compose a notification, and forward the image to the file helper.
After processing, delete the entry from the dictionary to free memory.
Step 6: Full script The complete script combines the above steps, creates a directory for saved files, and runs itchat.run() to keep the bot active. The code is shown below:
import itchat
from itchat.content import *
import os
import time
import xml.dom.minidom
temp = '/Users/yourname/Documents/itchat' + '/' + '撤回的消息'
if not os.path.exists(temp):
os.mkdir(temp)
itchat.auto_login(True)
dict = {}
@itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO])
def resever_info(msg):
global dict
info = msg['Text']
msgId = msg['MsgId']
info_type = msg['Type']
name = msg['FileName']
fromUser = itchat.search_friends(userName=msg['FromUserName'])['NickName']
ticks = msg['CreateTime']
time_local = time.localtime(ticks)
dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
dict[msgId] = {"info": info, "info_type": info_type, "name": name, "fromUser": fromUser, "dt": dt}
@itchat.msg_register(NOTE)
def note_info(msg):
if '撤回了一条消息' in msg['Text']:
content = msg['Content']
doc = xml.dom.minidom.parseString(content)
result = doc.getElementsByTagName('msgid')
msgId = result[0].childNodes[0].nodeValue
msg_type = dict[msgId]['info_type']
if msg_type == 'Recording':
recording_info = dict[msgId]['info']
info_name = dict[msgId]['name']
fromUser = dict[msgId]['fromUser']
dt = dict[msgId]['dt']
recording_info(temp + '/' + info_name)
send_msg = '【发送人:】' + fromUser + '\n' + '发送时间:' + dt + '\n' + '撤回了一条语音'
itchat.send(send_msg, 'filehelper')
itchat.send_file(temp + '/' + info_name, 'filehelper')
del dict[msgId]
print('保存语音')
elif msg_type == 'Text':
text_info = dict[msgId]['info']
fromUser = dict[msgId]['fromUser']
dt = dict[msgId]['dt']
send_msg = '【发送人:】' + fromUser + '\n' + '发送时间:' + dt + '\n' + '撤回内容:' + text_info
itchat.send(send_msg, 'filehelper')
del dict[msgId]
print('保存文本')
elif msg_type == 'Picture':
picture_info = dict[msgId]['info']
fromUser = dict[msgId]['fromUser']
dt = dict[msgId]['dt']
info_name = dict[msgId]['name']
picture_info(temp + '/' + info_name)
send_msg = '【发送人:】' + fromUser + '\n' + '发送时间:' + dt + '\n' + '撤回了一张图片'
itchat.send(send_msg, 'filehelper')
itchat.send_file(temp + '/' + info_name, 'filehelper')
del dict[msgId]
print('保存图片')
itchat.run()Running the script will display a console output confirming successful login and message handling, and the file helper will receive notifications and saved media whenever a friend recalls a message.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.