Exemplo n.º 1
0
async def _(session: NLPSession):
    unit_dict = {'秒': 1, '分钟': 60, '分': 60, '小时': 3600}

    pattern = re.compile(r'^(.*)(秒|分钟|分|小时)后提醒我(.*)$')

    todo_something = pattern.match(session.msg_text)

    if todo_something:
        o_time = todo_something.group(1)
        unit = todo_something.group(2)
        something = todo_something.group(3)

        try:
            lt = int(o_time)
        except ValueError:
            try:
                lt = cn2an.cn2an(o_time)
            except ValueError:
                return IntentCommand(75.0, ('todo', 'cancel'),
                                     args={'error': '时间设定错误'})

        unit_time = unit_dict.get(unit)
        if unit_time:
            scheduler_time = unit_time * lt
            return IntentCommand(75.0, ('todo', 'add'),
                                 args={
                                     'seconds': scheduler_time,
                                     'something': something,
                                     'o_time': o_time + unit + '后'
                                 })
Exemplo n.º 2
0
async def _(session: NLPSession):
    # 去掉消息首尾的空白符
    stripped_msg = session.msg_text.strip()
    word_list, _ = await word_cut(stripped_msg)

    location = ""
    for word in word_list:
        if await verifying_city(word):
            location = word
            break

    target_time = []
    if "今天" in word_list:
        target_time.append("今天")
    if "明天" in word_list:
        target_time.append("明天")
    if not target_time:
        target_time.append("接下来五天")

    if location == '':
        return IntentCommand(80.0,
                             name='查天气',
                             args={'target_time': target_time})
    else:
        return IntentCommand(80.0,
                             name='查天气',
                             args={'target_time': target_time},
                             current_arg=location)
Exemplo n.º 3
0
 async def _(self):
     assert isinstance(self.session, NLPSession)
     if datetime.now(timezone('Asia/Shanghai')).hour < 1:
         return IntentCommand(1000, "dd_no_sleep")
     stripped_msg = self.stripped_msg
     if stripped_msg == '' or re.search('^[~,,.。\\\\/!!…、]$', stripped_msg):
         return IntentCommand(100, 'nani')
Exemplo n.º 4
0
async def _(session: NLPSession):
    stripped_msg = session.msg_text.strip()
    if "雾宝来啦" in str(stripped_msg):
        return IntentCommand(100.0, 'block')
    if random.randint(0, 2) != 0:
        return IntentCommand(100.0, 'block')
    return IntentCommand(100.0, 'wubao')
Exemplo n.º 5
0
async def _(session: NLPSession):
    msg = session.ctx.get('message')
    msg = str(msg)

    pattern = re.compile(r'^(\d*)d(\d*)$')

    roll = pattern.match(msg)

    if roll:
        if roll.group(1) and roll.group(2):
            roll_1 = roll.group(1)
            roll_2 = roll.group(2)

            return IntentCommand(90,
                                 'roll_num',
                                 args={
                                     'roll_1': roll_1,
                                     'roll_2': roll_2
                                 })

        elif roll.group(2):
            roll_1 = 1
            roll_2 = roll.group(2)

            return IntentCommand(90,
                                 'roll_num',
                                 args={
                                     'roll_1': roll_1,
                                     'roll_2': roll_2
                                 })
Exemplo n.º 6
0
async def _(session: NLPSession):
    stripped_msg = session.msg_text.strip()
    if random.randint(1, 20) == 1:
        CUT_MES = False
        return IntentCommand(60.0, 'NLP', args={'message': session.msg_text})
    elif "nlp" in str(stripped_msg):
        CUT_MES = True
        return IntentCommand(60.0, 'NLP', args={'message': session.msg_text})
Exemplo n.º 7
0
async def _(session: NLPSession):
    stripped_msg = session.msg_text.strip()
    words = posseg.lcut(stripped_msg)
    for word in words:
        if word.word == "照片":
            return IntentCommand(60.0, 'sushe_img')
        if word.word == "洗澡":
            return IntentCommand(60.0, 'xizao')
    return IntentCommand(61.0, 'sushe')
