| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- """
- General utility functions.
- """
- import re
- from datetime import datetime, timedelta
- from discord import Guild
- from discord.ext.commands import Cog, Group
-
- def parse_timedelta(s: str) -> timedelta:
- """
- Parses a timespan. Format examples:
- "30m"
- "10s"
- "90d"
- "1h30m"
- "73d18h22m52s"
- """
- p = re.compile('^(?:[0-9]+[dhms])+$')
- if p.match(s) is None:
- raise ValueError("Illegal timespan value '{s}'.")
- p = re.compile('([0-9]+)([dhms])')
- days = 0
- hours = 0
- minutes = 0
- seconds = 0
- for m in p.finditer(s):
- scalar = int(m.group(1))
- unit = m.group(2)
- if unit == 'd':
- days = scalar
- elif unit == 'h':
- hours = scalar
- elif unit == 'm':
- minutes = scalar
- elif unit == 's':
- seconds = scalar
- return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
-
- def describe_timedelta(td: timedelta, max_components: int = 2) -> str:
- """
- Formats a human-readable description of a time span. E.g. "3 days 2 hours".
- """
- d = td.days
- h = td.seconds // 3600
- m = (td.seconds // 60) % 60
- s = td.seconds % 60
- components = []
- if d != 0:
- components.append('1 day' if d == 1 else f'{d} days')
- if h != 0:
- components.append('1 hour' if h == 1 else f'{h} hours')
- if m != 0:
- components.append('1 minute' if m == 1 else f'{m} minutes')
- if s != 0 or len(components) == 0:
- components.append('1 second' if s == 1 else f'{s} seconds')
- if len(components) > max_components:
- components = components[0:max_components]
- return ' '.join(components)
-
- def first_command_group(cog: Cog) -> Group:
- """
- Returns the first command Group found in a cog.
- """
- for member_name in dir(cog):
- member = getattr(cog, member_name)
- if isinstance(member, Group):
- return member
- return None
-
- def bot_log(guild: Guild, cog_class, message: str) -> None:
- """
- Logs a message to stdout with time, cog, and guild info.
- """
- now = datetime.now() # local
- s = f'[{now.strftime("%Y-%m-%dT%H:%M:%S")}|'
- s += f'{cog_class.__name__}|' if cog_class else '-|'
- s += f'{guild.name}] ' if guild else '-] '
- s += message
- print(s)
|