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用模块zlib压缩与解压字符串和文件的方法
Dec 16 Python
深入理解Python中的*重复运算符
Oct 28 Python
Python使用numpy实现BP神经网络
Mar 10 Python
Pandas:DataFrame对象的基础操作方法
Jun 07 Python
Python实现的简单计算器功能详解
Aug 25 Python
python的set处理二维数组转一维数组的方法示例
May 31 Python
解决pycharm运行程序出现卡住scanning files to index索引的问题
Jun 27 Python
Python Celery多队列配置代码实例
Nov 22 Python
python保存log日志,实现用log日志画图
Dec 24 Python
Python判断字符串是否为空和null方法实例
Apr 26 Python
Python的3种运行方式:命令行窗口、Python解释器、IDLE的实现
Oct 10 Python
SpringBoot首页设置解析(推荐)
Feb 11 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
JavaScript 撑出页面文字换行
2009/06/15 Javascript
formValidator3.3的ajaxValidator一些异常分析
2011/07/12 Javascript
通过JavaScript控制字体大小的代码
2011/10/04 Javascript
js获取元素相对窗口位置的实现代码
2014/09/28 Javascript
jQuery中:lt选择器用法实例
2014/12/29 Javascript
js兼容火狐获取图片宽和高的方法
2015/05/21 Javascript
JavaScript程序中实现继承特性的方式总结
2016/06/24 Javascript
jquery 动态合并单元格的实现方法
2016/08/26 Javascript
JS异步加载的三种实现方式
2017/03/16 Javascript
node跨域请求方法小结
2017/08/25 Javascript
Vue.js移动端左滑删除组件的实现代码
2017/09/08 Javascript
vue-resource + json-server模拟数据的方法
2017/11/02 Javascript
详解javascript中的babel到底是什么
2018/06/21 Javascript
webpack3里使用uglifyjs压缩js时打包报错的解决
2018/12/13 Javascript
Python字符串和文件操作常用函数分析
2015/04/08 Python
python3实现zabbix告警推送钉钉的示例
2019/02/20 Python
Python中如何导入类示例详解
2019/04/17 Python
python 一篇文章搞懂装饰器所有用法(建议收藏)
2019/08/23 Python
使用python实现离散时间傅里叶变换的方法
2019/09/02 Python
基于Python实现剪切板实时监控方法解析
2019/09/11 Python
python读取ini配置的类封装代码实例
2020/01/08 Python
pytorch 模拟关系拟合——回归实例
2020/01/14 Python
Python中 Global和Nonlocal的用法详解
2020/01/20 Python
Python selenium文件上传下载功能代码实例
2020/04/13 Python
Python数据可视化实现漏斗图过程图解
2020/07/20 Python
如何利用python正则表达式匹配版本信息
2020/12/09 Python
详解CSS3中border-image的使用
2015/07/18 HTML / CSS
全球虚拟主机商:HostGator
2017/02/06 全球购物
俄罗斯最大的灯具网站:Fandeco
2020/03/14 全球购物
大学毕业生个人自荐信范文
2014/01/08 职场文书
保安队长职务说明书
2014/02/23 职场文书
旷课检讨书范文
2014/10/30 职场文书
2014年监理个人工作总结
2014/12/11 职场文书
2015年庆祝国庆节66周年演讲稿
2015/07/30 职场文书
PHP命令行与定时任务
2021/04/01 PHP
pycharm 如何查看某一函数源码的快捷键
2021/05/12 Python