溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python實(shí)現(xiàn)微信防撤回神器

發(fā)布時(shí)間:2020-08-28 11:44:40 來(lái)源:腳本之家 閱讀:171 作者:nmyphp 欄目:開(kāi)發(fā)技術(shù)

本文實(shí)例為大家分享了python實(shí)現(xiàn)微信防撤回神器的具體代碼,供大家參考,具體內(nèi)容如下

手寫(xiě)辛苦,希望給贊

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

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

# 可以撤回的消息格式:文本、語(yǔ)音、視頻、圖片、位置、名片、分享、附件
# 存儲(chǔ)收到的消息
# 格式:{msg_id:{msg_from,msg_to,msg_time,msg_time_rec,msg_tye,msg_content,msg_share_url}}
msg_dict = {}

# 存儲(chǔ)消息中文件的臨時(shí)目錄,程序啟動(dòng)時(shí),先清空
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)

# 表情有一個(gè)問(wèn)題:消息和撤回提示的msg_id不一致
face_bug = None


# 監(jiān)聽(tīng)微信消息(只限可撤回的消息類型),存儲(chǔ)到本地,并清除超時(shí)的消息
# 可撤回的消息類型: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
 # 獲取發(fā)送人
 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'] # 優(yōu)先使用備注
  if msg_from is None:
   msg_from = msg['FromUserName']

 # 獲取消息內(nèi)容
 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 + " 經(jīng)度->" + 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分鐘之前的消息,并刪除緩存的消息對(duì)應(yīng)的文件
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)


# 設(shè)置發(fā)送人,當(dāng)消息是群消息的時(shí)候
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}


# 監(jiān)聽(tīng)通知,判斷是撤回通知,則將消息發(fā)給文件助手
@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')
   # 將撤回的消息發(fā)給文件助手
   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()
 # 子線程清除超時(shí)消息
 _thread.start_new_thread(clear_timeout_msg)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI