Experimental Discord bot written in Python
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

utils.py 4.6KB

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