示例#1
0
async def start_gamble(group_id):
    bot = nonebot.get_bot()
    hr = HorseRace()
    horse_list = await hr.search_horse()
    if len(horse_list) <= 4:
        await hr.set_state(1)
        response = ""
        for horse in horse_list:
            if horse[1] in HORSE_SKIN.keys():
                skin = HORSE_SKIN[horse[1]]
            else:
                skin = HORSE
            horse_line = "【%s】:%s的%s%s\n" % (horse[0], await get_nick_name(
                group_id, horse[2]), horse[1], skin)
            response += horse_line
        await bot.send_group_msg(group_id=group_id, message=response)
        delta = datetime.timedelta(seconds=60)
        trigger = DateTrigger(run_date=datetime.datetime.now() + delta)
        scheduler.add_job(
            func=start_game,
            trigger=trigger,
            args=(group_id, ),
            misfire_grace_time=60,
        )
    else:
        response = "检测到马数异常,赛马强制结束!"
        await bot.send_group_msg(group_id=group_id, message=response)
        await hr.end_race()
示例#2
0
async def setu(session: CommandSession):
    bot = get_bot()
    if session.current_arg == '':
        has_perm = await perm.check_permission(session.bot, session.event, perm.GROUP)
        if has_perm and is_setu_open:
            # msg1 = message.MessageSegment.image('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592212494831&di=ee6127d25949ab52d82402d2309a8537&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fzhidao%2Fwh%253D450%252C600%2Fsign%3D14f304ca50da81cb4eb38bc96756fc20%2Fae51f3deb48f8c542d7329113b292df5e0fe7f68.jpg')
            Flag = await can_get_a_setu(session.event.user_id)
            if not Flag:
                await session.send(message.MessageSegment.text('你看太多涩图了'))
                return
            msg1 = await get_a_setu()
            msg_data = await session.send(msg1)
            log.logger.debug(str(msg_data['message_id']))
            # 制作一个“10秒钟后”触发器
            delta = datetime.timedelta(seconds=20)
            trigger = DateTrigger(
                run_date=datetime.datetime.now() + delta
            )
            scheduler.add_job(
                func=bot.delete_msg,  # 要添加任务的函数,不要带参数
                trigger=trigger,  # 触发器
                kwargs={'message_id':msg_data['message_id'], 'self_id':session.event.self_id},  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
                # kwargs=None,
                misfire_grace_time=1,  # 允许的误差时间,建议不要省略
                # jobstore='default',  # 任务储存库
            )
         #   await asyncio.sleep(10)
         #   await bot.delete_msg(message_id = msg_data['message_id'], self_id = session.event.self_id)
        else:
            msg1 = message.MessageSegment.text('我们可以通过“色图”来表示所有自然界之色,国际照明学会规定分别用x、y、z来表示红、绿、蓝三原色之间的百分比。由于是百分比,三者相加必须等于1,故色调在色图中只需用x、y两值即可。将光谱色中各段波长所引起的色调感觉在x、y平面上做成图标时,即得色图。')
            await session.send(msg1)      
    pass

    
示例#3
0
文件: Chat0.py 项目: synodriver/ATRI
async def _(session: CommandSession):
    user = session.event.user_id
    group = session.event.group_id
    if checkNoob(user, group):
        if user == master:
            await session.send('那...请主人自己闭上眼!哼唧')
            return
        else:
            await session.send('恭喜!您已被ATRI屏蔽7小时')
            try:
                with open(
                        Path('.') / 'ATRI' / 'plugins' / 'noobList' /
                        'noobList.json', 'r') as f:
                    bL = json.load(f)
            except:
                bL = {}
            bL[f"{user}"] = f"{user}"
            file = Path(
                '.') / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json'
            f = open(file, 'w')
            f.write(json.dumps(bL))
            f.close()
            delta = timedelta(hours=7)
            trigger = DateTrigger(run_date=datetime.now() + delta)

            scheduler.add_job(  #type: ignore
                func=rmQQfromNoobLIST,
                trigger=trigger,
                args=(session.event.user_id, ),
                misfire_grace_time=60,
            )
