Home >WeChat Applet >WeChat Development >Python implements WeChat group message synchronization robot based on itchat

Python implements WeChat group message synchronization robot based on itchat

高洛峰
高洛峰Original
2017-02-28 09:03:533983browse

Recently, 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()
# 发送文本消息,发送目标是“文件传输助手”
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
# 注册消息响应事件,消息类型为itchat.content.TEXT,即文本消息
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
  # 返回同样的文本消息
  return msg['Text']

itchat.auto_login()
# 绑定消息响应事件后,让itchat运行起来,监听消息
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来区分
  # msg['FromUserName']就是发送者的ID
  # 将消息的类型和文本内容返回给发送者
  itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])

# 处理多媒体类消息
# 包括图片、录音、文件、视频
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
  # msg['Text']是一个文件下载函数
  # 传入文件名,将文件下载下来
  msg['Text'](msg['FileName'])
  # 把下载好的文件再发回给发送者
  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
# 即可保留登陆状态
# 即使程序关闭,一定时间内重新开启也可以不用重新扫码
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):
      # 转发到其他需要同步消息的群聊
      for item in groups.keys():
        if not item == source:
          # groups[source]: 消息来自于哪个群聊
          # msg['ActualNickName']: 发送者的名称
          # msg['Content']: 文本消息内容
          # item: 需要被转发的群聊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']: 分享的标题
          # 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:
        # 将图片或视频发送到其他需要同步消息的群聊
        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 = =).

Python implements WeChat group message synchronization robot based on itchat

Python implements WeChat group message synchronization robot based on itchat

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn