Example #1
0
async def weather_command(session: CommandSession):
    location = session.get('location', prompt=expr(e.WHERE))
    if location.province and not location.city and not location.district:
        # there is no city or district, ask the user for more info!
        if 'location_more' in session.state:
            del session.state['location_more']
        session.get('location_more',
                    prompt=expr(e.WHERE_IN_PROVINCE, location.province))

    logger.debug(f'Location: {location}')
    final_loc = location.heweather_format()
    weathers = await get_weather(final_loc)
    if len(weathers) > 1:
        await session.send(f'查询到 {len(weathers)} 个同名地区')
    elif len(weathers) == 0:
        session.finish(f'没有查询到{location.short_format()}的天气哦')

    for weather in weathers:
        basic = weather['basic']
        location_name = basic['admin_area']
        if basic['admin_area'] != basic['parent_city']:
            location_name += basic['parent_city']
        if basic['parent_city'] != basic['location']:
            location_name += basic['location']
        report_now = expr(e.REPORT_NOW, **weather['now'])
        report_tomorrow = expr(e.REPORT_FUTURE_DAY, '明天',
                               **weather['daily_forecast'][1])
        report_after_tomorrow = expr(e.REPORT_FUTURE_DAY, '后天',
                                     **weather['daily_forecast'][2])
        await session.send(f'{location_name}\n\n'
                           f'{report_now}\n\n'
                           f'{report_tomorrow}\n\n'
                           f'{report_after_tomorrow}')
Example #2
0
async def _(session: CommandSession):
    text = session.state.get('text')

    s = 1
    r = False
    t = 'default'

    # 输入关系
    if 'text' not in session.state:
        session.get('text', prompt=expr(e.INPPUT_MESSAGE))

    # 计算结果
    result = '、'.join(
        get_relation({
            'text': text,
            'sex': s,
            'reverse': r,
            'type': t
        }))

    # 输入格式不正确
    if result == '':
        session.finish(expr(e.FAULT_INSERT))

    # 返回结果
    reply = f'{expr(e.NAME)}{result}'
    session.finish(reply)
Example #3
0
async def _(session: CommandSession):
    count = await note_count(context_id(session.ctx))
    if count == 0:
        await session.send(expr(e.LIST_EMPTY))
        return

    all_notes = await Note.query.where(
        Note.context_id == context_id(session.ctx)).gino.all()
    for n in all_notes:
        await session.send(f'ID:{n.id}\r\n内容:{n.content}')
        await asyncio.sleep(0.8)
    await session.send(expr(e.LIST_COMPLETE, count=count))
Example #4
0
async def _(session: CommandSession):
    session.finish('本功能正在维护,暂时不可用咯')
    while True:
        text = session.state.get('text')

        if session.ctx['sender']['sex'] == 'male' or 'unknown':
            # 若获取不到性别(默认性别为“男”)
            s = 1
        else:
            s = 0
        r = False
        t = 'default'

        request_answer_filters = [
            extractors.extract_text,
            str.strip,
            converters.simple_chinese_to_bool,
        ]

        # 输入关系
        if 'text' not in session.state:
            session.get('text', prompt=expr(e.INPPUT_MESSAGE))

        # 计算结果
        result = '、'.join(
            get_relation({
                'text': text,
                'sex': s,
                'reverse': r,
                'type': t
            }))

        # 输入格式不正确
        if result == '':
            session.state.pop('text')
            await session.send(expr(e.FAULT_INSERT))
            await asyncio.sleep(0.8)
            continue

        # 返回结果
        reply = f'{expr(e.NAME)}{result},{expr(e.RE_ASK)}'
        session.get('con', prompt=reply, arg_filters=request_answer_filters)

        # 直接结束
        if not session.state['con']:
            session.finish(expr(e.MD_END_TASK))
        # 继续计算
        else:
            session.state.pop('text')
            session.state.pop('con')
Example #5
0
async def note_remove(session: CommandSession):
    ctx_id = context_id(session.ctx)
    count = await note_count(ctx_id)
    if count == 0:
        await session.send(expr(e.LIST_EMPTY))
        return

    id_ = session.get('id', prompt=expr(e.DEL_WHICH_ID))
    note_ = await Note.query.where((Note.context_id == ctx_id)
                                   & (Note.id == id_)).gino.first()
    if note_ is None:
        await session.send(expr(e.DEL_ID_NOT_EXISTS, id=id_))
    else:
        await note_.delete()
        await session.send(expr(e.DEL_SUCCESS, id=id_, content=note_.content))
