Beispiel #1
0
async def index(session: CommandSession):
    now = dt.beijing_now()
    year = session.get_optional('year', now.year)
    month = session.get_optional('month', math.ceil(now.month / 3) * 3 - 3 + 1)

    api_url = INDEX_API_URL.format(year=year, month=month)
    resp = await requests.get(api_url)
    payload = await resp.json()
    if not payload or payload.get('code') != 0:
        await session.send('查询失败了……')
        return

    anime_list = payload['result']['data']
    if not anime_list:
        await session.send('没有查询到相关番剧……')
        return

    reply = f'{year}年{month}月番剧\n按追番人数排序,前20部如下:\n\n'
    for anime in anime_list:
        title = anime.get('title')
        index_show = anime.get('index_show', '不详')
        if not title:
            continue

        reply += f'{title}  {index_show}\n'

    web_url = INDEX_WEB_URL.format(year=year, month=month)
    reply += f'\n更多详细资料见BiliBili官网 {web_url}'

    await session.send(reply)
Beispiel #2
0
async def ffxivitem(session: CommandSession):
    # 从 Session 对象中获取城市名称(city),如果当前不存在,则询问用户
    item = session.get_optional('item', default='NULL')
    if item == 'NULL':
        await session.send('请输入道具名')
    else:
        weather_report = await get_ffxivitem(item)
        await session.send(weather_report)
Beispiel #3
0
async def sched_remove(session: CommandSession):
    parser = ArgumentParser()
    parser.add_argument('name')
    args = await parse_args(session,
                            parser,
                            argv=session.get_optional('argv'),
                            help_msg=sched_remove_help)
    ok = await scheduler.remove_job(
        scheduler.make_job_id(PLUGIN_NAME, context_id(session.ctx), args.name))
    if ok:
        await session.send(f'成功删除计划任务 {args.name}')
    else:
        await session.send(f'没有找到计划任务 {args.name},请检查你的输入是否正确')
Beispiel #4
0
async def tuling(session: CommandSession):
    # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None
    message = session.get_optional('message')

    # 通过封装的函数获取图灵机器人的回复
    reply = await call_tuling_api(session, message)
    if reply:
        # 如果调用图灵机器人成功,得到了回复,则转义之后发送给用户
        # 转义会把消息中的某些特殊字符做转换,以避免酷 Q 将它们理解为 CQ 码
        await session.send(escape(reply))
    else:
        # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取图灵回复时的「表达」
        # 这里的 render_expression() 函数会将一个「表达」渲染成一个字符串消息
        await session.send(render_expression(EXPR_DONT_UNDERSTAND))
Beispiel #5
0
async def sched_get(session: CommandSession):
    parser = ArgumentParser()
    parser.add_argument('name')
    args = await parse_args(session,
                            parser,
                            argv=session.get_optional('argv'),
                            help_msg=sched_get_help)
    job = await scheduler.get_job(
        scheduler.make_job_id(PLUGIN_NAME, context_id(session.ctx), args.name))
    if not job:
        await session.send(f'没有找到计划任务 {args.name},请检查你的输入是否正确')
        return

    await session.send('找到计划任务如下')
    await session.send(format_job(args.name, job))
Beispiel #6
0
async def tuling(session: CommandSession):
    # 获取可选参数,这里如果没有 message 参数,命令不会被中断,message 变量会是 None
    message = session.get_optional('message')

    # 通过封装的函数获取图灵机器人的回复
    reply = await call_tuling_api(session, message)
    if reply:
        # 如果调用图灵机器人成功,得到了回复,则转义之后发送给用户
        # 转义会把消息中的某些特殊字符做转换,以避免酷 Q 将它们理解为 CQ 码
        await session.send(escape(reply))
    else:
        # 如果调用失败,或者它返回的内容我们目前处理不了,发送无法获取图灵回复时的「表达」
        # session.send_expr() 内部会调用 none.expression.render()
        # 该函数会将一个「表达」渲染成一个字符串消息
        await session.send_expr(EXPR_DONT_UNDERSTAND)
