SoFunction
Updated on 2024-11-19

Python implementation of WeChat to retrieve friends, group chat users to withdraw the message function example

In this article, examples of Python implementation of WeChat to retrieve friends, group chat users withdrawn message function. Shared for your reference, as follows:

Still curious about what message was withdrawn by a friend? What message was withdrawn by the group? The following code realizes that: even if the group, friends withdrew text messages, emoticons, pictures and other messages, you can know what was withdrawn yourself.

#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
@itchat.msg_register([TEXT,PICTURE,FRIENDS,CARD,MAP,SHARING,RECORDING,ATTACHMENT,VIDEO],isFriendChat=True,isGroupChat=True)
def receive_msg(msg):
  global face_bug
  msg_time_rec = ("%Y-%m-%d %H:%M:%S", ()) #Time to receive a message
  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) +")"
  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 msg['Type'] == 'Text' or msg['Type'] == 'Friends':   # If the message sent is a text or a friend recommendation
    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['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
      }
    }
  )
  del_info = []
  for k in msg_information:
    m_time = msg_information[k]['msg_time'] # Get message time
    if int(()) - m_time > 130: # Delete if the message time is 130 seconds or more ago.
      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)
()

Readers interested in more Python related content can check out this site's topic: theSummary of Python mathematical operations techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.