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使用scrapy采集数据过程中放回下载过大页面的方法
Apr 08 Python
python 实现tar文件压缩解压的实例详解
Aug 20 Python
python创建列表和向列表添加元素的实现方法
Dec 25 Python
用Python3创建httpServer的简单方法
Jun 04 Python
python读取excel指定列数据并写入到新的excel方法
Jul 10 Python
详解用pyecharts Geo实现动态数据热力图城市找不到问题解决
Jun 26 Python
树莓派使用python-librtmp实现rtmp推流h264的方法
Jul 22 Python
Django3.0 异步通信初体验(小结)
Dec 04 Python
使用 Python 读取电子表格中的数据实例详解
Apr 17 Python
解析Tensorflow之MNIST的使用
Jun 30 Python
TensorFlow Autodiff自动微分详解
Jul 06 Python
Python+OpenCV检测灯光亮点的实现方法
Nov 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
通过html表格发电子邮件
2006/10/09 PHP
跟我学Laravel之安装Laravel
2014/10/15 PHP
PHP程序员必须清楚的问题汇总
2014/12/18 PHP
PHP中strnatcmp()函数“自然排序算法”进行字符串比较用法分析(对比strcmp函数)
2016/01/07 PHP
php集成动态口令认证
2016/07/21 PHP
php实现用户注册密码的crypt加密
2017/06/08 PHP
Thinkphp 框架扩展之驱动扩展实例分析
2020/04/27 PHP
tp5.1 框架数据库高级查询技巧实例总结
2020/05/25 PHP
jQuery 获取URL参数的插件
2010/03/04 Javascript
JavaScript两种跨域技术全面介绍
2014/04/16 Javascript
简介JavaScript中toTimeString()方法的使用
2015/06/12 Javascript
Bootstrap的图片轮播示例代码
2015/08/31 Javascript
jQuery实现移动端滑块拖动选择数字效果
2015/12/24 Javascript
使用jQuery Rotare实现微信大转盘抽奖功能
2016/06/20 Javascript
Bootstrap零基础入门教程(三)
2016/07/18 Javascript
两行代码轻松搞定JavaScript日期验证
2016/08/03 Javascript
使用ReactJS实现tab页切换、菜单栏切换、手风琴切换和进度条效果
2016/10/17 Javascript
Node.js对MongoDB数据库实现模糊查询的方法
2017/05/03 Javascript
Javascript和jquery在selenium的使用过程
2019/10/31 jQuery
python启动办公软件进程(word、excel、ppt、以及wps的et、wps、wpp)
2009/04/09 Python
Python提示[Errno 32]Broken pipe导致线程crash错误解决方法
2014/11/19 Python
深入理解Python中的super()方法
2017/11/20 Python
Python+matplotlib实现计算两个信号的交叉谱密度实例
2018/01/08 Python
python使用yield压平嵌套字典的超简单方法
2019/11/02 Python
利用scikitlearn画ROC曲线实例
2020/07/02 Python
Python tkinter界面实现历史天气查询的示例代码
2020/08/23 Python
python一些性能分析的技巧
2020/08/30 Python
Python函数__new__及__init__作用及区别解析
2020/08/31 Python
使用css创建三角形 使用CSS3创建3d四面体原理及代码(html5实践)
2013/01/06 HTML / CSS
财务管理专业应届毕业生求职信
2013/09/22 职场文书
程序员岗位职责
2013/11/11 职场文书
经典促销广告词大全
2014/03/19 职场文书
2014银行领导班子群众路线对照检查材料思想汇报
2014/09/17 职场文书
大学生党员自我批评思想汇报
2014/10/10 职场文书
2015年底工作总结范文
2015/05/15 职场文书
党员学习型组织心得体会
2019/06/21 职场文书