async def api_filter(msg: Message, from_contact: Contact):
    flag = 0
    if msg.type() == MessageType.MESSAGE_TYPE_TEXT:
        result = request(text_url, urlencode({'text': msg.text()}))
        result = json.loads(result)
        if result['conclusion'] == '不合规' or '疑似':
            try:
                flag = 1
                word = result['data'][0]['msg']
                await msg.say(word)
                await msg.say(f"用户@{from_contact.name}违规")
            except Exception as e:
                print("合规")
                flag = 0

    elif msg.type() == MessageType.MESSAGE_TYPE_IMAGE:
        img = await msg.to_file_box()
        if not os.path.exists(f'./img/{img.name}'):
            await img.to_file(f'./img/{img.name}')
        result = request(image_url, urlencode({'image': base64.b64encode(read_file(f'./img/{img.name}'))}))
        result = json.loads(result)
        if result['conclusion'] == '不合规' or '疑似':
            try:
                flag = 1
                word = result['data'][0]['msg']
                await msg.say(word)
                await msg.say(f"用户@{from_contact.name}违规")
            except Exception as e:
                print('合规')
                flag = 0

    if flag == 0:
        print("api检测没毛病")
    return flag
Exemplo n.º 2
0
 async def on_message(self, msg: Message):
     """
     Message Handler for the Bot
     """
     contact = msg.talker()  # 发消息人
     content = msg.text()  # 消息内容
     room = msg.room()  # 是否是群消息
     contact_name = contact.name
     if room:  # 群聊入口,未做任何处理
         if room.room_id == config_list['room_id'] and (
                 msg.type() == Message.Type.MESSAGE_TYPE_TEXT):
             print('群聊')
             room_id = room.room_id
             print('群名:{},发消息人:{},内容:{}'.format(room_id, contact_name,
                                                content))
             print('使用API发送群消息')
     else:
         dividing_line()
         print('非群聊')
         if msg.type() == Message.Type.MESSAGE_TYPE_TEXT:  # 处理文本类型消息
             if content == 'ding':
                 await sendTextMsgToContact(contact=contact,
                                            text="这是自动回复: dong dong dong")
             elif content == 'hi' or content == '你好' or content == "帮助":
                 info0 = "我是机器人助手--懂懂,很高兴为您服务!\n"
                 info1 = "1.收到'ding',自动回复\n"
                 info2 = "2.收到'帮助',自动回复\n"
                 info3 = "3.收到'小程序'or'微信小程序',自动回复\n"
                 info4 = "4.收到'情话@your_content',自动回复,例如 情话@春天\n"
                 info5 = "5.收到'藏头诗@your_content',自动回复,例如 藏头诗@我喜欢你\n"
                 info6 = "6.收到'city+天气',自动回复,例如 长沙天气\n"
                 help_info = info0 + info1 + info2 + info3 + info4 + info5 + info6
                 await sendTextMsgToContact(contact=contact, text=help_info)
             elif content == '小程序' or content == "微信小程序":
                 file_url = 'https://upload-images.jianshu.io/upload_images/10519098-690ae0fde75147a1.png' \
                            '?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240'
                 await sendMediaMsgToContact(contact=contact,
                                             fileUrl=file_url,
                                             filePath='')
             elif '天气' in content:
                 city_name = content[:-2]
                 weather_info = get_weather_data(city_name)
                 await contact.say(weather_info)
             elif "情话" in content:
                 content = content[3:]
                 res = chat_bot(content=content, mode='1')
                 await contact.say(res)
             elif "藏头诗" in content:
                 # 藏头诗模式
                 content = content[4:]
                 res = chat_bot(content=content, mode='2')
                 await contact.say(res)
             else:
                 res = chat_bot(content=content, mode='0')
                 await contact.say(res)
         #  处理图片类型消息
         elif msg.type() == Message.Type.MESSAGE_TYPE_IMAGE:
             dividing_line()
             await contact.say(
                 '不好意思,暂时处理不了图片类型消息,我们已经在催程序员小哥哥日夜加班优化项目了!希望您能够理解!')