def my_trigger_cron(rss: rss_class.Rss):
    # 解析参数
    tmp_list = rss.time.split("_")
    times_list = ["*/5", "*", "*", "*", "*"]
    for index, value in enumerate(tmp_list):
        if value:
            times_list[index] = value
    try:
        # 制作一个触发器
        trigger = CronTrigger(
            minute=times_list[0],
            hour=times_list[1],
            day=times_list[2],
            month=times_list[3],
            day_of_week=times_list[4],
            timezone="Asia/Shanghai",
        )
    except Exception as e:
        logger.error(f"创建定时器错误!cron:{times_list} E:{e}")
        return

    # 添加任务
    scheduler.add_job(
        func=check_update,  # 要添加任务的函数,不要带参数
        trigger=trigger,  # 触发器
        args=(rss,),  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
        id=rss.name,
        misfire_grace_time=30,  # 允许的误差时间,建议不要省略
        max_instances=1,  # 最大并发
        default=ThreadPoolExecutor(64),  # 最大线程
        processpool=ProcessPoolExecutor(8),  # 最大进程
        coalesce=True,  # 积攒的任务是否只跑一次,是否合并所有错过的Job
    )
    logger.info(f"定时任务 {rss.name} 添加成功")
示例#5
0
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))
    # 超过30天的时间
    elif time - now > timedelta(days=30):
        session.finish(render_expression(EXPR_TOO_LONG))

    # 添加job
    time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    scheduler.add_job(  # type: ignore
        remind,
        "date",
        run_date=time,
        args=[target, session.event])
    session.finish(
        render_expression(
            EXPR_OK, time=time_str, action=target, escape_args=False) +
        f"\n提醒创建成功:\n"
        f"> 提醒时间:{time_str}\n"
        f"> 内容:{target}")
示例#6
0
文件: Chat.py 项目: mnixry/ATRI
async def _(session: CommandSession):
    global noobList0
    user = session.event.user_id
    group = session.event.group_id
    try:
        with open(
                Path('.') / 'ATRI' / 'plugins' / 'noobList' / 'noobGroup.json',
                'r') as f:
            data = json.load(f)
    except:
        data = {}
    try:
        with open(
                Path('.') / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json',
                'r') as f:
            data1 = json.load(f)
    except:
        data1 = {}

    if str(group) in data.keys():
        pass
    else:
        if str(user) in data1.keys():
            pass
        else:
            if 0 <= now_time() < 5.5:
                pass
            else:
                bL = {}
                await session.send('萝卜子是对机器人的蔑称!')
                noobList0.append(user)
                if countX(noobList0, user) == 2:
                    if user == master:
                        await session.send(
                            '是主人的话...那算了...呜呜\n即使到达了ATRI的最低忍耐限度......')
                        noobList0 = list(set(noobList0))
                        pass
                    await session.send(
                        '是亚托莉......萝卜子可是对机器人的蔑称......\n这是第二次警告哦,接下来5分钟我不会再理你了!哼唧!'
                    )
                    bL[f"{user}"] = f"{user}"
                    file = Path(
                        '.'
                    ) / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json'
                    f = open(file, 'w')
                    f.write(json.dumps(bL))
                    f.close()
                    noobList0 = list(set(noobList0))
                    print(noobList0)
                    delta = timedelta(minutes=5)
                    trigger = DateTrigger(run_date=datetime.now() + delta)

                    scheduler.add_job(  #type: ignore
                        func=rmQQfromNoobLIST,
                        trigger=trigger,
                        args=(user),
                        misfire_grace_time=60,
                    )
