Writing

WeChat Automation with wxpy

Simulated login

Simulated Login

from wxpy import *
bot = Bot()

Finding Chat Targets

Through the Bot object’s chats(), friends(), groups(), and mps() methods, you can get all chat targets, friends, group chats, and official accounts for the current bot.

from wxpy import *
bot = Bot()
# Get official account list
my_friend = bot.mps()
print(my_friend)

After fetching targets, use send to deliver messages:

# Send text
my_friend.send('Hello, WeChat!')
# Send image
my_friend.send_image('my_picture.png')
# Send video
my_friend.send_video('my_video.mov')
# Send file
my_friend.send_file('my_file.zip')
# Send image as animated sticker
my_friend.send('@img@my_picture.png')

After getting chat targets you can inspect friends’ gender, region, and other attributes and chart them:

image

Message Handling

Whenever the bot receives a message, it automatically:

  • Saves the message to Bot.messages

  • Finds and runs any pre-registered handler for that message (if matched)

# Forward important messages from the boss in the company group
from wxpy import *

bot = Bot()

# Locate company group
company_group = ensure_one(bot.groups().search('公司微信群'))

# Locate boss
boss = ensure_one(company_group.search('老板大名'))

# Forward boss messages to File Transfer
@bot.register(company_group)
def forward_boss_message(msg):
    if msg.member == boss:
        msg.forward(bot.file_helper, prefix='老板发言')

# Block thread
embed()

Auto-reply example:

if __name__ =="__main__":
    SourceSavePath = './RecieveFile/'

    bot = Bot(cache_path=True)
    myFriend = bot.friends()  # Targets to handle messages

    # myFriend += bot.groups().search('GroupName') # Add group

    @bot.register(myFriend)  # Register message handler
    def Del_GroupMsg(msg):
        print(msg.sender.name, ':', msg.text, 'Msg Type:', msg.type)
        msg.sender.mark_as_read()
        if msg.type == TEXT:
            return aiqa(msg.text)
        elif msg.type == PICTURE:  # On image, reply with same image
            print('this is PICTURE:{}'.format(msg.file_name))
            savaPath = SourceSavePath + msg.file_name
            msg.get_file(savaPath)
            msg.reply_image(savaPath)
        else:  # Forward other types back to sender
            msg.forward(msg.sender)
    embed()

Monitor Your Program via WeChat

Create a group chat in WeChat and add people who should receive logs. Use that group as the receiver.

from wxpy import get_wechat_logger

# Get a dedicated Logger
# Without `receiver`, logs go to "File Transfer" on the account you scan to log in
logger = get_wechat_logger()

# Send warning
logger.warning('This is a WARNING-level log—did you receive it?')

# Receive caught exceptions
try:
    1 / 0
except:
    logger.exception('What did you receive now?')