Exemplo n.º 8
0
async def nl_gn(session: NLPSession):
    #msg = session.msg_text.strip()
    #count = 0
    now = datetime.datetime.now().strftime('%H')
    if int(now) < 5 or int(now) > 22:
        return IntentCommand(90.0,'goodnight')
    else:
        return IntentCommand(50.0,'goodnight')
    pass
Exemplo n.º 9
0
async def nl_mn(session: NLPSession):
    #msg = session.msg_text.strip()
    #count = 0
    now = datetime.datetime.now().strftime('%H')
    if int(now) < 10:
        return IntentCommand(90.0,'goodmorning')
    else:
        return IntentCommand(50.0,'goodmorning')
    pass
async def _(session: NLPSession):

    stripped_msg = session.msg_text.strip()
    msg = session.msg

    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    if stripped_msg == "search":
        return IntentCommand(95.0, 'search', current_arg=msg or '')
    return IntentCommand(90.0, 'tagrc', current_arg=msg or '')
Exemplo n.º 11
0
Arquivo: speak.py Projeto: sdy623/nana
async def _(session: NLPSession):
    stripped_msg = session.msg.strip()
    if stripped_msg.startswith('跟我说'):
        content = stripped_msg[len('跟我说'):].lstrip()
        return IntentCommand(65.0, ('speak', 'to_me'),
                             args={'content': content})
    if stripped_msg.startswith('跟大家说'):
        content = stripped_msg[len('跟大家说'):].lstrip()
        return IntentCommand(65.0, ('speak', 'to_all'),
                             args={'content': content})
Exemplo n.º 12
0
    async def _(self):
        # 去掉消息首尾的空白符
        stripped_msg = self.stripped_msg
        if re.search('[??谁]', stripped_msg, re.M | re.I) is not None:
            return IntentCommand(85.0, 'get_name')
        print(stripped_msg)
        stripped_msg = re.sub('我[是叫]', '', stripped_msg)

        # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
        return IntentCommand(85.0, 'set_name', current_arg=stripped_msg or '')
Exemplo n.º 13
0
async def nl_pa(session: NLPSession):
    msg = session.msg_text.strip()
    #count = 0
    await asyncio.sleep(0.2)
    if 'bot' in msg.lower():
        return IntentCommand(90.0,'pa')
    elif '!' or '!' in msg.lower():
        return IntentCommand(30.0,'pa')
    else:
        return IntentCommand(70.0,'pa')
    pass
Exemplo n.º 14
0
async def _(session: NLPSession):
    msg = session.ctx.get('message')
    msg = str(msg)
    ctx_group_id = session.ctx.get('group_id')

    pattern = re.compile(r'^添加问(.*)答(.*)$')
    # pattern_global = re.compile(r'^全局添加问(.*)答(.*)$')
    boo = pattern.match(str(msg))
    # boo_global = pattern_global.match(str(msg))

    if boo:
        if boo.group(1) and boo.group(2):
            cmd = 'add_cmd'
        elif boo.group(2):
            cmd = 'cancel'
            return IntentCommand(100,
                                 cmd,
                                 args={
                                     'answer': boo.group(2),
                                     'group_id': ctx_group_id
                                 })
        else:
            cmd = 'empty_finish'
        return IntentCommand(100,
                             cmd,
                             args={
                                 'question': boo.group(1),
                                 'answer': boo.group(2),
                                 'group_id': ctx_group_id
                             })

    # if boo_global:
    #     user_id = session.ctx.get('sender').get('user_id')
    #     if user_id == 2301583973 or user_id == 963949236:
    #         if boo_global.group(1) and boo_global.group(2):
    #             cmd = 'add_cmd'
    #         else:
    #             cmd = 'empty_finish'
    #         return IntentCommand(100, cmd,
    #                              args={'question': boo_global.group(1), 'answer': boo_global.group(2), 'group_id': 1})
    # else:
    #     return IntentCommand(100, 'finish')

    sql = ('SELECT A, group_id FROM cmd WHERE Q=?;')
    cmd = sql_exe(sql, (msg, ))

    if cmd:
        print('-' * 20)
        cmd = cmd[0]
        answer = cmd[0]
        group_id = cmd[1]
        if group_id == ctx_group_id or group_id == 1:
            return IntentCommand(100, 'user_cmd', args={'answer': answer})