示例#7
0
async def free_group(session: CommandSession):
    number_of_group = function.plugins.report.number_of_group()
    your_qq_num = function.plugins.report.your_qq_num()
    message_type = session.ctx['message_type']
    user_id = session.ctx['user_id']
    if function.plugins.report.check_default():
        if message_type == 'private' and user_id == int(your_qq_num[0]):

            duration = str(
                session.get(
                    'duration',
                    prompt='什么时候解除禁言呀?例如7-45',
                    arg_filters=[controllers.handle_cancellation(session)]))

            duration = duration.split('-')

            if not duration[0].isdigit() and not duration[1].isdigit():
                await session.pause('时间应该是数字,例如:7,8,9')

            notice_of_free = session.get(
                'notice_of_free',
                prompt='解除禁言后你想通知什么内容?',
                arg_filters=[controllers.handle_cancellation(session)])

            notice_of_free += '[CQ:at,qq=all]'
            await session.send('定时解除设置成功')

            duration_hours = int(duration[0]) - int(
                time.strftime("%H", time.localtime()))
            duration_mins = int(duration[1]) - int(
                time.strftime("%M", time.localtime()))

            #触发器
            delta = datetime.timedelta(minutes=(duration_mins +
                                                duration_hours * 60))
            trigger = DateTrigger(run_date=datetime.datetime.now() + delta)

            for i in range(len(number_of_group)):
                #添加任务
                scheduler.add_job(
                    func=session.bot.send_group_msg,
                    trigger=trigger,
                    kwargs={
                        'group_id': int(number_of_group[i]),
                        'message': notice_of_free
                    },
                    misfire_grace_time=60,
                )

                scheduler.add_job(func=session.bot.set_group_whole_ban,
                                  trigger=trigger,
                                  kwargs={
                                      'group_id': int(number_of_group[i]),
                                      'enable': False
                                  })
    else:
        await session.send('请先初始化')
示例#8
0
 def enable(self):
     """ 开启新闻自动推送 """
     logger.info('初始化 最终幻想XIV 新闻推送')
     # 开启后先运行一次
     scheduler.add_job(self.push_news,
                       'date',
                       run_date=(datetime.now() + timedelta(seconds=30)))
     self._job = scheduler.add_job(self.push_news,
                                   'interval',
                                   minutes=self.interval)
     self._data.set_config('ff14', 'push_news', '1')
示例#9
0
def rss_trigger(times: int, rss: RSS_class.rss):
    # 制作一个“time分钟/次”触发器
    trigger = IntervalTrigger(minutes=times, jitter=10)
    # 添加任务
    scheduler.add_job(
        func=check_update,  # 要添加任务的函数,不要带参数
        trigger=trigger,  # 触发器
        args=(rss, ),  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
        id=rss.name,
        # kwargs=None,
        misfire_grace_time=60,  # 允许的误差时间,建议不要省略
        # jobstore='default',  # 任务储存库,在下一小节中说明
    )
示例#10
0
文件: Chat0.py 项目: synodriver/ATRI
async def _(session: CommandSession):
    global noobList1
    user = session.event.user_id
    group = session.event.group_id
    if checkNoob(user, group):
        if 0 <= now_time() < 5.5:
            pass
        else:
            msg = str(session.event.message)
            try:
                with open(
                        Path('.') / 'ATRI' / 'plugins' / 'noobList' /
                        'noobList.json', 'r') as f:
                    bL = json.load(f)
            except:
                bL = {}
            pattern = r"[nNηиɴИ][tT][rR]|[牛🐂🐮]头人"
            if re.findall(pattern, msg):
                noobList1.append(user)
                if countX(noobList1, user) == 5:
                    if user == master:
                        await session.send(
                            '是主人的话...那算了...呜呜\n即使到达了ATRI的最低忍耐限度......')
                        noobList1 = list(set(noobList1))
                        pass

                    else:
                        await session.send(
                            f'[CQ:at,qq={user}]哼!接下来30分钟别想让我理你!\n(好感度-2)')
                        DelFavoIMP(user, 2, False)
                        bL[f"{user}"] = f"{user}"
                        file = Path(
                            '.'
                        ) / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json'
                        f = open(file, 'w')
                        f.write(json.dumps(bL))
                        f.close()
                        noobList1 = list(set(noobList1))
                        print(noobList1)
                        delta = timedelta(minutes=30)
                        trigger = DateTrigger(run_date=datetime.now() + delta)

                        scheduler.add_job(  #type: ignore
                            func=rmQQfromNoobLIST,
                            trigger=trigger,
                            args=(session.event.user_id, ),
                            misfire_grace_time=60,
                        )

                else:
                    await session.send('你妈的,牛头人,' + request_api(KC_URL))