Example #6
0
async def _(session: CommandSession):
    if session.current_key == 'message':
        text = session.current_arg_text.strip()
        if ('拜拜' in text or '再见' in text) and len(text) <= 4:
            session.finish(expr(e.BYE_BYE))
            return
        session.state[session.current_key] = session.current_arg
Example #7
0
async def aichat(session: CommandSession):
    chat = session.state.get('chat')
    logger.info('[腾讯闲聊]指令被触发了,开始运行')
    aichat_re = await call_txai_api(chat)
    if aichat_re == 'ERROR4':
        logger.info('[腾讯闲聊]出现意外了:腾讯端还不会回答用户的问题,代码:4 - TXAI-16394')
        logger.info('[腾讯闲聊]向用户告知不会回答并结束')
        await session.send(expr(TXCHAT_NOANSWER),at_sender=True)
    elif aichat_re == 'ERROR6':
        logger.info('[腾讯闲聊]出现错误了:代码:6 - TXAI-YourNetworkBad')
        logger.debug('[腾讯闲聊]小提醒:腾讯端网络堵塞,请重新触发即可')
        logger.info('[腾讯闲聊]指令出现错误并结束')
        await session.send('通往次元的轮船堵船啦,请稍后再找我吧-_-|||',at_sender=True)
    elif aichat_re == 'ERROR5':
        logger.info('[腾讯闲聊]出现错误了:代码:5 - TXAI-16394')
        logger.debug('[腾讯闲聊]小提醒:您无法独自解决本问题,请联系管理员协助您处理吧')
        logger.info('[腾讯闲聊]指令出现错误并结束')    
        await session.send('因为小管家意外受伤了,你的信息无法传达。请呼唤管理员来拯救吧')
    elif aichat_re == 'ERROR7':
        logger.info('[腾讯闲聊]出现错误了:腾讯端ID不正确,代码:7 - TXAI-16388')
        logger.debug('[腾讯闲聊]小提示:请检查您的腾讯AI应用ID')
        logger.info('[腾讯闲聊]指令出现错误并结束')
        await session.send('出现意外了:\n小管家意外受伤了,暂时不能回答你的想法哦,请呼唤管理员来拯救吧',at_sender=True)
    else:
        logger.info('[腾讯闲聊]没有出现错误,正常向用户发送结果')
        logger.info('[腾讯闲聊]指令成功完成并结束')
        await session.send(aichat_re,at_sender=True)
Example #8
0
async def ai_chat(session: CommandSession):
    message = session.get('message', prompt=expr(e.I_AM_READY))

    ctx_id = context_id(session.event)

    tmp_msg = Message(message)
    text = tmp_msg.extract_plain_text()

    # call ai_chat api
    reply = await tencent_ai.chat(text, ctx_id)
    logger.debug(f'Got AI reply: {reply}')

    if reply:
        session.finish(escape(reply))
    else:
        session.finish(expr(e.I_DONT_UNDERSTAND))
Example #9
0
async def _(session: CommandSession):
    text = session.current_arg_text.strip()

    if session.is_first_run and text:
        # first run, and there is an argument, we take it as the id
        session.current_key = 'id'

    if session.current_key == 'id':
        id_ = None
        try:
            # try parse the text message as an id
            id_ = int(text)
        except ValueError:
            # it's not directly a number
            if not session.is_first_run:
                # we are in and interactive session, do nlp

                # user may want to ask for all notes, check it
                match_score = await nlp.sentence_similarity(
                    session.current_arg_text.strip(), '现在有哪些呢?')
                if match_score > 0.70:
                    # we think it matches
                    await session.send(expr(e.QUERYING_ALL))
                    # sleep to make conversation natural :)
                    await asyncio.sleep(1)
                    await call_command(session.bot,
                                       session.ctx, ('note', 'list'),
                                       check_perm=False,
                                       disable_interaction=True)

                    # pause the session and wait for further interaction
                    await session.pause()
                    return

                # user may also put the id in a natural sentence, check it
                m = re.search(r'\d+', text)
                if m:
                    possible_id = int(m.group(0))
                    match_score = await nlp.sentence_similarity(
                        session.current_arg_text.strip(), f'删掉笔记{possible_id}')
                    if match_score > 0.70:
                        # we think it matches
                        id_ = possible_id
        if id_ is not None:
            session.state['id'] = id_
        else:
            session.pause(expr(e.DEL_CANNOT_RECOGNIZE_ID))
