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.

cogsetting.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. """
  2. A guild configuration setting available for editing via bot commands.
  3. """
  4. from datetime import timedelta
  5. from typing import TYPE_CHECKING, Any, Literal, Optional, Union
  6. from discord import Interaction, Permissions
  7. from discord.app_commands import Range, Transform, describe
  8. from discord.app_commands.commands import Command, CommandCallback, Group, rename
  9. from discord.ext.commands import Bot
  10. from config import CONFIG
  11. from rocketbot.storage import Storage
  12. from rocketbot.utils import (
  13. MOD_PERMISSIONS,
  14. TimeDeltaTransformer,
  15. bot_log,
  16. dump_stacktrace,
  17. str_from_timedelta,
  18. )
  19. if TYPE_CHECKING:
  20. from rocketbot.cogs.basecog import BaseCog
  21. else:
  22. BaseCog = 'BaseCog'
  23. def describe_type(datatype: type) -> str:
  24. if datatype is int:
  25. return 'integer'
  26. if datatype is float:
  27. return 'float'
  28. if datatype is str:
  29. return 'string'
  30. if datatype is bool:
  31. return 'boolean'
  32. if datatype is timedelta:
  33. return 'timespan'
  34. if getattr(datatype, '__origin__', None) is Union:
  35. return '|'.join([ describe_type(a) for a in datatype.__args__ ])
  36. if getattr(datatype, '__origin__', None) is Literal:
  37. return '"' + ('"|"'.join(datatype.__args__)) + '"'
  38. return datatype.__class__.__name__
  39. class CogSetting:
  40. """
  41. Describes a configuration setting for a guild that can be edited by the
  42. mods of those guilds. BaseCog can generate "/get" and "/set" commands (or
  43. "/enable" and "/disable" commands for boolean values) automatically, reducing
  44. the boilerplate of generating commands manually. Offers simple validation rules.
  45. """
  46. permissions: Permissions = Permissions(Permissions.manage_messages.flag)
  47. def __init__(self,
  48. name: str,
  49. datatype: Optional[type],
  50. default_value: Any,
  51. brief: Optional[str] = None,
  52. description: Optional[str] = None,
  53. min_value: Optional[Any] = None,
  54. max_value: Optional[Any] = None,
  55. enum_values: Optional[set[Any]] = None):
  56. """
  57. Parameters
  58. ----------
  59. name: str
  60. Setting identifier. Must follow variable naming conventions.
  61. datatype: Optional[type]
  62. Datatype of the setting. E.g. int, float, str
  63. default_value: Any
  64. Value to use if a guild has not yet configured one.
  65. brief: Optional[str]
  66. Description of the setting, starting with lower case.
  67. Will be inserted into phrases like "Sets <brief>" and
  68. "Gets <brief>".
  69. description: Optional[str]
  70. Long-form description. Min, max, and enum values will be
  71. appended to the end, so does not need to include these.
  72. min_value: Optional[Any]
  73. Smallest allowable value. Must be of the same datatype as
  74. the value. None for no minimum.
  75. max_value: Optional[Any]
  76. Largest allowable value. None for no maximum.
  77. enum_values: Optional[set[Any]]
  78. Set of allowed values. None if unconstrained.
  79. """
  80. self.name: str = name
  81. self.datatype: type = datatype
  82. self.default_value = default_value
  83. self.brief: Optional[str] = brief
  84. self.description: str = description or '' # Can't be None
  85. self.min_value: Optional[Any] = min_value
  86. self.max_value: Optional[Any] = max_value
  87. self.enum_values: Optional[set[Any]] = enum_values
  88. if self.enum_values:
  89. value_list = '`' + ('`, `'.join(self.enum_values)) + '`'
  90. self.description += f' (Permitted values: {value_list})'
  91. elif self.min_value is not None and self.max_value is not None:
  92. self.description += f' (Value must be between `{self.min_value}` and `{self.max_value}`)'
  93. elif self.min_value is not None:
  94. self.description += f' (Minimum value: {self.min_value})'
  95. elif self.max_value is not None:
  96. self.description += f' (Maximum value: {self.max_value})'
  97. def validate_value(self, new_value: Any) -> None:
  98. """
  99. Checks if a value is legal for this setting. Raises a ValueError if not.
  100. """
  101. if self.min_value is not None and new_value < self.min_value:
  102. raise ValueError(f'`{self.name}` must be >= {self.min_value}')
  103. if self.max_value is not None and new_value > self.max_value:
  104. raise ValueError(f'`{self.name}` must be <= {self.max_value}')
  105. if self.enum_values is not None and new_value not in self.enum_values:
  106. allowed_values = '`' + ('`, `'.join(self.enum_values)) + '`'
  107. raise ValueError(f'`{self.name}` must be one of {allowed_values}')
  108. def set_up(self, cog: BaseCog) -> None:
  109. """
  110. Sets up getter and setter commands for this setting. This should
  111. usually only be called by BaseCog.
  112. """
  113. if self.name in ('enabled', 'is_enabled'):
  114. self.__enable_group.add_command(self.__make_enable_command(cog))
  115. self.__disable_group.add_command(self.__make_disable_command(cog))
  116. else:
  117. self.__get_group.add_command(self.__make_getter_command(cog))
  118. self.__set_group.add_command(self.__make_setter_command(cog))
  119. def to_stored_value(self, native_value: Any) -> Any:
  120. """Converts a configuration value to a JSON-compatible datatype."""
  121. if native_value is None:
  122. return None
  123. if self.datatype is timedelta:
  124. return native_value.total_seconds()
  125. return native_value
  126. def to_native_value(self, stored_value: Any) -> Any:
  127. """Converts the stored JSON-compatible datatype to its actual value."""
  128. if stored_value is None:
  129. return None
  130. if self.datatype is timedelta and isinstance(stored_value, (int, float)):
  131. return timedelta(seconds=stored_value)
  132. return stored_value
  133. @staticmethod
  134. def native_value_to_str(native_value: Any) -> str:
  135. """Formats a native configuration value to a user-presentable string."""
  136. if native_value is None:
  137. return '<no value>'
  138. if isinstance(native_value, timedelta):
  139. return str_from_timedelta(native_value)
  140. if isinstance(native_value, bool):
  141. return 'true' if native_value else 'false'
  142. return f'{native_value}'
  143. def __make_getter_command(self, cog: BaseCog) -> Command:
  144. setting: CogSetting = self
  145. setting_name = setting.name
  146. if cog.config_prefix is not None:
  147. setting_name = f'{cog.config_prefix}_{setting_name}'
  148. async def getter(interaction: Interaction) -> None:
  149. key = f'{cog.__class__.__name__}.{setting.name}'
  150. value = setting.to_native_value(Storage.get_config_value(interaction.guild, key))
  151. cog.log(interaction.guild, f'{interaction.user.name} used /get setting_name')
  152. if value is None:
  153. value = setting.default_value
  154. await interaction.response.send_message(
  155. f'{CONFIG["info_emoji"]} `{setting_name}` is using default of `{CogSetting.native_value_to_str(value)}`',
  156. ephemeral=True
  157. )
  158. else:
  159. await interaction.response.send_message(
  160. f'{CONFIG["info_emoji"]} `{setting_name}` is set to `{CogSetting.native_value_to_str(value)}`',
  161. ephemeral=True
  162. )
  163. bot_log(None, cog.__class__, f"Creating command: /get {setting_name}")
  164. command = Command(
  165. name=setting_name,
  166. description=f'Shows {self.brief}.',
  167. callback=getter,
  168. parent=CogSetting.__get_group,
  169. extras={
  170. 'cog': cog,
  171. 'setting': setting,
  172. 'long_description': setting.description,
  173. },
  174. )
  175. return command
  176. def __make_setter_command(self, cog: BaseCog) -> Command:
  177. setting: CogSetting = self
  178. setting_name = setting.name
  179. if cog.config_prefix is not None:
  180. setting_name = f'{cog.config_prefix}_{setting_name}'
  181. async def setter_general(interaction: Interaction, new_value) -> None:
  182. cog.log(interaction.guild, f'{interaction.user.name} used /set setting_name {new_value}')
  183. try:
  184. setting.validate_value(new_value)
  185. except ValueError as ve:
  186. await interaction.response.send_message(
  187. f'{CONFIG["failure_emoji"]} {ve}',
  188. ephemeral=True
  189. )
  190. return
  191. key = f'{cog.__class__.__name__}.{setting.name}'
  192. Storage.set_config_value(interaction.guild, key, setting.to_stored_value(new_value))
  193. await interaction.response.send_message(
  194. f'{CONFIG["success_emoji"]} `{setting_name}` is now set to `{setting.to_native_value(new_value)}`',
  195. ephemeral=True
  196. )
  197. await cog.on_setting_updated(interaction.guild, setting)
  198. setter: CommandCallback = setter_general
  199. field_description: str = self.brief
  200. if self.datatype is int:
  201. if self.min_value is not None or self.max_value is not None:
  202. r_min = self.min_value
  203. r_max = self.max_value
  204. async def setter_range(interaction: Interaction, new_value: Range[int, r_min, r_max]) -> None:
  205. await setter_general(interaction, new_value)
  206. setter = setter_range
  207. else:
  208. async def setter_int(interaction: Interaction, new_value: int) -> None:
  209. await setter_general(interaction, new_value)
  210. setter = setter_int
  211. elif self.datatype is float:
  212. async def setter_float(interaction: Interaction, new_value: float) -> None:
  213. await setter_general(interaction, new_value)
  214. setter = setter_float
  215. elif self.datatype is timedelta:
  216. field_description += ' (e.g. 30s, 5m, 1h30s, 7d)'
  217. async def setter_timedelta(interaction: Interaction, new_value: Transform[timedelta, TimeDeltaTransformer]) -> None:
  218. await setter_general(interaction, new_value)
  219. setter = setter_timedelta
  220. elif getattr(self.datatype, '__origin__', None) == Literal:
  221. dt = self.datatype
  222. async def setter_enum(interaction: Interaction, new_value: dt) -> None:
  223. await setter_general(interaction, new_value)
  224. setter = setter_enum
  225. elif self.datatype is str:
  226. if self.enum_values is not None:
  227. raise ValueError('Type for a setting with enum values should be typing.Literal')
  228. else:
  229. async def setter_str(interaction: Interaction, new_value: str) -> None:
  230. await setter_general(interaction, new_value)
  231. setter = setter_str
  232. elif self.datatype is bool:
  233. async def setter_bool(interaction: Interaction, new_value: bool) -> None:
  234. await setter_general(interaction, new_value)
  235. setter = setter_bool
  236. elif self.datatype is not None:
  237. raise ValueError(f'Invalid type {self.datatype}')
  238. setter = describe(new_value=field_description)(rename(new_value=self.name)(setter))
  239. bot_log(None, cog.__class__, f"Creating command: /set {setting_name} <{describe_type(self.datatype)}>")
  240. command = Command(
  241. name=setting_name,
  242. description=f'Sets {self.brief}.',
  243. callback=setter,
  244. parent=CogSetting.__set_group,
  245. extras={
  246. 'cog': cog,
  247. 'setting': setting,
  248. 'long_description': setting.description,
  249. },
  250. )
  251. return command
  252. def __make_enable_command(self, cog: BaseCog) -> Command:
  253. setting: CogSetting = self
  254. async def enabler(interaction: Interaction) -> None:
  255. key = f'{cog.__class__.__name__}.{setting.name}'
  256. Storage.set_config_value(interaction.guild, key, True)
  257. await interaction.response.send_message(
  258. f'{CONFIG["success_emoji"]} {setting.brief.capitalize()} enabled.',
  259. ephemeral=True
  260. )
  261. await cog.on_setting_updated(interaction.guild, setting)
  262. cog.log(interaction.guild, f'{interaction.user.name} used /enable {cog.__class__.__name__}')
  263. bot_log(None, cog.__class__, f"Creating command: /enable {cog.config_prefix}")
  264. command = Command(
  265. name=cog.config_prefix,
  266. description=f'Enables {cog.qualified_name} functionality.',
  267. callback=enabler,
  268. parent=CogSetting.__enable_group,
  269. extras={
  270. 'cog': cog,
  271. 'setting': setting,
  272. 'long_description': setting.description,
  273. },
  274. )
  275. return command
  276. def __make_disable_command(self, cog: BaseCog) -> Command:
  277. setting: CogSetting = self
  278. async def disabler(interaction: Interaction) -> None:
  279. key = f'{cog.__class__.__name__}.{setting.name}'
  280. Storage.set_config_value(interaction.guild, key, False)
  281. await interaction.response.send_message(
  282. f'{CONFIG["success_emoji"]} {setting.brief.capitalize()} disabled.',
  283. ephemeral=True
  284. )
  285. await cog.on_setting_updated(interaction.guild, setting)
  286. cog.log(interaction.guild, f'{interaction.user.name} used /disable {cog.__class__.__name__}')
  287. bot_log(None, cog.__class__, f"Creating command: /disable {cog.config_prefix}")
  288. command = Command(
  289. name=cog.config_prefix,
  290. description=f'Disables {cog.config_prefix} functionality',
  291. callback=disabler,
  292. parent=CogSetting.__disable_group,
  293. extras={
  294. 'cog': cog,
  295. 'setting': setting,
  296. 'long_description': setting.description,
  297. },
  298. )
  299. return command
  300. __set_group: Group
  301. __get_group: Group
  302. __enable_group: Group
  303. __disable_group: Group
  304. @classmethod
  305. def set_up_all(cls, cog: BaseCog, bot: Bot, settings: list['CogSetting']) -> None:
  306. """
  307. Sets up editing commands for a list of CogSettings and adds them to a
  308. cog. If the cog has a command Group, commands will be added to it.
  309. Otherwise, they will be added at the top level.
  310. """
  311. cls.__set_up_base_commands(bot)
  312. if len(settings) == 0:
  313. return
  314. for setting in settings:
  315. setting.set_up(cog)
  316. @classmethod
  317. def __set_up_base_commands(cls, bot: Bot) -> None:
  318. if getattr(cls, '_CogSetting__set_group', None) is not None:
  319. return
  320. cls.__set_group = Group(
  321. name='set',
  322. description='Sets a configuration value for this guild.',
  323. guild_only=True,
  324. default_permissions=MOD_PERMISSIONS,
  325. extras={
  326. 'long_description': 'Settings are guild-specific. If no value is set, a default is used. Use `/get` to '
  327. 'see the current value for this guild.',
  328. },
  329. )
  330. cls.__get_group = Group(
  331. name='get',
  332. description='Shows a configuration value for this guild.',
  333. guild_only=True,
  334. default_permissions=MOD_PERMISSIONS,
  335. extras={
  336. 'long_description': 'Settings are guild-specific. If no value is set, a default is used. Use `/set` to '
  337. 'change the value.',
  338. },
  339. )
  340. cls.__enable_group = Group(
  341. name='enable',
  342. description='Enables a module for this guild.',
  343. guild_only=True,
  344. default_permissions=MOD_PERMISSIONS,
  345. extras={
  346. 'long_description': 'Modules are enabled on a per-guild basis and are off by default. Use `/disable` '
  347. 'to disable an enabled module.',
  348. },
  349. )
  350. cls.__disable_group = Group(
  351. name='disable',
  352. description='Disables a module for this guild.',
  353. guild_only=True,
  354. default_permissions=MOD_PERMISSIONS,
  355. extras={
  356. 'long_description': 'Modules are enabled on a per-guild basis and are off by default. Use `/enable` '
  357. 're-enable a disabled module.',
  358. },
  359. )
  360. bot.tree.add_command(cls.__set_group)
  361. bot.tree.add_command(cls.__get_group)
  362. bot.tree.add_command(cls.__enable_group)
  363. bot.tree.add_command(cls.__disable_group)
  364. async def show_all(interaction: Interaction) -> None:
  365. from rocketbot.cogs.basecog import BaseCog
  366. try:
  367. bot_log(interaction.guild, None, f'{interaction.user.name} used /get all')
  368. guild = interaction.guild
  369. if guild is None:
  370. await interaction.response.send_message(
  371. f'{CONFIG["failure_emoji"]} No guild.',
  372. ephemeral=True,
  373. delete_after=10,
  374. )
  375. return
  376. text = '## :information_source: Configuration'
  377. for cog_name, cog in sorted(bot.cogs.items()):
  378. if not isinstance(cog, BaseCog):
  379. continue
  380. bcog: BaseCog = cog
  381. if len(bcog.settings) == 0:
  382. continue
  383. text += f'\n### {bcog.qualified_name} Module'
  384. for setting in sorted(bcog.settings, key=lambda s: (s.name != 'enabled', s.name)):
  385. key = f'{bcog.__class__.__name__}.{setting.name}'
  386. value = setting.to_native_value(Storage.get_config_value(guild, key))
  387. deflt = setting.default_value
  388. if setting.name == 'enabled':
  389. text += '\n- Module is '
  390. if value is not None:
  391. text += '**' + ('enabled' if value else 'disabled') + '**'
  392. else:
  393. text += ('enabled' if deflt else 'disabled') + ' _(default)_'
  394. else:
  395. if value is not None:
  396. text += f'\n- `{bcog.config_prefix}_{setting.name}` = **{CogSetting.native_value_to_str(value)}**'
  397. else:
  398. text += f'\n- `{bcog.config_prefix}_{setting.name}` = {CogSetting.native_value_to_str(deflt)} _(using default)_'
  399. await interaction.response.send_message(
  400. text,
  401. ephemeral=True,
  402. )
  403. except BaseException as e:
  404. dump_stacktrace(e)
  405. show_all_command = Command(
  406. name='all',
  407. description='Shows all configuration for this guild.',
  408. callback=show_all,
  409. )
  410. cls.__get_group.add_command(show_all_command)