Beispiel #7
0
async def tuling(session: CommandSession):
    message = session.get('message', prompt='我已经准备好啦,来跟我聊天吧~')

    finish = message in ('结束', '拜拜', '再见')
    if finish:
        session.finish('拜拜啦,你忙吧,下次想聊天随时找我哦~')
        return

    # call tuling api
    reply = f'你说了:{message}'

    one_time = session.get_optional('one_time', False)
    if one_time:
        session.finish(reply)
    else:
        session.pause(reply)
Beispiel #8
0
async def tuling(session: CommandSession):
    message = session.get('message', prompt='我已经准备好啦,来跟我聊天吧~')

    finish = message in ('结束', '拜拜', '再见')
    if finish:
        asyncio.ensure_future(session.send('拜拜啦,你忙吧,下次想聊天随时找我哦~'))
        return

    # call tuling api
    reply = f'你说了:{message}'

    one_time = session.get_optional('one_time', False)
    if one_time:
        asyncio.ensure_future(session.send(reply))
    else:
        del session.args['message']
        session.get('message', prompt=reply)
Beispiel #9
0
async def tuling(session: CommandSession):
    message = session.get('message', prompt='我已经准备好啦,来跟我聊天吧~')

    finish = message in ('结束', '拜拜', '再见')
    if finish:
        asyncio.ensure_future(session.send('拜拜啦,你忙吧,下次想聊天随时找我哦~'))
        return

    # call tuling api
    reply = f'你说了:{message}'

    one_time = session.get_optional('one_time', False)
    if one_time:
        asyncio.ensure_future(session.send(reply))
    else:
        del session.args['message']
        session.get('message', prompt=reply)