Example #10
0
async def _(session: NLPSession):
    if not session.msg:
        # empty message body
        nicks = list(session.bot.config.NICKNAME)
        if nicks:
            nick = nicks[0]
        else:
            nick = None
        await session.send(expr(expr_ack, nick=nick))
Example #11
0
async def nextchest(session: CommandSession):
    tag = session.get('tag',
                      prompt='收到,请回复您的游戏TAG哦。',
                      at_sender=True,
                      only_to_me=True)
    await session.send(expr(e.SYSTEM_WAITING))
    nextchest_report = await get_nextchest_of_tag(tag)
    await session.send(nextchest_report, at_sender=True)
    logger.info('[宝箱查询]结果已反馈用户,任务结束')
Example #12
0
async def _(session: NLPSession):
    if not session.msg.strip():
        # empty message body
        nicks = list(session.bot.config.NICKNAME)
        if nicks:
            nick = nicks[0]
        else:
            nick = None
        return IntentCommand(100.0,
                             'echo',
                             args={'message': expr(expr_ack, nick=nick)})
Example #13
0
async def tuling(session: CommandSession):
    message = session.get('message', prompt=expr(e.I_AM_READY))

    ctx_id = context_id(session.ctx)
    if ctx_id in tuling_sessions:
        del tuling_sessions[ctx_id]

    tmp_msg = Message(message)
    text = tmp_msg.extract_plain_text()
    images = [
        s.data['url'] for s in tmp_msg if s.type == 'image' and 'url' in s.data
    ]

    # call tuling api
    replies = await call_tuling_api(session, text, images)
    logger.debug(f'Got tuling\'s replies: {replies}')

    if replies:
        for reply in replies:
            await session.send(escape(reply))
            await asyncio.sleep(0.8)
    else:
        await session.send(expr(e.I_DONT_UNDERSTAND))

    one_time = session.state.get('one_time', False)
    if one_time:
        # tuling123 may opened a session, we should recognize the
        # situation that tuling123 want more information from the user.
        # for simplification, we only recognize named entities,
        # and since we will also check the user's input later,
        # here we can allow some ambiguity.
        ne_type = tuling_ne_type(replies, {
            'LOC': ('哪里', '哪儿', re.compile(r'哪\S城市'), '位置'),
            'TIME': ('什么时候', ),
        })
        if ne_type:
            logger.debug(f'One time call, '
                         f'and there is a tuling session for {ne_type}')
            tuling_sessions[ctx_id] = ne_type
    else:
        session.pause()
Example #14
0
async def lunch(session: CommandSession):
    where = ['去一食堂', '去二食堂', '吃日夜', '点外卖', '出去吃']
    kind = ['面条', '饭', '炒饭', '早点', '砂锅']

    request_answer_filters = [
        extractors.extract_text,
        str.strip,
        converters.simple_chinese_to_bool,
    ]

    if 'next1' not in session.state:
        # 先随机一个去处,问可不可以
        await session.send(expr(EXPR_WAIT))
        await asyncio.sleep(1)
        session.get('next1',
                    prompt=random.choice(where) + '吧,' + expr(EXPR_HOW),
                    arg_filters=request_answer_filters)

    if not session.state['next1']:
        # 去处被否决
        session.finish(expr(EXPR_CANCEL))

    # 去处 OK
    if 'next2' not in session.state:
        session.get('next2',
                    prompt=expr(EXPR_REQU),
                    arg_filters=request_answer_filters)

    if not session.state['next2']:
        session.finish(expr(EXPR_CANCEL))

    await asyncio.sleep(0.8)
    await session.send('经奶茶精选,今天' + random.choice(kind) + '与你更配哦🤔')
    await asyncio.sleep(0.3)
    await session.send(expr(EXPR_EMOJI))
