Recently all engineers develop strategy WeChat group of stack data has nearly 500 people, after opened a second group of messages between different WeChat group in order to get through, spend a little time to do a message synchronization robot, in any group of synchronization to other groups, when messages are received and will chat content uploaded to the database, for further analysis, statistics and presentation.

The basic idea is to use Python to simulate the login of wechat web version. After receiving messages in the group, the text, picture, share and other types of messages are processed separately and forwarded to other groups.

preparation

First of all, there must be a micro signal for code simulation landing. Since I have to keep my wechat account for myself, and now I have to use my mobile phone number to register my wechat account, I had to specially make an electrical signal to apply for a new wechat account, and the wechat account is Honlanbot. Although it seems that you can use Ali trumpet to register wechat, but I heard that there are repeated recycling and security risks, so do not use.

Secondly, we need to use a Python library itchat, which has done a good job of calling most functions of wechat with code. It is very easy to use. The official document is here, and you can use PIP when installing.

pip install itchatCopy the code

My mobile phone supports double cards and double waiting, so I put two cards in my mobile phone, and then double open wechat, and keep two wechat mobile phone online at the same time, almost can start to write code. Using itchat to call wechat is mainly to simulate the login of wechat web version, so it is necessary to keep wechat mobile online, because once wechat on the mobile end is quit, its authenticated accounts on the web, PC, MAC, IPAD and other corresponding terminals will also be quit.

A preliminary attempt to

Itchat provides some official code to give it a try by creating a new PY file on your laptop or computer.

Run the following code, a QR code will appear, scan the code after logging in will send a message to “file Transfer assistant”.

# import itchat # login to itchat.auto_login() # send text message, Itchat. send('Hello, fileHelper ', toUserName=' fileHelper ')Copy the code

The following code registers a message response event that defines how to handle a text message once it is received. In ItChat, you can define multiple message types such as text, image, business card, location, notification, share, and file to perform different processing.

@itchat.msg_register(itchat.content.text) def text_reply(MSG): Return MSG ['Text'] itchat.auto_login()Copy the code

To see how to handle other types of messages, you can print out the MSG in the message response event, which is a dictionary, to see what fields are of interest.

Import itchat # import all message types from itchat.content import * # Handle TEXT messages # include TEXT, location, business card, notification, share @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply(msg): # MSG ['FromUserName'] is the ID of the sender # return the type and text of the message to the sender itchat.send('%s: %s' % (MSG ['Type'], MSG ['Text']), MSG ['FromUserName']) RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): MSG ['Text'](MSG ['FileName']) return '@%s@%s' % ({'Picture': 'img', 'Video': If (MSG ['Type'], MSG ['FileName']) def add_friend(MSG): if (MSG ['Type'], MSG ['FileName']) # itchat.add_friend(** MSG ['Text']) # itchat.send_msg('Nice to meet you! ', MSG [' RecommendInfo] [' UserName ']) # processing group chat message. @ itchat msg_register (TEXT, isGroupChat = True) def text_reply (MSG) : if msg['isAt']: itchat.send(u'@%s\u2005I received: %s' % (MSG ['Content']), MSG ['FromUserName']) # Itchat.auto_login (True) itchat.run()Copy the code

Development of message synchronization robots

Through the above example code, we can summarize the development ideas of message synchronization robot:

  • Use after loginget_chatrooms()Obtain the data of all group chats, including the ID and nickname of each group chat, and save the group chats that need to synchronize messages to the address book;
  • If a group chat message is received from a group chat that needs to be synchronized, it is processed according to the message type and forwarded to other group chats that need to be synchronized.

Let’s start by defining a message response function. For TEXT messages, I’m interested in TEXT and SHARING. Use isGroupChat=True to specify that the message came from a group chat, which defaults to False.

# isGroupChat=True # isGroupChat @itchat.msg_register([TEXT, SHARING], isGroupChat=True) def group_reply_text(msg): ['FromUserName'] [username = MSG ['ActualNickName'] # if not chatroom_id in chatroom_ids: return if msg['Type'] == TEXT: content = msg['Content'] elif msg['Type'] == SHARING: If MSG ['Type'] == Text: for item in chatrooms: if not item['UserName'] == chatroom_id: itchat.send('%s\n%s' % (username, msg['Content']), item['UserName']) elif msg['Type'] == SHARING: for item in chatrooms: if not item['UserName'] == chatroom_id: itchat.send('%s\n%s\n%s' % (username, msg['Text'], msg['Url']), item['UserName'])Copy the code

Next to processing pictures and other multimedia messages.

# isGroupChat=True @itchat.msg_register([PICTURE, ATTACHMENT, VIDEO], isGroupChat=True) def group_reply_media(msg): ['FromUserName'] [username = MSG ['ActualNickName'] # if not If MSG ['FileName'][-4:] == '.gif': MSG ['FileName'] (MSG ['FileName']) if not item['UserName'] == chatroom_id: itchat.send('@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']), item['UserName'])Copy the code

The above code realizes the processing of text, share, picture and video messages. If you are interested in other types of messages, you can process them accordingly. Fill in the import code at the front, and the code to log in, get group chat data, and start monitoring, and you’re done.

The full code is here: pan.baidu.com/s/1bpAJk0B

Results show

Now the two groups can synchronize messages, and the group and the group can finally chat freely (when the group leader is not easy, often have to send a lot of red packets = =).

Further work

Of course, I can’t run this PY code on my laptop all the time, so I’ll just deploy it to a server and run it, either on Screen or IPython. If the account is occasionally offline, just run it again.

In addition, I also wrote an API, the response message will be the corresponding data to my server and stored in the database for further analysis, statistics and display, this is also my responsibility as a group leader ~

If you think the article is good, you might as well click on the lower left like ~