You can monitor specific chats for new messages using AddListenChat. This requires a callback function (e.g., on_message) that handles the incoming msg and chat objects. To keep the listener active, you must call wx.KeepRunning(). Use RemoveListenChat to stop monitoring a specific nickname.
Common tasks within a callback:
- Logging: Write
msg.content to a file. - Downloading: Use
msg.download() for image or video types. - Auto-reply: Use
msg.quote('text') if the message is an instance of FriendMessage.
from wxauto import WeChat
from wxauto.msgs import FriendMessage
import time
wx = WeChat()
def on_message(msg, chat):
# Log to file
with open('msgs.txt', 'a', encoding='utf-8') as f:
f.write(msg.content + '\n')
# Download media
if msg.type in ('image', 'video'):
print(msg.download())
# Auto-reply to friends
if isinstance(msg, FriendMessage):
msg.quote('收到')
# Start listening to '张三'
wx.AddListenChat(nickname="张三", callback=on_message)
# Keep the program running to listen
wx.KeepRunning()
# Later, to stop listening:
# wx.RemoveListenChat(nickname="张三")