Python arrow 模块,utcnow() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用arrow.utcnow()

项目:nameko-amqp-retry    作者:nameko    | 项目源码 | 文件源码
def test_event(self, container_factory, rabbit_config):

        from examples.retry import Service

        container = container_factory(Service, rabbit_config)
        container.start()

        timestamp = arrow.utcnow().replace(seconds=+1)

        dispatch = event_dispatcher(rabbit_config)
        with entrypoint_waiter(
            container, 'handle_event', callback=wait_for_result
        ) as result:
            payload = {'timestamp': timestamp.isoformat()}
            dispatch("src_service", "event_type", payload)

        res = result.get()
        assert arrow.get(re.match("Time is (.+)", res).group(1)) >= timestamp
项目:nameko-amqp-retry    作者:nameko    | 项目源码 | 文件源码
def test_message(self, container_factory, rabbit_config):

        from examples.retry import Service

        container = container_factory(Service, rabbit_config)
        container.start()

        timestamp = arrow.utcnow().replace(seconds=+1)

        publish = publisher(rabbit_config)
        with entrypoint_waiter(
            container, 'handle_message', callback=wait_for_result
        ) as result:
            payload = {'timestamp': timestamp.isoformat()}
            publish(payload, routing_key="messages")

        res = result.get()
        assert arrow.get(re.match("Time is (.+)", res).group(1)) >= timestamp
项目:donatemates    作者:donatemates    | 项目源码 | 文件源码
def test_delete_item(self):
        """Method to test receipt index"""
        campaign_table = DynamoTable('campaigns')

        # Add a record
        data = {"campaign_id": "my_campaign",
                "notified_on": arrow.utcnow().isoformat(),
                "campaign_status": "active"
                }
        campaign_table.put_item(data)

        # Verify write
        key = {"campaign_id": "my_campaign"}
        item = campaign_table.get_item(key)
        assert item is not None
        self.assertEqual(item["campaign_status"], "active")

        # Delete
        campaign_table.delete_item(key)

        # Verify it deleted
        item = campaign_table.get_item(key)
        assert item is None
项目:donatemates    作者:donatemates    | 项目源码 | 文件源码
def test_scan_table(self):
        """Method to test scanning a table"""

        def scan_func(items, input_val):
            for item in items:
                if item["campaign_status"]["S"] == "complete":
                    input_val['count'] += 1
            return input_val

        campaign_table = DynamoTable('campaigns')

        # Add a record
        for idx in range(0, 10):
            data = {"campaign_id": "my_campaign_{}".format(idx),
                    "notified_on": arrow.utcnow().isoformat(),
                    "campaign_status": "complete"
                    }
            campaign_table.put_item(data)

        # Scan table
        result = {"count": 0}
        campaign_table.scan_table(scan_func, result, "campaign_status")

        self.assertEqual(result["count"], 10)
项目:jarvis    作者:anqxyr    | 项目源码 | 文件源码
def send(bot, text, private=False, notice=False):
    """Send irc message."""
    text = str(text)
    tr = bot._trigger
    jarvis.db.Message.create(
        user=bot.config.core.nick,
        channel=tr.sender,
        time=arrow.utcnow().timestamp,
        text=text)
    mode = 'NOTICE' if notice else 'PRIVMSG'
    recipient = tr.nick if private or notice else tr.sender
    try:
        bot.sending.acquire()
        text = textwrap.wrap(text, width=420)[0]
        bot.write((mode, recipient), text)
    finally:
        bot.sending.release()
项目:jarvis    作者:anqxyr    | 项目源码 | 文件源码
def masstell(inp, *, names, separator, text, users, message):
    """Send a single message to several users."""
    if (names and users) or (text and message):
        return lex.masstell.arg_conflict
    names, text = names or users, text or message
    if not names or not text:
        return lex.masstell.missing_args

    time = arrow.utcnow().timestamp
    db.Tell.insert_many([dict(
        recipient=user,
        sender=inp.user,
        text=text,
        time=time,
        topic=None) for user in set(names)]).execute()
    return lex.tell.send
项目:csirtg-smrt-py    作者:csirtgadgets    | 项目源码 | 文件源码
def clean_indicator(self, i, rule):
        # check for de-fang'd feed
        if rule.replace:
            for e in i:
                if not rule.replace.get(e):
                    continue

                for k, v in rule.replace[e].items():
                    i[e] = i[e].replace(k, v)

        i = normalize_itype(i)

        if isinstance(i, dict):
            i = Indicator(**i)

        if not i.firsttime:
            i.firsttime = i.lasttime

        if not i.reporttime:
            i.reporttime = arrow.utcnow().datetime

        if not i.group:
            i.group = 'everyone'

        return i