Exemplo n.º 15
0
async def _(session: NLPSession):
    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    if session.msg_text == 'sudo PULL GROUP':
        return IntentCommand(95.0,
                             'PULL GROUP',
                             current_arg={
                                 'arg': session.msg_text,
                                 'only_to_me': True
                             })
    return IntentCommand(91.0,
                         'PROCESS_MESSAGE',
                         current_arg={
                             'arg': session.msg_text,
                             'only_to_me': True
                         })
Exemplo n.º 16
0
async def _(session: NLPSession):
    group_id = session.event.group_id
    user_id = session.event.user_id
    msg = session.msg
    bot = nonebot.get_bot()
    has_img, files = parse(msg)
    illegal = 0
    if has_img:
        for file in files:
            illegal = await AI.img_request(img=compress(file))
            if illegal:
                break
    if illegal:
        try:
            await bot.delete_msg(**session.event)
        except:
            pass
        type = '色情' if illegal == 1 else '暴恐'
        return IntentCommand(90.0,
                             'img_filter',
                             args={
                                 'user_id': user_id,
                                 'type': type
                             })
    record = records.get(group_id)
    ac_match = ac_filter.trie.iter(msg)
    bayes_match = bayes_filter.check(msg) if bot.config.BAYES else None
    if len(list(ac_match)) or bayes_match:
        try:
            await bot.delete_msg(**session.event)
        except:
            pass
        return IntentCommand(90.0, 'text_filter', current_arg=str(user_id))
    if record is None or msg != record.last_msg:
        record = Record(msg, user_id, repeat_count=1)
        records[group_id] = record
        return
    if record.last_user_id == user_id:
        return
    record.last_user_id = user_id
    record.repeat_count += 1
    if record.repeat_count == 2:
        return IntentCommand(90.0,
                             'repeater',
                             args={
                                 'delay': random.randint(5, 20) / 10,
                                 'message': msg
                             })
Exemplo n.º 17
0
async def chess_process(session: NLPSession, data: Dict[str, Any],
                        delete_func: Awaitable):
    command = session.msg_text
    qq = int(session.ctx['user_id'])
    board = data['board']
    if command in {"认输", "认负", "我认输", "我认负"}:
        isRed = data['black'] == qq
        await session.send(('黑' if not isRed else '白') + '方胜出')
        await delete_func()
    if len(command) != 2:
        return
    c1 = str_all.find(command[0])
    c2 = str_all.find(command[1])
    c1, c2 = max(c1, c2), min(c1, c2)
    if c1 >= 16 and c2 < 16:
        if (data['black'] == qq) != data['nowBlack']:
            await session.send('现在应该' + ('黑' if data['nowBlack'] else '白') +
                               '方走')
            return

        def _not_black():
            data['nowBlack'] = not data['nowBlack']

        return IntentCommand(100.0, ('play', 'bw', 'process'),
                             args={
                                 'args': (c2 % 8, c1 % 8),
                                 'isBlack': data['nowBlack'],
                                 'board': data['board'],
                                 'ifSuccess': _not_black,
                                 'ifWin': delete_func
                             })
Exemplo n.º 18
0
async def _(session: NLPSession):
    return IntentCommand(100.0, 'setu', current_arg=session.msg_text.strip())




#https://api.lolicon.app/setu/v1
Exemplo n.º 19
0
async def chess_process(session: NLPSession, data: Dict[str, Any],
                        delete_func: Awaitable):
    command = session.msg_text
    qq = int(session.ctx['user_id'])
    board = data['board']
    if command in {"认输", "认负", "我认输", "我认负"}:
        isRed = data['red'] == qq
        await session.send(('红' if not isRed else '黑') + '方胜出')
        await delete_func()
    if len(command) != 4 and len(command) != 5:
        return
    if command[0] in '前中后' and command[1] in all_name or command[0] in all_name:
        if command[-2] in '进平退':
            if (data['red'] == qq) != data['nowRed']:
                await session.send('现在应该' + ('红' if data['nowRed'] else '黑') +
                                   '方走')
                return

            def _not_red():
                data['nowRed'] = not data['nowRed']

            return IntentCommand(100.0, ('play', 'xiangqi', 'process'),
                                 args={
                                     'args': command,
                                     'isRed': data['nowRed'],
                                     'board': data['board'],
                                     'ifSuccess': _not_red,
                                     'ifWin': delete_func
                                 })
