Experimental Discord bot written in Python
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

basecog.py 10KB

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