项目:cloudwatch-fluent-metrics    作者:awslabs    | 项目源码 | 文件源码
def test_can_add_multiple_timers():
    name1 = 'test_timer_1'
    name2 = 'test_timer_2'
    m = FluentMetric()
    m.with_timer(name1)
    time.sleep(1)
    t = m.get_timer(name1)
    assert t.start < arrow.utcnow()
    assert t.elapsed_in_ms() > 1000 and t.elapsed_in_ms() < 2000

    m.with_timer(name2)
    time.sleep(1)
    u = m.get_timer(name2)
    assert u.start < arrow.utcnow()
    assert u.elapsed_in_ms() > 1000 and u.elapsed_in_ms() < 2000
    assert t.elapsed_in_ms() > 2000
项目:scriptworker    作者:mozilla-releng    | 项目源码 | 文件源码
def main():
    """Scriptworker entry point: get everything set up, then enter the main loop."""
    context, credentials = get_context_from_cmdln(sys.argv[1:])
    log.info("Scriptworker starting up at {} UTC".format(arrow.utcnow().format()))
    cleanup(context)
    conn = aiohttp.TCPConnector(limit=context.config['aiohttp_max_connections'])
    loop = asyncio.get_event_loop()
    with aiohttp.ClientSession(connector=conn) as session:
        context.session = session
        context.credentials = credentials
        while True:
            try:
                loop.run_until_complete(async_main(context))
            except Exception:
                log.critical("Fatal exception", exc_info=1)
                raise
项目:scriptworker    作者:mozilla-releng    | 项目源码 | 文件源码
def test_create_artifact(context, fake_session, successful_queue, event_loop):
    path = os.path.join(context.config['artifact_dir'], "one.txt")
    touch(path)
    context.session = fake_session
    expires = arrow.utcnow().isoformat()
    context.temp_queue = successful_queue
    event_loop.run_until_complete(
        create_artifact(context, path, "public/env/one.txt", content_type='text/plain', content_encoding=None, expires=expires)
    )
    assert successful_queue.info == [
        "createArtifact", ('taskId', 'runId', "public/env/one.txt", {
            "storageType": "s3",
            "expires": expires,
            "contentType": "text/plain",
        }), {}
    ]

    # TODO: Assert the content of the PUT request is valid. This can easily be done once MagicMock supports async
    # context managers. See http://bugs.python.org/issue26467 and https://github.com/Martiusweb/asynctest/issues/29.
    context.session.close()
项目:scriptworker    作者:mozilla-releng    | 项目源码 | 文件源码
def test_create_second_gpg_conf(mocker, tmpdir):
    now = arrow.utcnow()
    with mock.patch.object(arrow, 'utcnow') as p:
        p.return_value = now
        sgpg.create_gpg_conf(
            tmpdir, keyserver=GPG_CONF_PARAMS[0][0], my_fingerprint=GPG_CONF_PARAMS[0][1]
        )
        sgpg.create_gpg_conf(
            tmpdir, keyserver=GPG_CONF_PARAMS[1][0], my_fingerprint=GPG_CONF_PARAMS[1][1]
        )
        with open(os.path.join(tmpdir, "gpg.conf"), "r") as fh:
            assert fh.read() == GPG_CONF_PARAMS[1][2]
        with open(os.path.join(tmpdir, "gpg.conf.{}".format(now.timestamp)), "r") as fh:
            assert fh.read() == GPG_CONF_PARAMS[0][2]


# generate_key {{{1
项目:homingbot    作者:homingbot    | 项目源码 | 文件源码
def process_message(self, mailfrom, rcpttos, data):
        email = None
        messages = []
        emails = []
        splitted = data.split("\r\n", 1)
        subject = splitted[0] if (len(splitted) > 0) else ""
        body = splitted[1] if (len(splitted) > 1) else ""
        try:
            for recipient in rcpttos:
                num_emails = 0
                res = db_service.custom_query(COUNT_QUERY_TEMPLATE.format(recipient['address'])) #TODO async
                if (res is not None and len(res.current_rows) > 0):
                    num_emails = res.current_rows[0]['system.count(address)']
                msg = Message(address=recipient['address'], message_index=num_emails, body=data, size=len(data), sender=mailfrom, created=arrow.utcnow().datetime)
                messages.append(msg)
            db_service.batch_save(messages, ttl=recipient['ttl(created)']) # Save with the ttl of the email account
        except Exception as e:
            logger.error(e)
            return STATUS_ERROR
        return STATUS_OK
项目:science-gateway-middleware    作者:alan-turing-institute    | 项目源码 | 文件源码
def post(self):
        job_json = request.json
        if job_json is None:
            abort(400, message="Message body could not be parsed as JSON")
        # Try parsing Job JSON to Job object
        try:
            job = json_to_job(job_json)
        except:
            abort(400, message="Message body is not valid Job JSON")
        if self.jobs.exists(job.id):
            abort(409, message="Job with ID {} already "
                               "exists".format(job.id))
        else:
            # Set certain job properties when first persisted
            job.creation_datetime = arrow.utcnow()
            job.status = "Draft"
            job = self.jobs.create(job)
            return job_to_json(job), 200, {'Content-Type': 'application/json'}
