Esempio n. 1
0
 async def on_message(self, msg: Message):
     """listen message event"""
     self_contact = await self.my_self()
     from_contact = msg.talker()
     log.info('below are dict of message: ')
     log.info(str(msg.__dict__))
     quoted, text, mention = split_quote_and_mention(msg.text())
     log.info('finish spliting')
     log.info(f'quoted: {quoted}, text: {text}, mention: {mention}')
     room = msg.room()
     to_bot = self_contact.get_id() in msg.payload.mention_ids or\
              self_contact.get_id() == msg.payload.to_id or\
              self_contact.payload.name == mention
     conversation: Union[
         Room, Contact] = from_contact if room is None else room
     await conversation.ready()
     log.info(f'finish preprocess, talker: {from_contact.get_id()}, to_bot: {to_bot}')
     try:
         if self.tag_controller.handle_msg(quoted, text, from_contact.get_id(), to_bot):
             log.info('tag controller found reply')
             await conversation.say(self.tag_controller.get_reply())
         elif self.question_answering.handle_msg(text, to_bot):
             log.info('question answering found reply')
             await conversation.say(self.question_answering.get_reply())
         elif self.display.handle_msg(text, to_bot):
             log.info('display found reply')
             await conversation.say(self.display.get_reply())
     except Exception as error:
         log.info(f'something went wrong for tagging plugin: {error}')
Esempio n. 2
0
    async def on_message(self, msg: Message):
        """listen message event"""
        from_contact = msg.talker()
        text = msg.text()
        room = msg.room()

        if room is None:
            return

        if text in ['#ding', 'dong']:
            if room.room_id not in self.room_data:
                self.room_data[room.room_id] = {'__status__': 'running'}
                await self.re_init_job(room.room_id)
        if text == '#ding':
            self.room_data[room.room_id]['__ding__'] = True

        if text == '#ding start':
            self.room_data[room.room_id] = {'__status__': 'running'}
            await room.say('#ding')
            await self.re_init_job(room.room_id)

        if text == 'dong':
            if room.room_id in self.room_data:
                self.room_data[room.room_id][from_contact.contact_id] = {
                    'id': from_contact.contact_id,
                    'time': datetime.now(),
                    'name': from_contact.name,
                }
                # refresh the scheduler job
                await self.re_init_job(room.room_id)
    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 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
Esempio n. 5
0
    async def on_message(self, msg: Message):
        """listen message event"""
        self_contact = await self.my_self()
        from_contact = msg.talker()
        quoted, text, mention = split_quote_and_mention(msg.text())
        room = msg.room()
        to_bot = self_contact.get_id() in msg.payload.mention_ids or\
                 self_contact.get_id() == msg.payload.to_id or\
                 self_contact.payload.name == mention
        conversation: Union[Room,
                            Contact] = from_contact if room is None else room
        await conversation.ready()

        if isinstance(conversation, Contact):
            if not to_bot:
                return
            if self.language == 'zh':
                # await conversation.say('成员管理功能必须在群聊中使用')
                pass
            else:
                await conversation.say('Not work if not in chat room')
            return
        member_count = len(await conversation.member_list())
        # real people >= 4, 3 thumbsdown needed, 3 => 2, 2 => 1
        counts_limit = 3 if member_count > 4 else member_count // 2
        if text.strip() == self.thumbsdown:
            time_delta = datetime.now() - self.date[mention]
            if self.counts[mention] != 0 and time_delta > timedelta(hours=12):
                self.counts[mention] = 0  # former thumbsdown expired
            self.counts[mention] = self.counts[mention] + 1
            self.date[mention] = datetime.now()

            if self.language == 'zh':
                await conversation.say(
                    f'成员{mention}目前已经被踩{self.counts[mention]}次,'
                    f'被踩{counts_limit}次的成员将被移出群聊')
            else:
                await conversation.say(
                    f'thumbsdown of {mention} is currently {self.counts[mention]}, '
                    f'member with thumbsdown to {counts_limit} '
                    'will be removed from chat')
            if self.counts[mention] >= counts_limit:
                removed_contact = Contact.load(msg.payload.mention_ids[0])
                await removed_contact.ready()
                await conversation.delete(removed_contact)

                if self.language == 'zh':
                    await conversation.say(f'{removed_contact.name}已被移出群聊')
                else:
                    await conversation.say(
                        f'{removed_contact.name} is removed from chat')
        print(msg.__dict__)
 async def on_message(self, msg: Message):
     """listen message event"""
     from_contact = msg.talker()
     text = msg.text()
     room = msg.room()
     if text == '#ding':
         conversation: Union[
             Room, Contact] = from_contact if room is None else room
         conversation_id = from_contact.contact_id if room is None \
             else room.room_id
         if self.can_send_dong(conversation_id):
             await conversation.ready()
             await conversation.say('dong')
 async def on_message(self, msg: Message):
     """listen message event"""
     from_contact = msg.talker()
     text = msg.text()
     room = msg.room()
     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)
 async def on_message(self, msg: Message):
     """listen message event"""
     from_contact = msg.talker()
     text = msg.text()
     room = msg.room()
     if text == '今天天气如何':
         conversation: Union[
             Room, Contact] = from_contact if room is None else room
         await conversation.ready()
         response = requests.get('https://tianqiapi.com/api?version=v61&'
                                 'appid=32896971&appsecret=5bR8Gs9x')
         result = response.json()
         result_msg = f'今天{result["wea"]} 最低温度{result["tem2"]}度 ' \
                      f'最高温度{result["tem1"]}度'
         await conversation.say(result_msg)
    async def on_message(self, msg: Message):
        """check the keyword and reply to talker"""

        conversation: Union[
            Room, Contact] = msg.room() if msg.room() else msg.talker()
        await conversation.ready()

        text = msg.text()

        # find the match rules
        for matcher, rules in self.rule_map.items():
            is_match = await matcher.match(conversation)

            if is_match:
                for rule in rules:
                    if rule.keyword == text:
                        await conversation.say(rule.reply_content)
