Experimental Discord bot written in Python
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

basecog.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. """
  2. Base cog class and helper classes.
  3. """
  4. from datetime import datetime, timedelta, timezone
  5. from typing import Optional
  6. import discord
  7. from discord import (
  8. Guild,
  9. Intents,
  10. Interaction,
  11. Member,
  12. Message,
  13. RawReactionActionEvent,
  14. TextChannel,
  15. )
  16. from discord.abc import GuildChannel
  17. from discord.app_commands import AppCommandError
  18. from discord.app_commands.errors import CommandInvokeError
  19. from discord.ext.commands import Cog
  20. from config import CONFIG
  21. from rocketbot.bot import Rocketbot
  22. from rocketbot.botmessage import BotMessage, BotMessageReaction
  23. from rocketbot.cogsetting import CogSetting
  24. from rocketbot.collections import AgeBoundDict
  25. from rocketbot.storage import Storage
  26. from rocketbot.utils import bot_log, dump_stacktrace, norm_datetime
  27. class WarningContext:
  28. def __init__(self, member: Member, warn_time: datetime):
  29. self.member = member
  30. self.last_warned = warn_time
  31. class BaseCog(Cog):
  32. STATE_KEY_RECENT_WARNINGS = "BaseCog.recent_warnings"
  33. """
  34. Superclass for all Rocketbot cogs. Provides lots of conveniences for
  35. common tasks.
  36. """
  37. def __init__(
  38. self,
  39. bot: Rocketbot,
  40. config_prefix: Optional[str],
  41. short_description: str,
  42. long_description: Optional[str] = None,
  43. ):
  44. """
  45. Parameters
  46. ----------
  47. bot: Rocketbot
  48. config_prefix: str
  49. Prefix to show on variables in /set and /get commands to namespace
  50. configuration variables. E.g. if config_prefix is "foo", a config
  51. variable named "bar" in that cog will show as "foo.bar". If None,
  52. config variable acts as a top-level variable with no prefix.
  53. """
  54. self.bot: Rocketbot = bot
  55. self.are_settings_setup: bool = False
  56. self.settings: list[CogSetting] = []
  57. self.config_prefix: Optional[str] = config_prefix
  58. self.short_description: str = short_description
  59. self.long_description: str = long_description
  60. async def cog_app_command_error(self, interaction: Interaction, error: AppCommandError) -> None:
  61. if isinstance(error, CommandInvokeError):
  62. error = error.original
  63. bot_log(interaction.guild, type(self), f"Error in {interaction.command.qualified_name if interaction.command else 'unknown command'}")
  64. dump_stacktrace(error)
  65. message = f"\nException: {error.__class__.__name__}, "\
  66. f"Command: {interaction.command.qualified_name if interaction.command else None}, "\
  67. f"User: {interaction.user}, "\
  68. f"Time: {discord.utils.format_dt(interaction.created_at, style='F')}"
  69. try:
  70. await interaction.response.send_message(f"An error occurred: {message}", ephemeral=True)
  71. except discord.InteractionResponded:
  72. try:
  73. await interaction.followup.send(f"An error occurred: {message}", ephemeral=True)
  74. except BaseException:
  75. interaction.channel.send
  76. bot_log(interaction.guild, None, message)
  77. @property
  78. def basecogs(self) -> list['BaseCog']:
  79. """
  80. List of BaseCog instances. Cogs that do not inherit from BaseCog are omitted.
  81. """
  82. return [
  83. bcog
  84. for bcog in sorted(self.bot.cogs.values(), key=lambda c: c.qualified_name)
  85. if isinstance(bcog, BaseCog)
  86. ]
  87. @property
  88. def basecog_map(self) -> dict[str, 'BaseCog']:
  89. """
  90. Map of qualified names to BaseCog instances. Cogs that do not inherit
  91. from BaseCog are omitted.
  92. """
  93. return {
  94. qname: bcog
  95. for qname, bcog in self.bot.cogs.items()
  96. if isinstance(bcog, BaseCog)
  97. }
  98. # Config
  99. def add_setting(self, setting: CogSetting) -> None:
  100. """
  101. Called by a subclass in __init__ to register a mod-configurable
  102. guild setting. A "get" and "set" command will be generated. If the
  103. setting is named "enabled" (exactly) then "enable" and "disable"
  104. commands will be created instead which set the setting to True/False.
  105. If the cog has a command group it will be detected automatically and
  106. the commands added to that. Otherwise, the commands will be added at
  107. the top level.
  108. Changes to settings can be detected by overriding `on_setting_updated`.
  109. """
  110. self.settings.append(setting)
  111. @classmethod
  112. def get_guild_setting(cls,
  113. guild: Optional[Guild],
  114. setting: CogSetting,
  115. use_cog_default_if_not_set: bool = True):
  116. """
  117. Returns the configured value for a setting for the given guild. If no
  118. setting is configured the default for the cog will be returned,
  119. unless the optional `use_cog_default_if_not_set` is `False`, then
  120. `None` will be returned.
  121. """
  122. if guild:
  123. key = f'{cls.__name__}.{setting.name}'
  124. stored_value = Storage.get_config_value(guild, key)
  125. if stored_value is not None:
  126. return setting.to_native_value(stored_value)
  127. if use_cog_default_if_not_set:
  128. return setting.default_value
  129. return None
  130. @classmethod
  131. def set_guild_setting(cls,
  132. guild: Guild,
  133. setting: CogSetting,
  134. new_value) -> None:
  135. """
  136. Manually sets a setting for the given guild. BaseCog creates "get" and
  137. "set" commands for guild administrators to configure values themselves,
  138. but this method can be used for hidden settings from code. A ValueError
  139. will be raised if the new value does not pass validation specified in
  140. the CogSetting.
  141. """
  142. setting.validate_value(new_value)
  143. key = f'{cls.__name__}.{setting.name}'
  144. stored_value = setting.to_stored_value(new_value)
  145. Storage.set_config_value(guild, key, stored_value)
  146. # @commands.Cog.listener()
  147. async def __on_ready(self):
  148. """Event listener"""
  149. if not self.are_settings_setup:
  150. self.are_settings_setup = True
  151. CogSetting.set_up_all(self, self.bot, self.settings)
  152. async def on_setting_updated(self, guild: Guild, setting: CogSetting) -> None:
  153. """
  154. Subclass override point for being notified when a CogSetting is edited.
  155. """
  156. # Warning squelch
  157. def was_warned_recently(self, member: Member) -> bool:
  158. """
  159. Tests if a given member was included in a mod warning message recently.
  160. Used to suppress redundant messages. Should be checked before pinging
  161. mods for relatively minor warnings about single users, but warnings
  162. about larger threats involving several members (e.g. join raids) should
  163. issue warnings regardless. Call record_warning or record_warnings after
  164. triggering a mod warning.
  165. """
  166. recent_warns: AgeBoundDict[int, WarningContext, datetime, timedelta] = Storage.get_state_value(member.guild,
  167. BaseCog.STATE_KEY_RECENT_WARNINGS)
  168. if recent_warns is None:
  169. return False
  170. context: WarningContext = recent_warns.get(member.id)
  171. if context is None:
  172. return False
  173. squelch_warning_seconds: int = CONFIG['squelch_warning_seconds']
  174. return datetime.now(timezone.utc) - context.last_warned < timedelta(seconds=squelch_warning_seconds)
  175. def record_warning(self, member: Member):
  176. """
  177. Records that mods have been warned about a member and do not need to be
  178. warned about them again for a short while.
  179. """
  180. recent_warns: AgeBoundDict[int, WarningContext, datetime, timedelta] = Storage.get_state_value(member.guild,
  181. BaseCog.STATE_KEY_RECENT_WARNINGS)
  182. if recent_warns is None:
  183. recent_warns = AgeBoundDict(timedelta(seconds=CONFIG['squelch_warning_seconds']),
  184. lambda i, context0 : context0.last_warned)
  185. Storage.set_state_value(member.guild, BaseCog.STATE_KEY_RECENT_WARNINGS, recent_warns)
  186. context: WarningContext = recent_warns.get(member.id)
  187. if context is None:
  188. context = WarningContext(member, datetime.now(timezone.utc))
  189. recent_warns[member.id] = context
  190. else:
  191. context.last_warned = datetime.now(timezone.utc)
  192. def record_warnings(self, members: list[Member]):
  193. """
  194. Records that mods have been warned about some members and do not need to
  195. be warned about them again for a short while.
  196. """
  197. for member in members:
  198. self.record_warning(member)
  199. # Bot message handling
  200. @classmethod
  201. def __bot_messages(cls, guild: Guild) -> AgeBoundDict[int, BotMessage, datetime, timedelta]:
  202. bm: AgeBoundDict[int, BotMessage, datetime, timedelta] = Storage.get_state_value(guild, 'bot_messages')
  203. if bm is None:
  204. far_future = datetime.now(timezone.utc) + timedelta(days=1000)
  205. bm = AgeBoundDict(timedelta(seconds=600),
  206. lambda k, v : norm_datetime(v.message_sent_at()) or far_future)
  207. Storage.set_state_value(guild, 'bot_messages', bm)
  208. return bm
  209. async def post_message(self, message: BotMessage) -> bool:
  210. """
  211. Posts a BotMessage to a guild. Returns whether it was successful. If
  212. the caller wants to listen to reactions they should be added before
  213. calling this method. Listen to reactions by overriding `on_mod_react`.
  214. """
  215. message.source_cog = self
  216. await message.update()
  217. return message.is_sent()
  218. @Cog.listener()
  219. async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
  220. """Event handler"""
  221. # Avoid any unnecessary requests. Gets called for every reaction
  222. # multiplied by every active cog.
  223. if payload.user_id == self.bot.user.id:
  224. # Ignore bot's own reactions
  225. return
  226. guild: Guild = self.bot.get_guild(payload.guild_id) or await self.bot.fetch_guild(payload.guild_id)
  227. if guild is None:
  228. # Possibly a DM
  229. return
  230. guild_messages: dict[int, BotMessage] = Storage.get_bot_messages(guild)
  231. bot_message = guild_messages.get(payload.message_id)
  232. if bot_message is None:
  233. # Unknown message (expired or was never tracked)
  234. return
  235. if self is not bot_message.source_cog:
  236. # Belongs to a different cog
  237. return
  238. reaction = bot_message.reaction_for_emoji(payload.emoji)
  239. if reaction is None or not reaction.is_enabled:
  240. # Can't use this reaction with this message
  241. return
  242. g_channel: GuildChannel = guild.get_channel(payload.channel_id) or await guild.fetch_channel(payload.channel_id)
  243. if g_channel is None:
  244. # Possibly a DM
  245. return
  246. if not isinstance(g_channel, TextChannel):
  247. return
  248. channel: TextChannel = g_channel
  249. member: Member = payload.member
  250. if member is None:
  251. return
  252. if not channel.permissions_for(member).ban_members:
  253. # Not a mod (could make permissions configurable per BotMessageReaction some day)
  254. return
  255. message: Message = await channel.fetch_message(payload.message_id)
  256. if message is None:
  257. # Message deleted?
  258. return
  259. if message.author.id != self.bot.user.id:
  260. # Bot didn't author this
  261. return
  262. await self.on_mod_react(bot_message, reaction, member)
  263. async def on_mod_react(self,
  264. bot_message: BotMessage,
  265. reaction: BotMessageReaction,
  266. reacted_by: Member) -> None:
  267. """
  268. Subclass override point for receiving mod reactions to bot messages sent
  269. via `post_message()`.
  270. """
  271. # Helpers
  272. @classmethod
  273. def log(cls, guild: Optional[Guild], message) -> None:
  274. """
  275. Writes a message to the console. Intended for significant events only.
  276. """
  277. bot_log(guild, cls, message)
  278. # Meta
  279. @classmethod
  280. def supports_intents(cls, intents: Intents) -> bool:
  281. return True