示例#11
0
async def clock(session: CommandSession):

    if not session.state["valid_cmd"]:
        await session.send("闹钟指令格式有误~例如设置8小时12分3秒后的闹钟,内容为'起床',命令格式为:%s" %
                           (clock_sample))
        return

    if session.event.group_id:
        await session.send("闹钟设置失败~该功能只能通过私聊使用噢~")
        return

    try:
        # 获取时间,生成提示文本
        time_delta_str = ""
        hour = int(session.state["hour"])
        time_delta_str += "%d小时" % (hour)
        if session.state["minute"]:
            minute = int(session.state["minute"])
            time_delta_str += "%d分" % (minute)
        else:
            minute = 0
        if session.state["second"]:
            second = int(session.state["second"])
            time_delta_str += "%d秒" % (second)
        else:
            second = 0

        output_str = "喵喵喵~你%s前设置的闹钟响啦~" % (time_delta_str)

        if session.state["text"]:
            text = session.state["text"]
            output_str += "内容为'%s'" % (text)

        # 创建触发器
        delta = datetime.timedelta(hours=hour, minutes=minute, seconds=second)
        trigger = DateTrigger(run_date=datetime.datetime.now() + delta)

        # 添加任务
        scheduler.add_job(
            func=session.send,  # 要添加任务的函数,不要带参数
            trigger=trigger,  # 触发器
            args=(output_str, ),  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
            # kwargs=None,
            misfire_grace_time=60,  # 允许的误差时间,建议不要省略
            # jobstore='default',  # 任务储存库
        )

        await session.send('收到~凯露酱会在%s后提醒你~' % (time_delta_str))
    except Exception as e:
        await session.send("遇到了奇怪的错误...请检查输入格式再试一次,或联系管理员")
示例#12
0
async def rss_trigger(hash_str: str, group_ids: list, name: str):
    # 制作一个“time分钟/次”触发器
    trigger = IntervalTrigger(seconds=int(config.down_status_msg_date), jitter=10)
    job_defaults = {"max_instances": 1}
    # 添加任务
    scheduler.add_job(
        func=check_down_status,  # 要添加任务的函数,不要带参数
        trigger=trigger,  # 触发器
        args=(hash_str, group_ids, name),  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
        id=hash_str,
        misfire_grace_time=60,  # 允许的误差时间,建议不要省略
        job_defaults=job_defaults,
    )
    await send_msg(f"👏 {name}\nHash: {hash_str} \n下载任务添加成功!")
示例#13
0
async def _(session: CommandSession):
    global noobList
    user = session.event.user_id
    with open('ATRI/plugins/noobList/noobList.json', 'r') as f:
        data = json.load(f)

    if str(user) in data.keys():
        pass
    else:
        if 0 <= now_time() < 5.5:
            pass
        else:
            msg = str(session.event.message)
            bL = {}
            pattern = r"[nNηиɴИ][tT][rR]|[牛🐂]头人"
            if re.findall(pattern, msg):
                await session.send('你妈的,牛头人,' + response.request_api(KC_URL))
                noobList.append(user)
                print(noobList)
                print(countX(noobList, user))
                if countX(noobList, user) == 5:
                    if user == master:
                        await session.send('是主人的话...那算了...呜呜\n即使到达了ATRI的最低忍耐限度......')
                        noobList = list(set(noobList))
                        pass

                    else:
                        await session.send(f'[CQ:at,qq={user}]哼!接下来10分钟别想让我理你!')
                        bL[f"{user}"] = f"{user}"
                        file = Path('.') / 'ATRI' / 'plugins' / 'noobList' / 'noobList.json'
                        f = open(file, 'w')
                        f.write(json.dumps(bL))
                        f.close()
                        noobList = list(set(noobList))
                        print(noobList)
                        delta = timedelta(minutes = 10)
                        trigger = DateTrigger(
                            run_date = datetime.now() + delta
                        )

                        scheduler.add_job( #type: ignore
                            func = rmQQfromNoobLIST,
                            trigger = trigger,
                            args = (user),
                            misfire_grace_time = 60,
                        )

                else:
                    pass
示例#14
0
async def group_increase(session: NoticeSession):
    # 发送欢迎消息
    grpid = repr(session.ctx['group_id'])
    welcome = db.getvar('welcome_' + grpid)
    warning = db.getvar('warning_' + grpid)
    await session.send(welcome)
    await session.send(warning)
    if grpid == '667556362':
        scheduler.add_job(kick25boy,
                          'date',
                          run_date=datetime.datetime.now() +
                          datetime.timedelta(minutes=360),
                          args=[str(session.ctx['user_id'])],
                          id=str(session.ctx['user_id']),
                          replace_existing=True)