Esempio n. 10
0
 async def on_message(self, msg: Message):
     """listen message event"""
     self_contact = await self.my_self()
     from_contact = msg.talker()
     quoted, text, mention = split_quote_and_mention(msg.text())
     room = msg.room()
     to_bot = self_contact.get_id() in msg.payload.mention_ids or\
              self_contact.get_id() == msg.payload.to_id or\
              self_contact.payload.name == mention
     conversation: Union[Room,
                         Contact] = from_contact if room is None else room
     await conversation.ready()
     try:
         if self.help.handle_msg(text, to_bot):
             log.info('help system found reply')
             await conversation.say(self.help.get_reply())
     except Exception as error:
         log.info(f'something went wrong for help system plugin: {error}')
async def calculatespeak(msg: Message, from_contact: Contact, room: Room, collection):
    print("对用户发出信息进行对应操作")
    if room == None:
        return
    find_res = find(collection=collection, id=from_contact.contact_id)
    update(collection, from_contact.contact_id, "speak_num", find_res["speak_num"] + 1)

    if msg.message_type() == MessageType.MESSAGE_TYPE_IMAGE:
        update(collection, from_contact.contact_id, "imgs_num", find_res["imgs_num"] + 1)
Esempio n. 12
0
 async def on_message(self, msg: Message):
     user = msg.talker()
     text = msg.text()
     if Judge.is_ask_self_weight(text):
         msg_ = await Search.search_weight(user)
         await msg.say(msg_)
     if Judge.is_ask_self_login(text):
         user = await Search.create_self(user)
         if user:
             await msg.say('成功,欢迎🥳{}'.format(user.name))
     if Judge.is_ask_tag_weight(text):
         text = text.replace(':', ':')
         text = text.split(':')
         msg_ = await Search.update_weight(user, tag_weight=float(text[-1]))
         await msg.say(msg_)
     if Judge.is_ask_present_weight(text):
         text = text.replace(':', ':')
         text = text.split(':')
         msg_ = await Search.update_weight(user,
                                           present_weight=float(text[-1]))
         await msg.say(msg_)
     if Judge.is_ask_me(text):
         await msg.say('我在')
     if Judge.is_ask_weather(text):
         text = text.replace("天气", '')
         URL2 = 'https://geoapi.qweather.com/v2/city/lookup?location={}&key=86bae3f81a9c4af9ae7187b23250dffc'.format(
             text)
         resp = requests.get(URL2)
         city = resp.json()
         if int(city.get('code', 0)) != 200:
             await msg.say('找不到这个城市')
         else:
             url = 'https://devapi.qweather.com/v7/weather/now?location={}&key=86bae3f81a9c4af9ae7187b23250dffc'.format(
                 city.get('location', [])[0].get('id'))
             resp = requests.get(url)
             weather = resp.json()
             if int(weather.get('code', 0)) != 200:
                 await msg.say('搜索不到该气温')
             else:
                 msg_ = '{}\n🍁天气:{}\n🍁当前温度为:{}摄氏度\n🍁体感温度为:{}摄氏度'.format(
                     text, weather['now']['text'], weather['now']['temp'],
                     weather['now']['feelsLike'])
                 await msg.say(msg_)