项目:freqtrade    作者:gcarq    | 项目源码 | 文件源码
def buy(pair: str, rate: float, amount: float) -> str:
    if _CONF['dry_run']:
        global _DRY_RUN_OPEN_ORDERS
        order_id = 'dry_run_buy_{}'.format(randint(0, 10**6))
        _DRY_RUN_OPEN_ORDERS[order_id] = {
            'pair': pair,
            'rate': rate,
            'amount': amount,
            'type': 'LIMIT_BUY',
            'remaining': 0.0,
            'opened': arrow.utcnow().datetime,
            'closed': arrow.utcnow().datetime,
        }
        return order_id

    return _API.buy(pair, rate, amount)
项目:freqtrade    作者:gcarq    | 项目源码 | 文件源码
def sell(pair: str, rate: float, amount: float) -> str:
    if _CONF['dry_run']:
        global _DRY_RUN_OPEN_ORDERS
        order_id = 'dry_run_sell_{}'.format(randint(0, 10**6))
        _DRY_RUN_OPEN_ORDERS[order_id] = {
            'pair': pair,
            'rate': rate,
            'amount': amount,
            'type': 'LIMIT_SELL',
            'remaining': 0.0,
            'opened': arrow.utcnow().datetime,
            'closed': arrow.utcnow().datetime,
        }
        return order_id

    return _API.sell(pair, rate, amount)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def on_cooldown(self, cmd, user):
        if isinstance(user, str):
            cd_name = f'cd_{cmd}_{user}'
        else:
            cd_name = f'cd_{cmd}_{user.id}'
        entry = self.cache.get_cache(cd_name)
        if entry is None:
            entry = await self.cds.find_one({'name': cd_name})
        if entry:
            end_stamp = entry['end_stamp']
            now_stamp = arrow.utcnow().timestamp
            if now_stamp > end_stamp:
                cooldown = False
            else:
                cooldown = True
        else:
            cooldown = False
        return cooldown
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def set_cooldown(self, cmd, user, amount):
        if isinstance(user, str):
            cd_name = f'cd_{cmd}_{user}'
        else:
            cd_name = f'cd_{cmd}_{user.id}'
        entry = self.cache.get_cache(cd_name)
        if entry:
            self.cache.del_cache(cd_name)
        else:
            entry = await self.cds.find_one({'name': cd_name})
        end_stamp = arrow.utcnow().timestamp + amount
        if entry:
            await self.cds.update_one({'name': cd_name}, {'$set': {'end_stamp': end_stamp}})
        else:
            cd_data = {
                'name': cd_name,
                'end_stamp': end_stamp
            }
            await self.cds.insert_one(cd_data)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def add_cmd_stat(db, cmd, message, args):
    if not message.author.bot:
        if message.guild:
            channel_id = message.channel.id
            guild_id = message.guild.id
        else:
            channel_id = None
            guild_id = None
        stat_data = {
            'command': cmd.name,
            'args': args,
            'author': message.author.id,
            'channel': channel_id,
            'guild': guild_id,
            'timestamp': {
                'created': arrow.get(message.created_at).float_timestamp,
                'executed': arrow.utcnow().float_timestamp
            }
        }
        await db[db.db_cfg.database]['CommandStats'].insert_one(stat_data)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def wfalerts(cmd, message, args):
    alert_url = 'https://deathsnacks.com/wf/data/alerts_raw.txt'
    async with aiohttp.ClientSession() as session:
        async with session.get(alert_url) as data:
            alert_data = await data.text()
    alert_list = parse_alert_data(alert_data)
    response = discord.Embed(color=0xFFCC66)
    response.set_author(name='Currently Ongoing Alerts')
    for alert in alert_list:
        alert_desc = f'Levels: {alert["levels"]["low"]} - {alert["levels"]["high"]}'
        alert_desc += f'\nLocation: {alert["node"]} ({alert["planet"]})'
        alert_desc += f'\nReward: {alert["rewards"]["credits"]}cr'
        time_left = alert['stamps']['end'] - arrow.utcnow().timestamp
        death_time = str(datetime.timedelta(seconds=time_left))
        if alert['rewards']['item']:
            alert_desc += f'\nItem: **{alert["rewards"]["item"]}**'
        alert_desc += f'\nDisappears In: {death_time}'
        response.add_field(name=f'Type: {alert["faction"]} {alert["type"]}', value=f'{alert_desc}', inline=False)
        response.set_thumbnail(url='https://i.imgur.com/99ennZD.png')
        response.set_footer(text='Timers are not updated live.')
    await message.channel.send(embed=response)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def server_data_fill(ev):
    global finished
    if ev.bot.guilds:
        ev.log.info('Filling server details...')
        start_stamp = arrow.utcnow().float_timestamp
        srv_coll = ev.db[ev.db.db_cfg.database].ServerDetails
        await srv_coll.drop()
        server_list = []
        for guild in ev.bot.guilds:
            srv_data = await generate_server_data(guild)
            server_list.append(srv_data)
            if len(server_list) >= 1000:
                await srv_coll.insert_many(server_list)
                server_list = []
                await asyncio.sleep(0.5)
        if server_list:
            await srv_coll.insert_many(server_list)
        end_stamp = arrow.utcnow().float_timestamp
        diff = round(end_stamp - start_stamp, 3)
        finished = True
        ev.log.info(f'Server detail filler finished in {diff}s')
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def generate_log_embed(message, target, channel, deleted):
    response = discord.Embed(color=0x696969, timestamp=arrow.utcnow().datetime)
    response.set_author(name=f'#{channel.name} Has Been Pruned', icon_url=user_avatar(message.author))
    if target:
        target_text = f'{target.mention}\n{target.name}#{target.discriminator}'
    else:
        target_text = 'No Filter'
    response.add_field(name='?? Prune Details',
                       value=f'Amount: {len(deleted)} Messages\nTarget: {target_text}', inline=True)
    author = message.author
    response.add_field(name='?? Responsible',
                       value=f'{author.mention}\n{author.name}#{author.discriminator}',
                       inline=True)
    response.set_footer(text=f'ChannelID: {channel.id}')
    return response