Example #15
0
async def goodjuan(session: CommandSession):
    tag = session.get('tag')
    await session.send(expr(e.SYSTEM_WAITING))
    goodjuan_report = await get_goodjuan(tag)
    if goodjuan == 'ERROR-CR404':
        logger.info('[升职查询]查询完毕,官方无此TAG信息')
        logger.debug('[升职查询]查询脚本执行完毕并返回信息到Nonebot脚本')
        logger.info('[升职查询]任务处理完成')
        await session.send('出现意外了:\n你想查询的用户被抓到二次元了,请检查一下再重新发送指令查询吧(⊙﹏⊙)',
                           at_sender=True)
    elif goodjuan == 'ERROR-CR400':
        logger.info('[升职查询]出现错误了:官方API查询400,提示详见Debug模式')
        logger.info('[升职查询]你可以前往CR开发者网站查询详情')
        logger.debug('[升职查询]详细信息:没有使用正确的查询地址或官方关闭API了,或许也倒闭了吧( •̀ ω •́ )')
        logger.debug('[升职查询]查询脚本执行完毕并返回信息到Nonebot脚本')
        logger.info('[升职查询]任务处理完成')
        await session.send('QAQ小管家迷路了,请联系管理员协助修复吧', at_sender=True)
    elif goodjuan == 'ERROR-CRTimeOut':
        logger.info('[升职查询]出现错误了:官方API查询超时,提示详见Debug模式')
        logger.debug('[升职查询]详细信息:查询超时.详见小管家Wiki')
        logger.debug('[升职查询]查询脚本执行完毕并返回信息到Nonebot脚本')
        logger.info('[升职查询]任务处理完成')
        await session.send('出现意外了:\n因为连接速度太慢所以主动放弃查询了,请您重新使用指令再查询一下吧',
                           at_sender=True)
    elif goodjuan == 'ERROR-CRNotCallMe':
        logger.info('[升职查询]用户意外触发或未正常放弃,查询无效,提示详见Debug模式')
        logger.debug('[升职查询]详细信息:包含英文数字以外的其他语言,查询无效.详见小管家Wiki')
        logger.debug('[升职查询]查询脚本执行完毕并返回信息到Nonebot脚本')
        logger.info('[升职查询]任务处理完成')
        await session.send('对不起,你似乎不是来查询信息的(。﹏。)', at_sender=True)
    elif goodjuan == 'ERROR-CRNotError':
        logger.info('[升职查询]用户并不在皇家部落内,拒绝查询并回复用户,提示详见Debug模式')
        logger.debug('[升职查询]详细信息:用户并不在皇家部落内,主动放弃查询.详见小管家Wiki')
        logger.debug('[升职查询]查询脚本执行完毕并返回信息到Nonebot脚本')
        logger.info('[升职查询]任务处理完成')
        await session.send('本周暂无捐卡达标的小伙伴,请继续加油(⊙o⊙)哦', at_sender=True)
        #await session.send('本服务仅对部落内的小伙伴所开放哦,Sorry。QAQ',at_sender=True)
    else:
        await session.send(goodjuan_report, at_sender=True)
        logger.info('[升职查询]结果无错误并已查询完毕并发送给用户,任务结束')
Example #16
0
        break
    else:
        pass
for item in xblret["items"]:
    item_utc = datetime.datetime.strptime(item["lastSeen"],
                                          "%Y%m%dT%H%M%S.%fZ")
    if now - item_utc > datetime.timedelta(days=7):
        xblshow = True
        show = True
        break
    else:
        pass
if show != True:
    print("Very Good,没有部落的伙伴是木头人,加油owo")
elif show == True:
    print("%s木头人清单如下:" % (expr(e.APP_FOOLSHIT)))
    if dblshow == True:
        print('大部落:')
        for item in dblret["items"]:
            #格式化时间
            item_utc = datetime.datetime.strptime(item["lastSeen"],
                                                  "%Y%m%dT%H%M%S.%fZ")
            if match > 8:
                print('还有不少木头人,管理怎么看的部落啊,请自己前往游戏查看吧')
                break
            elif now - item_utc > datetime.timedelta(days=5):
                match = match + 1
                date_str = datetime.datetime.strftime(item_utc,
                                                      '%Y-%m-%d %H:%M:%S')
                memstat = ("成员:%s,Tag:%s,%s天未登录" %
                           (item["name"], item["tag"], now.day - item_utc.day))
Example #17
0
async def note_add(session: CommandSession):
    content = session.get('content', prompt=expr(e.ADD_WHAT_CONTENT))
    new_note = await Note.create(content=content,
                                 context_id=context_id(session.ctx))
    await session.send(
        expr(e.ADD_SUCCESS, id=new_note.id, content=new_note.content))