Experimental Discord bot written in Python
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. """
  2. A guild configuration setting available for editing via bot commands.
  3. """
  4. from datetime import timedelta
  5. from typing import Any, Optional, Type, TypeVar, Literal
  6. from discord import Interaction, Permissions
  7. from discord.app_commands import Range, Transform
  8. from discord.app_commands.commands import Command, Group, CommandCallback
  9. from discord.ext.commands import Bot
  10. from config import CONFIG
  11. from rocketbot.storage import Storage
  12. from rocketbot.utils import bot_log, TimeDeltaTransformer
  13. # def _fix_command(command: Command) -> None:
  14. # """
  15. # HACK: Fixes bug in discord.py 2.3.2 where it's requiring the user to
  16. # supply the context argument. This removes that argument from the list.
  17. # """
  18. # params = command.params
  19. # del params['context']
  20. # command.params = params
  21. BaseCog = TypeVar('BaseCog', bound='rocketbot.cogs.BaseCog')
  22. class CogSetting:
  23. permissions: Permissions = Permissions(Permissions.manage_messages.flag)
  24. """
  25. Describes a configuration setting for a guild that can be edited by the
  26. mods of those guilds. BaseCog can generate "get" and "set" commands (or
  27. "enable" and "disable" commands for boolean values) automatically, reducing
  28. the boilerplate of generating commands manually. Offers simple validation rules.
  29. """
  30. def __init__(self,
  31. name: str,
  32. datatype: Optional[Type],
  33. brief: Optional[str] = None,
  34. description: Optional[str] = None,
  35. usage: Optional[str] = None,
  36. min_value: Optional[Any] = None,
  37. max_value: Optional[Any] = None,
  38. enum_values: Optional[set[Any]] = None):
  39. """
  40. Parameters
  41. ----------
  42. name: str
  43. Setting identifier. Must follow variable naming conventions.
  44. datatype: Optional[Type]
  45. Datatype of the setting. E.g. int, float, str
  46. brief: Optional[str]
  47. Description of the setting, starting with lower case.
  48. Will be inserted into phrases like "Sets <brief>" and
  49. "Gets <brief".
  50. description: Optional[str]
  51. Long-form description. Min, max, and enum values will be
  52. appended to the end, so does not need to include these.
  53. usage: Optional[str]
  54. Description of the value argument in a set command, e.g. "<maxcount:int>"
  55. min_value: Optional[Any]
  56. Smallest allowable value. Must be of the same datatype as
  57. the value. None for no minimum.
  58. max_value: Optional[Any]
  59. Largest allowable value. None for no maximum.
  60. enum_values: Optional[set[Any]]
  61. Set of allowed values. None if unconstrained.
  62. """
  63. self.name: str = name
  64. self.datatype: Type = datatype
  65. self.brief: Optional[str] = brief
  66. self.description: str = description or '' # Can't be None
  67. self.usage: Optional[str] = usage
  68. self.min_value: Optional[Any] = min_value
  69. self.max_value: Optional[Any] = max_value
  70. self.enum_values: Optional[set[Any]] = enum_values
  71. if self.enum_values or self.min_value is not None or self.max_value is not None:
  72. self.description += '\n'
  73. if self.enum_values:
  74. allowed_values = '`' + ('`, `'.join(enum_values)) + '`'
  75. self.description += f'\nAllowed values: {allowed_values}'
  76. if self.min_value is not None:
  77. self.description += f'\nMin value: {self.min_value}'
  78. if self.max_value is not None:
  79. self.description += f'\nMax value: {self.max_value}'
  80. if self.usage is None:
  81. self.usage = f'<{self.name}>'
  82. def validate_value(self, new_value: Any) -> None:
  83. """
  84. Checks if a value is legal for this setting. Raises a ValueError if not.
  85. """
  86. if self.min_value is not None and new_value < self.min_value:
  87. raise ValueError(f'`{self.name}` must be >= {self.min_value}')
  88. if self.max_value is not None and new_value > self.max_value:
  89. raise ValueError(f'`{self.name}` must be <= {self.max_value}')
  90. if self.enum_values is not None and new_value not in self.enum_values:
  91. allowed_values = '`' + ('`, `'.join(self.enum_values)) + '`'
  92. raise ValueError(f'`{self.name}` must be one of {allowed_values}')
  93. def set_up(self, cog: BaseCog, bot: Bot) -> None:
  94. """
  95. Sets up getter and setter commands for this setting. This should
  96. usually only be called by BaseCog.
  97. """
  98. if self.name in ('enabled', 'is_enabled'):
  99. self.__enable_group.add_command(self.__make_enable_command(cog))
  100. self.__disable_group.add_command(self.__make_disable_command(cog))
  101. else:
  102. self.__get_group.add_command(self.__make_getter_command(cog))
  103. self.__set_group.add_command(self.__make_setter_command(cog))
  104. def __make_getter_command(self, cog: BaseCog) -> Command:
  105. setting: CogSetting = self
  106. setting_name = setting.name
  107. if cog.config_prefix is not None:
  108. setting_name = f'{cog.config_prefix}_{setting_name}'
  109. async def getter(self, interaction: Interaction) -> None:
  110. print(f"invoking getter for {setting_name}")
  111. key = f'{self.__class__.__name__}.{setting.name}'
  112. value = Storage.get_config_value(interaction.guild, key)
  113. if value is None:
  114. value = self.get_cog_default(setting.name)
  115. await interaction.response.send_message(
  116. f'{CONFIG["info_emoji"]} `{setting_name}` is using default of `{value}`',
  117. ephemeral=True
  118. )
  119. else:
  120. await interaction.response.send_message(
  121. f'{CONFIG["info_emoji"]} `{setting_name}` is set to `{value}`',
  122. ephemeral=True
  123. )
  124. setattr(cog.__class__, f'_cmd_get_{setting.name}', getter)
  125. getter.__qualname__ = f'{self.__class__.__name__}._cmd_get_{setting.name}'
  126. getter.__self__ = cog
  127. bot_log(None, cog.__class__, f"Creating /get {setting_name}")
  128. command = Command(
  129. name=setting_name,
  130. description=f'Shows {self.brief}.',
  131. callback=getter,
  132. parent=CogSetting.__get_group,
  133. )
  134. return command
  135. def __make_setter_command(self, cog: BaseCog) -> Command:
  136. setting: CogSetting = self
  137. setting_name = setting.name
  138. if cog.config_prefix is not None:
  139. setting_name = f'{cog.config_prefix}_{setting_name}'
  140. async def setter_general(self, interaction: Interaction, new_value) -> None:
  141. print(f"invoking setter for {setting_name} with value {new_value}")
  142. try:
  143. setting.validate_value(new_value)
  144. except ValueError as ve:
  145. await interaction.response.send_message(
  146. f'{CONFIG["failure_emoji"]} {ve}',
  147. ephemeral=True
  148. )
  149. return
  150. key = f'{self.__class__.__name__}.{setting.name}'
  151. Storage.set_config_value(interaction.guild, key, new_value)
  152. await interaction.response.send_message(
  153. f'{CONFIG["success_emoji"]} `{setting_name}` is now set to `{new_value}`',
  154. ephemeral=True
  155. )
  156. await self.on_setting_updated(interaction.guild, setting)
  157. self.log(interaction.guild, f'{interaction.user.name} set {key} to {new_value}')
  158. setter: CommandCallback = setter_general
  159. if self.datatype == int:
  160. if self.min_value is not None or self.max_value is not None:
  161. r_min = self.min_value
  162. r_max = self.max_value
  163. async def setter_range(self, interaction: Interaction, new_value: Range[int, r_min, r_max]) -> None:
  164. await self.setter_general(interaction, new_value)
  165. setter = setter_range
  166. else:
  167. async def setter_int(self, interaction: Interaction, new_value: int) -> None:
  168. await self.setter_general(interaction, new_value)
  169. setter = setter_int
  170. elif self.datatype == float:
  171. async def setter_float(self, interaction: Interaction, new_value: float) -> None:
  172. await self.setter_general(interaction, new_value)
  173. setter = setter_float
  174. elif self.datatype == timedelta:
  175. async def setter_timedelta(self, interaction: Interaction, new_value: Transform[timedelta, TimeDeltaTransformer]) -> None:
  176. await self.setter_general(interaction, new_value)
  177. setter = setter_timedelta
  178. elif getattr(self.datatype, '__origin__', None) == Literal:
  179. dt = self.datatype
  180. async def setter_enum(self, interaction: Interaction, new_value: dt) -> None:
  181. await self.setter_general(interaction, new_value)
  182. setter = setter_enum
  183. elif self.datatype == str:
  184. if self.enum_values is not None:
  185. raise ValueError('Type for a setting with enum values should be typing.Literal')
  186. else:
  187. async def setter_str(self, interaction: Interaction, new_value: str) -> None:
  188. await self.setter_general(interaction, new_value)
  189. setter = setter_str
  190. elif setting.datatype == bool:
  191. async def setter_bool(self, interaction: Interaction, new_value: bool) -> None:
  192. await self.setter_general(interaction, new_value)
  193. setter = setter_bool
  194. elif setting.datatype is not None:
  195. raise ValueError(f'Invalid type {self.datatype}')
  196. setattr(cog.__class__, f'_cmd_set_{setting.name}', setter)
  197. setter.__qualname__ = f'{cog.__class__.__name__}._cmd_set_{setting.name}'
  198. setter.__self__ = cog
  199. bot_log(None, cog.__class__, f"Creating /set {setting_name} {self.datatype}")
  200. command = Command(
  201. name=setting_name,
  202. description=f'Sets {self.brief}.',
  203. callback=setter,
  204. parent=CogSetting.__set_group,
  205. )
  206. # HACK: Passing `cog` in init gets ignored and set to `None` so set after.
  207. # This ensures the callback is passed the cog as `self` argument.
  208. # command.cog = cog
  209. # _fix_command(command)
  210. return command
  211. def __make_enable_command(self, cog: BaseCog) -> Command:
  212. setting: CogSetting = self
  213. async def enabler(self: BaseCog, interaction: Interaction) -> None:
  214. print(f"invoking enable for {self.config_prefix}")
  215. key = f'{self.__class__.__name__}.{setting.name}'
  216. Storage.set_config_value(interaction.guild, key, True)
  217. await interaction.response.send_message(
  218. f'{CONFIG["success_emoji"]} {setting.brief.capitalize()} enabled.',
  219. ephemeral=True
  220. )
  221. await self.on_setting_updated(interaction.guild, setting)
  222. self.log(interaction.guild, f'{interaction.user.name} enabled {self.__class__.__name__}')
  223. setattr(cog.__class__, f'_cmd_enable', enabler)
  224. enabler.__qualname__ = f'{cog.__class__.__name__}._cmd_enable'
  225. enabler.__self__ = cog
  226. bot_log(None, cog.__class__, f"Creating /enable {cog.config_prefix}")
  227. command = Command(
  228. name=cog.config_prefix,
  229. description=f'Enables {cog.config_prefix} functionality',
  230. callback=enabler,
  231. parent=CogSetting.__enable_group,
  232. )
  233. # command.cog = cog
  234. # _fix_command(command)
  235. return command
  236. def __make_disable_command(self, cog: BaseCog) -> Command:
  237. setting: CogSetting = self
  238. async def disabler(self: BaseCog, interaction: Interaction) -> None:
  239. print(f"invoking disable for {self.config_prefix}")
  240. key = f'{self.__class__.__name__}.{setting.name}'
  241. Storage.set_config_value(interaction.guild, key, False)
  242. await interaction.response.send_message(
  243. f'{CONFIG["success_emoji"]} {setting.brief.capitalize()} disabled.',
  244. ephemeral=True
  245. )
  246. await self.on_setting_updated(interaction.guild, setting)
  247. self.log(interaction.guild, f'{interaction.user.name} disabled {self.__class__.__name__}')
  248. setattr(cog.__class__, f'_cmd_disable', disabler)
  249. disabler.__qualname__ = f'{cog.__class__.__name__}._cmd_disable'
  250. disabler.__self__ = cog
  251. bot_log(None, cog.__class__, f"Creating /disable {cog.config_prefix}")
  252. command = Command(
  253. name=cog.config_prefix,
  254. description=f'Disables {cog.config_prefix} functionality',
  255. callback=disabler,
  256. parent=CogSetting.__disable_group,
  257. )
  258. # command.cog = cog
  259. # _fix_command(command)
  260. return command
  261. __has_set_up_base_commands: bool = False
  262. __set_group: Group
  263. __get_group: Group
  264. __enable_group: Group
  265. __disable_group: Group
  266. @classmethod
  267. def set_up_all(cls, cog: BaseCog, bot: Bot, settings: list['CogSetting']) -> None:
  268. """
  269. Sets up editing commands for a list of CogSettings and adds them to a
  270. cog. If the cog has a command Group, commands will be added to it.
  271. Otherwise, they will be added at the top level.
  272. """
  273. cls.__set_up_base_commands(bot)
  274. if len(settings) == 0:
  275. return
  276. bot_log(None, cog.__class__, f"Setting up slash commands for {cog.__class__.__name__}")
  277. for setting in settings:
  278. setting.set_up(cog, bot)
  279. bot_log(None, cog.__class__, f"Done setting up slash commands for {cog.__class__.__name__}")
  280. @classmethod
  281. def __set_up_base_commands(cls, bot: Bot) -> None:
  282. if cls.__has_set_up_base_commands:
  283. return
  284. cls.__has_set_up_base_commands = True
  285. cls.__set_group = Group(
  286. name='set',
  287. description='Sets a bot configuration value for this guild',
  288. default_permissions=cls.permissions
  289. )
  290. cls.__get_group = Group(
  291. name='get',
  292. description='Shows a configured bot value for this guild',
  293. default_permissions=cls.permissions
  294. )
  295. cls.__enable_group = Group(
  296. name='enable',
  297. description='Enables bot functionality for this guild',
  298. default_permissions=cls.permissions
  299. )
  300. cls.__disable_group = Group(
  301. name='disable',
  302. description='Disables bot functionality for this guild',
  303. default_permissions=cls.permissions
  304. )
  305. bot.tree.add_command(cls.__set_group)
  306. bot.tree.add_command(cls.__get_group)
  307. bot.tree.add_command(cls.__enable_group)
  308. bot.tree.add_command(cls.__disable_group)