


Python implements WeChat group message synchronization robot based on itchat
Feb 28, 2017 am 09:03 AMRecently, the WeChat group for full-stack data engineer training has nearly 500 people. After opening the second group, in order to open up the messages between different WeChat groups, I spent some time to make a message synchronization robot, which can be received in any group. Messages are synchronized to other groups, and chat content is uploaded to the database for further analysis, statistics, and display.
The basic idea is to use Python to simulate WeChat login. After receiving group messages, various message types such as text, pictures, and sharing are processed separately and forwarded to other groups.
Preliminary preparation
First of all, you must have a WeChat ID for code simulation login. Since I have to keep my WeChat ID for myself, and currently I need a mobile phone number to register for WeChat, I had to create a special email account and use it to apply for a new WeChat account. The WeChat ID is honlanbot. Although it seems that you can use Ali account to register WeChat, I heard that there are repeated recycling and security risks, so I don't use it.
Secondly, you need to use a Python library itchat. This library has already prepared most of the functions of WeChat using code. It is very easy to use. The official documentation is here. You can use pip when installing.
pip install itchat
My phone supports dual SIM cards and dual standby, so I installed both SIM cards in the phone, opened WeChat, and kept both WeChat IDs online at the same time. , you can almost start writing code. Using itchat to call WeChat is mainly to simulate logging in to the WeChat web version, so the WeChat ID phone must be kept online, because once WeChat on the mobile phone is logged out, its account authenticated on the web, PC, MAC, IPAD and other corresponding terminals will also be logged out.
Initial attempt
itchat provides some official code, let us create a new py file on our laptop or computer and give it a preliminary try.
Run the following code, a QR code will appear. After scanning the code to log in, a message will be sent to the "File Transfer Assistant".
# 加載包 import itchat # 登陸 itchat.auto_login() # 發(fā)送文本消息,發(fā)送目標(biāo)是“文件傳輸助手” itchat.send('Hello, filehelper', toUserName='filehelper')
The following code registers a message response event to define how to handle the text message after receiving it. Various message types such as text, pictures, business cards, locations, notifications, sharing, and files are defined in itchat, and different processing can be performed separately.
import itchat # 注冊消息響應(yīng)事件,消息類型為itchat.content.TEXT,即文本消息 @itchat.msg_register(itchat.content.TEXT) def text_reply(msg): # 返回同樣的文本消息 return msg['Text'] itchat.auto_login() # 綁定消息響應(yīng)事件后,讓itchat運(yùn)行起來,監(jiān)聽消息 itchat.run()
Let’s take a look at how to handle other types of messages. You can print out the msg in the message response event. It is a dictionary to see what you are interested in. field.
import itchat # import全部消息類型 from itchat.content import * # 處理文本類消息 # 包括文本、位置、名片、通知、分享 @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply(msg): # 微信里,每個用戶和群聊,都使用很長的ID來區(qū)分 # msg['FromUserName']就是發(fā)送者的ID # 將消息的類型和文本內(nèi)容返回給發(fā)送者 itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName']) # 處理多媒體類消息 # 包括圖片、錄音、文件、視頻 @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): # msg['Text']是一個文件下載函數(shù) # 傳入文件名,將文件下載下來 msg['Text'](msg['FileName']) # 把下載好的文件再發(fā)回給發(fā)送者 return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']) # 處理好友添加請求 @itchat.msg_register(FRIENDS) def add_friend(msg): # 該操作會自動將新好友的消息錄入,不需要重載通訊錄 itchat.add_friend(**msg['Text']) # 加完好友后,給好友打個招呼 itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName']) # 處理群聊消息 @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']) # 在auto_login()里面提供一個True,即hotReload=True # 即可保留登陸狀態(tài) # 即使程序關(guān)閉,一定時間內(nèi)重新開啟也可以不用重新掃碼 itchat.auto_login(True) itchat.run()
Develop message synchronization robot
Through the above example code, we can summarize the development ideas of message synchronization robot:
Maintain a dictionary called groups. It is used to store all group chats that need to synchronize messages. The key is the ID of the group chat, and the value is the name of the group chat;
When receiving a group chat message, if the message comes from a group chat that needs to be synchronized, it will be processed according to the message type and forwarded to other group chats that need to be synchronized.
Let’s go straight to the code. First define a message response function. The text messages I am interested in are TEXT and SHARING. Use isGroupChat=True to specify that the message comes from For group chat, this parameter defaults to False.
@itchat.msg_register([TEXT, SHARING], isGroupChat=True) def group_reply_text(msg): # 獲取群聊的ID,即消息來自于哪個群聊 # 這里可以把source打印出來,確定是哪個群聊后 # 把群聊的ID和名稱加入groups source = msg['FromUserName'] # 處理文本消息 if msg['Type'] == TEXT: # 消息來自于需要同步消息的群聊 if groups.has_key(source): # 轉(zhuǎn)發(fā)到其他需要同步消息的群聊 for item in groups.keys(): if not item == source: # groups[source]: 消息來自于哪個群聊 # msg['ActualNickName']: 發(fā)送者的名稱 # msg['Content']: 文本消息內(nèi)容 # item: 需要被轉(zhuǎn)發(fā)的群聊ID itchat.send('%s: %s\n%s' % (groups[source], msg['ActualNickName'], msg['Content']), item) # 處理分享消息 elif msg['Type'] == SHARING: if groups.has_key(source): for item in groups.keys(): if not item == source: # msg['Text']: 分享的標(biāo)題 # msg['Url']: 分享的鏈接 itchat.send('%s: %s\n%s\n%s' % (groups[source], msg['ActualNickName'], msg['Text'], msg['Url']), item)
Let’s process multimedia messages such as pictures.
# 處理圖片和視頻類消息 @itchat.msg_register([PICTURE, VIDEO], isGroupChat=True) def group_reply_media(msg): source = msg['FromUserName'] # 下載圖片或視頻 msg['Text'](msg['FileName']) if groups.has_key(source): for item in groups.keys(): if not item == source: # 將圖片或視頻發(fā)送到其他需要同步消息的群聊 itchat.send('@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']), item)
The above code implements the processing of four types of messages: text, sharing, pictures, and videos. If you are also interested in other types of messages, proceed accordingly Just process it. Add the import code in the front, add the login and running code in the back, and you're done.
Result Display
Currently, messages can be synchronized between the two groups, and the friends in the first and second groups can finally chat happily (when the group leader It’s not easy, I often have to give out a lot of red envelopes = =).
Further work
Of course, I can’t be on my laptop all the time To run such py code, just deploy it to the server and run it. You can open a screen or use IPython. If the account goes offline occasionally, just run it again.
In addition, I also wrote an API. When responding to the message, I will POST the corresponding data to my server and save it to the database for further analysis, statistics and display. This is why I, as a group The responsibilities of the master~
The above is the entire content of this article. I hope it will be helpful to everyone's study, and I also hope that everyone will support the PHP Chinese website.
For more articles related to python implementing WeChat group message synchronization robot based on itchat, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
