Experimental Discord bot written in Python
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

utils.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. """
  2. General utility functions.
  3. """
  4. import re
  5. from datetime import datetime, timedelta
  6. from typing import Any, Optional, Type, Union
  7. from discord import Guild
  8. from discord.ext.commands import Cog, Group
  9. def timedelta_from_str(s: str) -> timedelta:
  10. """
  11. Parses a timespan. Format examples:
  12. "30m"
  13. "10s"
  14. "90d"
  15. "1h30m"
  16. "73d18h22m52s"
  17. """
  18. p: re.Pattern = re.compile('^(?:[0-9]+[dhms])+$')
  19. if p.match(s) is None:
  20. raise ValueError("Illegal timespan value '{s}'.")
  21. p = re.compile('([0-9]+)([dhms])')
  22. days: int = 0
  23. hours: int = 0
  24. minutes: int = 0
  25. seconds: int = 0
  26. for m in p.finditer(s):
  27. scalar = int(m.group(1))
  28. unit = m.group(2)
  29. if unit == 'd':
  30. days = scalar
  31. elif unit == 'h':
  32. hours = scalar
  33. elif unit == 'm':
  34. minutes = scalar
  35. elif unit == 's':
  36. seconds = scalar
  37. return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  38. def str_from_timedelta(td: timedelta) -> str:
  39. """
  40. Encodes a timedelta as a str. E.g. "3d2h"
  41. """
  42. d: int = td.days
  43. h: int = td.seconds // 3600
  44. m: int = (td.seconds // 60) % 60
  45. s: int = td.seconds % 60
  46. components: list[str] = []
  47. if d != 0:
  48. components.append(f'{d}d')
  49. if h != 0:
  50. components.append(f'{h}h')
  51. if m != 0:
  52. components.append(f'{m}m')
  53. if s != 0 or len(components) == 0:
  54. components.append(f'{s}s')
  55. return ''.join(components)
  56. def describe_timedelta(td: timedelta, max_components: int = 2) -> str:
  57. """
  58. Formats a human-readable description of a time span. E.g. "3 days 2 hours".
  59. """
  60. d: int = td.days
  61. h: int = td.seconds // 3600
  62. m: int = (td.seconds // 60) % 60
  63. s: int = td.seconds % 60
  64. components: list[str] = []
  65. if d != 0:
  66. components.append('1 day' if d == 1 else f'{d} days')
  67. if h != 0:
  68. components.append('1 hour' if h == 1 else f'{h} hours')
  69. if m != 0:
  70. components.append('1 minute' if m == 1 else f'{m} minutes')
  71. if s != 0 or len(components) == 0:
  72. components.append('1 second' if s == 1 else f'{s} seconds')
  73. if len(components) > max_components:
  74. components = components[0:max_components]
  75. return ' '.join(components)
  76. def first_command_group(cog: Cog) -> Optional[Group]:
  77. """Returns the first command Group found in a cog."""
  78. for member_name in dir(cog):
  79. member = getattr(cog, member_name)
  80. if isinstance(member, Group):
  81. return member
  82. return None
  83. def bot_log(guild: Optional[Guild], cog_class: Optional[Type], message: Any) -> None:
  84. """Logs a message to stdout with time, cog, and guild info."""
  85. now: datetime = datetime.now() # local
  86. s = f'[{now.strftime("%Y-%m-%dT%H:%M:%S")}|'
  87. s += f'{cog_class.__name__}|' if cog_class else '-|'
  88. s += f'{guild.name}] ' if guild else '-] '
  89. s += str(message)
  90. print(s)
  91. __QUOTE_CHARS: str = '\'"'
  92. __ID_REGEX: re.Pattern = re.compile('^[0-9]{17,20}$')
  93. __MENTION_REGEX: re.Pattern = re.compile('^<@[!&]([0-9]{17,20})>$')
  94. __USER_MENTION_REGEX: re.Pattern = re.compile('^<@!([0-9]{17,20})>$')
  95. __ROLE_MENTION_REGEX: re.Pattern = re.compile('^<@&([0-9]{17,20})>$')
  96. def is_user_id(val: str) -> bool:
  97. """Tests if a string is in user/role ID format."""
  98. return __ID_REGEX.match(val) is not None
  99. def is_mention(val: str) -> bool:
  100. """Tests if a string is a user or role mention."""
  101. return __MENTION_REGEX.match(val) is not None
  102. def is_role_mention(val: str) -> bool:
  103. """Tests if a string is a role mention."""
  104. return __ROLE_MENTION_REGEX.match(val) is not None
  105. def is_user_mention(val: str) -> bool:
  106. """Tests if a string is a user mention."""
  107. return __USER_MENTION_REGEX.match(val) is not None
  108. def user_id_from_mention(mention: str) -> str:
  109. """Extracts the user ID from a mention. Raises a ValueError if malformed."""
  110. m = __USER_MENTION_REGEX.match(mention)
  111. if m:
  112. return m.group(1)
  113. raise ValueError(f'"{mention}" is not an @ user mention')
  114. def mention_from_user_id(user_id: Union[str, int]) -> str:
  115. """Returns a Markdown user mention from a user id."""
  116. return f'<@!{user_id}>'
  117. def mention_from_role_id(role_id: Union[str, int]) -> str:
  118. """Returns a Markdown role mention from a role id."""
  119. return f'<@&{role_id}>'
  120. def str_from_quoted_str(val: str) -> str:
  121. """Removes the leading and trailing quotes from a string."""
  122. if len(val) < 2 or val[0:1] not in __QUOTE_CHARS or val[-1:] not in __QUOTE_CHARS:
  123. raise ValueError(f'Not a quoted string: {val}')
  124. return val[1:-1]