SoFunction
Updated on 2024-11-19

Getting withdrawn messages from friends and groups using Python's WeChat library itchat

The specific code is described below:

#coding=utf-8
import itchat
from  import TEXT
from  import *
import sys
import time
import re
import os
msg_information = {}
face_bug=None #For emoji content
# TEXT here means if someone sends a text message ()
# TEXT Text Text content (text message)
# MAP Map Location Text (Location Sharing)
# CARD Business Card Referrer's Dictionary (Referrer's Business Card)
# SHARING Share Name of the share (music or article shared, etc.)
# PICTURE How to download images/expressions
# RECORDING Voice Download Method
# ATTACHMENT Attachment Download Method
# VIDEO How to Download
# FRIENDS Friends Invitation Required parameters to add friends
# SYSTEM System Message A list consisting of the UserName of the user or group chat that updated the content.
# NOTE Notification Notification text (message retraction, etc.), then the following method is called
# where isFriendChat means between friends, isGroupChat means group chat, isMapChat means public
@itchat.msg_register([TEXT,PICTURE,FRIENDS,CARD,MAP,SHARING,RECORDING,ATTACHMENT,VIDEO],isFriendChat=True,isGroupChat=True)
def receive_msg(msg):
  global face_bug
  # print("The message is: " + str(msg))
  msg_time_rec = ("%Y-%m-%d %H:%M:%S", ()) #Time to receive a message
  # ActualNickName : Actual NickName This value is only available in group messages (msg).
  if 'ActualNickName' in msg:
    from_user = msg['ActualUserName'] #Unique identifier of the sender of the group message, the user.
    msg_from = msg['ActualNickName']# Nicknames in the sender's group
    friends = itchat.get_friends(update=True)# Get all your friends
    for f in friends:
      if from_user == f['UserName']: #If a group message is sent by a friend
        if f['RemarkName']: # Prioritize friends' note names, or nicknames if they don't have them
          msg_from = f['RemarkName']
        else:
          msg_from = f['NickName']
        break
    groups = itchat.get_chatrooms(update=True)# Get all the groups
    for g in groups:
      if msg['FromUserName'] == g['UserName']:# Match the group message with the FromUserName of the group message.
        group_name = g['NickName']
        group_menbers = g['MemberCount']
        break
    group_name = group_name + "(" + str(group_menbers) +")"
  #Otherwise it's a personal friend's message
  else:
    if itchat.search_friends(userName=msg['FromUserName'])['RemarkName']:# Prioritize the use of memo names
      msg_from = itchat.search_friends(userName=msg['FromUserName'])['RemarkName']
    else:
      msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName'] # Look up the nicknames of friends who send messages in the friends list
    group_name = ""
  msg_time = msg['CreateTime'] # of time the message was sent
  msg_id = msg['MsgId']  # id of each message
  msg_content = None   # Content of stored information
  msg_share_url = None  #Store shared links, such as shared articles and music
  # If the message sent is text or a friend recommendation
  if msg['Type'] == 'Text' or msg['Type'] == 'Friends':
    msg_content = msg['Text']
  # If the message sent is an attachment, video, picture, voice
  elif msg['Type'] == "Attachment" or msg['Type'] == "Video" \
      or msg['Type'] == 'Picture' \
      or msg['Type'] == 'Recording':
    msg_content = msg['FileName']  # The contents are their filenames
    #msg_content = "F:\\weixininfo\\"+msg['FileName']
    msg['Text'](str(msg_content))  #Download file
  elif msg['Type'] == 'Map':  # If the message is shared location information
    x, y, location = (
      "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1, 2, 3)
    if location is None:
      msg_content = r"Latitude->" + x.__str__() + " Longitude->" + y.__str__()   #Content for detailed address
    else:
      msg_content = r"" + location
  elif msg['Type'] == 'Sharing':   # If the message is a shared music or article, the details are the title of the article or the name of the share
    msg_content = msg['Text']
    msg_share_url = msg['Url']    #record the shared url
  face_bug = msg_content
  # Store the messages in a dictionary, with each msg_id corresponding to a message
  (2)
  msg_information.update(
    {
      msg_id: {
        "msg_from": msg_from,
        "msg_time": msg_time,
        "msg_time_rec": msg_time_rec,
        "msg_type": msg["Type"],
        "msg_content": msg_content,
        "msg_share_url": msg_share_url,
        "group_name":group_name
      }
    }
  )
  #Automatically deletes messages older than 130 seconds to avoid memory shortage caused by too much data.
  del_info = []
  for k in msg_information:
    m_time = msg_information[k]['msg_time'] # Get message time
    if int(()) - m_time > 130:
      del_info.append(k)
  if del_info:
    for i in del_info:
      msg_information.pop(i)
# Listen for message withdrawals
@itchat.msg_register(NOTE,isFriendChat=True,isGroupChat=True,isMpChat=True)
def information(msg):
  # If the msg['Content'] here contains the message withdrawal and id, execute the following statement
  if 'Withdrew a message' in msg['Content']:
    old_msg_id = ("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) # Find the id of the withdrawn message in the returned content
    old_msg = msg_information.get(old_msg_id)  # Get the original message, type: dictionary
    print(old_msg)
    if len(old_msg_id)<11: #If you're sending an emoji
      itchat.send_file(face_bug,toUserName='filehelper')
    else: #Send withdrawn alerts to file helpers
      msg_body = old_msg['group_name'] + old_msg['msg_from'] +"\n" + old_msg['msg_time_rec'] \
            + "Withdrawn:" + "\n" + r"" + old_msg['msg_content']
      #If it's a shared file that's been withdrawn, then add the shared url to msg_body to send to the file helper
      if old_msg['msg_type'] == "Sharing":
        msg_body += "\n link is:" + old_msg.get('msg_share_url')
      #print(msg_body)
      itchat.send_msg(msg_body, toUserName='filehelper')# Send the withdrawal message to the document assistant
      #Send the file back if there is one.
      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' % (old_msg['msg_content'])
        (msg=file, toUserName='filehelper')
        (old_msg['msg_content'])
      msg_information.pop(old_msg_id)# Delete old dictionary messages
itchat.auto_login(hotReload=True,enableCmdQR=1)
()

reasoning

1) Login with itchat, a python wechat library

itchat.auto_login Scanning login required
hotReload=True Means no scanning next time. will be generated locally

2)

