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.

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