Exemplo n.º 1
0
 async def on_message(self, msg: Message):
     """
     listen for message event
     """
     from_contact = msg.talker()
     text = msg.text()
     room = msg.room()
     to = msg.to()
     if room is None and to.contact_id == self.contact_id:
         # say msg to the bot
         if text == '#status':
             msg = 'busy' if self.busy else 'free'
             await from_contact.say(
                 f'My status: {msg}')
             await from_contact.say(self.auto_reply_comment)
         elif text == '#free':
             await from_contact.say('auto reply stopped.')
         elif text == '#busy':
             self.busy= True
             await from_contact.say('auto reply enabled')
         else:
             await from_contact.say(self.auto_reply_comment)
    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