Exemplo n.º 20
0
async def _(session: NLPResult):
    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    # 置信度的计算需要自然语言处理器的编写者进行恰当的设计,以确保各插件之间的功能不会互相冲突。
    # 在 NoneBot 中,自然语言处理器的工作方式就是将用户的自然语言消息解析成一个命令和命令所需的参数,
    # 由于自然语言消息的模糊性,在解析时不可能完全确定用户的意图,因此还需要返回一个置信度作为这个命令的确定程度。
    #
    return IntentCommand(90.0, 'wuhan')
Exemplo n.º 21
0
async def _(session: NLPSession):
    test = session.msg
    try:
        re.search('CQ:image,file=B407F708A2C6A506342098DF7CAC4A57.jpg', test).span()
        return IntentCommand(90.0, 'R18')
    except:
        pass
Exemplo n.º 22
0
async def _(session: NLPSession):
    # 去掉消息首尾的空白符
    stripped_msg = session.msg_text.strip()
    # 对消息进行分词和词性标注
    words = posseg.lcut(stripped_msg)
    dates = {'今天': 0,
             '明天': 1,
             '后天': 2
             }
    searchInfo={'city': None,
                'date': None}
    # 遍历 posseg.lcut 返回的列表
    for word in words:
        # 每个元素是一个 pair 对象,包含 word 和 flag 两个属性,分别表示词和词性
        if word.flag == 'ns' and searchInfo['city'] is None:
            # ns 词性表示地名
            searchInfo['city'] = word.word
        if word.flag == 't' and searchInfo['date'] is None:
            if word.word in dates:

                searchInfo['date'] = dates[word.word]
        if (not searchInfo['city'] is None) and ( not searchInfo['date'] is None):
            break
    if searchInfo['date'] is None:
        searchInfo['date'] =0

    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    return IntentCommand(80.0, 'weather', current_arg=json.dumps(searchInfo) or '')
Exemplo n.º 23
0
async def _(session: NLPSession):
    msg = session.msg_text.replace('\u202d', '').replace('\u202e',
                                                         '')  # LRO, RLO
    ctx_id = context_id(session.ctx)
    ui = _running.get(ctx_id)
    if msg and ui is not None and ui.input_pending:
        return IntentCommand(80, ('_ui', 'feed_input'), current_arg=msg)
Exemplo n.º 24
0
async def _(session: NLPSession):
    text = re.sub(r'\s+', '', session.msg_text.strip())
    if not text:
        return

    confidence = 70.0

    if re.match(r'(?:怎么|咋)样\S{0,5}$', text) or \
            re.search(r'查(?:一?下|查看?)', text):
        confidence += 10.0
    if text.endswith('?') or text.endswith('?'):
        confidence += 5.0

    args = {}

    seg_paragraphs = await nlp.lexer(text)
    if seg_paragraphs:
        words = seg_paragraphs[0]
        for word in words:
            if word['ne'] == 'LOC':
                location = await nlp.parse_location(word['basic_words'])
                if any((location.province, location.city, location.district)):
                    args['location'] = location
            elif word['ne'] == 'TIME':
                args['time'] = word['item']

    confidence += len(args) * 5 if args else 0.0
    return IntentCommand(min(confidence, 100.0), ('weather', 'weather'),
                         args=args)
Exemplo n.º 25
0
async def _(session: NLPSession):
    # 以置信度 60.0 返回 tuling 命令
    # 确保任何消息都在且仅在其它自然语言处理器无法理解的时候使用 tuling 命令
    # print(session.ctx['message'])# 消息内容
    # print(session.ctx)# 有些人会报错 unicode Encode Error
    msg = str(session.ctx['message'])
    msg_type = str(session.ctx['message_type'])
    to_me = str(session.ctx['to_me'])
    # print('-------------------------------')
    # print(msg,type(msg))
    # print(len(msg),msg[1:])
    # print('-------------------------------')

    if (len(msg) > 5) and ('什么垃圾' in msg[1:]):
        print('========')
        us_data = await trash_sorter(msg)
        if msg_type == 'group' and to_me == 'True':
            # print(2222222,str(session.ctx['user_id']))
            await session.send(us_data,at_sender=True)
            pass
        else:
            await session.send(us_data)
            pass
    else:
        return IntentCommand(60.0, 'tuling', args={'message': session.msg_text})