Esempio n. 13
0
async def on_message(msg: Message):

    who = msg.talker()  # 发消息的人

    #设置好微信名,只要是他发的消息就回复
    if who.name == 'TTZO':
        #输入,翻译,模型输出,翻译,发送
        tf = fanyi(text, 'zh-CHS2en')
        robott = module.generate(list(tf))
        returns = fanyi(robott[0], 'en2zh-CHS')
        await msg.say(returns)
Esempio n. 14
0
async def on_message(msg: Message):
    """
    Message Handler for the Bot
    """
    if msg.text() == 'ding':
        await msg.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 msg.say(file_box)
Esempio n. 15
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(
                 '不好意思,暂时处理不了图片类型消息,我们已经在催程序员小哥哥日夜加班优化项目了!希望您能够理解!')
Esempio n. 16
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):
        """check the keyword and reply to talker"""

        # don't listen in room
        if msg.room():
            return

        talker = msg.talker()

        for message_matcher, rules in self.rules.items():
            is_match = await message_matcher.match(msg)

            if is_match:
                # cache the rooms data
                rooms = []
                for rule in rules:
                    # pytype: disable=attribute-error
                    matched_rooms = await rule.find_rooms(self.bot)
                    rooms.extend(matched_rooms)

                # invite person to the room
                for room in rooms:
                    self.welcome_ids[room.room_id].append(talker.contact_id)
                    await room.add(talker)
Esempio n. 18
0
 async def on_message(self, msg: Message):
     if msg.age() > 3 * 60:
         log.info(
             'Bot' + 'on(message) skip age("%d") > 3 * 60 seconds: "%s"',
             msg.age(), msg)
         return
     room = msg.room()
     talker = msg.talker()
     text = msg.text()
     if not talker:
         return
     if msg.is_self():
         return
     if re.search('^ding$', text):
         if room:
             if re.search('^ding', await room.topic()):
                 await get_out_room(talker, room)
         else:
             try:
                 dingRoom = await self.Room.find('^ding')
                 if dingRoom:
                     log.info('Bot' + 'onMessage: got dingRoom: "%s"' %
                              await dingRoom.topic())
                     if await dingRoom.has(talker):
                         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 talker.say(
                             'no need to ding again, because you are already in room: "{}"'
                             .format(topic))
                     else:
                         log.info(
                             'Bot' +
                             'onMessage: add sender("%s") to dingRoom("%s")'
                             % (talker.name, dingRoom.topic()))
                         await talker.say('ok, I will put you in ding room!'
                                          )
                         await put_in_room(talker, dingRoom)
                 else:
                     log.info(
                         'Bot' +
                         'onMessage: dingRoom not found, try to create one')
                     newRoom = await create_ding_room(self, talker)
                     print('create_ding_room id:', newRoom.id)
                     await manage_ding_room(self)
             except Exception as e:
                 log.exception(e)