# noinspection PyBroadException
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def statistics(cmd, message, args):
    sigma_image = 'https://i.imgur.com/mGyqMe1.png'
    sigma_title = 'Apex Sigma: Statistics'
    support_url = 'https://discordapp.com/invite/aEUCHwX'
    role_count = 0
    for guild in cmd.bot.guilds:
        role_count += len(guild.roles)
    time_dif = arrow.utcnow().timestamp - cmd.bot.start_time.timestamp
    command_rate = str(cmd.bot.command_count / time_dif)[:5]
    message_rate = str(cmd.bot.message_count / time_dif)[:5]
    pop_text = f'Servers: **{len(cmd.bot.guilds)}**'
    pop_text += f'\nChannels: **{len(list(cmd.bot.get_all_channels()))}**'
    pop_text += f'\nRoles: **{role_count}**'
    pop_text += f'\nMembers: **{len(list(cmd.bot.get_all_members()))}**'
    exec_text = f'Commands: **{cmd.bot.command_count}**'
    exec_text += f'\nCommand Rate: **{command_rate}/s**'
    exec_text += f'\nMessages: **{cmd.bot.message_count}**'
    exec_text += f'\nMessage Rate: **{message_rate}/s**'
    response = discord.Embed(color=0x1B6F5F, timestamp=cmd.bot.start_time.datetime)
    response.set_author(name=sigma_title, icon_url=sigma_image, url=support_url)
    response.add_field(name='Population', value=pop_text)
    response.add_field(name='Usage', value=exec_text)
    response.set_footer(text=f'Tracking since {cmd.bot.start_time.humanize()}')
    await message.channel.send(embed=response)
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def cycler(ev):
    poll_coll = ev.db[ev.db.db_cfg.database].ShadowPolls
    while True:
        now = arrow.utcnow().timestamp
        poll_files = await poll_coll.find({'settings.expires': {'$lt': now}, 'settings.active': True}).to_list(None)
        for poll_file in poll_files:
            poll_id = poll_file['id']
            poll_file['settings'].update({'active': False})
            await ev.db[ev.db.db_cfg.database].ShadowPolls.update_one({'id': poll_id}, {'$set': poll_file})
            author = discord.utils.find(lambda x: x.id == poll_file['origin']['author'], ev.bot.get_all_members())
            if author:
                response = discord.Embed(color=0xff3333, title=f'? Your poll {poll_file["id"]} has expired.')
                try:
                    await author.send(embed=response)
                except discord.Forbidden:
                    pass
        await asyncio.sleep(1)
项目:Chaos    作者:Chaosthebot    | 项目源码 | 文件源码
def get_vote_weight(api, username, contributors):
    """ for a given username, determine the weight that their -1 or +1 vote
    should be scaled by """
    user = users.get_user(api, username)

    # we don't want new spam malicious spam accounts to have an influence on the project
    # if they've got a PR merged, they get a free pass
    if user["login"] not in contributors:
        # otherwise, check their account age
        now = arrow.utcnow()
        created = arrow.get(user["created_at"])
        age = (now - created).total_seconds()
        if age < settings.MIN_VOTER_AGE:
            return 0

    if username.lower() == "smittyvb":
        return 0.50002250052

    return 1
