Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
0
Archivo: speak.py Proyecto: 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})
Ejemplo n.º 4
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 '')
Ejemplo n.º 5
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
Ejemplo n.º 6
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})
Ejemplo n.º 7
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
                         })
Ejemplo n.º 8
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
                             })
Ejemplo n.º 9
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
                             })
Ejemplo n.º 10
0
async def _(session: NLPSession):
    return IntentCommand(100.0, 'setu', current_arg=session.msg_text.strip())




#https://api.lolicon.app/setu/v1
Ejemplo n.º 11
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
                                 })
Ejemplo n.º 12
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 '')
Ejemplo n.º 13
0
async def _(session: NLPResult):
    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    # 置信度的计算需要自然语言处理器的编写者进行恰当的设计,以确保各插件之间的功能不会互相冲突。
    # 在 NoneBot 中,自然语言处理器的工作方式就是将用户的自然语言消息解析成一个命令和命令所需的参数,
    # 由于自然语言消息的模糊性,在解析时不可能完全确定用户的意图,因此还需要返回一个置信度作为这个命令的确定程度。
    #
    return IntentCommand(90.0, 'wuhan')
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
async def _(session: NLPSession):
    stripped_msg = session.msg_text.strip()

    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    return IntentCommand(90.0,
                         'music_recommend',
                         current_arg=stripped_msg or '')
Ejemplo n.º 16
0
async def _(session: NLPSession):
    if (not isAllowTo(session.ctx)):
        return
    if session.msg_images:
        return IntentCommand(80.0,
                             'checkCat',
                             args={"picList": session.msg_images})
Ejemplo n.º 17
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
Ejemplo n.º 18
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)
Ejemplo n.º 19
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})
Ejemplo n.º 20
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
Ejemplo n.º 21
0
async def nlp_clanba_time(session: NLPSession):
    if random.random() < 0.10:
        return IntentCommand(90.0,
                             __private_send_pic_cmd,
                             args={'pic_name': '我的天啊你看看都几点了.jpg'})
    else:
        return None
Ejemplo n.º 22
0
async def _(session: NLPSession):
    confidence = None  # by default we don't return result

    if session.ctx['to_me']:
        # if the user is talking to us, we may consider reply to him/her
        confidence = 60.0

    ctx_id = context_id(session.ctx)
    if ctx_id in tuling_sessions:
        ne_type = tuling_sessions[ctx_id]
        lex_result = await nlp.lexer(session.msg_text)
        # we only mind the first paragraph
        words = lex_result[0] if lex_result else []
        for w in words:
            if ne_type == w['ne']:
                # if there is a tuling session existing,
                # and the user's input is exactly what tuling wants,
                # we are sure that the user is replying tuling
                confidence = 100.0 - len(words) * 5.0
                break

    if confidence:
        return IntentCommand(confidence,
                             'tuling',
                             args={
                                 'message': session.msg,
                                 'one_time': True
                             })
Ejemplo n.º 23
0
async def nlp_rank(session: NLPSession):
    arg = session.msg_text.strip()
    if re.search('前', arg):
        return IntentCommand(90.0,
                             __private_send_pic_cmd,
                             args={'pic_name': './priconne/quick/前卫rank.jpg'})
    if re.search('中', arg):
        return IntentCommand(90.0,
                             __private_send_pic_cmd,
                             args={'pic_name': './priconne/quick/中卫rank.jpg'})
    if re.search('后', arg):
        return IntentCommand(90.0,
                             __private_send_pic_cmd,
                             args={'pic_name': './priconne/quick/后卫rank.jpg'})
    if re.search('rank推荐表', arg, re.I):
        session.send('输入前/中/后卫rank表以查看')
Ejemplo n.º 24
0
async def nlp_neigui(session: NLPSession):
    if random.random() < 0.30:
        return IntentCommand(90.0,
                             __private_send_pic_cmd,
                             args={'pic_name': '内鬼.jpg'})
    else:
        return None
Ejemplo 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})
Ejemplo n.º 26
0
async def timeline1(session: NLPSession):
    m = re.match(
        r'(?:b\s*站)?(?P<day_str>(?:前|昨|今|明|大?后)天)?(?P<name>.+?)'
        r'(?P<day_str2>(?:前|昨|今|明|大?后)天)?[会有]?更(?:不更)?新', session.msg_text,
        re.IGNORECASE)
    day_str, name = None, None
    if m:
        day_str = m.group('day_str') or m.group('day_str2')
        name = m.group('name')

    if not name:
        return None

    confidence = 92
    if not day_str:
        confidence -= 5
    if '吗' in session.msg_text:
        confidence += 3
    if not re.search(r'b\s*站', session.msg_text, re.IGNORECASE):
        confidence -= 10

    delta_day_dict = {'前天': -2, '昨天': -1, '今天': 0, '明天': 1, '后天': 2, '大后天': 3}
    delta_day = delta_day_dict.get(day_str, 0)
    date = (datetime.now() + timedelta(days=delta_day)).strftime('%m-%d')

    return IntentCommand(confidence, ('bilibili_anime', 'timeline'),
                         args={
                             'date': date,
                             'name': name
                         })
Ejemplo n.º 27
0
async def _(session: NLPSession):

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

    # 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
    return IntentCommand(90.0, 'tagrc', current_arg=msg or '')
Ejemplo n.º 28
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})
Ejemplo 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 '')
Ejemplo n.º 30
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:])