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 9.7KB

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