项目:vishleva.com    作者:webmalc    | 项目源码 | 文件源码
def test_calendar(self):
        """
        Test calendar page
        """
        now = arrow.utcnow()
        event = Event()
        event.begin = now.replace(hours=+24).datetime
        event.end = now.replace(hours=+36).datetime
        event.title = 'test_title_now'
        event.status = 'open'
        event.save()

        self._login_superuser()
        url = reverse('admin:events_calendar')
        response = self.client.get(url)
        self._is_succesful(
            response, title='Events calendar | Django site admin')
        self.assertContains(response, 'test_title_now')
        self.assertContains(
            response, 'events-calendar-date">' + now.format('D MMM').lower())
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def convert(self, ctx: DogbotContext, argument: str) -> str:
        cog: 'Time' = ctx.command.instance

        # resolve another user's timezone
        try:
            member = await MemberConverter().convert(ctx, argument)
            timezone = await cog.get_timezone_for(member)
            if timezone:
                return timezone
        except BadArgument:
            pass

        # hippo checking
        blacklisted = list('`\\<>@')
        if any(character in argument for character in blacklisted) or len(argument) > 30:
            raise BadArgument("That doesn't look like a timezone.")

        # actually check if it's a valid timezone with arrow's parser
        try:
            arrow.utcnow().to(argument)
        except arrow.parser.ParserError:
            raise BadArgument('Invalid timezone.')

        return argument
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def add_cmd_stat(db, cmd, message, args):
    if not message.author.bot:
        command_data = {
            'name': cmd.name,
        }
        for key in ['global', 'sfw', 'admin', 'partner', 'pmable']:
            command_data[key] = cmd.perm[key]
        if message.guild:
            channel_id = message.channel.id
            guild_id = message.guild.id
        else:
            channel_id = None
            guild_id = None
        stat_data = {
            'command': command_data,
            'args': args,
            'author': message.author.id,
            'channel': channel_id,
            'guild': guild_id,
            'timestamp': arrow.utcnow().timestamp
        }
        db.insert_one('CommandStats', stat_data)
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def refactor_users_node(db, usrgen):
    usrs = list(usrgen)
    db['UserList'].drop()
    db.log.info('UserList Dropped And Starting Refactoring Process...')
    start_time = arrow.utcnow().timestamp
    usercount = 0
    for user in usrs:
        usercount += 1
        user_ava = user_avatar(user)
        data = {
            'UserID': user.id,
            'UserName': user.name,
            'Avatar': user_ava,
            'Discriminator': user.discriminator
        }
        db['UserList'].insert_one(data)
        await asyncio.sleep(0.001)
    elapsed_time = arrow.utcnow().timestamp - start_time
    db.log.info(f'{usercount} Users Updated in {elapsed_time} seconds.')
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def refactor_servers_node(db, servers):
    srvs = servers
    db['ServerList'].drop()
    db.log.info('ServerList Dropped And Starting Refactoring Process...')
    start_time = arrow.utcnow().timestamp
    for server in srvs:
        owner = server.owner
        if owner:
            owner_name = owner.name
            owner_id = owner.id
        else:
            owner_name = 'None'
            owner_id = 'Unknown'
        data = {
            'ServerID': server.id,
            'Icon': server.icon_url,
            'ServerName': server.name,
            'Owner': owner_name,
            'OwnerID': owner_id
        }
        db['ServerList'].insert_one(data)
        await asyncio.sleep(0.001)
    elapsed_time = arrow.utcnow().timestamp - start_time
    db.log.info(f'{len(servers)} Servers Updated in {elapsed_time} seconds.')
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def wffissures(cmd, message, args):
    fissure_url = 'https://deathsnacks.com/wf/data/activemissions.json'
    async with aiohttp.ClientSession() as session:
        async with session.get(fissure_url) as data:
            fissure_data = await data.read()
            fissure_list = json.loads(fissure_data)
    response = discord.Embed(color=0x66ccff)
    response.set_author(name='Current Ongoing Fissures', icon_url='https://i.imgur.com/vANGxqe.png')
    for fis in fissure_list:
        relic_tier = tier_names[fis['Modifier']]
        fis_desc = f'Location: {fis["Node"]}'
        time_left = fis['Expiry']['sec'] - arrow.utcnow().timestamp
        death_time = str(datetime.timedelta(seconds=time_left))
        fis_desc += f'\nDisappears In: {death_time}'
        response.add_field(name=f'{relic_tier} Void Fissure', value=fis_desc)
    response.set_footer(text='Timers are not updated live.')
    await message.channel.send(embed=response)
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def version_updater(ev):
    if DevMode:
        with open('VERSION', 'r') as version_file:
            current_version_data = yaml.safe_load(version_file)
        beta = current_version_data['beta']
        build_date = arrow.utcnow().timestamp
        major = current_version_data['version']['major']
        minor = current_version_data['version']['minor']
        patch = current_version_data['version']['patch'] + 1
        codename = current_version_data['codename']
        data_out = {
            'beta': beta,
            'build_date': build_date,
            'version': {
                'major': major,
                'minor': minor,
                'patch': patch
            },
            'codename': codename
        }
        with open('VERSION', 'w') as version_out:
            yaml.dump(data_out, version_out, default_flow_style=False)
        ev.log.info('Updated Version File.')
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def move_log_join(ev, member):
    try:
        log_channel_id = ev.db.get_settings(member.guild.id, 'LoggingChannel')
    except:
        log_channel_id = None
    if log_channel_id:
        log_channel = discord.utils.find(lambda x: x.id == log_channel_id, member.guild.channels)
        if log_channel:
            response = discord.Embed(color=0x66CC66, timestamp=arrow.utcnow().datetime)
            response.set_author(name=f'A Member Has Joined', icon_url=user_avatar(member))
            response.add_field(name='?? Joining Member', value=f'{member.mention}\n{member.name}#{member.discriminator}')
            new_acc, diff_msg = get_time_difference(member)
            if new_acc:
                response.add_field(name='? Account Is New', value=f'Made {diff_msg.title()}', inline=True)
            else:
                response.add_field(name='?? Account Created', value=f'{diff_msg.title()}', inline=True)
            response.set_footer(text=f'UserID: {member.id}')
            await log_channel.send(embed=response)
        else:
            ev.db.set_settings(member.guild.id, 'LoggingChannel', None)
