コード例 #1
0
ファイル: commands.py プロジェクト: progray/iswust_bot
async def alarm(session: CommandSession):
    time: datetime = session.get("time")
    target: str = session.get("target")

    # 过滤时间
    now = datetime.now()
    # 过去的时间
    if time <= now:
        session.finish(render_expression(EXPR_COULD_NOT))

    time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    await add_job(
        remind,
        trigger="date",
        run_date=time,
        id=make_job_id(
            PLUGIN_NAME,
            session.event,
            (random_string(1, string.ascii_lowercase) +
             random_string(7, string.ascii_lowercase + string.digits)),
        ),
        args=[target, session.event],
        kwargs={"remark": target},
    )
    cmd, current_arg = CommandManager().parse_command(session.bot, target)
    if cmd:
        tmp_session = CommandSession(session.bot,
                                     session.event,
                                     cmd,
                                     current_arg=current_arg)
        if await cmd.run(tmp_session, dry=True):
            await add_scheduled_commands(
                ScheduledCommand(cmd.name, current_arg),
                job_id=make_job_id(
                    PLUGIN_NAME,
                    session.event,
                    (random_string(1, string.ascii_lowercase) +
                     random_string(7, string.ascii_lowercase + string.digits)),
                ),
                event=session.event,
                trigger="date",
                run_date=time,
                replace_existing=True,
            )

    session.finish(
        render_expression(
            EXPR_OK, time=time_str, action=target, escape_args=False) +
        f"\n提醒创建成功:\n"
        f"> 提醒时间:{time_str}\n"
        f"> 内容:{target}")
コード例 #2
0
    async def get_user_sub(cls, event: Event) -> dict:
        result = {}
        jobs = await get_jobs(make_job_id(PLUGIN_NAME, event))
        for job in jobs:
            job: Job
            key = job.kwargs["key"]
            result[key] = cls.dct()[key]

        return result
コード例 #3
0
 async def del_sub(cls, event: Event, key: str) -> Tuple[bool, str]:
     name = cls.dct().get(key, "")
     if name:
         res = await remove_job(make_job_id(PLUGIN_NAME, event, key))
         if res:
             return True, f"删除 `{name}` 成功"
         else:
             return False, f"删除 `{name}` 失败,请稍后再试"
     else:
         return False, "输入有误"
コード例 #4
0
ファイル: score.py プロジェクト: progray/iswust_bot
async def handle_rm_score(event, idx):
    if idx.startswith(PREFIX):
        bot = get_bot()
        idx = idx.replace(PREFIX, "")
        if idx.isdigit():
            idx = int(idx)  # type: ignore
            if idx == 0:
                res = await remove_job(make_job_id(PLUGIN_NAME, event))
                if res:
                    await bot.send(event, f"删除 `{lst[0]}` 成功")
                else:
                    await bot.send(event, "删除失败,请稍后再试")
        else:
            await bot.send(event, "序号不存在")
        raise _FinishException
コード例 #5
0
 async def add_sub(cls, event: Event, key: str) -> Tuple[bool, str]:
     name = cls.dct().get(key, "")
     cmd = cls.sub_info.get(name, "")
     func = getattr(CheckUpdate, cmd, None)
     if func:
         await add_job(
             func=func,
             trigger=IntervalTrigger(seconds=Config.CACHE_SESSION_TIMEOUT +
                                     120,
                                     jitter=10),
             args=(event, ),
             id=make_job_id(PLUGIN_NAME, event, key),
             misfire_grace_time=60,
             job_defaults={"max_instances": 10},
             replace_existing=True,
             kwargs={"key": key},
         )
         return True, f"添加 `{name}` 成功!"
     else:
         return False, "输入序号有误"
コード例 #6
0
ファイル: score.py プロジェクト: progray/iswust_bot
async def handle_subscribe_score(event, msg: str):
    if msg.startswith(PREFIX):
        bot = get_bot()
        try:
            idx = int(msg.replace(PREFIX, ""))
            if idx == 0:
                # 添加任务
                await add_job(
                    func=check_update,
                    trigger=IntervalTrigger(
                        seconds=Config.CACHE_SCORE_INTERVAL + 120, jitter=10
                    ),
                    args=(event,),
                    id=make_job_id(PLUGIN_NAME, event),
                    misfire_grace_time=60,
                    job_defaults={"max_instances": 10},
                    replace_existing=True,
                )
                await bot.send(event, "添加成功!")
        except Exception as e:
            await bot.send(event, "输入有误")
            logger.exception(e)
        raise _FinishException
コード例 #7
0
ファイル: score.py プロジェクト: progray/iswust_bot
async def handle_get_scores(event):
    result = {}
    job = await get_job(make_job_id(PLUGIN_NAME, event))
    if job:
        result[f"{PREFIX}0"] = lst[0]
    return result
コード例 #8
0
ファイル: commands.py プロジェクト: progray/iswust_bot
async def get_push_jobs(event) -> List[Job]:
    return await get_jobs(make_job_id(PLUGIN_NAME, event))
コード例 #9
0
ファイル: commands.py プロジェクト: progray/iswust_bot
async def push(session: CommandSession):
    message = session.get(
        "message",
        prompt="你想让我提醒什么内容呢?语句命令都可,输入 `取消、不` 等来取消",
        arg_filters=[
            controllers.handle_cancellation(session),
            str.lstrip,
            validators.not_empty("请输入有效内容哦~"),
        ],
    )
    tn = TimeNormalizer()
    hour = session.state.get("hour")
    minute = session.state.get("minute")
    if hour is None or minute is None:
        time = session.get(
            "time",
            prompt="你希望我在每天的什么时候给你提醒呢?",
            arg_filters=[
                controllers.handle_cancellation(session),
                str.lstrip,
                validators.not_empty("请输入有效内容哦~"),
            ],
        )
        m = re.match(r"(\d{1,2})[.::](\d{1,2})", time)
        if m:
            hour = int(m.group(1))
            minute = int(m.group(2) or 0)
        else:
            time_json = tn.parse(time)
            if time_json["type"] == "error":
                del session.state["time"]
                session.pause("时间格式不对啦,请重新发送")
            elif time_json["type"] == "timedelta":
                time_diff = time_json["timedelta"]
                hour = time_diff["hour"]
                minute = time_diff["minute"]
            elif time_json["type"] == "timestamp":
                time_target = datetime.strptime(time_json["timestamp"],
                                                "%Y-%m-%d %H:%M:%S")
                # 默认时间点为中午12点
                if (not re.search(r"[\d+一二两三四五六七八九十]+点", time)
                        and time_target.hour == 0 and time_target.minute == 0
                        and time_target.second == 0):
                    time_target.replace(hour=12)
                hour = time_target.hour
                minute = time_target.minute

    session.state["hour"] = hour
    session.state["minute"] = minute
    escaped_message = message.replace("\\", "\\\\").replace('"', '\\"')
    switch_arg = f'--repeat "{escaped_message}"'

    try:
        job = await add_scheduled_commands(
            ScheduledCommand("switch", switch_arg),
            job_id=make_job_id(
                PLUGIN_NAME,
                session.ctx,
                (random_string(1, string.ascii_lowercase) +
                 random_string(7, string.ascii_lowercase + string.digits)),
            ),
            event=session.event,
            trigger="cron",
            hour=hour,
            minute=minute,
            replace_existing=False,
        )
        session.finish(f"添加提醒成功啦,下次提醒时间 "
                       f'{job.next_run_time.strftime("%Y-%m-%d %H:%M")}')
    except JobIdConflictError:
        session.finish("添加提醒失败,有可能只是运气不好哦,请稍后重试~")