Exemplo n.º 3
0
    async def handle(self, msg: Message):
        self._counter += 1
        log.error('%s: received %s messages' %
                  (datetime.datetime.now(), self._counter))
        me = self._bot.Contact.load('paulhybryant')
        text = msg.text()
        mention_self = await msg.mention_self()
        mention_text = await msg.mention_text()
        self._db.set(msg.talker().name, msg.talker().get_id())
        if msg.room():
            topic = await msg.room().topic()
            log.error('room: %s, topic %s' % (msg.room().room_id, topic))
            log.error('Message: %s, Contact: %s, Name: %s' %
                      (msg, msg.talker(), msg.talker().name))
            forward = self.handle_room(topic, text, mention_self, mention_text,
                                       msg.room().room_id, msg.type(),
                                       msg.talker())
            self._db.set(topic, msg.room().room_id)
            if forward:
                await me.say('来自群: %s,联系人: %s' % (topic, msg.talker().name))
                if msg.type() == MessageType.MESSAGE_TYPE_ATTACHMENT:
                    filebox = await msg.to_file_box()
                    await me.say(filebox)
                else:
                    await msg.forward(me)
        else:
            log.error('Message: %s, Contact: %s, Name: %s' %
                      (msg, msg.talker(), msg.talker().name))
            result = self.handle_cmd(text)
            if result:
                log.error(result)
                await msg.say(result)

            if msg.talker().get_id() in [
                    'wxid_p7xyfpcx7aoa12', 'wxid_5av5yw0udmgp12',
                    'wxid_lbvhcdjlgg0a21'
            ] and msg.type() == MessageType.MESSAGE_TYPE_ATTACHMENT:
                filebox = await msg.to_file_box()
                doc_re = re.compile(r'(.*)\.docx?')
                m = doc_re.match(filebox.name)
                if m:
                    if self._db.get('doc2pdf'):
                        f = '/tmp/%s' % filebox.name
                        await filebox.to_file(f, True)
                        converted, error = self.doc2pdf(f, m.group(1))
                        if converted:
                            pdf = filebox.from_file(converted)
                            await me.say(pdf)

            if msg.type() == MessageType.MESSAGE_TYPE_URL:
                talker = msg.talker()
                if talker.name in self._subscriptions:
                    await me.say('来自公众号: %s' % talker.name)
                    await msg.forward(me)
    async def on_message(self, msg: Message):
        """listen message event"""
        talker = msg.talker()
        room = msg.room()

        conversation_id = room.room_id if room else talker.contact_id

        # 1. TODO: use finder to match Room/Contact
        if conversation_id not in self.conversation_ids:
            return

        # only process the plain text message
        if msg.type() != MessageType.MESSAGE_TYPE_TEXT:
            return

        rasa_response = requests.post(
            self.endpoint,
            json=dict(
                sender=conversation_id,
                message=msg.text()
            )
        )
        messages: List[dict] = rasa_response.json()
        if len(messages) == 0:
            return

        conversational: Union[Room, Contact] = room if room else talker
        for message in messages:
            msg_text = message.get('text', None)
            if not msg_text:
                continue
            await conversational.say(msg_text)
    async def on_message(self, msg: Message):
        """
        listen for msg event.
        :param msg: received msg.
        :return: none
        """

        # msg
        # attrs:
        # message_id(str) '3037907331459016207'
        # from_id(str) 'wxid_qgho9l2kdha311'
        # mention_ids(list)
        # room_id(str)  ''
        # text(str) '1'
        # timestamp(int) 1620493045
        # to_id(str) 'wxid_vj8wsjhms91j22'


        # busy-bot: 可以输入特定指令使得机器人不会进行自动回答,可以用于进群验证时的维护状态


        from_contact = msg.talker()
        # attrs:
        # name(str) 'KIERAN.'
        # contact_id(str) 'wxid_qgho9l2kdha311'
        # address ''
        # alias ''
        # avatar 'https://wx.qlogo.cn/mmhead/ver_1/NFn8dpgY2taGWzz0jOnZFZ2rMsiaoINkFRuLDRtxTKyFREY56tIrWCXmdHMicB7cQxK7bJXqiajadVnicaM9CrAh0z1krDEpMs8AKEdMoHjaXvw/0'
        # city ''
        # friend True
        # gender 1
        # signature '短期计划者'
        # weixin 'kieran00000'

        text = msg.text()

        room = msg.room()

        to = msg.to()
        # attrs:
        # name(str) '随便取个名吧'
        # contact_id(str) 'wxid_vj8wsjhms91j22'
        # address ''
        # alias ''
        # avatar ''
        # city ''
        # friend True
        # gender 0
        # signature ''
        # weixin ''

        print(msg.type())

        if msg.is_self():
            return

        await savecontent(msg, from_contact, room, self.collection2)

        await calculatespeak(msg, from_contact, room, self.collection3)

        # if msg.type() == MessageType.MESSAGE_TYPE_AUDIO:
        #     audio = await msg.to_file_box()
        #     # save the image as local file
        #     await audio.to_file(f'./{audio.name}')

        # if msg.type() == MessageType.MESSAGE_TYPE_ATTACHMENT:
        #     file = await msg.to_file_box()
        #     await file.to_file(f"./{file.name}")
        #     print("保存文件成功")

        if msg.type() == MessageType.MESSAGE_TYPE_RECALLED:
            # recalledMessage = await msg.to_recalled()
            # 方法有错误,下面自己手写debug得到。

            msg_text = msg.text()
            # recalledMessage = self.Message.load(message_id=msg_text)
            # await recalledMessage.ready()
            origin_message_id = re.findall(r'<newmsgid>(.*?)</newmsgid>', msg_text)[0]

            # recalledMessage = self.Message.find_all(message_id=origin_message_id)
            recalledMessage = self.Message.load(message_id=origin_message_id)
            await recalledMessage.ready()
            log.info('Bot' + f'EVENT: Detect Recalled text : {recalledMessage.text()} . FROM {from_contact.contact_id}')
            print(f"Recalled msg is {recalledMessage.text()}")





        # 此处的if
        if room == None and to.contact_id == self.contact_id:
            # When someone try to contact with the bot
            if text == '#状态':
                msg = 'busy' if self.busy else 'free'
                await from_contact.say(
                    f'My status: {msg}')
                if self.busy == True:
                    await from_contact.say(self.busy_auto_reply_comment)

            elif text == '#开启':
                # Problem: the talker should be an authentic wechat user.
                self.busy = False
                await from_contact.say('关闭自动回复')

            elif text == '#关闭':
                # Problem: the talker should be an authentic wechat user.
                self.busy = True
                await from_contact.say('打开自动回复.')

            elif self.busy == False:
                # 添加基本的进群验证功能。
                if msg.text() == 'ding':
                    await from_contact.say('dong')
                    # await from_contact.say('目前只能进行ding的回复,请继续等待后续开发😂')

                if msg.text() == '#帮助':
                    await from_contact.say('1. 发送 \'#加群\' 给bot,bot会发送给用户对应的验证码图片\n'
                                           '2. 发送 \'#验证 XXXX\' 给bot,bot会完成验证并给予答复,拉人接口暂时还未完善\n'
                                           '3. 发送 \'ding\' 给bot,bot会答复dong')

                elif msg.text().startswith('#加群'):

                    find_result = find(self.collection3, from_contact.contact_id)
                    if find_result != False and find_result['remove'] != 0:
                        passed_time = time.time() - find_result['time_leave_room']
                        if passed_time < 300:
                            await from_contact.say(f"你的冷静期还未结束。还剩余{300 - int(passed_time)}秒")
                            return

                    inserted_dict = {"_id": from_contact.contact_id, "quiz_ans": "", "quiz_time": 0}
                    insert(self.collection1, from_contact.contact_id, inserted_dict)

                    await from_contact.say('请稍等验证码生成,并在60s内完成回答')

                    img, code = getVerifyCode()

                    update(self.collection1, from_contact.contact_id, "quiz_ans", code)
                    update(self.collection1, from_contact.contact_id, "quiz_time", time.time())
                    # 为了防止用户连续两次进行请求

                    # self.verify_info[from_contact.contact_id] = code

                    img = FileBox.from_file('./temp_verify.jpg')
                    await from_contact.say(img)
                    # print(self.verify_info[from_contact.contact_id])
                    print(code)

                    # await from_contact.say("目前进群功能仍在开发中")
                    # await from_contact.say('请耐心等待开发')


                elif msg.text() == '#我是你爹':
                    await from_contact.say("主人sama,马上把您拉上群")


                    try:
                        dingRoom = await self.Room.find('新测试群')
                        if dingRoom:
                            log.info('Bot' + 'onMessage: got dingRoom: "%s"' % await dingRoom.topic())
                            await checkandinvite(from_contact=from_contact, room = dingRoom, collection_user=self.collection3)
                            #
                            #
                            # if self.boton_quit.__contains__(dingRoom.room_id):
                            #     boton_quit_list = self.boton_quit[dingRoom.room_id]
                            # else:
                            #     boton_quit_list = []
                            #
                            # if from_contact.contact_id not in boton_quit_list and await dingRoom.has(from_contact):
                            #     topic = await dingRoom.topic()
                            #     log.info('Bot' + 'onMessage: sender has already in dingRoom')
                            #     # await dingRoom.say('I found you have joined in room "{0}"!'.format(topic), talker)
                            #     await dingRoom.say(f'您 @{from_contact.name} 已经在群聊 "{topic}"中!')
                            #     await from_contact.say(
                            #         '不需要再次申请入群,因为您已经在群"{}"中'.format(topic))
                            # else:
                            #     inserted_dict = {"_id": from_contact.contact_id, "time_in": time.time(), "warning": 0,
                            #                      "time_last_warning": 0}
                            #     insert(collection2, from_contact.contact_id, inserted_dict)
                            #     update(collection2, from_contact.contact_id, "warning", 0)
                            #     update(collection2, from_contact.contact_id, "time_last_warning", 0)
                            #
                            #
                            #     if from_contact.contact_id in boton_quit_list:
                            #         self.boton_quit[dingRoom.room_id].remove(from_contact.contact_id)
                            #     log.info('Bot' + 'onMessage: add sender("%s") to dingRoom("%s")' % (
                            #         from_contact.name, dingRoom.topic()))
                            #     await put_in_room(from_contact, dingRoom)
                            #     await from_contact.say('已经您拉入群中')


                    except Exception as e:
                        log.exception(e)



                elif msg.text().startswith('#验证'):
                    user_verify_code = msg.text()[4:]
                    print(user_verify_code)

                    find_result = find(self.collection1, from_contact.contact_id)
                    # if not self.verify_info.__contains__(from_contact.contact_id):
                    if find_result == False:
                        await from_contact.say('并未进行加群请求!,请先发送 #加群 至机器人获取专属验证码')
                        return

                    if time.time() - find_result['quiz_time'] > 60:
                        # expired_code = self.verify_info.pop(from_contact.contact_id)
                        delete(self.collection1, from_contact.contact_id)
                        print(f'previous code has benn expired')
                        await from_contact.say("超时未回答正确验证码信息,请重新发送 #加群 再进行尝试")

                    elif user_verify_code == find_result['quiz_ans']:

                        # TODO: 需不需要再在roominvite中删除?
                        delete(self.collection1, from_contact.contact_id)
                        print(f"在room_invite中删除一认证用户{from_contact.name}")


                        await from_contact.say("通过测试,后续会将您拉入群中")
                        # put_in_room()
                        # await from_contact.say("目前进群功能仍在开发中")



                        try:
                            dingRoom = await self.Room.find('新测试群')
                            if dingRoom:
                                log.info('Bot' + 'onMessage: got dingRoom: "%s"' % await dingRoom.topic())
                                await checkandinvite(from_contact=from_contact, room=dingRoom,
                                                    collection_user=self.collection3)

                                # if self.boton_quit.__contains__(dingRoom.room_id):
                                #     boton_quit_list = self.boton_quit[dingRoom.room_id]
                                # else:
                                #     boton_quit_list = []
                                #
                                # if from_contact.contact_id not in boton_quit_list and await dingRoom.has(from_contact):
                                #     topic = await dingRoom.topic()
                                #     log.info('Bot' + 'onMessage: sender has already in dingRoom')
                                #     # await dingRoom.say('I found you have joined in room "{0}"!'.format(topic), talker)
                                #     await dingRoom.say(f'您 @{from_contact.name} 已经在群聊 "{topic}"中!')
                                #     await from_contact.say(
                                #         '不需要再次申请入群,因为您已经在群"{}"中'.format(topic))
                                # else:
                                #     if from_contact.contact_id in boton_quit_list:
                                #         self.boton_quit[dingRoom.room_id].remove(from_contact.contact_id)
                                #
                                #     inserted_dict = {"_id": from_contact.contact_id, "time_in": time.time(),
                                #                      "warning": 0, "time_last_warning": 0}
                                #     insert(collection2, from_contact.contact_id, inserted_dict)
                                #     update(collection2, from_contact.contact_id, "warning", 0)
                                #     update(collection2, from_contact.contact_id, "time_last_warning", 0)
                                #     print("完成新人信息的插入")
                                #
                                #     log.info('Bot' + 'onMessage: add sender("%s") to dingRoom("%s")' % (
                                #         from_contact.name, dingRoom.topic()))
                                #     await put_in_room(from_contact, dingRoom)
                                #     await from_contact.say('已经您拉入群中')

                        except Exception as e:
                            log.exception(e)


                    else:
                        # 输入失败
                        await from_contact.say("验证失败,请再次尝试。")
                # 正常文字信息
                else:
                    if await regex_filter(msg, from_contact) != 0:
                        print("正则匹配得到")
                        # print("是这里吗?")
                        return
                    elif await dict_filter(msg, from_contact) != 0:
                        # print("regex passed")
                        print("字典检测得到")
                    # elif
                    # TODO:
                    elif await api_filter(msg, from_contact) != 0:
                        print("api匹配得到")
                        # print("regex passed")
                        # print("dict passed")

                    # else:
                        # print("regex passed")
                        # print("dict passed")
                        # print("api passed")



            else:
                await from_contact.say(self.busy_auto_reply_comment)

        # Room talk
        elif room.room_id == '23402005339@chatroom':
            print(1)
            if msg.text() == 'ding':
                await msg.say('dong')
                # await msg.say('目前只能进行ding的回复,请继续等待后续开发😂')

            else:
                # 正常的群中对话信息
                if await regex_filter(msg, from_contact) != 0:
                    print("正则匹配得到")
                    if from_contact.contact_id in owner_contact_id_list:
                        await room.say("管理员测试中")
                        return
                    await warnandcheck(from_contact, room, self.collection3)
                    return

                elif await dict_filter(msg, from_contact) != 0:
                    print("字典得到")
                    if from_contact.contact_id in owner_contact_id_list:
                        await room.say("管理员测试中")
                        return
                    await warnandcheck(from_contact, room, self.collection3)
                    return

                elif await api_filter(msg, from_contact) != 0:
                    print("API完成检测")
                    if from_contact.contact_id in owner_contact_id_list:
                        await room.say("管理员测试中")
                        return
                    await warnandcheck(from_contact, room, self.collection3)
                    return