项目:apex-sigma    作者:lu-ci    | 项目源码 | 文件源码
def move_log_leave(ev, member):
    try:
        log_channel_id = ev.db.get_settings(member.guild.id, 'LoggingChannel')
    except:
        log_channel_id = None
    if log_channel_id:
        log_channel = discord.utils.find(lambda x: x.id == log_channel_id, member.guild.channels)
        if log_channel:
            response = discord.Embed(color=0xDB0000, timestamp=arrow.utcnow().datetime)
            response.set_author(name=f'A Member Has Left', icon_url=user_avatar(member))
            response.add_field(name='?? Leaving Member', value=f'{member.mention}\n{member.name}#{member.discriminator}')
            new_acc, diff_msg = get_time_difference(member, leave=True)
            response.add_field(name='?? Member Joined', value=f'{diff_msg.title()}', inline=True)
            response.set_footer(text=f'UserID: {member.id}')
            await log_channel.send(embed=response)
        else:
            ev.db.set_settings(member.guild.id, 'LoggingChannel', None)
项目:hardware-lab    作者:Buzzvil    | 项目源码 | 文件源码
def update_public_url():
    response = requests.get('http://localhost:4040/api/tunnels')

    public_url = response.json()['tunnels'][0]['public_url']
    # TODO: ???? http/https ??? ???? ???? ? ??? ?? ???? - by zune
    public_url = public_url.replace('http://', 'https://')
    logger.info('public url {}'.format(public_url))

    PublicUrl(
        machine_id=get_machine_id(),
        location=settings.AC_LOCATION,
        public_url=public_url,
        updated_at=arrow.utcnow().datetime,
        ttl=arrow.utcnow().shift(days=1).datetime,
        hostname=os.environ.get('HOSTNAME') or socket.gethostname(),
    ).save()
项目:remote-docker    作者:phizaz    | 项目源码 | 文件源码
def test_Job_dict(self):
        import arrow
        a = arrow.utcnow()
        d = {
            'tag': 'tag',
            'hosts': ['host1', 'host2'],
            'using_host': 'host1',
            'step': 'step',
            'docker': 'nvidia-docker',
            'remote_path': 'remote_path',
            'command': 'command',
            'start_time': str(a),
            'container': 'container',
            'oth': dict(a=10),
        }
        job = utils.Job.parse(d)
        self.assertDictEqual(job.dict(), d)
