python itchat implements the third-party module method of calling wechat interface

itchat is an open-source wechat personal ID interface. Calling wechat with python has never been so simple.

With less than 30 lines of code, you can complete a wechat robot that can process all information.

Of course, the api uses far more than one robot, and more functions are waiting for you to find, such as these.

Interface and official account interface itchatmp
Share similar operation methods and learn to master two tools at a time.

Now wechat has become a large part of personal social networking. I hope this project can help you expand your personal wechat and facilitate your life.

[article background] I haven't been doing anything in recent days. I came across the itchat package in Python last night. It has completed wechat's personal account API interface, which makes it easier to crawl personal wechat information. In view of the fact that I wanted to know such issues as the gender ratio of my wechat friends from which city long ago, I decided to climb my wechat together.

First, install the itchat package on the terminal. pip install itchat

After installation, import the package, and then log in to your own wechat. A landing QR code will be produced in the process, and you can log in after scanning the code. After successful login, climb down the relevant information of your friends.

    import itchat
    itchat.login()
    #Crawl your friends' information and return a json file
    friends = itchat.get_friends(update=True)[0:]
    

With the above friends data, we can analyze the data of friends or circle of friends!

python implements wechat interface (itchat)

**Installation
**

    sudo pip install itchat
    

Sign in

itchat.auto_login()
This method will log in by scanning QR code through wechat, but this login method does log in for a short time and will not retain the login status, that is, the QR code needs to be scanned next time. If hotReload==True is added, the login status will be retained and the QR code will not be scanned again at least in the following login processes, This parameter generates a static file, itchat Pkl is used to store login status

Specific methods invoked after completion of logout and logon completion.

The grey function method is mainly used here. The method after login needs to be assigned in loginCallback. The method after exit needs to be assigned in exitCallback If not set
The value of loginCallback will automatically delete the QR code picture and clear the command line display

    import itchat, time
    def lc():
      print("Finash Login!")
    def ec():
      print("exit")
     
    itchat.auto_login(loginCallback=lc, exitCallback=ec)
    time.sleep()
    itchat.logout()  #Force logout  
    

Reply message

send

send(msg="Text Message", toUserName=None)

Parameters:

msg: text message content

  • @ fil@path_to_file : send file
  • @ img@path_to_img : send pictures
  • @ vid@path_to_video : send video
  • toUserName: send object. If left blank, it will be sent to yourself

Return value

  • True or False

Example code

    # coding-utf-8
    import itchat
    itchat.auto_login()
    itchat.send("Hello World!")
    ithcat.send("@fil@%s" % '/tmp/test.text')
    ithcat.send("@img@%s" % '/tmp/test.png')
    ithcat.send("@vid@%s" % '/tmp/test.mkv')
    

send_msg

send_msg(msg = 'Text Message', toUserName=None), where msg is the text to be sent and toUserName is the sending object,
If left blank, it will be sent to itself, and the return value is True or False

Example code

    import itchat
    itchat.auto_login()
    itchat.send_msg("hello world.")

send_file

send_file(fileDir, toUserName=None) fileDir is the file path. When the file does not exist,
The reminder without this file will be printed, and the return value is True or False

Example code

    import itchat
     
    itchat.auto_login()
    itchat.send_file("/tmp/test.txt")
    

send_image

send_ The image (filedir, tousername = none) parameter is the same as above

Example code

    import itchat
     
    itchat.auto_login()
    itchat.send_img("/tmp/test.txt")

send_video

send_ The video (filedir, tousername = none) parameter is the same as above

Example code

    import itchat
     
    itchat.auto_login()
    itchat.send_video("/tmp/test.txt")

Register message method

itchat will find the corresponding registered method according to the received message type

If a message type has no corresponding registration method, the message will be discarded

You can also dynamically register methods during operation, and the registration methods and results remain unchanged

Registration method

Without specific object registration, it will be registered as the reply method of ordinary message

    import itchat
    from itchat.content import *
    @itchat.msg_register(TEXT)  #TEXT here means that if someone sends a TEXT message, the following method will be called
    def simple_reply(msg):
      #This is to send a message to the sender
      itchat.send_msg('A text message has been received. The message content is%s'%msg['Text'],toUserName=msg['FromUserName'])
      return "T reveived: %s" % msg["Text"]   #The message returned to the other party, msg["Text"] indicates the content of the message
    