Exemplo n.º 26
0
async def _(session: NLPSession):
    QQ = session.ctx['user_id']
    message = session.msg.strip()
    # 先把所有的数据都读出来
    sql = "SELECT thekey,replay,weight FROM ckeyword WHERE thekey LIKE '%" + message + "%'"
    result = sql_dql(sql)
    #这里是优先级的设置
    priority = 70
    a = len(result)
    if a > 0:
        klen = 0
        strg = ""
        # 我们这里匹配最长的
        for data in result:
            tlen = len(data[0])
            #如果完全匹配
            if data[0].strip() == message:
                priority = 95
                strg = data[1]
                break
            elif tlen > klen:
                klen = tlen
                strg = data[1]
        content = strg
    else:
        return None
    return IntentCommand(priority, 'keyword', args={'message': content})
Exemplo n.º 27
0
async def _(session: NLPSession):
    # 只复读群消息,与没有对机器人说的话
    if not session.event['to_me']:
        # 以置信度 60.0 返回 repeat 命令
        # 确保任何消息都在且仅在其它自然语言处理器无法理解的时候使用 repeat 命令
        return IntentCommand(60.0, ('repeat', 'group'),
                             args={'message': session.msg})
Exemplo n.º 28
0
async def _(session: NLPSession):
    # 去掉消息首尾的空白符
    await check_group(session)
    stripped_msg = session.msg_text.strip()
    logger.debug(stripped_msg)
    if stripped_msg[:2] == '押马':
        return IntentCommand(90.0, 'bet', current_arg=stripped_msg[2:])
Exemplo n.º 29
0
async def _(session: NLPSession):
    QQ = session.ctx['user_id']
    # 去掉消息首尾的空白符
    message = session.msg.strip()
    content = ""
    # 下面是常见命令
    back_list = ['撤回我刚才的内容', '快撤回', '撤回', '撤回我说的']
    #下面是命令判断
    if message in back_list:
        sql = "SELECT lmessageid FROM chat WHERE QQ='" + str(QQ) + "'"
        result = sql_dql(sql)
        bot = session.bot
        try:
            await bot.delete_msg(message_id=result[0][0])
            await session.send('撤回成功!')
        except:
            await session.send('撤回失败!')
            content = 'ok'
    elif message.startswith("状态"):
        if QQ == 1487998424:
            row = message[2:]
            sql = "UPDATE options SET thevalue='" + row + "' WHERE id=1"
            if sql_dml(sql):
                await session.send("更新状态成功!")
            else:
                await session.send("更新状态失败!")
            content = 'ok'
        else:
            return None
    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    return IntentCommand(90.0, 'tools', current_arg=content or '')
Exemplo n.º 30
0
async def _(session: NLPSession):
    # logger.debug(session.msg_text)
    # logger.debug(session.msg)
    group_id = context_id(session.ctx, mode='group')
    user_id = session.ctx['user_id']
    msg = session.msg

    record = records.get(group_id)  # 查找是否有原来的复读信息

    # 如果没有就添加进去
    if record is None:
        record = Record(last_msg=msg, last_usr_id=user_id, repeat_count=1)
        records[group_id] = record
        return

    # 如果之前已经有了不同人复读信息
    if record.last_msg != msg or \
            record.last_usr_id == user_id:
        record.last_msg = msg
        record.repeat_count = 1
        return

    record.last_usr_id = user_id
    record.repeat_count += 1

    logger.debug(record.repeat_count)
    logger.debug("msg" + msg)

    if record.repeat_count == 5:
        record.repeat_count = 1
        if record.repeat_msg != msg:
            record.repeat_msg = msg
            return IntentCommand(60.0, 'say', current_arg=msg)
    return