async def savecontent(msg: Message, from_contact: Contact, room: Room, collection):
    if room == None:
        return
    inserted_msg_dict = {"_id": msg.message_id, "wxid": from_contact.contact_id, "content": "", "type": 0, "time": 0}

    if msg.type() == MessageType.MESSAGE_TYPE_TEXT:
        # 文字类型的messgae为1
        inserted_msg_dict["type"] = 1
        inserted_msg_dict["content"] = msg.text()

    elif msg.type() == MessageType.MESSAGE_TYPE_IMAGE:
        img = await msg.to_file_box()
        await img.to_file(f'./img/{img.name}')

        # 图片类型的messgae为2
        inserted_msg_dict["type"] = 2
        inserted_msg_dict["content"] = f"./img/{img.name}"

    elif msg.type() == MessageType.MESSAGE_TYPE_AUDIO:
        audio = await msg.to_file_box()
        await audio.to_file(f'./audio/{audio.name}')

        # 音频类型的messgae为3
        inserted_msg_dict["type"] = 3
        inserted_msg_dict["content"] = f"./audio/{audio.name}"

    elif msg.type() == MessageType.MESSAGE_TYPE_VIDEO:
        video = await msg.to_file_box()
        await video.to_file(f'./video/{video.name}')

        # 视频类型的messgae为4
        inserted_msg_dict["type"] = 4
        inserted_msg_dict["content"] = f"./video/{video.name}"

    elif msg.type() == MessageType.MESSAGE_TYPE_ATTACHMENT:
        file = await msg.to_file_box()
        await file.to_file(f'./file/{file.name}')

        # 文件类型的messgae为5
        inserted_msg_dict["type"] = 5
        inserted_msg_dict["content"] = f"./file/{file.name}"

    elif msg.type() == MessageType.MESSAGE_TYPE_CONTACT:

        # contact类型的messgae为6
        inserted_msg_dict["type"] = 6
        inserted_msg_dict["content"] = f"contact"

    elif msg.type() == MessageType.MESSAGE_TYPE_EMOTICON:

        # EMOTICON类型的messgae为7
        inserted_msg_dict["type"] = 7
        inserted_msg_dict["content"] = f"EMOTICON"

    else:
        # 其他类型的msg为8
        inserted_msg_dict["type"] = 8
        inserted_msg_dict["content"] = "OTHER"

    inserted_msg_dict["time"] = time.time()
    if insert(collection, msg.message_id, inserted_msg_dict):
        print(f"完成如下内容的记录保存{str(inserted_msg_dict)}")
    else:
        print("记录失败")
