python实现微信防撤回神器


Posted in Python onApril 29, 2019

本文实例为大家分享了python实现微信防撤回神器的具体代码,供大家参考,具体内容如下

手写辛苦,希望给赞

#!/usr/local/bin/python3
# coding=utf-8

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

# 可以撤回的消息格式:文本、语音、视频、图片、位置、名片、分享、附件
# 存储收到的消息
# 格式:{msg_id:{msg_from,msg_to,msg_time,msg_time_rec,msg_tye,msg_content,msg_share_url}}
msg_dict = {}

# 存储消息中文件的临时目录,程序启动时,先清空
rev_tmp_dir = "/Users/chenlong/d1/wechat/rev/"
if not os.path.exists(rev_tmp_dir):
 os.mkdir(rev_tmp_dir)
else:
 for f in os.listdir(rev_tmp_dir):
  path = os.path.join(rev_tmp_dir, f)
  if os.path.isfile(path):
   os.remove(path)

# 表情有一个问题:消息和撤回提示的msg_id不一致
face_bug = None


# 监听微信消息(只限可撤回的消息类型),存储到本地,并清除超时的消息
# 可撤回的消息类型:TEXT、PICTURE、MAP、CARD、SHARING、RECORDING、ATTACHMENT、VIDEO、FRIENDS、NOTE
@itchat.msg_register([TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS, NOTE],
      isFriendChat=True, isGroupChat=True, isMpChat=True)
def handler_reveive_msg(msg):
 global face_bug
 msg_time_rev = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 msg_id = msg['MsgId']
 msg_time = msg['CreateTime']
 msg_share_url = None
 group_name = None
 # 获取发送人
 if 'ActualNickName' in msg:
  sender_info = set_sender_group_chat(msg)
  msg_from = sender_info['msg_from']
  group_name = sender_info['group_name']
 else:
  msg_from = (itchat.search_friends(userName=msg['FromUserName']))['RemarkName'] # 优先使用备注
  if msg_from is None:
   msg_from = msg['FromUserName']

 # 获取消息内容
 if msg['Type'] == 'Text' or msg['Type'] == 'Friends':
  msg_content = msg['Text']
 elif msg['Type'] == 'Recording' or msg['Type'] == 'Attachment' \
   or msg['Type'] == 'Video' or msg['Type'] == 'Picture':
  msg_content = r"" + msg['FileName']
  msg['Text'](rev_tmp_dir + msg['FileName'])
 elif msg['Type'] == 'Card':
  msg_content = msg['RecommendInfo']['NickName'] + r" 的名片"
 elif msg['Type'] == 'Map':
  x, y, location = re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1,
                             2,
                             3)
  if location is None:
   msg_content = r"维度->" + x + " 经度->" + y
  else:
   msg_content = r"" + location
 elif msg['Type'] == 'Sharing':
  msg_content = msg['Text']
  msg_share_url = msg['Url']

 face_bug = msg_content
 # 缓存消息
 msg_dict.update({
  msg_id: {
   "msg_from": msg_from,
   "msg_time": msg_time,
   "msg_time_rev": msg_time_rev,
   "msg_type": msg['Type'],
   "msg_content": msg_content,
   "msg_share_url": msg_share_url,
   "group_name": group_name
  }
 })


# 遍历本地消息字典,清除2分钟之前的消息,并删除缓存的消息对应的文件
def clear_timeout_msg():
 need_del_msg_ids = []
 for m in msg_dict:
  msg_time = msg_dict[m]['msg_time']
  if int(time.time()) - msg_time > 120:
   need_del_msg_ids.append(m)

 if len(need_del_msg_ids) > 0:
  for i in need_del_msg_ids:
   old_msg = msg_dict.get(i)
   if old_msg['msg_type'] == PICTURE or old_msg['msg_type'] == RECORDING or old_msg['msg_type'] == VIDEO \
     or old_msg['msg_type'] == ATTACHMENT:
    os.remove(rev_tmp_dir + old_msg['msg_content'])
   msg_dict.pop(i)


# 设置发送人,当消息是群消息的时候
def set_sender_group_chat(msg):
 msg_from = msg['ActualNickName']
 # 查找用户备注名称
 friends = itchat.get_friends(update=True)
 from_user = msg['ActualUserName']
 for f in friends:
  if from_user == f['UserName']:
   msg_from = f['RemarkName'] or f['NickName']
   break

 groups = itchat.get_chatrooms(update=True)
 for g in groups:
  if msg['FromUserName'] == g['UserName']:
   group_name = g['NickName']
   break

 return {'msg_from': msg_from, 'group_name': group_name}