示例#15
0
async def _(session: CommandSession):
    res = requests.get("https://api.lolicon.app/setu/?r18=0&apikey=" + apikey)
    json_str = json.loads(res.text)
    if json_str['code'] == 401:
        await session.send("API接口超过调用限制(每令牌每天限制300)或API令牌被封禁")
        return
    url = json_str['data'][0]['url']
    author = json_str['data'][0]['author']
    pid = json_str['data'][0]['pid']
    title = json_str['data'][0]['title']
    await _bot.send(
        session.event, "图片信息:\n"
        "作者:" + str(author) + "\n图片PID:" + str(pid) + "\n图片标题:" + str(title) +
        "\n注意:图片将在二十秒后撤回")
    scheduler.add_job(task, args=[session.event, url])
示例#16
0
def delcache_trigger():
    # 制作一个“time分钟/次”触发器
    trigger = IntervalTrigger(
        days=config.DELCACHE,
        #minutes=1,
        jitter=10)
    # 添加任务
    scheduler.add_job(
        func=del_img,  # 要添加任务的函数,不要带参数
        trigger=trigger,  # 触发器
        args=(1, ),  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
        id='DELCACHE',
        # kwargs=None,
        misfire_grace_time=60,  # 允许的误差时间,建议不要省略
        # jobstore='default',  # 任务储存库,在下一小节中说明
    )
示例#17
0
async def wcr_horserace(session: CommandSession):
    hr = HorseRace()
    state = await hr.race_state()
    if state == -1:
        response = "wcr赛马现在接受报名!报名时间为1分钟!参赛上限为4人!\n报名方法为输入【出马 角色名】(e.g. 出马 毛二力)\n角色只能选择在wcr抽卡中获得的3星角色\n输入【wcr查看】可以看自己拥有哪些角色"
        await hr.set_state(0)
        delta = datetime.timedelta(seconds=60)
        trigger = DateTrigger(run_date=datetime.datetime.now() + delta)
        scheduler.add_job(
            func=end_join,
            trigger=trigger,
            args=(session.ctx['group_id'], ),
            misfire_grace_time=60,
        )
    else:
        response = "已有正在进行的赛马!"
    await session.send(response)
示例#18
0
def add_delay_job(task, id=None, delay_time: int = 30, args=[]):
    now = datetime.datetime.now()
    job = scheduler.add_job(task,
                            'date',
                            id=id,
                            run_date=now +
                            datetime.timedelta(seconds=delay_time),
                            misfire_grace_time=5,
                            args=args)
    return job
示例#19
0
def rss_trigger(rss: rss_class.Rss):
    if re.search(r"[_*/,-]", rss.time):
        my_trigger_cron(rss)
        return
    # 制作一个“time分钟/次”触发器
    trigger = IntervalTrigger(minutes=int(rss.time), jitter=10)
    # 添加任务
    scheduler.add_job(
        func=check_update,  # 要添加任务的函数,不要带参数
        trigger=trigger,  # 触发器
        args=(rss,),  # 函数的参数列表,注意:只有一个值时,不能省略末尾的逗号
        id=rss.name,
        misfire_grace_time=30,  # 允许的误差时间,建议不要省略
        max_instances=1,  # 最大并发
        default=ThreadPoolExecutor(64),  # 最大线程
        processpool=ProcessPoolExecutor(8),  # 最大进程
        coalesce=True,  # 积攒的任务是否只跑一次,是否合并所有错过的Job
    )
    logger.info(f"定时任务 {rss.name} 添加成功")
示例#20
0
async def todo_add(session: CommandSession):
    seconds = session.get('seconds')  # unit: s
    something = session.get('something')
    o_time = session.get('o_time')

    user_id = session.ctx.get('user_id')

    delta = datetime.timedelta(seconds=seconds)

    trigger = DateTrigger(run_date=datetime.datetime.now() + delta)

    something = MessageSegment.at(user_id) + ' ' + something

    scheduler.add_job(func=session.send,
                      trigger=trigger,
                      args=(something, ),
                      misfire_grace_time=60)

    await session.send(f'好的,我会在{o_time}提醒你{something}')