async def regex_filter(msg: Message, from_contact: Contact):
    '''
    正则匹配模块:
    1. 匹配`淘口令`
    2. 匹配`加QQ`类广告
    3. 匹配`加微信`类广告
    4. 匹配`身份证号码`
    5. 匹配`身份证/密码`得敏感词汇
    6. 匹配`汇款`等敏感语句

    '''
    regex = [r'([\p{Sc}])\w{8,12}([\p{Sc}])',
             r'(?:[加qQ企鹅号码\s]{2,}|[群号]{1,})(?:[\u4e00-\u9eff]*)(?:[:,:]?)([\d\s]{6,})',
             r'(?:[加+微++➕薇?vV威卫星♥❤姓xX信]{2,}|weixin|weix)(?:[,❤️.\s]?)(?:[\u4e00-\u9eff]?)(?:[:,:]?)([\w\s]{6,})',
             r'(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)',
             r'身份证号码|(?i)(银行卡|账号|QQ)密码',
             r'(微信|支付宝|银行|账户|银行卡|卡)+[\s\S]*([打钱]|[转账]|[汇款])+[\s\S]*[0-9]*'
             ]

    # print("enter regex")
    reply = ['识别为淘口令',
             '请不要在群内发QQ广告' + f'@{from_contact.name}',
             '请不要在群内发wx广告' + f'@{from_contact.name}',
             '请保护好个人敏感信息' + f'@{from_contact.name}',
             '请保护好个人敏感信息',
             '⚠️谨防受骗⚠️'
             ]

    flag = 0
    for i in range(len(regex)):
        r = re.compile(regex[i])
        if re.search(r, msg.text()):
            await msg.say(reply[i])
            flag = 1
            print("1")
        else:
            continue

    if flag == 0:
        print("正则匹配没毛病")
    return flag
async def dict_filter(msg: Message, from_contact:Contact):
    file_name = ["./data/政治.txt",
                 "./data/色情.txt",
                 "./data/广告.txt",
                 "./data/敏感词.txt",
                 "./data/暴恐.txt"]
    warning = ["不当政治言论", "色情信息", "广告", "敏感信息", "暴力恐怖"]
    words = jieba.cut(msg.text(), cut_all = False)
    words = list(words)
    words = np.array(words)
    tag = 0     #记录有无违规信息
    temp = 0

    atrocious_list = []

    for k in file_name:
        flag = 0 #针对每一种具体类别记录有无违规信息
        with open(k, 'r', encoding='utf-8') as fr:
            frrd = np.array(fr.readlines())
            for i in frrd:
                i = i.strip()
                for j in words:
                    if i == j:
                        flag = 1
                        tag = 1
        if flag:
            print("内容包含" + warning[temp])
            atrocious_list.append(warning[temp])
        temp = temp + 1

    if tag == 0:
        print("字典检测没毛病")
    else:
        await msg.say(f"亲爱的用户@{from_contact.name},即便不在群中也不能违规,你的言语违规,进行一次警告")
        admolish_sentence = "你触犯了:"
        for i in atrocious_list:
            admolish_sentence += i + ','
        await msg.say(admolish_sentence)

    return tag
Esempio n. 21
0
    async def on_message(self, msg: Message):
        if msg.age() > 3 * 60:
            log.info(
                'Bot' + 'on(message) skip age("%d") > 3 * 60 seconds: "%s"',
                msg.age(), msg)
            return
        room = msg.room()
        talker = msg.talker()
        text = msg.text()
        if not talker:
            return
        if msg.is_self():
            return

        if re.search('^market$', text):
            if room:
                if re.search(TOPIC_NAME, await room.topic()):
                    await get_out_room(talker, room)
            else:
                try:
                    marketRoom = await self.Room.find(TOPIC_NAME)
                    if marketRoom:
                        log.info('Bot' + 'onMessage: got marketRoom: "%s"' %
                                 await marketRoom.topic())
                        if await marketRoom.has(talker):
                            topic = await marketRoom.topic()
                            log.info(
                                'Bot' +
                                'onMessage: sender has already in marketRoom')
                            await talker.say("已加入群组{}".format(topic))
                        else:
                            log.info(
                                'Bot' +
                                'onMessage: add sender("%s") to marketRoom("%s")'
                                % (talker.name, marketRoom.topic()))
                            await talker.say("邀请加入群组")
                            await put_in_room(talker, marketRoom)
                    else:
                        log.info(
                            'Bot' +
                            'onMessage: marketRoom not found, try to create one'
                        )
                        await create_market_room(self, talker)
                        await manage_market_room(self)
                except Exception as e:
                    log.exception(e)
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("记录失败")
Esempio n. 23
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
Esempio n. 24
0
async def on_message(msg: Message):
    if msg.text() == 'ding':
        await msg.say('dong')
    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