# 监听通知,判断是撤回通知,则将消息发给文件助手
@itchat.msg_register([NOTE], isFriendChat=True, isGroupChat=True, isMpChat=True)
def send_msg_helper(msg):
 global face_bug
 if re.search(r"\<\!\[CDATA\[.*撤回了一条消息\]\]\>", msg['Content']) is not None:
  old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
  old_msg = msg_dict.get(old_msg_id, {})
  if len(old_msg_id) < 11:
   itchat.send_file(rev_tmp_dir + face_bug, toUserName='filehelper')
   os.remove(rev_tmp_dir + face_bug)
  else:
   msg_body = old_msg.get('msg_from') + "撤回了" + old_msg.get('msg_type') \
      + "消息\n" \
      + old_msg.get('msg_time_rev') + "\n" \
      + old_msg.get('msg_content')
   if old_msg.get('group_name') is not None:
    msg_body = old_msg.get('group_name') + ">" + msg_body
   if old_msg['msg_type'] == "Sharing":
    msg_body += "\n" + old_msg.get('msg_share_url')
   # 将撤回的消息发给文件助手
   itchat.send(msg_body, toUserName='filehelper')
   if old_msg['msg_type'] == PICTURE or old_msg['msg_type'] == RECORDING or old_msg['msg_type'] == VIDEO \
     or old_msg['msg_type'] == ATTACHMENT:
    file = '@fil@%s' % (rev_tmp_dir + old_msg['msg_content'])
    itchat.send(msg=file, toUserName='filehelper')
    os.remove(rev_tmp_dir + old_msg['msg_content'])
   msg_dict.pop(old_msg_id)


if __name__ == '__main__':
 itchat.auto_login(hotReload=True, enableCmdQR=2)
 itchat.run()
 # 子线程清除超时消息
 _thread.start_new_thread(clear_timeout_msg)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python类的用法实例浅析
May 27 Python
Python单体模式的几种常见实现方法详解
Jul 28 Python
python3实现点餐系统
Jan 24 Python
Python如何获得百度统计API的数据并发送邮件示例代码
Jan 27 Python
Python第三方包之DingDingBot钉钉机器人
Apr 09 Python
Django中的AutoField字段使用
May 18 Python
浅谈pytorch 模型 .pt, .pth, .pkl的区别及模型保存方式
May 25 Python
音频处理 windows10下python三方库librosa安装教程
Jun 20 Python
Python字典取键、值对的方法步骤
Sep 30 Python
python 对象真假值的实例(哪些视为False)
Dec 11 Python
Python实现8种常用抽样方法
Jun 27 Python
Python中第三方库Faker的使用详解
Apr 02 Python
python实现文件助手中查看微信撤回消息
Apr 29 #Python
Python实现微信消息防撤回功能的实例代码
Apr 29 #Python
python控制nao机器人身体动作实例详解
Apr 29 #Python
python实现nao机器人身体躯干和腿部动作操作
Apr 29 #Python
解决Python找不到ssl模块问题 No module named _ssl的方法
Apr 29 #Python
GitHub 热门:Python 算法大全,Star 超过 2 万
Apr 29 #Python
python实现nao机器人手臂动作控制
Apr 29 #Python
You might like
.htaccess文件保护实例讲解
2011/02/06 PHP
php数组函数序列之array_splice() - 在数组任意位置插入元素
2011/11/07 PHP
php批量更改数据库表前缀实现方法
2013/10/26 PHP
PHP实现伪静态方法汇总
2016/01/13 PHP
PHP生成各种随机验证码的方法总结【附demo源码】
2017/06/05 PHP
TP5框架请求响应参数实例分析
2019/10/17 PHP
JavaScript 变量命名规则
2009/09/23 Javascript
基于jQuery实现表格数据的动态添加与统计的代码
2011/01/31 Javascript
5个最佳的Javascript日期处理类库分享
2012/04/15 Javascript
js 本地预览的简单实现方法
2014/02/18 Javascript
Javascript中call与apply的学习笔记
2014/09/22 Javascript
jQuery判断数组是否包含了指定的元素
2015/03/10 Javascript
js数组如何添加json数据及js数组与json的区别
2015/10/27 Javascript
jQuery-1.9.1源码分析系列(十)事件系统之事件包装
2015/11/20 Javascript
JS滚轮控制图片缩放大小和拖动的实例代码
2018/11/20 Javascript
微信公众号H5支付接口调用方法
2019/01/10 Javascript
[02:40]DOTA2英雄基础教程 巨牙海民
2013/12/23 DOTA
python小技巧之批量抓取美女图片
2014/06/06 Python
python通过pil模块将raw图片转换成png图片的方法
2015/03/16 Python
Django框架下在视图中使用模版的方法
2015/07/16 Python
Python从ZabbixAPI获取信息及实现Zabbix-API 监控的方法
2018/09/17 Python
Python使用while循环花式打印乘法表
2019/01/28 Python
Python脚本利用adb进行手机控制的方法
2019/07/08 Python
Django中的FBV和CBV用法详解
2019/09/15 Python
python FTP编程基础入门
2021/02/27 Python
python抢购软件/插件/脚本附完整源码
2021/03/04 Python
团支书的期末学习总结自我评价
2013/11/01 职场文书
服务行业个人求职的自我评价
2013/12/12 职场文书
创业资金计划书
2014/02/06 职场文书
电子商务专业毕业生自荐书
2014/06/22 职场文书
做一个有道德的人活动实施方案
2014/08/23 职场文书
典型事迹材料范文
2014/12/29 职场文书
担保书范本
2015/01/20 职场文书
2015年党员干部承诺书
2015/01/21 职场文书
2015年初中生自我评价范文
2015/03/03 职场文书
追讨欠款律师函
2015/06/24 职场文书