示例#21
0
async def set_close_setu_time(session):
    match = re.match(r'^(\d+):(\d+)', session.current_arg)
    if not match:
        return
    hour = int(match.group(1))
    minute = int(match.group(2))
    if hour < 0 or hour > 23 or minute < 0 or minute > 59:
        await session.send(message.MessageSegment.text('输入错误'))
        return
    global setu_scheduled_close
    global setu_scheduled_close_time
    setu_scheduled_close_time = (hour, minute)
    if setu_scheduled_close != None:
        scheduler.remove_job(setu_scheduled_close)
        setu_scheduled_close = None

    scheduler.add_job(close_setu_scheduled, 'cron', hour = hour, minute = minute, id = 'setu_close')
    setu_scheduled_close = 'setu_close'
    await session.send(message.MessageSegment.text('设置成功,当前涩图每日关闭时间为:{}:{}'.format(str(hour).zfill(2), str(minute).zfill(2))))
示例#22
0
def add_cron_job(task, id=None, hour='*', minute='0', second='0', args=[]):
    job = scheduler.add_job(task,
                            'cron',
                            id=id,
                            hour=hour,
                            minute=minute,
                            second=second,
                            misfire_grace_time=5,
                            args=args)
    return job
示例#23
0
async def set_open_crawl_score_line(session):
    match = re.match(r'^(\d+):(\d+)', session.current_arg)
    if not match:
        return
    hour = int(match.group(1))
    minute = int(match.group(2))
    global Crawl_Score_Lines
    if Crawl_Score_Lines != None:
        scheduler.remove_job(Crawl_Score_Lines)
        Crawl_Score_Lines = None
    scheduler.add_job(write_down_score_line_scheduled,
                      'cron',
                      hour=hour,
                      minute=minute,
                      id='crawl_score_lines_open')
    Crawl_Score_Lines = 'crawl_score_lines_open'
    await session.send(
        message.MessageSegment.text('每日{}:{}会自动爬取数据'.format(
            str(hour).zfill(2),
            str(minute).zfill(2))))
示例#24
0
async def _():
    bot = nonebot.get_bot()
    now = datetime.now(pytz.timezone('Asia/Shanghai'))
    if now.hour >= 1 and now.hour <= 7:
        return None
    global _can_auto_check
    if not _can_auto_check:
        return None
    check_list = get_random_list()
    try:
        await bot.send_group_msg(group_id= 【数据删除】,
                                 message='抽查 '+ check_list[0])
        delta = timedelta(seconds=60)
        trigger = DateTrigger(
            run_date=datetime.now() + delta
        )
        scheduler.add_job(
            func=bot.send_group_msg, 
            trigger=trigger,
            kwargs= {'group_id': 【数据删除】, 'message': check_list[0] + ":" + check_list[1]},
            misfire_grace_time=60, 
        )    
    except CQHttpError:
        pass
示例#25
0
async def random_check_function(session: CommandSession):
    global _can_random_check
    arg = session.current_arg_text.strip().lower()
    if arg:
        return None
    if not _can_random_check:
        await session.send(
            '无法抽查菜鸡已经挂科的科目。')
        return
    check_list = get_random_list()
    try:
        await session.send('抽查 '+ check_list[0])
        delta = timedelta(seconds=60)
        trigger = DateTrigger(
            run_date=datetime.now() + delta
        )        
        scheduler.add_job(
            func=session.send,  
            trigger=trigger,  
            args=(check_list[0] + ":" + check_list[1],),  
            misfire_grace_time=60,  
        )    
    except CQHttpError:
        pass
