Python学习笔记-WXPY初识

项目地址:https://github.com/youfou/wxpy

帮助文档:https://wxpy.readthedocs.io/zh/latest/index.html

安装:pip install -U wxpy

简单使用代码记录

# -*- coding:utf-8 -*-

import os
import sys
import json
import urllib
import requests
from wxpy import *
from bs4 import BeautifulSoup

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)


def handle_dt(keyword, max_size=10):
    resp = requests.get('https://www.doutula.com/search', {'keyword': keyword})
    b_soup = BeautifulSoup(resp.content, 'lxml')
    a_tags = b_soup.select('#search-result-page > div > div > div > div > div.search-result.list-group-item > div > div > a > img')
    picture_name_list = []
    i = 0
    for a_tag in a_tags:
        link = a_tag.get('data-original')
        if link is not None and str(link).endswith('jpg'):
            link = str(link).strip()
            picture_name = link[link.rindex('/') + 1:]
            parent_dir = os.path.join(os.path.dirname(__file__), 'picture')
            urllib.urlretrieve(link, os.path.join(parent_dir, picture_name))
            picture_name_list.append(picture_name)
            i += 1
            if i == max_size:
                break
    return picture_name_list


def print_user_info(user):
    print '{} {} {} {} {} {} {} {}'.format(user.is_friend, user.name, user.nick_name,
        user.remark_name, user.sex, user.signature, user.province, user.city)


if __name__ == '__main__':
    bot = Bot(cache_path=True)
    # 设置历史消息的最大保存数量
    bot.messages.max_history = 1000

    friends = bot.friends()

    t_friend_1 = friends.search(u'朋友1')[0]
    print_user_info(t_friend_1)

    t_friend_2 = friends.search(u'朋友2')[0]
    print_user_info(t_friend_2)

    groups = bot.groups()

    t_group_1 = ensure_one(groups.search(u'组1'))
    for member in t_group_1.members:
        print_user_info(member)

    t_person_1 = ensure_one(t_group_1.search(u'组员1'))
    print_user_info(t_person_1)

    history_msgs = bot.messages.search(keywords=u'关键字', sender=bot.self)
    for history_msg in history_msgs:
        print history_msg

    @bot.register(msg_types=FRIENDS)
    def listen_and_accept_friends(msg):
        a_friend = bot.accept_friend(msg.card)
        a_friend.send('hello')

    @bot.register(chats=[t_friend_1, t_friend_2])
    def listen_and_reply_friends(msg):
        print 'received msg:[{}] {}'.format(msg.type, msg.text)
        if msg.type == 'Picture':
            parent_dir = os.path.join(os.path.dirname(__file__), 'picture')
            print 'picture dir {} name {}'.format(parent_dir, msg.file_name)
            msg.get_file(save_path=os.path.join(parent_dir, msg.file_name))
        elif msg.type == 'Video':
            parent_dir = os.path.join(os.path.dirname(__file__), 'video')
            print 'video dir {} name {}'.format(parent_dir, msg.file_name)
            msg.get_file(save_path=os.path.join(parent_dir, msg.file_name))
        elif msg.type == 'Recording':
            parent_dir = os.path.join(os.path.dirname(__file__), 'recording')
            print 'recording dir {} name {}'.format(parent_dir, msg.file_name)
            msg.get_file(save_path=os.path.join(parent_dir, msg.file_name))
        else:
            msg.reply('thank you ! i have received it')

        parent_dir = os.path.join(os.path.dirname(__file__), 'picture')
        picture_name_list = handle_dt(msg.text, max_size=2)
        for picture_name in picture_name_list:
            msg.reply_image(os.path.join(parent_dir, picture_name))

    @bot.register(Group)
    def listen_and_reply_groups(msg):
        msg_member = msg.member
        print 'received member {} {} {}'.format(msg_member.group, msg_member.name, msg_member.display_name)
        print 'received msg:[{}] {}'.format(msg.type, msg.text)
        sender = msg.sender
        if isinstance(sender, Group):
            print_user_info(sender.owner)
        receiver = msg.receiver
        if isinstance(receiver, User):
            print_user_info(receiver)
        if isinstance(msg.chat, Group) and msg.is_at:
            msg.reply('thank you ! i have received it')

    @bot.register(t_group_1)
    def listen_and_reply_t_group_1(msg):
        parent_dir = os.path.join(os.path.dirname(__file__), 'picture')
        picture_name_list = handle_dt(msg.text, max_size=4)
        for picture_name in picture_name_list:
            msg.reply_image(os.path.join(parent_dir, picture_name))
        if msg.member == t_person_1:
            msg.forword(bot.file_helper, prefix=u'留言')

    embed()

 

你可能感兴趣的:(Python)