With object parameter registration, the corresponding message object will call the method, where isFriendChat means a friend, isGroupChat means group chat, and isMapChat means official account.

    import itchat
    from itchat.content import *
     
    @itchat.msg_register(TEXT, isFriendChat=True, isGroupChat=True,isMpChat=True)
    def text_reply(msg):
      msg.user.send("%s : %s" % (mst.type, msg.text))
    

Message type

The msg passed in to the registration method contains all the contents of the dictionary returned by wechat Text and type (i.e. parameter) keys are added to itchat to facilitate operation

itcaht.content contains all message type parameters, as shown in the following table

parameterl typeText key value
TEXTtextText content (text message)
MAPMapLocation text (location sharing)
CARDbusiness cardRecommender Dictionary (recommender's business card)
SHARINGshareShare name (shared music or articles, etc.)
PICTURE download methodPicture / expression
RECORDINGvoiceDownload method
ATTACHMENTenclosureDownload method
VIDEOSmall videoDownload method
FRIENDSFriend invitationParameters required for adding friends
SYSTEMSystem messageA list of names of users or group chat who update content
NOTEnoticeNotification text (message withdrawal, etc.)

Downloading and sending of attachments

The attachment download method of itchat is stored in the Text key of msg

The sent file name (the default file name given in the picture) is stored in the FileName key of msg

Download method, accept an available location parameter (including file name), and store the file response

Note: the downloaded file is stored in the specified file. You can directly connect the path with FileName, such as msg "Text"

    @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
    def download_files(msg):
      #msg.download(msg['FileName'])  #This is also the way to download files
      msg['Text'](msg['FileName'])   #Download File
      #Send the downloaded file to the sender
      itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' else 'fil', msg["FileName"]), msg["FromUserName"])
    

Group message

Three key values are added as follows:

  • isAt determines whether @ this number
  • ActualNickName: actual nickname (nickname)
  • Content: actual content

Test procedure

    import itcaht
    from itchat.content import TEXT
     
    @itchat.msg_register(TEXT, isGroupChat=True)
    def text_reply(msg):
      if(msg.isAt):  #Judge whether someone @ himself
      #If someone @ himself, send a message to tell the other party that I have received the message
      itchat.send_msg("I have received from{0}The actual content of the message is{1}".format(msg['ActualNickName'],msg['Text']),toUserName=msg['FromUserName'])
     
    itchat.auto_login()
    itchat.run()
    

Priority of registration message

Generally speaking, messages of the same type registered later will overwrite the messages registered earlier. See the document for details https://itchat.readthedocs.io/zh/latest/

Message content

Note: all message contents can be accessed by key value pairs. For example, msg["FromUserName] is used to view the sender, and itchhat. Search_friends (username = MSG ['FromUserName') ['NickName'] is used to view the NickName of the sender

General news

General messages follow the following:

    {
      "FromUserName": "",
      "ToUserName": "",
      "Content": "",
      "StatusNotifyUserName": "",
      "ImgWidth": 0,
      "PlayLength": 0,
      "RecommendInfo": {},
      "StatusNotifyCode": 0,
      "NewMsgId": "",
      "Status": 0,
      "VoiceLength": 0,
      "ForwardFlag": 0,
      "AppMsgType": 0,
      "Ticket": "",
      "AppInfo": {},
      "Url": "",
      "ImgStatus": 0,
      "MsgType": 0,
      "ImgHeight": 0,
      "MediaId": "",
      "MsgId": "",
      "FileName": "",
      "HasProductId": 0,
      "FileSize": "",
      "CreateTime": 0,
      "SubMsgType": 0
    }
    

Initialization message

    MsgType: 51
      FromUserName: own ID
      ToUserName: own ID
      StatusNotifyUserName: Recent contacts ID
      Content:
        <msg>
          <op id='4'>
            <username>
              # Recent contacts
              filehelper,xxx@chatroom,wxid_xxx,xxx,...
            </username>
            <unreadchatlist>
              <chat>
                <username>
                # Wechat Moments
                  MomentsUnreadMsgStatus
                </username>
                <lastreadtime>
                  1454502365
                </lastreadtime>
              </chat>
            </unreadchatlist>
            <unreadfunctionlist>
            # Unread function, account message, group sending assistant, drifting bottle, etc
            </unreadfunctionlist>
          </op>
        </msg>
    

Text message

    MsgType: 1
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Content: Message content
    

Picture message

itchat adds the Text key, which is the method of downloading the picture

    MsgType: 3
      FromUserName: Sender ID
      ToUserName: Receiver ID
      MsgId: It is used to obtain pictures and represent each message
      Content:
        <msg>
          <img length="6503" hdlength="0" />
          <commenturl></commenturl>
        </msg>
    

Extension: if you want to get the specific Content in the Content, you can use regular expressions to match it

Video message

itchat adds the Text key, which is the method of downloading the video

      MsgType: 62
      FromUserName: Sender ID
      ToUserName: Receiver ID
      MsgId: For getting small videos
      Content:
        <msg>
          <img length="6503" hdlength="0" />
          <commenturl></commenturl>
        </msg>
    

Geographic location message

The Text key is added to itchat, and the key value is the Text form of the location

    MsgType: 1
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Content: http://weixin.qq.com/cgi-bin/redirectforward?args=xxx
      
      OriContent:<?xml version="1.0"?>
    <msg>
      <location x="34.195278" y="117.177803" scale="16" label="Haihe Road, Xinqu, Tongshan District, Xuzhou City, Jiangsu Province" maptype="0" poiname="College student apartment Park of Jiangsu Normal University" />
    </msg>
    

Business card message

The Text key is added to itchat, and the key value is the call add_friend requires attributes

    MsgType: 42
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Content:
        <?xml version="1.0"?>
        <msg bigheadimgurl="" smallheadimgurl="" username="" nickname="" shortpy="" alias="" imagestatus="3" scene="17" province="" city="" sign="" sex="1" certflag="0" certinfo="" brandIconUrl="" brandHomeUrl="" brandSubscriptConfigUrl="" brandFlags="0" regionCode="" />
     
      RecommendInfo:
        {
          "UserName": "xxx", # ID, here is the nickname
          "Province": "xxx",  
          "City": "xxx",  
          "Scene": 17, 
          "QQNum": 0, 
          "Content": "", 
          "Alias": "xxx", # wechat number
          "OpCode": 0, 
          "Signature": "", 
          "Ticket": "", 
          "Sex": 0, # 1: Male, 2: Female
          "NickName": "xxx", # nickname
          "AttrStatus": 4293221, 
          "VerifyFlag": 0
        }
    

The following is the test code for adding friends

    @itchat.msg_register(itchat.content.CARD,isFriendChat=True)
    def simply(msg):
      print msg['Text']
      print msg['Content']
      itchat.add_friend(userName=msg['Text']['UserName']) #Add recommended friends
      print msg['RecommendInfo']
      print msg['RecommendInfo']['UserName']
    

Voice message

*itchat adds the Text key. The key value is the method of downloading the voice file. What is downloaded is MP3 format

    MsgType: 34
      FromUserName: Sender ID
      ToUserName: Receiver ID
      MsgId: Used to get voice
      Content:
        <msg>
          <voicemsg endflag="1" cancelflag="0" forwardflag="0" voiceformat="4" voicelength="1580" length="2026" bufid="216825389722501519" clientmsgid="49efec63a9774a65a932a4e5fcd4e923filehelper174_1454602489" fromusername="" />
        </msg>
    

Download method: msg 'Text'

Animation expression

itchat adds a Text key. The key value is the method to download the image expression.

Note: I personally tested that the expressions provided by some wechat stores cannot be downloaded successfully. The self-contained expression emoji here belongs to the category of TEXT, so it cannot be monitored if it is registered as the type of PICTURE message

     MsgType: 47
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Content:
        <msg>
          <emoji fromusername = "" tousername = "" type="2" idbuffer="media:0_0" md5="e68363487d8f0519c4e1047de403b2e7" len = "86235" productid="com.tencent.xin.emoticon.bilibili" androidmd5="e68363487d8f0519c4e1047de403b2e7" androidlen="86235" s60v3md5 = "e68363487d8f0519c4e1047de403b2e7" s60v3len="86235" s60v5md5 = "e68363487d8f0519c4e1047de403b2e7" s60v5len="86235" cdnurl = "http://emoji.qpic.cn/wx_emoji/eFygWtxcoMF8M0oCCsksMA0gplXAFQNpiaqsmOicbXl1OC4Tyx18SGsQ/" designerid = "" thumburl = "http://mmbiz.qpic.cn/mmemoticon/dx4Y70y9XctRJf6tKsy7FwWosxd4DAtItSfhKS0Czr56A70p8U5O8g/0" encrypturl = "http://emoji.qpic.cn/wx_emoji/UyYVK8GMlq5VnJ56a4GkKHAiaC266Y0me0KtW6JN2FAZcXiaFKccRevA/" aeskey= "a911cc2ec96ddb781b5ca85d24143642" ></emoji> 
          <gameext type="0" content="0" ></gameext>
        </msg>
    

Common links or applications share messages

Mainly aimed at sharing articles and so on

     MsgType: 49
      AppMsgType: 5
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Url: Link address
      FileName: Link title
      Content:
        <msg>
          <appmsg appid="" sdkver="0">
            <title></title>
            <des></des>
            <type>5</type>
            <content></content>
            <url></url>
            <thumburl></thumburl>
            ...
          </appmsg>
          <appinfo>
            <version></version>
            <appname></appname>
          </appinfo>
        </msg>
    

Music link message

Mainly for music

     MsgType: 49
      AppMsgType: 3
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Url: Link address
      FileName: Music name
     
      AppInfo: # Share linked apps
        {
          Type: 0, 
          AppID: wx485a97c844086dc9
        }
     
      Content:
        <msg>
          <appmsg appid="wx485a97c844086dc9" sdkver="0">
            <title></title>
            <des></des>
            <action></action>
            <type>3</type>
            <showtype>0</showtype>
            <mediatagname></mediatagname>
            <messageext></messageext>
            <messageaction></messageaction>
            <content></content>
            <contentattr>0</contentattr>
            <url></url>
            <lowurl></lowurl>
            <dataurl>
              http://ws.stream.qqmusic.qq.com/C100003i9hMt1bgui0.m4a?vkey=6867EF99F3684&amp;guid=ffffffffc104ea2964a111cf3ff3edaf&amp;fromtag=46
            </dataurl>
            <lowdataurl>
              http://ws.stream.qqmusic.qq.com/C100003i9hMt1bgui0.m4a?vkey=6867EF99F3684&amp;guid=ffffffffc104ea2964a111cf3ff3edaf&amp;fromtag=46
            </lowdataurl>
            <appattach>
              <totallen>0</totallen>
              <attachid></attachid>
              <emoticonmd5></emoticonmd5>
              <fileext></fileext>
            </appattach>
            <extinfo></extinfo>
            <sourceusername></sourceusername>
            <sourcedisplayname></sourcedisplayname>
            <commenturl></commenturl>
            <thumburl>
              http://imgcache.qq.com/music/photo/album/63/180_albumpic_143163_0.jpg
            </thumburl>
            <md5></md5>
          </appmsg>
          <fromusername></fromusername>
          <scene>0</scene>
          <appinfo>
            <version>29</version>
            <appname>Shake and search the song</appname>
          </appinfo>
          <commenturl></commenturl>
        </msg>
    

Group message

itchat adds three group chat related keys:

  • isAt: judge whether @ this number
  • ActualNickName: actual NickName
  • Content: actual content
    MsgType: 1
    FromUserName: @@xxx
    ToUserName: @xxx
    Content:
      @xxx:<br/>xxx
    

Red envelope message

     MsgType: 49
      AppMsgType: 2001
      FromUserName: Sender ID
      ToUserName: Receiver ID
      Content: unknown
    

System message

     MsgType: 10000
      FromUserName: Sender ID
      ToUserName: own ID
      Content:
        "You have added xxx ,Now you can start chatting."
        "If a stranger takes the initiative to add you as a friend, please carefully verify the identity of the other person."
        "After receiving the red envelope, please check it on your mobile phone"
    

account type

tchat provides overall access and search methods for all three accounts

Friends

get_friends

itchat.get_friends() returns the complete list of friends

  • Each friend is a dictionary, in which the first item is my account information;
  • Pass in update = true to update the friends list and return to get_friends(update=True)

search_friends

  • itchat. get_ There are four ways to search for friends
  • Get only your own user information
    # Get your own user information and return your own attribute dictionary
    itchat.search_friends()

Get user information for a specific UserName

    # Get user information for a specific UserName
    itchat.search_friends(userName='@abcdefg1234567') 
     
    ## Get the details of the friend who sent the message
    @itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
    def reply(msg):
      print msg['FromUserName']
      print itchat.search_friends(userName=msg['FromUserName'])  #detailed information
      print itchat.search_friends(userName=msg['FromUserName'])['NickName']  #Get nickname
    

Get the user whose comment, micro signal and nickname are equal to the name key value (can be used with the next configuration.)

For example, there is a person with autolife in my wechat. I can use this method to search for detailed information

    # Get any user whose item is equal to the name key value
    itchat.search_friends(name='autolife')
    Get comments,wechat number, The user whose nickname is equal to the corresponding key value. (Can be used with the previous configuration.)
    
    # Obtain the users corresponding to the corresponding key values
    itchat.search_friends(wechatAccount='littlecodersh')
    # 3, The four functions can be used together
    itchat.search_friends(name='LittleCoder robot', wechatAccount='littlecodersh')
    
    

update_friend

Mainly used for friend updates

  • Specific user: pass in the user UserName and return the latest information of the specified user
  • User list: pass in the list composed of UserName and return the list composed of the latest user information
    memberList = itchat.update_friend('@abcdefg1234567')

official account

get_mps

The complete list of work numbers will be returned

  • Each official account is a dictionary.
  • Incoming update=True will update the official account list and return it.

search_mps

  • Get the official account of a specific UserName
    # The official account for a specific UserName is returned to a dictionary.
    itchat.search_mps(userName='@abcdefg1234567')
    Get the official account of a specific character in the name..
    
    # Gets the official account with a specific character in the name, and returns a list of dictionaries.
    itchat.search_mps(name='LittleCoder')
    
    

When two warriors are returned, they will return to the official account of specific UserName only.

Group chat

  • get_chatrooms: return the complete group chat list
  • search_chatrooms: group chat search
  • update_chatroom: get the list of group chat users or update the group chat
    • Group chat will not get the user list of group chat in the first acquisition, so you need to call this command to obtain group chat members
    • Enter the UserName of the group chat and return the details of the specific group chat
    • Pass in the list composed of UserName and return the list composed of the latest information of the specified user
    memberList = itchat.update_chatroom('@@abcdefg1234567', detailedMember=True)

Create group chat and add / delete group chat users:

  • Due to the previous program of detecting whether it is hacked by friends through group chat, the frequency of use of these three methods is strictly limited
  • To delete group chat, this account needs to be an administrator, otherwise it is invalid
  • Adding users to group chat includes directly joining and sending invitations, which can be set through useInvitation
  • Group chat with more than 40 people can't join directly
    memberList = itchat.get_frients()[1:]
    # Create a group chat, and the topic key value is the group chat name
    chatroomUserName = itchat.create_chatroom(memberList, "test chatroom")
    # Delete users in group chat
    itchat.delete_member_from_chatroom(chatroomUserName, memberList[0])
    # Add users to group chat
    itchat.add_member_into_chatroom(chatroomUserName, memberList[0], useInvitation=False)
    

Method summary

    itchat.add_friend 
    itchat.new_instance 
    itchat.add_member_into_chatroom 
    itchat.originInstance 
    itchat.auto_login 
    itchat.returnvalues 
    itchat.check_login 
    itchat.run 
    itchat.components 
    itchat.search_chatrooms 
    itchat.config 
    itchat.search_friends 
    itchat.configured_reply 
    itchat.search_mps 
    itchat.content 
    itchat.send 
    itchat.core 
    itchat.send_file 
    itchat.Core 
    itchat.send_image 
    itchat.create_chatroom 
    itchat.send_msg 
    itchat.delete_member_from_chatroom 
    itchat.send_raw_msg 
    itchat.dump_login_status 
    itchat.send_video 
    itchat.get_chatrooms 
    itchat.set_alias 
    itchat.get_contact 
    itchat.set_chatroom_name 
    itchat.get_friends 
    itchat.set_logging 
    itchat.get_head_img 
    itchat.set_pinned 
    itchat.get_mps 
    itchat.show_mobile_login 
    itchat.get_msg 
    itchat.start_receiving 
    itchat.get_QR 
    itchat.storage 
    itchat.get_QRuuid 
    itchat.update_chatroom 
    itchat.instanceList 
    itchat.update_friend 
    itchat.load_login_status 
    itchat.upload_file 
    itchat.log 
    itchat.utils 
    itchat.login 
    itchat.VERSION 
    itchat.logout 
    itchat.web_init 
    itchat.msg_register
    
    

example

The following is a program written by the blogger. The main function of the program is to monitor the withdrawal message, and if there is a message withdrawal, the withdrawn message will be sent to you. In the future, you don't have to worry about not seeing the withdrawal message of your friend. Because the comments are written in detail, we won't explain it in detail here, but directly post the code

code

    # coding:utf-8
    import itchat
    from itchat.content import TEXT
    from itchat.content import *
    import sys
    import time
    import re
     
    reload(sys)
    sys.setdefaultencoding('utf8')
    import os
     
    msg_information = {}
    face_bug=None #Content for expression pack
     
     
    @itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO],isFriendChat=True, isGroupChat=True, isMpChat=True)
    def handle_receive_msg(msg):
      global face_bug
      msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  #Time of message acceptance
      msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName']  #Query the nickname of the friend who sent the message in the friend list
      msg_time = msg['CreateTime']  #Time of message sending
      msg_id = msg['MsgId']  #id of each message
      msg_content = None   #Contents of stored information
      msg_share_url = None  #Store shared links, such as shared articles and music
      print msg['Type']
      print msg['MsgId']
      if msg['Type'] == 'Text' or msg['Type'] == 'Friends':   #If the message sent is text or recommended by friends
        msg_content = msg['Text']
        print msg_content
     
      #If the message sent is 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 content is their file name
        msg['Text'](str(msg_content))  #Download File
        # print msg_content
      elif msg['Type'] == 'Card':  #If the message is a recommended business card
        msg_content = msg['RecommendInfo']['NickName'] + 'My business card'  #The content is the nickname and gender of the recommender
        if msg['RecommendInfo']['Sex'] == 1:
          msg_content += 'Male gender'
        else:
          msg_content += 'Gender is female'
     
        print msg_content
      elif msg['Type'] == 'Map':  #If the message is shared location information
        x, y, location = re.search(
          "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1, 2, 3)
        if location is None:
          msg_content = r"latitude->" + x.__str__() + " longitude->" + y.__str__()   #The content is the detailed address
        else:
          msg_content = r"" + location
      elif msg['Type'] == 'Sharing':   #If the message is a shared music or article, the detailed content is the title of the article or the name of the share
        msg_content = msg['Text']
        msg_share_url = msg['Url']    #Record shared url
        print msg_share_url
      face_bug=msg_content
     
    ##Store the information in the dictionary, each msg_id corresponds to a message
      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
          }
        }
      )
     
     
    ##This is used to monitor whether a message is withdrawn
    @itchat.msg_register(NOTE, isFriendChat=True, isGroupChat=True, isMpChat=True)
    def information(msg):
      #If msg['Content '] here contains message recall and id, execute the following statement
      if 'A message was withdrawn' in msg['Content']:
        old_msg_id = re.search("\<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 news
        print old_msg
        if len(old_msg_id)<11: #If you're sending an emoticon packet
          itchat.send_file(face_bug,toUserName='filehelper')
        else: #Send recall prompt to file assistant
          msg_body = "Tell you a secret~" + "\n" \
                + old_msg.get('msg_from') + " Withdrawn " + old_msg.get("msg_type") + " news" + "\n" \
                + old_msg.get('msg_time_rec') + "\n" \
                + "Withdrawn what ⇣" + "\n" \
                + r"" + old_msg.get('msg_content')
          #If the shared file is withdrawn, add the shared url to MSG_ Send to file assistant in body
          if old_msg['msg_type'] == "Sharing":
            msg_body += "\n That's the link➣ " + old_msg.get('msg_share_url')
     
          # Send recall message to file assistant
          itchat.send_msg(msg_body, toUserName='filehelper')
          # If there are documents, you should also send them back
          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'])
            itchat.send(msg=file, toUserName='filehelper')
            os.remove(old_msg['msg_content'])
          # Delete dictionary old messages
          msg_information.pop(old_msg_id)
     
    itchat.auto_login(hotReload=True)
    itchat.run()
    

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support the script home.

Keywords: Python

Added by Cliftron on Sat, 29 Jan 2022 14:36:52 +0200