async def accountinfo(self, ctx, user: discord.Member = None): """ Gives basic account information of requested user """ if user is None: user = ctx.author if user.nick is not None: name = f"{user.name} ({user.nick})" else: name = user.name # Make and send an embed to the channel listing account information embed = discord.Embed(colour=0xBAFFC9, title=f"Account Information For {name}") embed.set_thumbnail(url=user.avatar_url) embed.add_field(name="ID", value=user.id) embed.add_field(name="Account Created", value=user.created_at.strftime("%m/%d/%Y %H:%M:%S")) embed.add_field(name="Account Age", value=humanize.precisedelta(dt.now() - user.created_at)) embed.add_field(name="Joined Server", value=user.joined_at.strftime("%m/%d/%Y %H:%M:%S")) embed.add_field(name="Join Server Age", value=humanize.precisedelta(dt.now() - user.joined_at)) await ctx.send(embed=embed)
async def end(bot, ends_at: int, message_id: int, channel_id: int, embed): interval = 5 message = await bot.get_channel(channel_id).fetch_message(message_id) embed = discord.Embed.from_dict(json.loads(embed)) left = int(ends_at - time.time()) remaining = left % interval for i in range(left // interval): embed = edit_field(embed, 1, bold.sub(r'**\1**', precisedelta(left))) await message.edit(embed=embed) await asyncio.sleep(interval) left -= interval await asyncio.sleep(remaining) prize = embed.title embed.title = 'LAST CHANCE TO ENTER!!!' left = interval for i in range(interval): embed = edit_field(embed, 1, bold.sub(r'**\1**', precisedelta(left))) embed.colour = discord.Colour.red() await message.edit(embed=embed) left -= 1 await asyncio.sleep(1) query = 'SELECT winners_num, prize FROM giveaways WHERE message_id = $1' res = await bot.db.fetchrow(query, message_id) users = await message.reactions[0].users().flatten() if message.guild.me in users: users.remove(message.guild.me) winners = [] if not users: await message.channel.send('No one has entered the giveaway.') else: for i in range(res['winners_num']): try: winner = random.choice(users) except IndexError: break users.remove(winner) if await can_enter(bot, winner, message.id): winners.append(winner) query = '''UPDATE giveaways SET winners = $1 WHERE message_id = $2 ''' await bot.db.execute(query, [winner.id for winner in winners], message_id) bot.message_ids.remove(message_id) winners = ', '.join(winner.mention for winner in winners) await message.channel.send( f'Congratulations {winners}! ' f'You won the **{prize}**\n{message.jump_url}') embed = discord.Embed(title=prize, description=embed.description, color=discord.Colour.dark_orange(), timestamp=datetime.utcnow()).add_field( name='Winners', value=winners or 'No winners.').set_footer(text='Ended at ->') await message.edit(embed=embed)
def test_i18n(): three_seconds = dt.timedelta(seconds=3) one_min_three_seconds = dt.timedelta(milliseconds=67_000) assert humanize.naturaltime(three_seconds) == "3 seconds ago" assert humanize.ordinal(5) == "5th" assert humanize.precisedelta( one_min_three_seconds) == "1 minute and 7 seconds" try: humanize.i18n.activate("ru_RU") assert humanize.naturaltime(three_seconds) == "3 секунды назад" assert humanize.ordinal(5) == "5ый" assert humanize.precisedelta( one_min_three_seconds) == "1 минута и 7 секунд" except FileNotFoundError: pytest.skip( "Generate .mo with scripts/generate-translation-binaries.sh") finally: humanize.i18n.deactivate() assert humanize.naturaltime(three_seconds) == "3 seconds ago" assert humanize.ordinal(5) == "5th" assert humanize.precisedelta( one_min_three_seconds) == "1 minute and 7 seconds"
async def osinfo(self, ctx): """ Show some info about what the bot's running on, package versions, and more. """ packages_for_info = [ "discord.py", "tortoise-orm", "markovify", "pillow" ] osembed = discord.Embed(title=ctx.bot.user.name, color=discord.Color.purple()) py_ver = p.python_version() osembed.add_field(name="Python version", value=py_ver) osembed.add_field(name="System uptime", value=humanize.precisedelta(f.get_uptime(), minimum_unit="seconds")) osembed.add_field(name="Bot uptime", value=humanize.precisedelta( bot.started_at, minimum_unit="seconds", format="%0.0f", suppress=["months", "years"])) for package in packages_for_info: osembed.add_field(name=f"**{package}** version", value=version(package)) os_ver = f"{p.system()} {p.release()}" osembed.add_field(name="OS type", value=os_ver or "Unknown") osembed.add_field(name="Architecture", value=p.machine() or p.processor() or "Unknown") await ctx.send(embed=osembed)
def _get_last_feeds(db: Session, baby: Baby): feeds = db.query(Feed).order_by(desc( Feed.start_at)).filter_by(baby=baby)[:4] rows = [] for feed in feeds: end_at = "" amount = "" if feed.end_at is not None: end_at = humanize.precisedelta(feed.end_at - feed.start_at, minimum_unit="minutes", format="%0.0f") amount = f"{feed.amount} ml" rows.append( dict(cells=[ dict(text=humanize.precisedelta( feed.start_at - datetime.utcnow(), minimum_unit="minutes", format="%0.0f", ) + " ago", ), dict(text=end_at), dict(text=amount), ])) return dict(table=dict( columns=[ dict(header="Started"), dict(header="Duration"), dict(header="Amount"), ], rows=rows, subtitle=f"last feedings for {baby.name}", title="Feedings", ))
async def userinfo(self, ctx, member: discord.Member = None): if member is None: member = ctx.author embed = discord.Embed(title=f"Information on {member}", description=member.mention, color=self.bot.color) perms_list = [] for permission, value in member.guild_permissions: if value: perms_list.append(permission.replace("_", " ").title()) for perm in perms_list: ignored_perms = ["Add Reactions", "Priority Speaker", "Stream", "Embed Links", "Read Message History", "External Emojis", "Connect", "Speak", "Mute Members", "Deafen Members", "Move Members", "Use Voice Activation", "Change Nickname", "Manage Webhooks", "Request To Speak"] if perm in ignored_perms: perms_list.pop(perms_list.index(perm)) permissions_str = ", ".join(perm for perm in perms_list) joined = humanize.precisedelta(datetime.datetime.now() - member.joined_at) created = humanize.precisedelta(datetime.datetime.now() - member.created_at) embed.add_field(name=f"Joined {ctx.guild.name} on", value=joined) embed.add_field(name="Created account on", value=created) embed.add_field(name="Permissions", value=permissions_str) embed.add_field(name="Status", value=str(member.status).replace("dnd", "DND <:status_dnd:844215897206947930>").replace( "do_not_disturb", "<:status_dnd:844215897206947930> DND").replace("online", "Online <:status_online:844215865951911968>").replace( "idle", "Idle <:status_idle:844216072265531452>").replace("offline", "Offline <:status_offline:844216076543721523>")) embed.add_field(name=f"Roles [{len(member.roles)}]", value=member.top_role.mention) await ctx.send(embed=embed)
def get_stats(cls): completed_fasts = cls.fast_history() fast_count = len(completed_fasts) if fast_count > 0: last_fast_time = max([x.end_time for x in completed_fasts]) total_hours = sum([x.duration for x in completed_fasts], datetime.timedelta()) total_hours_text = humanize.precisedelta(total_hours, minimum_unit="hours", format="%0.0f") longest_fast = max([x.duration for x in completed_fasts]) longest_fast_text = humanize.precisedelta(longest_fast, minimum_unit="hours", format="%0.0f") now = datetime.datetime.today() time_passed = now - last_fast_time time_passed_text = humanize.precisedelta(time_passed, minimum_unit="hours", format="%0.0f") result_dict = { "fast_count": fast_count, "last_time_passed_text": time_passed_text, "total_fasted_time": total_hours_text, "longest_fast_text": longest_fast_text, "now": swap_dt(now) } return result_dict
def test_precisedelta_bogus_call(): assert humanize.precisedelta(None) is None with pytest.raises(ValueError): humanize.precisedelta(1, minimum_unit="years", suppress=["years"]) with pytest.raises(ValueError): humanize.naturaldelta(1, minimum_unit="years")
def _get_text(): text = '' current_datetime = datetime.now() subjects = get_subjects_by_date(current_datetime.date()) checking_datetime = datetime.combine(date.today(), time(8, 30)) humanize.i18n.activate(current_app.config['LOCATE']) if current_datetime < checking_datetime: time_to_end = checking_datetime - current_datetime humanize_time_to_end = humanize.precisedelta(time_to_end, minimum_unit='minutes') text = f'До первой пары осталось еще <b>{humanize_time_to_end}</b>' return text for i in range(len(subjects)): if checking_datetime < current_datetime < checking_datetime + timedelta( minutes=75): time_to_end = (checking_datetime + timedelta(minutes=75)) - current_datetime humanize_time_to_end = humanize.precisedelta( time_to_end, minimum_unit='minutes', format='%0.0f') text = (f'Сейчас: <b>{subjects[i].name}</b>\n' f'До конца еще <b>{humanize_time_to_end}</b>\n\n') if i < len(subjects) - 1: text += f'Следующая пара: <b>{subjects[i + 1].name}</b>' break checking_datetime += timedelta(minutes=75) if i == len(subjects) - 1: break if checking_datetime < current_datetime < checking_datetime + timedelta( minutes=10): time_to_end = (checking_datetime + timedelta(minutes=10)) - current_datetime humanize_time_to_end = humanize.precisedelta( time_to_end, minimum_unit='minutes', format='%0.0f') text = ('Сейчас перемена\n' f'До конца еще <b>{humanize_time_to_end}</b>\n\n' f'Следующая пара: <b>{subjects[i + 1].name}</b>') break checking_datetime += timedelta(minutes=10) if text == '': text = 'Сегодня пар больше не будет' return text.rstrip()
async def about(self, ctx: SlashContext): embed = discord.Embed( description= "...is a currency bot with :third_place: as its currency! To start earning medals, type `/compete`. You can look at all the commands by typing `/` then scrolling through my commands!", colour=Colours.BRONZE) embed.set_author(name="Bronze Medalist", url="https://bronzemedalist.netlify.app") embed.set_thumbnail(url=self.bot.user.avatar_url) embed.add_field(name="Version", value="v" + __version__) embed.add_field(name="Servers", value=str(len(self.bot.guilds))) embed.add_field(name="Medals", value="{:,}".format(self.bot.medals)) embed.add_field(name="Latency", value="{:.3f}ms".format(self.bot.latency * 1000)) embed.add_field(name="Uptime", value=precisedelta(datetime.now() - self.bot.startup)) embed.add_field(name="\u200b", value="\u200b") embed.add_field( name="Invite link", value=f"[Click me]({self.bot.invite} \"{self.bot.invite}\")") embed.add_field( name="GitHub", value= "[Click me](https://github.com/realcyguy/bronze-medalist \"realcyguy/bronze-medalist\")" ) embed.add_field( name="Website", value= f"[Click me](https://bronzemedalist.netlify.app \"bronzemedalist.netlify.app\")" ) embed.set_footer(text="Made by RealCyGuy#1919!") await ctx.send(embed=embed)
async def append_reminder(self, timestamp: datetime, ctx: Context, content: str) -> None: """Add reminder to database and schedule it.""" sql = ( "INSERT INTO reminders(jump_url, user_id, channel_id, end_time, content) " "VALUES ($1, $2, $3, $4, $5)RETURNING reminder_id") async with self.bot.db_pool.acquire() as connection: reminder_id = await connection.fetchval( sql, ctx.message.jump_url, ctx.author.id, ctx.channel.id, timestamp, content, ) embed = Embed( title=":white_check_mark: Reminder set", color=Colours.green, description=REMINDER_DESCRIPTION.format( arrive_in=humanize.precisedelta(timestamp - datetime.utcnow(), format="%0.0f"), ), ) embed.set_footer(text=f"ID: {reminder_id}") await ctx.send(embed=embed) self.reminders[reminder_id] = { "reminder_id": reminder_id, "jump_url": ctx.message.jump_url, "user_id": ctx.author.id, "channel_id": ctx.channel.id, "end_time": timestamp, "content": content, } await self.schedule_reminder(self.get_recent_reminder())
async def update_giveaway_messages(self): query = '''SELECT channel_id, message_id, embed, ends_at FROM giveaways WHERE ended = $1 ''' res = await self.bot.db.fetch(query, False) for res in res: if res['ends_at'] < time.time() + 32: query = '''UPDATE giveaways SET ended = $1 WHERE message_id = $2 ''' await self.bot.db.execute(query, True, res['message_id']) args = (self.bot, res['ends_at'], res['message_id'], res['channel_id'], res['embed']) self.bot.loop.create_task(end(*args)) else: left = res['ends_at'] - time.time() embed = discord.Embed.from_dict(json.loads(res['embed'])) embed = edit_field(embed, 1, bold.sub(r'**\1**', precisedelta(left))) try: await self.bot.http.edit_message(res['channel_id'], res['message_id'], embed=embed.to_dict()) except discord.NotFound: query = '''UPDATE giveaways SET ended = $1, winners = $2 WHERE message_id = $3 ''' await self.bot.db.execute(query, True, [], res['message_id'])
async def recentbotadd(self, ctx, **flags): reverse = flags.pop("reverse", False) def predicate(m): return m.bot and m.joined_at.replace( tzinfo=None) > ctx.message.created_at.replace( tzinfo=None) - datetime.timedelta(days=1) members = {m.id: m for m in filter(predicate, ctx.guild.members)} if not members: member = max(filter(lambda x: x.bot, ctx.guild.members), key=lambda x: x.joined_at) time_add = humanize.precisedelta( member.joined_at.replace(tzinfo=None), minimum_unit="minutes") return await ctx.embed( title="Bots added today", description= "Looks like there are no bots added in the span of 24 hours.\n" f"The last time a bot was added was `{time_add}` for `{member}`" ) db_data = await self.bot.pool_pg.fetch( "SELECT * FROM confirmed_bots WHERE bot_id=ANY($1::BIGINT[])", list(members)) member_data = [ BotAdded.from_json(bot=members[data["bot_id"]], **data) for data in db_data ] member_data.sort(key=lambda x: x.joined_at, reverse=not reverse) menu = MenuBase(source=bot_added_list(member_data)) await menu.start(ctx)
async def biden(ctx): """Tbh I don't think Biden will run again""" est = timezone('US/Eastern') kick = datetime(2025, 1, 20, hour=12).astimezone(est) now = datetime.now().astimezone(est) delta = precisedelta((kick - now).total_seconds()) await ctx.send(f'Time until Biden\'s term ends:\n\n{delta}')
def respond_to_reset(reset): try: from secret import secret, password, username, app_id reddit = praw.Reddit(client_id=app_id, client_secret=secret, username=username, password=password, user_agent="Reset Bot") last_reset = get_last_reset() if last_reset is None: return comment = reddit.comment(id=reset.id) number_of_resets = get_user_reset_number(reset.author) if number_of_resets is None: number_of_resets_text = f"Congratulations on your first reset /u/{reset.author}!" else: number_of_resets_text = f"/u/{reset.author} reset the counter {number_of_resets + 1} times." time_delta = humanize.precisedelta(reset.date - last_reset.date) body = f"""{reset.spoiler}Counter is reset! There's been no reset for: {time_delta}{reset.spoiler_close} {reset.spoiler}{number_of_resets_text}{reset.spoiler_close} {reset.spoiler}[Last reset]({reddit_prefix}{last_reset.permalink}) was on {last_reset.date} by /u/{last_reset.user.username}{reset.spoiler_close}""" comment.reply(body) logging.info(f"Responding to {reset.id}") except ModuleNotFoundError: logging.critical("secrets.py not found") raise ModuleNotFoundError( "secrets.py not found, create secrets.py file " "with following variables: secret, password, username, app_id")
def get_time_remaining(current: int, leaving: int): leaving_time = datetime.datetime.utcfromtimestamp(leaving) current_time = datetime.datetime.utcfromtimestamp(current) remaining = leaving_time - current_time return humanize.precisedelta(remaining)
async def ping_role(self, ctx, *, role_obj: common.classes.FuzzyRoleConverter): """Pings the role specified if the role isn't on cooldown and has been added to a list.""" ping_roles = self.bot.config[ctx.guild.id]["pingable_roles"] if ping_roles == {}: raise utils.CustomCheckFailure( "There are no roles for you to ping!") if not str(role_obj.id) in ping_roles.keys(): raise commands.BadArgument("That role isn't pingable!") role_entry = ping_roles[str(role_obj.id)] now = datetime.datetime.utcnow() time_period = datetime.timedelta(seconds=role_entry["time_period"]) last_used = datetime.datetime.utcfromtimestamp(role_entry["last_used"]) next_use = last_used + time_period if now < next_use: till_next_time = next_use - now time_text = humanize.precisedelta(till_next_time, format='%0.1f') raise utils.CustomCheckFailure( f"You cannot ping that role yet! Please wait: `{time_text}` before trying to ping the role again." ) else: await ctx.send( role_obj.mention, allowed_mentions=discord.AllowedMentions(roles=True)) self.bot.config[ctx.guild.id]["pingable_roles"][str( role_obj.id)]["last_used"] = now.timestamp()
async def reminder_list(self, ctx: ErisContext): ''' Mostra seus timers ativos. ''' sql = ''' SELECT id, expires, extra #>> '{args,2}' FROM reminders WHERE event = 'reminder' AND extra #>> '{args,0}'= $1 ORDER BY expires LIMIT 10; ''' fetch = await ctx.pool.fetch(sql, str(ctx.author.id)) if len(fetch) == 0: return await ctx.reply('Você não possui nenhum lembrete ativo.') fields = [] for reminder_id, expires, message in fetch: now = datetime.datetime.utcnow() delta = humanize.precisedelta(expires - now.replace(microsecond=0), format='%0.0f') field = { 'name': f'[{reminder_id}] Em {delta}', 'value': message, 'inline': False } fields.append(field) menu = ErisMenuPages(fields, source=SourceType.FIELD) await menu.start(ctx, wait=True)
def _ban_duration_text(self): ban_duration = self.ban_expiry - datetime.utcnow() if ban_duration.days > 365 * 100: return "forever" humanized_ban_duration = humanize.precisedelta(ban_duration, minimum_unit="hours") return f"for {humanized_ban_duration}"
def run(f: Path, index: int, total: int, quiet=False): msg = f"Running {index}/{total}: {f.name}" if not quiet: label(msg) else: LOGGER.info(msg) kwargs = { "check": True, } if quiet: kwargs["stdout"] = subprocess.DEVNULL kwargs["stderr"] = subprocess.DEVNULL start = time() subprocess.run([sys.executable, f], **kwargs) # nosec elapsed = time() - start LOGGER.debug( "Finished {index}/{total}: {name} in {time}", index=index, total=total, name=f.name, time=precisedelta(timedelta(seconds=elapsed)), ) LOGGER.complete()
async def error_list(self, ctx: ErisContext): ''' Mostra todos os tickets de erros ativos. ''' sql = ''' SELECT id, created, error FROM error_tracker WHERE is_solved = FALSE ''' fetch = await ctx.pool.fetch(sql) if not fetch: return await ctx.reply( 'Não há nenhum erro registrado, isso é um bom sinal.') entries = [] for record in fetch: error = record['error'] ticket_id = record['id'] created_at = record['created'] delta = humanize.precisedelta(ctx.message.created_at - created_at, format='%0.0f') entries.append( f'`[#{ticket_id}]` **Há {delta}**\n```py\n{error}```') menu = ErisMenuPages(entries) await menu.start(ctx)
def json_dict(self) -> dict: # not dry but better explicit than implicit for security etc return { "id": self.id, "createdAt": self.created_at, "displayName": self.display_name, "fileName": self.file_name, "fileSizeBytes": self.file_size_bytes, "fileSizeDisplay": humanize.naturalsize(self.file_size_bytes, binary=True), "uniqueLines": self.unique_lines, "totalLines": self.total_lines, "elapsedTimeNs": self.elapsed_time_ns, "elapsedTimeDisplay": humanize.precisedelta( timedelta(microseconds=round(self.elapsed_time_ns / 1000)), minimum_unit='milliseconds') }
async def nowplaying(self, ctx: commands.Context): """Mostra qual música está atualmente tocando.""" player = ctx.bot.lavalink.player_manager.get(ctx.guild.id) current = player.current if not current: raise BotNotPlaying() title = self.escape_markdown(current.title) requester = ctx.guild.get_member( current.requester).mention or '**[usuário desconhecido]**' try: duration = humanize.precisedelta( timedelta(milliseconds=current.duration)) except OverflowError: duration = '**[ao vivo]**' # TODO: Add "is_stream" and current music timestamp. messages = [ f'Música: [{title}]({current.uri})', f'Canal: **{current.author}**', f'Duração: **{duration}**', f'Solicitante: {requester}' ] size = 24 placeholder = '▬' * size percentage = int((size * int(player.position)) / int(current.duration)) messages.append(placeholder[:percentage] + '○' + placeholder[percentage + 1:]) await ctx.send('\n'.join(messages))
async def date_info(self, ctx: Context, name: str) -> None: """Getting the name of the date and the difference between now and then.""" async with self.bot.pool.acquire() as conn: d = await conn.fetch( "SELECT t FROM Dates WHERE name = $1 AND id = $2", name, ctx.author.id) if len(d): delta = precisedelta(datetime.now() - d[0]["t"], minimum_unit="days", format="%0.4f", suppress=["months"]) if datetime.now() > d[0]["t"]: embed = DefaultEmbed( ctx, description= f'{delta} have passed since {naturaldate(d[0]["t"])}, the start of "{name}".', ) else: embed = DefaultEmbed( ctx, description=f'{naturaldate(d[0]["t"])} is in {delta}.') await ctx.send(embed=embed) else: embed = DefaultEmbed( ctx, description= f'Could not find date named "{name}" stored in the database.') await ctx.send(embed=embed)
async def set_slowmode(self, ctx: Context, channel: Optional[TextChannel], delay: DurationDelta) -> None: """Set the slowmode delay for a text channel.""" # Use the channel this command was invoked in if one was not given if channel is None: channel = ctx.channel # Convert `dateutil.relativedelta.relativedelta` to `datetime.timedelta` # Must do this to get the delta in a particular unit of time utcnow = datetime.utcnow() slowmode_delay = (utcnow + delay - utcnow).total_seconds() humanized_delay = humanize.precisedelta(slowmode_delay, minimum_unit='seconds', format=r'%0.0f') # Ensure the delay is within discord's limits if slowmode_delay <= SLOWMODE_MAX_DELAY: log.info( f'{ctx.author} set the slowmode delay for #{channel} to {humanized_delay}.' ) await channel.edit(slowmode_delay=slowmode_delay) await ctx.send( f'✅ The slowmode delay for {channel.mention} is now {humanized_delay}.' ) else: log.info( f'{ctx.author} tried to set the slowmode delay of #{channel} to {humanized_delay}, ' 'which is not between 0 and 6 hours.') await ctx.send( '❌ The slowmode delay must be between 0 and 6 hours.')
def draw(filename: str, entries: List[CalendarEntry], weather: List[Tuple[str, WeatherForecast]], quality: AirQuality, icons_location: str) -> None: dwg = svgwrite.Drawing(filename=filename, debug=True, size=(880 * px, 528 * px)) bg = dwg.add(dwg.g(id='bg')) bg.add(dwg.rect(insert=(0 * px, 0 * px), size=(880 * px, 528 * px), fill='white', stroke_width=0)) draw_big(20, 20, dwg, weather=weather[0][1], air_quality=quality.humanize(), icons_location=icons_location) draw_small(400, 20, dwg, time=weather[1][0], weather=weather[1][1], icons_location=icons_location) draw_small(640, 20, dwg, time=weather[2][0], weather=weather[2][1], icons_location=icons_location) calendar_entries: list[str] = [] for entry in entries[:4]: formatted_delta = humanize.precisedelta(entry.length).replace("and", "") # TODO: make it more concise time = "Ongoing" if entry.start.replace(tzinfo=None) < datetime.datetime.now() else \ humanize.naturaltime(entry.start.replace(tzinfo=None)) if entry.start.date() != datetime.date.today() \ else f"{entry.start.strftime('%H:%M')}, {formatted_delta}" calendar_entries.append(f"{time}") calendar_entries.append(f"{entry.title[:24]}{'...' if len(entry.title) > 24 else ''}") draw_calendar(400, 180, dwg, calendar_entries) paragraph = dwg.add(dwg.g(font_size=20)) paragraph.add(dwg.text(f"Last update: {datetime.datetime.now().strftime('%d/%m/%Y, %H:%M:%S')}", (10, 500))) dwg.save()
async def uptime(self, ctx): """Returns the uptime of the bot.""" uptime = humanize.precisedelta(self.bot.start_time - datetime.datetime.utcnow(), format="%0.0f") await ctx.send(embed=ctx.embed( description=f"I've been up for {uptime}"))
def _duration_since(start: datetime.datetime) -> str: """ inputs: start: a datetime object of when the duration started returns: string with humanized duration of start to now """ return humanize.precisedelta(datetime.datetime.now() - start)
def __exit__(self, type, value, traceback): delta = dt.timedelta(seconds=self.__stop_time()) humanized_delta = humanize.precisedelta(delta, minimum_unit="microseconds", format="%0.0f") self.__logger.info( f'Desc: \'{self.__desc}\' - Time: {humanized_delta}')
def get_cooldown(self, command: Command) -> str | None: cooldown = command.cooldown if cooldown: rate = cooldown.rate _type = command._buckets.type.name per = humanize.precisedelta(cooldown.per) time = "times" if rate > 1 else "time" return f"{per} every {rate} {time} per {_type}" return None