项目:remote-docker    作者:phizaz    | 项目源码 | 文件源码
def __init__(self, tag, hosts, using_host,
                 remote_path, command, step, docker='docker',
                 start_time=None, container=None, oth=None):
        assert isinstance(hosts, list)
        import arrow
        self.tag = tag
        self.hosts = hosts
        self.using_host = using_host
        self.remote_path = remote_path
        self.command = command
        self.step = step
        self.docker = docker
        if not start_time:
            self.start_time = arrow.utcnow()
        else:
            self.start_time = arrow.get(start_time)
        self.container = container
        self.oth = oth
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def wffissures(cmd, message, args):
    fissure_url = 'https://deathsnacks.com/wf/data/activemissions.json'
    async with aiohttp.ClientSession() as session:
        async with session.get(fissure_url) as data:
            fissure_data = await data.read()
            fissure_list = json.loads(fissure_data)
    response = discord.Embed(color=0x66ccff, title='Currently Ongoing Fissures')
    fissure_list = sorted(fissure_list, key=lambda k: k['Modifier'])
    for fis in fissure_list:
        relic_tier = tier_names[fis['Modifier']]
        fis_desc = f'Location: {fis["Node"]}'
        time_left = fis['Expiry']['sec'] - arrow.utcnow().timestamp
        death_time = str(datetime.timedelta(seconds=time_left))
        fis_desc += f'\nDisappears In: {death_time}'
        response.add_field(name=f'{relic_tier} Void Fissure', value=fis_desc, inline=False)
    response.set_footer(text='Timers are not updated live.')
    response.set_thumbnail(url=fissure_icon)
    await message.channel.send(embed=response)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def wfalerts(cmd, message, args):
    alert_url = 'https://deathsnacks.com/wf/data/alerts_raw.txt'
    async with aiohttp.ClientSession() as session:
        async with session.get(alert_url) as data:
            alert_data = await data.text()
    alert_list = parse_alert_data(alert_data)
    response = discord.Embed(color=0xFFCC66)
    response.set_author(name='Currently Ongoing Alerts')
    for alert in alert_list:
        alert_desc = f'Levels: {alert["levels"]["low"]} - {alert["levels"]["high"]}'
        alert_desc += f'\nLocation: {alert["node"]} ({alert["planet"]})'
        alert_desc += f'\nReward: {alert["rewards"]["credits"]}cr'
        time_left = alert['stamps']['end'] - arrow.utcnow().timestamp
        death_time = str(datetime.timedelta(seconds=time_left))
        if alert['rewards']['item']:
            alert_desc += f'\nItem: **{alert["rewards"]["item"]}**'
        alert_desc += f'\nDisappears In: {death_time}'
        response.add_field(name=f'Type: {alert["faction"]} {alert["type"]}', value=f'{alert_desc}', inline=False)
        response.set_thumbnail(url='https://i.imgur.com/99ennZD.png')
        response.set_footer(text='Timers are not updated live.')
    await message.channel.send(embed=response)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def population_insert_clock(ev):
    while True:
        if not ev.bot.cool_down.on_cooldown(ev.name, 'stats_logger'):
            ev.bot.cool_down.set_cooldown(ev.name, 'stats_logger', 3600)
            collection = 'StatisticsLogs'
            database = ev.bot.cfg.db.database
            server_count = len(list(ev.bot.guilds))
            member_count = len(list(ev.bot.get_all_members()))
            channel_count = len(list(ev.bot.get_all_channels()))
            command_count = ev.db[database].CommandStats.count()
            stat_data = {
                'stamp': arrow.utcnow().timestamp,
                'guilds': server_count,
                'users': member_count,
                'channels': channel_count,
                'commands': command_count
            }
            ev.db[database][collection].insert_one(stat_data)
        await asyncio.sleep(300)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def user_data_fill(ev):
    ev.log.info('Filling member details...')
    threads = ThreadPoolExecutor(2)
    start_stamp = arrow.utcnow().float_timestamp
    ev.bot.cool_down.set_cooldown(ev.name, 'member_details', 3600)
    mem_coll = ev.db[ev.db.db_cfg.database].UserDetails
    mem_coll.drop()
    for x in range(0, ev.bot.shard_count):
        shard_start = arrow.utcnow().float_timestamp
        member_list = []
        for guild in ev.bot.guilds:
            if guild.shard_id == x:
                for member in guild.members:
                    mem_data = await generate_member_data(member)
                    member_list.append(mem_data)
        task = functools.partial(mem_coll.insert, member_list)
        await ev.bot.loop.run_in_executor(threads, task)
        shard_end = arrow.utcnow().float_timestamp
        shard_diff = round(shard_end - shard_start, 3)
        ev.log.info(f'Filled Shard #{x} Members in {shard_diff}s.')
    end_stamp = arrow.utcnow().float_timestamp
    diff = round(end_stamp - start_stamp, 3)
    ev.log.info(f'Member detail filler finished in {diff}s.')
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def version_updater(ev):
    if ev.bot.cfg.pref.dev_mode:
        with open('info/version.yml', 'r') as version_file:
            current_version_data = yaml.safe_load(version_file)
        beta = current_version_data['beta']
        build_date = arrow.utcnow().timestamp
        major = current_version_data['version']['major']
        minor = current_version_data['version']['minor']
        patch = current_version_data['version']['patch'] + 1
        codename = current_version_data['codename']
        data_out = {
            'beta': beta,
            'build_date': build_date,
            'version': {
                'major': major,
                'minor': minor,
                'patch': patch
            },
            'codename': codename
        }
        with open('info/version.yml', 'w') as version_out:
            yaml.dump(data_out, version_out, default_flow_style=False)
        ev.log.info('Updated Version File.')
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def statistics(cmd, message, args):
    sigma_image = 'https://i.imgur.com/mGyqMe1.png'
    sigma_title = 'Apex Sigma: Statistics'
    support_url = 'https://discordapp.com/invite/aEUCHwX'
    role_count = 0
    for guild in cmd.bot.guilds:
        role_count += len(guild.roles)
    time_dif = arrow.utcnow().timestamp - cmd.bot.start_time.timestamp
    command_rate = str(cmd.bot.command_count / time_dif)[:5]
    message_rate = str(cmd.bot.message_count / time_dif)[:5]
    pop_text = f'Servers: **{len(cmd.bot.guilds)}**'
    pop_text += f'\nChannels: **{len(list(cmd.bot.get_all_channels()))}**'
    pop_text += f'\nRoles: **{role_count}**'
    pop_text += f'\nMembers: **{len(list(cmd.bot.get_all_members()))}**'
    exec_text = f'Commands: **{cmd.bot.command_count}**'
    exec_text += f'\nCommand Rate: **{command_rate}/s**'
    exec_text += f'\nMessages: **{cmd.bot.message_count}**'
    exec_text += f'\nMessage Rate: **{message_rate}/s**'
    response = discord.Embed(color=0x1B6F5F, timestamp=cmd.bot.start_time.datetime)
    response.set_author(name=sigma_title, icon_url=sigma_image, url=support_url)
    response.add_field(name='Population', value=pop_text)
    response.add_field(name='Usage', value=exec_text)
    response.set_footer(text=f'Tracking since {cmd.bot.start_time.humanize()}')
    await message.channel.send(embed=response)
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
def timeconvert(cmd, message, args):
    if args:
        conv_input = ' '.join(args).split('>')
        if len(conv_input) == 2:
            from_pieces = conv_input[0].split()
            if len(from_pieces) == 2:
                from_time = from_pieces[0]
                from_zone = from_pieces[1]
                to_zone = conv_input[1]
                from_string = f'{arrow.utcnow().format("YYYY-MM-DD")} {from_time}:00'
                from_arrow = arrow.get(arrow.get(from_string).datetime, from_zone)
                to_arrow = from_arrow.to(to_zone)
                time_out = to_arrow.format('YYYY-MM-DD HH:mm:ss (ZZ GMT)')
                response = discord.Embed(color=0x696969, title=f'?? {time_out}')
            else:
                response = discord.Embed(color=0xBE1931, title='? Invalid first argument.')
        else:
            response = discord.Embed(color=0xBE1931, title='? Invalid input arguments.')
    else:
        response = discord.Embed(color=0xBE1931, title='? Nothing inputted.')
    await message.channel.send(embed=response)