Exemplo n.º 7
0
    async def on_message(self, msg: Message):
        """
        listen for message event
        """
        from_contact: Contact = msg.talker()
        text: str = msg.text()
        room: Optional[Room] = msg.room()
        msg_type: MessageType = msg.type()
        file_box: Optional[FileBox] = None
        if text == '#ding':
            conversation: Union[
                Room, Contact] = from_contact if room is None else room
            await conversation.ready()
            await conversation.say('dong')
            file_box = FileBox.from_url(
                'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/'
                'u=1116676390,2305043183&fm=26&gp=0.jpg',
                name='ding-dong.jpg')
            await conversation.say(file_box)

        elif msg_type == MessageType.MESSAGE_TYPE_IMAGE:
            logger.info('receving image file')
            # file_box: FileBox = await msg.to_file_box()
            image: Image = msg.to_image()

            hd_file_box: FileBox = await image.hd()
            await hd_file_box.to_file('./hd-image.jpg', overwrite=True)

            thumbnail_file_box: FileBox = await image.thumbnail()
            await thumbnail_file_box.to_file('./thumbnail-image.jpg',
                                             overwrite=True)
            artwork_file_box: FileBox = await image.artwork()
            await artwork_file_box.to_file('./artwork-image.jpg',
                                           overwrite=True)
            # reply the image
            await msg.say(hd_file_box)

        # pylint: disable=C0301
        elif msg_type in [
                MessageType.MESSAGE_TYPE_AUDIO,
                MessageType.MESSAGE_TYPE_ATTACHMENT,
                MessageType.MESSAGE_TYPE_VIDEO
        ]:
            logger.info('receving file ...')
            file_box = await msg.to_file_box()
            if file_box:
                await file_box.to_file(file_box.name)

        elif msg_type == MessageType.MESSAGE_TYPE_MINI_PROGRAM:
            logger.info('receving mini-program ...')
            mini_program: Optional[MiniProgram] = await msg.to_mini_program()
            if mini_program:
                await msg.say(mini_program)

        elif text == 'get room members' and room:
            logger.info('get room members ...')
            room_members: List[Contact] = await room.member_list()
            names: List[str] = [
                room_member.name for room_member in room_members
            ]
            await msg.say('\n'.join(names))

        elif text.startswith('remove room member:'):
            logger.info('remove room member:')
            if not room:
                await msg.say('this is not room zone')
                return

            room_member_name = text[len('remove room member:') + 1:]

            room_member: Optional[Contact] = await room.member(
                query=RoomMemberQueryFilter(name=room_member_name))
            if room_member:
                if self.login_user and self.login_user.contact_id in room.payload.admin_ids:
                    await room.delete(room_member)
                else:
                    await msg.say('登录用户不是该群管理员...')

            else:
                await msg.say(
                    f'can not fine room member by name<{room_member_name}>')
        elif text.startswith('get room topic'):
            logger.info('get room topic')
            if room:
                topic: Optional[str] = await room.topic()
                if topic:
                    await msg.say(topic)

        elif text.startswith('rename room topic:'):
            logger.info('rename room topic ...')
            if room:
                new_topic = text[len('rename room topic:') + 1:]
                await msg.say(new_topic)
        elif text.startswith('add new friend:'):
            logger.info('add new friendship ...')
            identity_info = text[len('add new friend:') + 1:]
            weixin_contact: Optional[Contact] = await self.Friendship.search(
                weixin=identity_info)
            phone_contact: Optional[Contact] = await self.Friendship.search(
                phone=identity_info)
            contact: Optional[Contact] = weixin_contact or phone_contact
            if contact:
                self.Friendship.add(contact, 'hello world ...')

        elif text.startswith('at me'):
            await msg.say(self.login_user)

        else:
            pass
