Experimental Discord bot written in Python
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

utils.py 3.9KB

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