项目:dbas    作者:hhucn    | 项目源码 | 文件源码
def get_count_of_votes_of_user(user, limit_on_today=False):
    """
    Returns the count of marked ones of the user

    :param user: User
    :param limit_on_today: Boolean
    :return: Int, Int
    """
    if not user:
        return 0

    db_arg = DBDiscussionSession.query(MarkedArgument).filter(ClickedArgument.author_uid == user.uid)
    db_stat = DBDiscussionSession.query(MarkedStatement).filter(ClickedStatement.author_uid == user.uid)

    if limit_on_today:
        today = arrow.utcnow().to('Europe/Berlin').format('YYYY-MM-DD')
        db_arg = db_arg.filter(MarkedArgument.timestamp >= today)
        db_stat = db_stat.filter(MarkedStatement.timestamp >= today)

    db_arg = db_arg.all()
    db_stat = db_stat.all()

    return len(db_arg), len(db_stat)
项目:dbas    作者:hhucn    | 项目源码 | 文件源码
def get_count_of_clicks(user, limit_on_today=False):
    """
    Returns the count of clicks of the user

    :param user: User
    :param limit_on_today: Boolean
    :return: Int, Int
    """
    if not user:
        return 0

    db_arg = DBDiscussionSession.query(ClickedArgument).filter(ClickedArgument.author_uid == user.uid)
    db_stat = DBDiscussionSession.query(ClickedStatement).filter(ClickedStatement.author_uid == user.uid)

    if limit_on_today:
        today = arrow.utcnow().to('Europe/Berlin').format('YYYY-MM-DD')
        db_arg = db_arg.filter(ClickedArgument.timestamp >= today)
        db_stat = db_stat.filter(ClickedStatement.timestamp >= today)

    db_arg = db_arg.all()
    db_stat = db_stat.all()

    return len(db_arg), len(db_stat)
项目:ardy    作者:avara1986    | 项目源码 | 文件源码
def my_handler(event, context):

    utc = arrow.utcnow()
    local = utc.to('US/Pacific')
    date_to_print = local.humanize()

    message = 'Hello world lambda1! at {}'.format(date_to_print)
    return {
        'message': message
    }
项目:nameko-amqp-retry    作者:nameko    | 项目源码 | 文件源码
def test_rpc(self, container_factory, rabbit_config):

        from examples.retry import Service

        container = container_factory(Service, rabbit_config)
        container.start()

        timestamp = arrow.utcnow().replace(seconds=+1)

        with ServiceRpcProxy('service', rabbit_config) as service_rpc:
            res = service_rpc.method(timestamp.isoformat())
        assert arrow.get(re.match("Time is (.+)", res).group(1)) >= timestamp
项目:nameko-amqp-retry    作者:nameko    | 项目源码 | 文件源码
def test_decorated_rpc(self, container_factory, rabbit_config):

        from examples.retry import Service

        container = container_factory(Service, rabbit_config)
        container.start()

        timestamp = arrow.utcnow().replace(seconds=+1)

        with ServiceRpcProxy('service', rabbit_config) as service_rpc:
            res = service_rpc.decorated_method(timestamp.isoformat())
        assert arrow.get(re.match("Time is (.+)", res).group(1)) >= timestamp
项目:nameko-amqp-retry    作者:nameko    | 项目源码 | 文件源码
def generate_message(self):
        return "Time is {}".format(arrow.utcnow())