@itchat.msg_register Called when the corresponding message type is received.

The corresponding types are as follows

# TEXT here means if someone sends a text message ()
# TEXT Text Text content (text message)
# MAP Map Location Text (Location Sharing)
# CARD Business Card Referrer's Dictionary (Referrer's Business Card)
# SHARING Share Name of the share (music or article shared, etc.)
# PICTURE How to download images/expressions
# RECORDING Voice Download Method
# ATTACHMENT Attachment Download Method
# VIDEO How to Download
# FRIENDS Friends Invitation Required parameters to add friends
# SYSTEM System Message A list consisting of the UserName of the user or group chat that updated the content.
# NOTE Notification Notification text (message retraction, etc.), then the following method is called
# included among theseisFriendChatdenotes a close friend,isGroupChatIndicates a group chat,isMapChatdenote a public number

Then get the contents of the msg such as send time msg_time

Send content msg_content etc. Store these messages in msg_information.

Determine the content of the message has withdrawn a message according to the message id go to msg_information to get the content of the object send to the phone assistant and print on the screen finally if the time is more than 130 seconds delete the content of the msg_information

The running image is below:

summarize

The above is a small introduction to the use of Python WeChat library itchat to get friends and groups have withdrawn the message, I hope to help you, if you have any questions welcome to leave me a message, I will reply to you in a timely manner!