Python once said to me: "Time is running out, hurry up and use Python." So I saw an open source WeChat library based on Python: itchat. I played with it for a day and made a program that can collect the withdrawn private chat information and send it to the file transfer assistant of personal WeChat, including: - who :who sent it
- when: when the message is sent
- what: what information
- which: which type of information, including: text, pictures, voice, video, sharing, location, attachments...
01 Code Implementation - # -*-encoding:utf-8-*-
- import os
- import re
- import shutil
- import time
- import itchat
- from itchat.content import *
-
- # Note: Text, voice, video, picture, location, business card, share, and attachment can be withdrawn
-
- # {msg_id:(msg_from,msg_to,msg_time,msg_time_rec,msg_type,msg_content,msg_share_url)}
- msg_dict = {}
-
- # Temporary directory for file storage
- rev_tmp_dir = "/home/alic/RevDir/"
- if not os.path.exists(rev_tmp_dir): os.mkdir(rev_tmp_dir)
-
- # There is a problem with the expression | The msg_id of receiving the message and receiving the note are inconsistent. Coincidental solution
- face_bug = None
-
- # Store the received messages in the dictionary. When a new message is received, clear the timed messages in the dictionary. | Do not accept messages that do not have the recall function.
-
- # [TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS, NOTE]
- @itchat.msg_register([TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO])
- def handler_receive_msg(msg):
- global face_bug
- # Get the local timestamp and format the local timestamp e: 2017-04-21 21:30:08
- msg_time_rec = time .strftime( "%Y-%m-%d %H:%M:%S" , time .localtime())
- # Message ID
- msg_id = msg[ 'MsgId' ]
- # Message time
- msg_time = msg[ 'CreateTime' ]
- # Nickname of the message sender | You can also use RemarkName here, but for yourself or someone without a remark, it is None
- msg_from = (itchat.search_friends(userName=msg[ 'FromUserName' ]))[ "NickName" ]
- # Message content
- msg_content = None
- # Shared link
- msg_share_url = None
- 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' ]
- # Save the file
- msg[ 'Text' ](rev_tmp_dir + msg[ 'FileName' ])
- elif msg[ 'Type' ] == 'Card' :
- msg_content = msg[ 'RecommendInfo' ][ 'NickName' ] + r "Business card"
- 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 "latitude->" + x.__str__() + "longitude->" + y.__str__()
- else :
- msg_content = r "" + location
- elif msg[ 'Type' ] == 'Sharing' :
- msg_content = msg[ 'Text' ]
- msg_share_url = msg[ 'Url' ]
- face_bug = msg_content
- # Update dictionary
- msg_dict.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
- }
- }
- )
-
- # Receive note notification messages, determine whether to withdraw and perform corresponding operations
-
- @itchat.msg_register([NOTE])
- def send_msg_helper(msg):
- global face_bug
- if re.search(r "\<\!\[CDATA\[.*Retracted a message\]\]\>" , msg[ 'Content' ]) is not None:
- # Get the message id
- 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 = "Tell you a secret~" + "\n" \
- + old_msg.get( 'msg_from' ) + "Withdrawn" + old_msg.get( "msg_type" ) + "Message" + "\n" \
- + old_msg.get( 'msg_time_rec' ) + "\n" \
- + "What was withdrawn ⇣" + "\n" \
- + r "" + old_msg.get( 'msg_content' )
- # If the link exists,
- if old_msg[ 'msg_type' ] == "Sharing" : msg_body += "\nThis is the link ➣ " + old_msg.get( 'msg_share_url' )
-
- # Send the recall message to the file assistant
- itchat.send(msg_body, toUserName= 'filehelper' )
- # If there is a file, send it 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' % (rev_tmp_dir + old_msg[ 'msg_content' ])
- itchat.send(msg=file, toUserName= 'filehelper' )
- os.remove(rev_tmp_dir + old_msg[ 'msg_content' ])
- # Delete old dictionary messages
- msg_dict.pop(old_msg_id)
-
- if __name__ == '__main__' :
- itchat.auto_login(hotReload= True ,enableCmdQR=2)
- itchat.run()
The program can be run directly in the terminal. You can log in successfully by scanning the code in the terminal. It can also be packaged and run in the window system (note to modify the path, it is recommended to use a relative path). - ➜ ~ python wx.py
- Getting uuid of QR code.
- Downloading QR code.
- Please scan the QR code to log in .
- Please press confirm on your phone.
- Loading the contact, this may take a little while.
- �[3;J
- Login successfully as AlicFeng
- Start auto replying.
02 Rendering 03 itchat The above are all trivial things in programming logic. I will still record the itchat WeChat open source library. 1. Introduction itchat is an open source WeChat personal account interface. It is very simple to call WeChat using Python. It is easy to use itchat code to build an instant messaging based on WeChat. What is more, it is convenient to expand the communication functions of personal WeChat on other platforms. 2. Installation pip3 install itchat 3. itchat - Helloworld Just three lines of code to send a message to the file transfer assistant. - import itchat
- itchat.auto_login(hotReload= True )
- itchat.send( 'Hello AlicFeng' , toUserName= 'filehelper' )
4. View the client [[237838]] The most important thing to learn is the API manual: Github for itchat: - https://github.com/liduanwei/ItChat
Chinese API: - http://itchat.readthedocs.io/zh/latest/
|