Python——实现防止微信撤回消息

调用itchat模块

话不多说上代码

import itchat
from itchat.content import *
import time,os,re

rec_tmp_dir = os.path.join(os.getcwd(), 'tmp/')
rec_msg_dict = {}

# 好友信息监听
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=True)
def handle_friend_msg(msg):
    #pprint(msg)
    msg_id = msg['MsgId']
    msg_from_user = msg['User']['NickName']
    msg_content = ''#定义
    
    # 收到信息的时间
    msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    msg_create_time = msg['CreateTime']
    msg_type = msg['Type']
    
    if msg['Type']=='Text':
        msg_content=msg['Content']
    elif msg['Type'] == 'Picture' \
            or msg['Type'] == 'Recording' \
            or msg['Type'] == 'Video' \
            or msg['Type'] == 'Attachment':
        msg_content = r"" + msg['FileName']
        msg['Text'](rec_tmp_dir + msg['FileName'])
        #文字,图片(表情),音频,视频,文件五种,后面四种都需要下载到本地,itchat中提供了一个下载文件的方法msg['Text'](文件存储路径),调用这个方法即可完成文件下载
    
    rec_msg_dict.update({
        msg_id: {
            'msg_from_user': msg_from_user,
            'msg_time_rec': msg_time_rec,
            'msg_create_time': msg_create_time,
            'msg_type': msg_type,
            'msg_content': msg_content
        }
    })
    print('检查临时文件夹')
    clear_cache()
    
    

    
# 群聊信息监听
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)
def information(msg):
    msg_id = msg['MsgId']
    msg_from_user = msg['ActualNickName']
    msg_content = ''
    # 收到信息的时间
    msg_time_rec = time.strftime("%Y-%m-%d %H:%M%S", time.localtime())
    msg_create_time = msg['CreateTime']
    msg_type = msg['Type']

    if msg['Type'] == 'Text':
        msg_content = msg['Content']
    elif msg['Type'] == 'Picture' \
            or msg['Type'] == 'Recording' \
            or msg['Type'] == 'Video' \
            or msg['Type'] == 'Attachment':
        msg_content = r"" + msg['FileName']
        msg['Text'](rec_tmp_dir + msg['FileName'])
    rec_msg_dict.update({
        msg_id: {
            'msg_from_user': msg_from_user,
            'msg_time_rec': msg_time_rec,
            'msg_create_time': msg_create_time,
            'msg_type': msg_type,
            'msg_content': msg_content
        }
    })
    print('检查临时文件夹...')
    clear_cache()
    
    
 
@itchat.msg_register([NOTE], isFriendChat=True, isGroupChat=True)
def revoke_msg(msg):
    if '撤回了一条消息' in msg['Content']:
        old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
        old_msg = rec_msg_dict.get(old_msg_id, {})
        # 先发送一条文字信息
        itchat.send_msg(str(old_msg.get('msg_from_user') + "撤回了一条信息,(发送时间:"+str(old_msg.get('msg_time_rec'))+")"
                            + old_msg.get('msg_content')), toUserName="filehelper")
        # 判断文msg_content是否存在,不存在说明可能是
        if os.path.exists(os.path.join(rec_tmp_dir, old_msg.get('msg_content'))):
            if old_msg.get('msg_type') == 'Picture':
                itchat.send_image(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
                                  toUserName="filehelper")
            elif old_msg.get('msg_type') == 'Video':
                itchat.send_video(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
                                  toUserName="filehelper")
            elif old_msg.get('msg_type') == 'Attachment' \
                    or old_msg.get('msg_type') == 'Recording':
                itchat.send_file(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
                                 toUserName="filehelper")
                                 
                                 

def clear_cache():
    # 当前时间
    cur_time = time.time()
    # 遍历字典,如果有创建时间超过2分钟(120s)的记录,删除,非文本的话,连文件也删除
    for key in list(rec_msg_dict.keys()):
        if int(cur_time) - int(rec_msg_dict.get(key).get('msg_create_time')) > 120:
            if not rec_msg_dict.get(key).get('msg_type') == 'Text':
                file_path = os.path.join(rec_tmp_dir, rec_msg_dict.get(key).get('msg_content'))
                print(file_path,'(已清除过期临时文件)')
                if os.path.exists(file_path):
                    os.remove(file_path)
            rec_msg_dict.pop(key)

def del_file(path):#删除文件夹下所有文件
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_file(c_path)
        else:
            os.remove(c_path)



if __name__ == '__main__':
    
    if not os.path.exists(rec_tmp_dir):
        os.mkdir(rec_tmp_dir)
    elif os.path.exists(rec_tmp_dir):
        del_file(rec_tmp_dir)

    itchat.auto_login(hotReload=True)
    itchat.run()

代码大部分都是摘抄,过程很有乐趣,再也不怕别人撤回消息了

目前把代码放在手机上跑着,实现24小时监控,偶尔会报一些错,但不影响使用,看来代码还得继续优化呀

在这里插入图片描述

但是这样也造成了一个尴尬的现象,没法使用电脑版的微信了,但是聪明的我灵光一现:

编写个GUI,实现微信消息同步(一个小的局域网通讯工具),运行的py脚本发送消息到GUI,通过GUI实现消息提醒和回复!

话不多说,明天接着百度怎么写局域网通讯工具。。。。。

猜你喜欢

转载自blog.csdn.net/weixin_43087443/article/details/87995442
今日推荐