示例#26
0
async def actual_guess(bot, ev: CQEvent):
    if gm.is_playing(ev.group_id):
        await bot.finish(ev, "游戏仍在进行中…")
    if not os.path.exists(DIR_PATH) or len(
            os.listdir(DIR_PATH)) < DOWNLOAD_THRESHOLD:
        await download_actual_photo(bot, ev)
        return
    # with gm.start_game(ev.group_id) as game:
    game = gm.start_game(ev.group_id)
    file_list = os.listdir(DIR_PATH)
    chosen_chara = random.choice(file_list)
    await bot.send(ev, f'猜猜这张图片是哪个角色? ({ONE_TURN_TIME}s后公布答案)')
    await bot.send(ev, R.img(f'priconne/unit/actual/{chosen_chara}').cqcode)
    game.answer = int(chosen_chara[0:4])
    game.set_schedule(
        scheduler.add_job(check,
                          'date',
                          args=(
                              bot,
                              ev,
                          ),
                          next_run_time=datetime.datetime.now() +
                          datetime.timedelta(seconds=ONE_TURN_TIME)))
示例#27
0
    reply = await bot.proc_async(ctx)
    if reply != "" and reply is not None:
        session.finish(reply)


async def send_it(func):
    if asyncio.iscoroutinefunction(func):
        to_sends = await func()
    else:
        to_sends = func()
    if to_sends is None:
        return
    tasks = [cqbot.send_msg(**kwargs) for kwargs in to_sends]
    await asyncio.gather(*tasks)


jobs = bot.active_jobs()
if jobs:
    for trigger, job in jobs:
        scheduler.add_job(
            func=send_it,
            args=(job, ),
            trigger=trigger,
            coalesce=True,
            max_instances=1,
            misfire_grace_time=60,
        )

__plugin_name__ = 'pcr'
__plugin_usage__ = 'pcr assistant'
示例#28
0
 def enable(self):
     self._job = scheduler.add_job(
         self.monitor_server_status, 'interval', seconds=self.interval
     )
     self._data.set_config('ff14', 'monitor_server_status', '1')
示例#29
0
async def start_game(group_id):
    bot = nonebot.get_bot()
    hr = HorseRace()
    state = await hr.race_state()
    current_round = state
    response = "行动阶段#%s\n" % current_round
    horse_list = await hr.search_horse()
    for horse in horse_list:
        move = await hr.move_horse(horse[0])
        if move > 0:
            response += "%s的%s向前冲了%s步!\n" % (await get_nick_name(
                group_id, horse[2]), horse[1], move)
        else:
            response += "%s的%s摸鱼了!\n" % (await get_nick_name(
                group_id, horse[2]), horse[1])
    response += "战斗阶段\n"
    r = random.randint(1, 8)
    if r <= 3:
        response += "上帝鸽了\n"
    else:
        response += await hr.god_attack(group_id)
    ub_list = await hr.search_sorted_horse_ascend()
    for horse in ub_list:
        if horse[4] >= 100:
            response += await hr.ub(horse, group_id)
    response += "最终状态\n"
    horse_list = await hr.search_horse()
    champ_list = list()
    for horse in horse_list:
        if horse[1] in HORSE_SKIN.keys():
            skin = HORSE_SKIN[horse[1]]
        else:
            skin = HORSE
        horse_line = "[CQ:emoji,id=%s]:" % (10000048 + horse[0]) + "=" * (
            horse[3] - 1) + skin + "=" * (10 - horse[3]) + "\n"
        response += horse_line
        if horse[3] == 10:
            champ_list.append(horse)
    await bot.send_group_msg(group_id=group_id, message=response)
    if len(champ_list) > 0:
        response = "赛马结束了!恭喜\n"
        for horse in champ_list:
            response += "%s的%s\n" % (await get_nick_name(group_id,
                                                         horse[2]), horse[1])
            await hr.add_winner(horse[1])
        response += "获得了冠军!"
        for horse in horse_list:
            await hr.add_race(horse[1])
        await bot.send_group_msg(group_id=group_id, message=response)
        await resolve_gamble(group_id, champ_list)
        await hr.end_race()
    else:
        await hr.set_state(current_round + 1)
        delta = datetime.timedelta(seconds=10)
        trigger = DateTrigger(run_date=datetime.datetime.now() + delta)
        scheduler.add_job(
            func=start_game,
            trigger=trigger,
            args=(group_id, ),
            misfire_grace_time=60,
        )
示例#30
0
def add_date_job(task, id=None, run_date=None, args=[]):
    job = scheduler.add_job(task, 'date', id=id, run_date=run_date, args=args)
    return job