Python implements WeChat group message synchronization robot based on itchat

Source: Internet
Author: User
This article mainly introduces the implementation of group message synchronization robot based on itchat in python. I think it is quite good in small series. now I will share it with you and give you a reference. Let's take a look at the small Editor. Recently, there have been nearly 500 people in the group where full-stack data engineers have developed the strategy. after the second group was opened, in order to open up messages between different groups, it took some time for a message synchronization robot to synchronize messages received by any group to other groups and upload the chat content to the database for further analysis, statistics, and display.

The basic idea is to use Python to simulate login. after receiving messages from a group, the system processes texts, images, shares, and other message types separately and forwards them to other groups.

Preparations

First, you must have a number used for simulated login by code. Because I had to keep my phone number for use, and now I have to register a mobile phone number, so I had to apply for a new electrical signal, which is honlanbot. Although it seems that we can use Alibaba's account number for registration, we have heard that there are repeated recovery and security risks, so we do not use it.

Second, you need to use a Python library itchat, which has completed most of the functions called with code, which is very easy to use. the official documentation is here, you can use pip during installation.

pip install itchat

My mobile phone supports dual-card dual-wait, so I packed both cards into my mobile phone and opened them again. at the same time, I kept the two mobile phones online and almost started to write code. Using itchat is mainly to simulate web login, so the phone number must be kept online, because once the mobile phone end exits, the accounts that are authenticated on the webpage, PC, MAC, IPAD, and other terminals will also exit.

Preliminary attempt

Itchat provides some official code for us to create a new py file in our own book or computer and try it out.

Run the following code to see a QR code. after scanning the QR code and logging in, a message will be sent to the "File Transfer Assistant.

# Loading package import itchat # log on to itchat. auto_login () # send a text message with the target "file transfer assistant" itchat. send ('Hello, filehelper ', toUserName = 'filehelper ')

The following code registers a message response event to define how to handle a received text message. In itchat, multiple message types are defined, including text, images, business cards, locations, notifications, shares, and files, which can be processed separately.

Import itchat # register the message response event. the Message Type is itchat. content. TEXT message @ itchat. msg_register (itchat. content. TEXT) def text_reply (msg): # return the same Text message return msg ['text'] itchat. auto_login () # After binding the message response event, let itchat run and listen to the message itchat. run ()

Let's take a look at how to process other types of messages. we can print the msg in the message response event as a dictionary to see what fields are of interest.

Import itchat # import all message types from itchat. content import * # process text messages # including text, location, business card, notification, and sharing @ itchat. msg_register ([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply (msg): # every user and group chat, both use a long ID to distinguish # msg ['fromusername'] is the sender's ID # return the message type and text content to the sender's itchat. send ('% s: % s' % (msg ['type'], msg ['text']), msg ['fromusername']) # processing multimedia messages # Including images, recordings, files, and videos @ itchat. msg_register ([PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download _ Files (msg): # msg ['text'] is a file download function # Input a file name and download the file msg ['text'] (msg ['filename']) # send the downloaded file back to the sender '@ % s @ % s' % ({'picture': 'IMG ', 'video': 'vid '}. get (msg ['type'], 'Fil '), msg ['filename']) # process friend adding request @ itchat. msg_register (FRIENDS) def add_friend (msg): # this operation automatically enters messages of new FRIENDS, and does not need to reload the address book itchat. add_friend (** msg ['text']) # After adding a friend, send a greeting to the friend itchat. send_msg ('Nice to meet you! ', Msg ['recommendinfo'] ['username']) # process group chat messages @ itchat. msg_register (TEXT, isGroupChat = True) def text_reply (msg): if msg ['isat']: itchat. send (u' @ % s \ u2005I received: % s' % (msg ['actualnickname'], msg ['content']), msg ['fromusername']) # provide a True value in auto_login (), that is, hotReload = True # The login status can be retained. # even if the program is closed, you do not need to scan itchat again after a certain period of time. auto_login (True) itchat. run ()

Develop a message synchronization robot

After the above sample code, we can summarize the development ideas of the message synchronization robot:

  • Maintain a dictionary called groups to store all group chats for message synchronization. The key is the group chat ID and the value is the group chat name;

  • When a group chat message is received, if the message comes from the 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.

The code is ready. First, define a message response function. I am interested in TEXT messages and SHARING messages. use isGroupChat = True to specify that messages come from the group chat, this parameter defaults to False.

@ Itchat. msg_register ([TEXT, SHARING], isGroupChat = True) def group_reply_text (msg): # obtain the group chat ID, that is, the group chat from which the message comes from. # The source can be printed here, after determining which group chat is used # add the group chat ID and name to groups source = msg ['fromusername'] # process TEXT messages if msg ['type'] = TEXT: # The message comes from the group chat that requires message synchronization if groups. has_key (source): # group chat for item in groups. keys (): if not item = source: # groups [source]: group chat from which the message comes from # msg ['actualnickname']: name of the sender # msg ['content']: text message content # item: ID of the group chat to be forwarded itchat. send ('% s: % s \ n % s' % (groups [source], msg ['actualnickname'], msg ['content']), item) # processing shared message elif msg ['type'] = SHARING: if groups. has_key (source): for item in groups. keys (): if not item = source: # msg ['text']: share Title # msg ['URL']: share link itchat. send ('% s: % s \ n % s' % (groups [source], msg ['actualnickname'], msg ['text'], msg ['URL']), item)

Then, process the multi-media messages such as slices.

# Process image and video messages @ itchat. msg_register ([PICTURE, VIDEO], isGroupChat = True) def group_reply_media (msg ): source = msg ['fromusername'] # download an image or video msg ['text'] (msg ['filename']) if groups. has_key (source): for item in groups. keys (): if not item = source: # send an image or video to another group chat itchat that requires message synchronization. send ('@ % s @ % s' % ({'picture': 'IMG ', 'video': 'vid '}. get (msg ['type'], 'Fil '), msg ['filename']), item)

The above code processes four types of messages: Text, sharing, image, and video. if you are interested in other types of messages, you can simply process them accordingly. Add the import code in the front, and add the login and running code in the back.

Result Display

At present, messages can be synchronized between the two groups, and the Friends of the first and second groups can finally chat happily (when the group owner is not easy, many red packets are often sent = ).

The above is all the content of this article. I hope it will help you learn and support PHP.

For more python articles about implementing a group message synchronization robot based on itchat, refer to PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.