Beispiel #10
0
async def tuling(session: CommandSession):
    message = session.get('message', prompt_expr=expr.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(expr.I_DONT_UNDERSTAND)

    one_time = session.get_optional('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()
Beispiel #11
0
async def _(session: none.CommandSession):
    await session.send(session.get_optional('message') or session.current_arg)
Beispiel #12
0
async def weather(session: CommandSession):
    info = (session.get_optional('message') or session.current_arg).split(' ')
    if len(info) == 1:
        await session.send(query_weather(info[0]))
    else:
        await session.send(query_weather(info[0], info[1]))
Beispiel #13
0
async def inform(session: CommandSession):
    await session.send(session.get_optional('message') or session.current_arg)
Beispiel #14
0
async def _(session: CommandSession):
    await session.send(
        unescape(session.get_optional('message') or session.current_arg))
Beispiel #15
0
async def sched_add(session: CommandSession):
    parser = ArgumentParser('schedule.add')
    parser.add_argument('-S', '--second')
    parser.add_argument('-M', '--minute')
    parser.add_argument('-H', '--hour')
    parser.add_argument('-d', '--day')
    parser.add_argument('-m', '--month')
    parser.add_argument('-w', '--day-of-week')
    parser.add_argument('-f', '--force', action='store_true', default=False)
    parser.add_argument('-v', '--verbose', action='store_true', default=False)
    parser.add_argument('--name', required=True)
    parser.add_argument('commands', nargs='+')

    argv = session.get_optional('argv')
    if not argv:
        await session.send(_sched_add_help)
        return

    try:
        args = parser.parse_args(argv)
    except ParserExit as e:
        if e.status == 0:
            # --help
            await session.send(_sched_add_help)
        else:
            await session.send('参数不足或不正确,请使用 --help 参数查询使用帮助')
        return

    if not re.match(r'[_a-zA-Z][_\w]*', args.name):
        await session.send(
            '计划任务名必须仅包含字母、数字、下划线,且以字母或下划线开头')
        return

    parsed_commands = []
    invalid_commands = []
    for cmd_str in args.commands:
        cmd, current_arg = parse_command(session.bot, cmd_str)
        if cmd:
            tmp_session = CommandSession(session.bot, session.ctx, cmd,
                                         current_arg=current_arg)
            if await cmd.run(tmp_session, dry=True):
                parsed_commands.append((cmd.name, current_arg))
            else:
                invalid_commands.append(cmd_str)
    if invalid_commands:
        invalid_commands_joined = '\r\n'.join(
            [f'{i+1}: {c}' for i, c in enumerate(invalid_commands)])
        await session.send(f'计划任务添加失败,'
                           f'因为下面的 {len(invalid_commands)} 个命令无法被运行'
                           f'(命令不存在或权限不够):\r\n\r\n'
                           f'{invalid_commands_joined}')
        return

    job_id = f'{context_id(session.ctx)}/job/{args.name}'
    trigger_args = {k: v for k, v in args.__dict__.items()
                    if k in {'second', 'minute', 'hour',
                             'day', 'month', 'day_of_week'}}
    try:
        job = _scheduler.add_job(
            _schedule_callback,
            trigger='cron', **trigger_args,
            id=job_id,
            kwargs={
                'ctx': session.ctx,
                'name': args.name,
                'commands': parsed_commands,
                'verbose': args.verbose,
            },
            replace_existing=args.force,
            misfire_grace_time=30
        )
    except ConflictingIdError:
        # a job with same name exists
        await session.send(f'计划任务 {args.name} 已存在,'
                           f'若要覆盖请使用 --force 参数')
        return

    await session.send(f'计划任务 {args.name} 添加成功,下次运行时间:'
                       f'{job.next_run_time.strftime("%Y-%m-%d %H:%M:%S")}')
Beispiel #16
0
async def sched_add(session: CommandSession):
    parser = ArgumentParser()
    parser.add_argument('-S', '--second')
    parser.add_argument('-M', '--minute')
    parser.add_argument('-H', '--hour')
    parser.add_argument('-d', '--day')
    parser.add_argument('-m', '--month')
    parser.add_argument('-w', '--day-of-week')
    parser.add_argument('-f', '--force', action='store_true', default=False)
    parser.add_argument('-v', '--verbose', action='store_true', default=False)
    parser.add_argument('--name', required=True)
    parser.add_argument('commands', nargs='+')

    args = await parse_args(session,
                            parser,
                            argv=session.get_optional('argv'),
                            help_msg=sched_add_help)

    if not re.match(r'[_a-zA-Z][_a-zA-Z0-9]*', args.name):
        await session.send('计划任务名必须仅包含字母、数字、下划线,且以字母或下划线开头')
        return

    parsed_commands: List[ScheduledCommand] = []
    invalid_commands: List[str] = []

    if args.verbose:
        parsed_commands.append(
            ScheduledCommand(('echo', ), f'开始执行计划任务 {args.name}……'))

    for cmd_str in args.commands:
        cmd, current_arg = parse_command(session.bot, cmd_str)
        if cmd:
            tmp_session = CommandSession(session.bot,
                                         session.ctx,
                                         cmd,
                                         current_arg=current_arg)
            if await cmd.run(tmp_session, dry=True):
                parsed_commands.append(ScheduledCommand(cmd.name, current_arg))
                continue
        invalid_commands.append(cmd_str)
    if invalid_commands:
        invalid_commands_joined = '\n'.join(
            [f'- {c}' for c in invalid_commands])
        await session.send(f'计划任务添加失败,'
                           f'因为下面的 {len(invalid_commands)} 个命令无法被运行'
                           f'(命令不存在或权限不够):\n'
                           f'{invalid_commands_joined}')
        return

    trigger_args = {
        k: v
        for k, v in args.__dict__.items()
        if k in {'second', 'minute', 'hour', 'day', 'month', 'day_of_week'}
    }
    try:
        job = await scheduler.add_scheduled_commands(
            parsed_commands,
            job_id=scheduler.make_job_id(PLUGIN_NAME, context_id(session.ctx),
                                         args.name),
            ctx=session.ctx,
            trigger='cron',
            **trigger_args,
            replace_existing=args.force)
    except scheduler.JobIdConflictError:
        # a job with same name exists
        await session.send(f'计划任务 {args.name} 已存在,' f'若要覆盖请使用 --force 参数')
        return

    await session.send(f'计划任务 {args.name} 添加成功')
    await session.send(format_job(args.name, job))
Beispiel #17
0
async def _(session: CommandSession):
    await session.send(
        unescape(session.get_optional('message') or session.current_arg))
Beispiel #18
0
async def echo(session: CommandSession):
    await session.send(session.get_optional('message') or session.current_arg)