Esempio n. 26
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)
Esempio n. 27
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)
Esempio n. 28
0
    async def on_message(self, msg: Message):

        # 加载消息发送者
        talker = msg.talker()
        await talker.ready()

        # 忽略自己发的消息
        if talker.contact_id == self.my_contact_id:
            return

        # 加载聊天室信息
        room = msg.room()
        room_topic = None
        if room:
            await room.ready()
            room_topic = await room.topic()

        # 基本信息
        msg_text = msg.text()
        msg_text_inline = msg.text().replace('\n', '')
        msg_type = msg.message_type()
        msg_id = msg.message_id
        if msg_type == 6:
            log.info('Received text, msg_type = {}, id = {}'.format(
                msg_type, msg_id))
        else:
            log.info('Received text = {}, msg_type = {}, id = {}'.format(
                msg_text, msg_type, msg_id))

        # 保存聊天记录
        insert_data = {
            'contact_id': talker.contact_id,
            'contact_name': talker.name,
            'room_id': room.room_id if room else None,
            'room_name': room_topic,
            'msg_id': msg_id,
            'msg_text': msg_text[:20],
            'created_at': datetime.now()
        }
        keys = ','.join(['`{}`'.format(str(v)) for v in insert_data.keys()])
        values = ','.join(
            ['\'{}\''.format(str(v)) for v in insert_data.values()])
        sql = 'INSERT INTO {table}({keys}) VALUES({values})'.format(
            table='msg_records', keys=keys, values=values)
        try:
            self.db.cursor.execute(sql)
            self.db.db.commit()
        except Exception as e:
            log.error(e)
            self.db.db.rollback()

        # 鉴定是否为广告
        if room and not re.match(r'.*(kda|kadena|可达).*',
                                 msg_text_inline.lower()):
            is_ad = False
            if msg_type == 4:
                pass
            elif msg_type == 5:
                # 识别是否有二维码
                img = await msg.to_file_box()
                log.info('get img {}'.format(img.name))
                img_path = './images/{}'.format(img.name)
                img_file = await img.to_file(img_path)
                log.info('get img stored')
                img = cv2.imread(img_path)
                data, bbox, straight_qrcode = self.detector.detectAndDecode(
                    img)
                log.info('qrcode results: {}, {}, {}'.format(
                    data, bbox, straight_qrcode))
                if bbox is not None:
                    log.info('ad detected qr_code')
                    is_ad = True
                os.remove(img_path)
            elif msg_type == 6:
                if len(msg_text) >= 50 and re.match(
                        r'.*(http|空投|撸).*',
                        msg_text) and not re.match(r'.*bihu\.com.*', msg_text):
                    log.info('ad detected text')
                    is_ad = True

            if is_ad:
                sql = """SELECT count(*) as msg_cnt FROM {} where contact_id = '{}'""".format(
                    'msg_records', talker.contact_id)
                self.db.cursor.execute(sql)
                if list(self.db.cursor.fetchall())[0]['msg_cnt'] < 10:
                    q_list = list(self.ad_qa_dict.keys())
                    question = q_list[random.randrange(0, len(q_list))]
                    threading.Thread(target=self.kick_member,
                                     args=(talker, room, question)).start()
                    reply = '@{}\n你有打广告的嫌疑哦,请在15秒内回答以下问题,否则给你抱出去~~~\n{}'.format(
                        talker.name, question)
                    await room.say(reply, mention_ids=[talker.contact_id])
                    return

        # GOD的指令
        if talker.contact_id == self.god_contact_id and 'c/' in msg_text:
            if 'c/new' in msg_text:
                if '上一条' in msg_text:
                    sql = """SELECT msg_id FROM {} where contact_id = '{}' order by created_at desc""".format(
                        'msg_records', self.god_contact_id)
                    self.db.cursor.execute(sql)
                    refer_msg_id = list(self.db.cursor.fetchall())[1]['msg_id']
                    title = msg_text
                else:
                    root = ET.fromstring(msg_text)
                    refer_msg_id = root.find('.//refermsg//svrid').text
                    title = root.find('.//title').text
                keyword = re.findall('#.+#', title)[0].replace('#', '')
                log.info('title = {}, keyword = {}'.format(title, keyword))
                insert_data = {
                    'keyword': keyword,
                    'msg_id': refer_msg_id,
                    'created_at': datetime.now()
                }
                keys = ','.join(
                    ['`{}`'.format(str(v)) for v in insert_data.keys()])
                values = ','.join(
                    ['\'{}\''.format(str(v)) for v in insert_data.values()])
                sql = 'INSERT INTO {table}({keys}) VALUES({values})'.format(
                    table='materials', keys=keys, values=values)
                try:
                    self.db.cursor.execute(sql)
                    self.db.db.commit()
                    log.info('INSERT succesfully: {}'.format(sql))
                except Exception as e:
                    log.error(e)
                    self.db.db.rollback()

                reply = '指令已储存,关键词:{}'.format(keyword)
                await msg.say(reply)

            elif 'c/list' in msg_text:
                sql = """SELECT keyword FROM {} group by keyword""".format(
                    'materials')
                self.db.cursor.execute(sql)
                reply = '现有指令'
                for row in self.db.cursor.fetchall():
                    reply += '\n' + row['keyword']

                await msg.say(reply)

            elif 'c/show' in msg_text:
                keyword = re.findall('#.+#', msg_text)[0].replace('#', '')
                await self.send_msg_with_keyword(keyword,
                                                 contact=talker,
                                                 room=room)

            elif 'c/active' in msg_text:
                today = datetime.now()
                start_dt = datetime(today.year, today.month, today.day)
                sql = """SELECT contact_id, count(*) as msg_cnt
                        FROM {} where room_id = '{}' and created_at >= '{}'
                        group by contact_id""".format('msg_records',
                                                      room.room_id, start_dt)
                self.db.cursor.execute(sql)
                records = [
                    row['contact_id'] for row in self.db.cursor.fetchall()
                ]
                member_list = await room.member_list()
                reply = '今日群内未发言成员:'
                for member in member_list:
                    if member.contact_id != self.my_contact_id and member.contact_id not in records:
                        reply += '\n' + member.name

                topic = await room.topic()
                if '星火' in topic:
                    reply += '\n如果没法保持每天活跃,会被移出此群哦~'
                await msg.say(reply)

            elif 'c/fixroomname' in msg_text:
                log.info('to fix room name')
                sql = """SELECT * FROM {} WHERE room_id is not null and room_name = ''""".format(
                    'msg_records')
                self.db.cursor.execute(sql)
                for row in self.db.cursor.fetchall():
                    to_fix_room = self.Room(room_id=row['room_id'])
                    await to_fix_room.ready()
                    to_fix_room_name = await to_fix_room.topic()

                    sql = """UPDATE {} SET room_name = '{}' where id = {}""".format(
                        'msg_records', to_fix_room_name, row['id'])
                    try:
                        self.db.cursor.execute(sql)
                        self.db.db.commit()
                        log.info('update succesfully: {}'.format(sql))
                    except Exception as e:
                        log.error(e)
                        self.db.db.rollback()

                log.info('finished')

            elif 'c/kdashill_to_tg' in msg_text:
                log.info('to send telegram')
                sql = """SELECT * FROM {} WHERE has_sent_tg is null""".format(
                    'kdashill_records')
                self.db.cursor.execute(sql)
                for row in self.db.cursor.fetchall():
                    url = 'https://m.bihu.com/shortcontent/{}'.format(
                        row['content_id'])
                    data = None
                    with concurrent.futures.ThreadPoolExecutor() as executor:
                        future = executor.submit(self.telegram.send_msg, url)
                        data = future.result()

                    log.info('get res: {}'.format(data))
                    if data:
                        sql = """UPDATE {} SET has_sent_tg = {} where content_id = '{}'""".format(
                            'kdashill_records', 1, row['content_id'])
                        try:
                            self.db.cursor.execute(sql)
                            self.db.db.commit()
                            log.info('update succesfully: {}'.format(sql))
                        except Exception as e:
                            log.error(e)
                        self.db.db.rollback()

                    time.sleep(1)
                    break

            return

        # 推荐活动
        if room and re.match(r'.*[bihu|chainnode]\.com.*', msg_text_inline):
            content_id = None
            match_results = re.search(r'(?<=bihu\.com/s/)[0-9A-Za-z]{1,}',
                                      msg_text)
            if match_results:
                key = match_results[0]
                x = 0
                for y in key:
                    k = digit62.find(y)
                    if k >= 0:
                        x = x * 62 + k
                content_id = str(x)
                platform = 'bihu'
                log.info('transfer {} to {}'.format(key, content_id))
            elif 'bihu' in msg_text:
                match_results = re.search(
                    r'(?<=bihu\.com/shortcontent/)\d{1,}',
                    msg_text_inline.lower())
                content_id = match_results[0]
                platform = 'bihu'
            elif 'chainnode' in msg_text:
                match_results = re.search(r'(?<=chainnode\.com/post/)\d{1,}',
                                          msg_text_inline.lower())
                content_id = match_results[0]
                platform = 'chainnode'
            else:
                log.info('not find pattern')

            if content_id:
                log.info('get content id = {}'.format(content_id))
                data = None
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    if platform == 'bihu':
                        future = executor.submit(self.crawler.fetch_bihu,
                                                 content_id)
                    else:
                        future = executor.submit(self.crawler.fetch_chainnode,
                                                 content_id)
                    data = future.result()

                log.info('fetched data = {}'.format(data))
                if data:
                    content_inline = data['content'].replace('\n', '')
                    post_date = data['post_date']
                    if not re.match(r'.*(kda|kadena|可达).*',
                                    content_inline.lower()):
                        reply = '未发现Kadena相关信息哦~'
                        reply = reply + ' @{}'.format(talker.name)
                        await room.say(reply, mention_ids=[talker.contact_id])
                        return
                    elif post_date < datetime(
                            2021, 3, 26) or post_date >= datetime(2021, 4, 2):
                        reply = '文章发布时间不在活动范围内,不能算入哦~'
                        reply = reply + ' @{}'.format(talker.name)
                        await room.say(reply, mention_ids=[talker.contact_id])
                        return

                    # 展示
                    sql = """SELECT * FROM {} where phase = 1 and platform = '{}' and content_id = '{}'""".format(
                        'kdashill_records', platform, content_id)
                    self.db.cursor.execute(sql)
                    results = list(self.db.cursor.fetchall())
                    if len(results):
                        # 处理重复
                        is_duplicate = True
                        ww_id = results[0]['id']
                        from_room = self.Room(room_id=results[0]['room_id'])
                        await from_room.ready()
                        from_room_name = await from_room.topic()
                        room_name_str = '「{}」\n'.format(
                            from_room_name.replace('Kadena', ''))
                        from_contact = self.Contact(
                            contact_id=results[0]['contact_id'])
                        await from_contact.ready()
                        from_contact_name = from_contact.name
                    else:
                        is_duplicate = False
                        sql = """SELECT max(id) as max_id FROM {} """.format(
                            'kdashill_records')
                        self.db.cursor.execute(sql)
                        max_id = list(self.db.cursor.fetchall())[0]['max_id']
                        ww_id = max_id + 1
                        room_name_str = '「{}」\n'.format(
                            room_topic.replace('Kadena', ''))
                        from_contact_name = talker.name

                    reply_title = '可达秀.{:02} @ {}'.format(
                        ww_id, from_contact_name)
                    if platform == 'bihu':
                        reply_url = 'https://m.bihu.com/shortcontent/{}'.format(
                            content_id)
                        score = 1
                        if 'img_url' in data:
                            prefix = 'https://oss-cdn1.bihu-static.com/'
                            reply_thumbnail = prefix + data['img_url']
                        else:
                            reply_thumbnail = 'https://m.bihu.com/static/img/pic300.jpg'
                    else:
                        score = 2
                        reply_url = 'https://www.chainnode.com/post/{}'.format(
                            content_id)
                        if 'img_url' in data:
                            reply_thumbnail = data['img_url']
                        else:
                            reply_thumbnail = 'https://webcdn.chainnode.com/mobile-1.3.15/img/ChainNode.4e5601a.svg'
                    reply_description = room_name_str + data['content'][:60]
                    log.info('to create url_link: {},{},{},{}'.format(
                        reply_url, reply_title, reply_thumbnail,
                        reply_description))
                    reply_link = UrlLink.create(reply_url, reply_title,
                                                reply_thumbnail,
                                                reply_description)
                    log.info('url created')

                    # 查重
                    if is_duplicate:
                        reply = '文章已有录入哦~'
                        reply = reply + ' @{}'.format(talker.name)
                        await room.say(reply, mention_ids=[talker.contact_id])

                        return

                    # 记分
                    insert_data = {
                        'phase': 2,
                        'platform': platform,
                        'content_id': content_id,
                        'contact_id': talker.contact_id,
                        'contact_name': talker.name,
                        'room_id': room.room_id,
                        'created_at': datetime.now(),
                        'score': score,
                    }
                    keys = ','.join(
                        ['`{}`'.format(str(v)) for v in insert_data.keys()])
                    values = ','.join([
                        '\'{}\''.format(str(v)) for v in insert_data.values()
                    ])
                    sql = 'INSERT INTO {table}({keys}) VALUES({values})'.format(
                        table='kdashill_records', keys=keys, values=values)
                    try:
                        self.db.cursor.execute(sql)
                        self.db.db.commit()
                        log.info('INSERT succesfully: {}'.format(sql))
                    except Exception as e:
                        log.error(e)
                        self.db.db.rollback()

                    # 报积分
                    sql = """SELECT contact_id, sum(score) as score FROM {} where phase = 2 group by contact_id order by score desc""".format(
                        'kdashill_records')
                    self.db.cursor.execute(sql)
                    rank = 0
                    for row in self.db.cursor.fetchall():
                        rank += 1
                        if row['contact_id'] == talker.contact_id:
                            reply = '感谢参加可达秀 [KDA-Show] 活动!🍻\n'
                            reply += '您当前积分为{},排名为{}'.format(
                                row['score'], rank)
                            break

                    reply = reply + ' @{}'.format(talker.name)
                    await room.say(reply, mention_ids=[talker.contact_id])

                    # 发送至其他群
                    sql = """SELECT room_id, max(room_name) as room_name FROM {} group by room_id""".format(
                        'msg_records')
                    self.db.cursor.execute(sql)
                    for row in self.db.cursor.fetchall():
                        if '可达社区信息流' in row['room_name']:
                            forward_room = self.Room(room_id=row['room_id'])
                            await forward_room.ready()
                            try:
                                await forward_room.say(reply_link)
                            except Exception as e:
                                log.exception(e)

                    # 发送至Telegram
                    #threading.Thread(target=self.telegram.send_msg, args=(reply_url)).start()

                    return

                else:
                    reply = '未查到相关网页'
                    reply = reply + ' @{}'.format(talker.name)
                    await room.say(reply, mention_ids=[talker.contact_id])
                    return

        # 关键词回复
        if re.match(r'(资料|学习|学习资料|新人)', msg_text_inline):
            await self.send_msg_with_keyword('新手指南', contact=talker, room=room)
            return

        coin_dict = {
            'kda': 'kadena',
            'btc': 'bitcoin',
            'eth': 'ethereum',
            'dot': 'polkadot',
            'link': 'chainlink',
            'atom': 'cosmos',
            'mkr': 'maker',
            'luna': 'terra-luna',
            'celo': 'celo',
        }
        if room and msg_text.lower() in coin_dict:
            name = msg_text.lower()
            full_name = coin_dict[name]
            url = 'https://api.coingecko.com/api/v3/coins/{}/market_chart?vs_currency=usd&days=30&interval=daily'.format(
                full_name)
            data = requests.get(url).json()
            log.info('get chart, response: {}'.format(data))
            url = 'http://*****:*****@{}'.format(self.my_contact_name)
                              in msg_text):
            data = {'msg': msg_text, 'appid': '0', 'key': 'free'}
            url = 'http://api.qingyunke.com/api.php'
            res = requests.get(url, params=data)
            log.info('get AI request: {}, {}, response: {}'.format(
                url, data, res.text))
            data = res.json()
            reply = data['content'].replace('{br}', '\n')
            reply = reply + ' @{}'.format(talker.name)
            if room:
                await room.say(reply, mention_ids=[talker.contact_id])
            else:
                await msg.say(reply)