wxpy to realize wechat robot

wxpy is probably the most elegant wechat personal number API. Based on itchat, it improves the ease of use of the module through a large number of interface optimization, and expands its functions. It can easily call Turing robot and build its own chat robot. Please refer to Official documents of wxpy
                     !

1. View message recall

def dlDoc(fPath, ra, content, flag):
    """
    download_document
    :param fPath: filePath
    :param ra: rawData
    :param content:
    :param flag:
    :return:
    """
    ra.get('Text')(fPath)
    bot.file_helper.send(content)
    if 4 == flag:
        bot.file_helper.send_image(fPath)
    elif 7 == flag:
        bot.file_helper.send_video(fPath)
    else:
        bot.file_helper.send_file(fPath)
    os.remove(fPath)

  monitor code:

@bot.register(except_self=False, run_async=True, enabled=True)
def handleReceiveMsg(msg):
    """
    //Monitoring messages
    :param msg: Matching message objects
    :return:
    """
    raw = msg.raw  # Raw data (dict data)
    mss = msg.bot.messages  # Get all messages of the bot
    le = len(mss)

    if raw['Status'] == 4:
        # Get message ID
        oldmsgid = re.search(re.compile('<msgid>(.*?)</msgid>', re.S), raw['Content']).group(1)

        for i in range(le - 1, -1, -1):
            if oldmsgid == str(mss[i].id):
                name = msg.chat.name
                if name is None or name == '':
                    name = msg.chat.nick_name
                if mss[i].type == 'Text':
                    bot.file_helper.send(name + 'A message was recalled:' + mss[i].text)
                    break
                elif mss[i].type == 'Map':
                    bot.file_helper.send(name + 'A location message was recalled:' + mss[i].location['label'])
                    break
                elif mss[i].type == 'Card':
                    card = mss[i].card
                    name = card.name
                    if name is None or name == '':
                        name = card.nick_name
                    sex = str(card.sex)
                    if sex == '1':
                        sex = 'male'
                    else:
                        sex = 'female'
                    bot.file_helper.send(name + 'Recalled a business card: Name:' + name + ',Gender:' + sex)
                    break
                elif mss[i].type == 'Sharing':
                    bot.file_helper.send(name + 'Withdrawn a share:' + mss[i].url)
                    break
                elif mss[i].type == 'Picture':
                    dlDoc(mss[i].file_name, mss[i].raw, name + 'Recalled a picture, the picture is loading...')
                    break
                elif mss[i].type == 'Recording':
                    dlDoc(mss[i].file_name, mss[i].raw, name + 'A voice has been recalled. The voice is loading...')
                    break
                elif mss[i].type == 'Attachment':
                    dlDoc(mss[i].file_name, mss[i].raw, name + 'Recalled a file, file loading...')
                    break
                elif mss[i].type == 'Video':
                    dlDoc(mss[i].file_name, mss[i].raw, name + 'Recalled a video, video loading...')
                    break

2. View course schedule

  a) data structure: This design is a bit rough. It is written in memory simply and roughly. You can have a clever database design, hhh

day_dict = {
    0: 'Monday',
    1: 'Tuesday',
    2: 'Wednesday',
    3: 'Thursday',
    4: 'Friday',
    5: 'Saturday',
    6: 'Sunday',
}

classes = {
    0: {1: "", 2: "9:55-11:35AM B203 JAVA Program design", 3: '', 4: '', 5: '18:00-21:00 A214 computer network/Java Experiment'},
    1: {1: "", 2: "9:55-11:35AM B213 technological economics", 3: '', 4: '', 5: '18:00-21:00 A314 E-commerce experiment'},
    2: {1: "8:00-9-40 B203 Pharmaceutical English", 2: "9:55-11:35AM B201 Matlab",
        3: '1:30-3.10 A214 matlab Experiment', 4: '3:25-5.10 A214 R Language experiment', 5: '18:00-21:00 D207 Pharmaceutical informatics '},
    3: {1: "", 2: "9:55-11:35AM B201 project management", 3: '1:30-3.10 B201 Electronic Commerce', 4: '', 5: ''},
    4: {1: "", 2: "9:55-11:35AM B213 computer network", 3: '1:30-4:10 B201 GMP', 4: '', 5: ''}
}

  b) event listening Code:

@bot.register([file_helper], TEXT, except_self=False)
def reply_file_helper(msg):
    """
    //Course schedule query
    :param msg:
    :return:
    """
    if 'Class Schedule Card' in msg.text:
        weekday_id = localtime(time())[6]
        if weekday_id < 5:
            day_classes = classes[weekday_id]
            text = 'Today's course:\r\n'
            for key, value in day_classes.items():
                if value:
                    text += (value + '\r\n')
            msg.reply(text)
        else:
            msg.reply('There are no classes on weekends!')
    else:
        return


embed()

3. Face detection

a) face detection using dlib

#! /usr/bin/python
# _*_ coding: utf-8 _*_
__author__ = 'Jeffery'
__date__ = '2018/5/1 23:10'
import cv2
import numpy as np
import dlib


def rect_to_bb(rect):
    """
    :param rect: dlib Face area detection output
    :return: Returns a rectangular coordinate
    """
    x = rect.left()
    y = rect.top()
    w = rect.right() - x
    h = rect.bottom() - y
    return x, y, w, h


def shape_to_np(shape, dtype="int"):
    """

    :param shape: dlib Output of facial feature detection
    :param dtype:
    :return:
    """
    coords = np.zeros((68, 2), dtype=dtype)
    for i in range(0, 68):
            coords[i] = (shape.part(i).x, shape.part(i).y)

    return coords


def resize(image, width=1200):
    """

    :param image: Pictures to detect
    :param width:
    :return:
    """
    r = width * 1.0 / image.shape[1]
    dim = (width, int(image.shape[0] * r))
    resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
    return resized


def detect(image_file):
    """

    :param image_file: image_file_path
    :return:
    """
    count = 0
    image = cv2.imread('./imgs/'+image_file)
    # image = resize(image, width=1200)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    detector = dlib.get_frontal_face_detector()
    rects = detector(gray, 1)

    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

    for (i, rect) in enumerate(rects):
        count += 1
        shape = predictor(gray, rect)

        shape = shape_to_np(shape)

        (x, y, w, h) = rect_to_bb(rect)

        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10),
        #             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        for (x, y) in shape:
            cv2.circle(image, (x, y), 1, (0, 0, 255), -1)
    cv2.imwrite('./res_imgs/detect_res_'+image_file, image)
    return './res_imgs/detect_res_'+image_file, count


if __name__ == '__main__':
    detect('1.png')

  b) event monitoring
                        

@bot.register(Friend, PICTURE, except_self=False, enabled=True)
def reply_pic(msg):
    file_name = msg.file_name
    if os.path.splitext(file_name) != '.gif':
        msg.get_file('./imgs/' + file_name)
        img_path, count = detect(file_name)
        if count > 0:
            msg.reply_image(img_path)
            msg.reply(u"Detected%d Zhang faces" % count)
        else:
            msg.reply(u'Picture received, no face detected')

4. Late night reminder

This is easy

@bot.register(Friend, TEXT, except_self=True)
def reply_text(msg):
    """
    //Reply to friend message
    :param msg:Match message objects on
    :return: msg.reply
    """
    struct_time = localtime(time())
    if struct_time[3] >= 23 or struct_time[3] <= 7:
        now_time = strftime('%Y-%m-%d %H:%M:%S', struct_time)
        weekday = day_dict[struct_time[6]]
        msg.reply(u'[Automatic recovery]It's Beijing time:' + now_time + " " + weekday +
                  ', It's late. Have a rest early. The host will reply you as soon as he sees the news tomorrow morning')

5. Turing robot

  for the use of Turing robot, you only need to apply for an api_key. Of course, you can also train a unique chat robot with your own corpus.

bot = Bot(cache_path=False, console_qr=False)
tuling = Tuling(api_key='api_key')
@bot.register(Friend, TEXT, except_self=True)
def reply_text(msg):
    """
    Reply to friend message
    : param msg: match message object on
    :return: msg.reply
    """
    tuling.do_reply(msg)

Tags: Java network MATLAB Database

Posted on Thu, 19 Mar 2020 11:16:19 -0400 by steviewdr