Exemplo n.º 8
0
async def on_message(msg: Message):
    if msg.text() == 'ding':
        await msg.say('这是自动回复: dong dong dong')

    if msg.text() == '小队长':
        await msg.say('我好想你的!!快点好起来,上班来看我!!')

    if msg.text() == '小仙女':
        await msg.say('宇宙超级无敌可爱美丽的人,303之光!')

    if msg.text() == '小余':
        await msg.say('一直想要骗我钱的女人!但是我还是很爱她!')

    if msg.text() == 'hi' or msg.text() == '你好':
        await msg.say(
            '这是自动回复: 机器人目前的功能是\n- 收到"ding", 自动回复"dong dong dong"\n- 收到"图片", 自动回复一张图片\n- 还会把图片变成漫画样子,不过这个案例是参考细菌的\n- 收到"藏头诗:我是菜鸟",自动以"我是菜鸟"作藏头诗一首,当然也可以输入其他的4个字作诗'
        )

    if msg.text().startswith('藏头诗'):
        #await msg.say('请输入4个字作为藏头诗的头')
        test_texts = [msg.text()[-4:]]
        results = module.generate(texts=test_texts, use_gpu=True, beam_width=5)
        #for result in results:
        await msg.say(results[0][0])

    if msg.text() == '图片':
        url = 'http://qrul2d5a1.hn-bkt.clouddn.com/image/street.jpg'
        file_box_12 = FileBox.from_url(url=url, name='xx.jpg')

        await msg.say(file_box_12)

    if msg.text() == '周深':
        url = 'https://z3.ax1x.com/2021/04/27/gC0EtA.jpg'
        file_box_11 = FileBox.from_url(url=url, name='xx.jpg')

        await msg.say(file_box_11)

    if msg.text() == '费玉清' or msg.text() == '小哥':
        url = 'https://z3.ax1x.com/2021/04/27/gCBeUJ.jpg'

        # 构建一个FileBox
        file_box_1 = FileBox.from_url(url=url, name='xx.jpg')

        await msg.say(file_box_1)
    # 如果收到的message是一张图片
    if msg.type() == Message.Type.MESSAGE_TYPE_IMAGE:

        # 将Message转换为FileBox
        file_box_2 = await msg.to_file_box()

        # 获取图片名
        img_name = file_box_2.name

        # 图片保存的路径
        img_path = './image/' + img_name

        # 将图片保存为本地文件
        await file_box_2.to_file(file_path=img_path)

        # 调用图片风格转换的函数
        img_new_path = img_transform(img_path, img_name)
        img_new_path1 = img_transform1(img_path, img_name)

        # 从新的路径获取图片
        file_box_3 = FileBox.from_file(img_new_path)
        file_box_4 = FileBox.from_file(img_new_path1)
        await msg.say(file_box_4)