Teach you how to use Python to view messages withdrawn by WeChat friends

一、pip Install itchat

Now that python is used to solve the problem, the first step is of course to clarify what library to use, and directly execute pip install itchat:

picture

done! 

Two, itchat.login ()

After downloading the library, you have to try the most basic usage of the library, la la la:

picture

But I didn't expect that when the reproduction reached this step, there would be a problem. Directly use the itchat library to operate like the above, and the login will be the web version of WeChat. In order to prevent people from using computers to automatically operate WeChat, which may cause some security problems, Tencent has blocked the web version of WeChat API. If it is just like the above If you do, the console will remind you that "Due to security reasons, this WeChat account cannot use the web version of WeChat. You can use +Windows+ version of WeChat or +Mac+ version of WeChat to log in."

ok, men have to be patient and calm when things happen, google+ Zhihu, if you haven't tried seven or forty-nine solutions, you must not directly consider smashing the computer.

Well, after some trial and error, I found a simple and convenient solution:

picture

Very good, the above operations are completed, and the login is successful!

三、itchat.search_friends() + send()

Very good, the login is successful, let's try to send a message to a friend?

I roughly executed code like this:

picture

Results of the:

picture

Very good, sent successfully!

4. @itchat.msg_register()

Next, we want to listen to the messages sent by our friends, and try to execute this code in the reference document locally:

picture

The effect reproduced on my local machine, there is nothing wrong with it, the effect is great, I can monitor everything on the console, hehehe:

picture

五、def reserver_info(msg)

Next, let's reproduce the following paragraph:

picture

The situation on my machine

picture

六、@itchat.msg_register([TEXT, PICTURE, RECORDING])

The monitoring of the text content has been completed above, and the next step is to experience how to deal with pictures and voices.

Try to reproduce the following code:

picture

This machine reproduced successfully, but I will not let it go, otherwise I have to code again, which is very troublesome [cover face] The explanation of the image format and audio format in the original text:

picture

七、os.mkdir() + info()

We are now involved in how to store pictures and voice information.

And what I will continue to do next, the statement of low EQ is: continue to copy; the statement of high EQ: the reusability of other people's code is very high.

Reproduce this code locally:

picture

Results of the:

picture

Is it that python is so easy to execute smoothly, making people feel boring and tedious? Hhh, if labor and management wanted to use other people's C++ code back then, they didn't have the spirit of learning from the past, and it would be impossible to adjust to such a difficult life.

Eight, note_info (msg)

Now we can store chat messages, that is, since we are making anti-withdrawal software, we should only need to store those withdrawn messages, so how can we judge which messages are withdrawn messages? The Content module provides us with the NOTE type, which refers to system messages:

picture

Ok, let's continue to reproduce the above program locally:

picture

Successful reproduction is boring.

Nine, the complete program code

Finally, the code of the complete program:

import itchat
from itchat.content import *
import os
import time
import xml.dom.minidom    # 解析xml模块

# 这是保存撤回消息的文件目录(如:图片、语音等),这里已经写死了,大家可以自行修改
temp = '/Users/yourname/Documents/itchat' + '/' + '撤回的消息'
if not os.path.exists(temp):
    os.mkdir(temp)

itchat.auto_login(True)    # 自动登录

dict = {}    # 定义一个字典


# 这是一个装饰器,给下面的函数添加新功能
# 能够捕获好友发送的消息,并传递给函数参数msg
@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结点值
        content = msg['Content']
        # Content值为xml,解析xml
        doc = xml.dom.minidom.parseString(content)
        # 取出msgid标签的值
        result = doc.getElementsByTagName("msgid")
        # 该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()

operation result:

picture

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/132456422