Experimental Discord bot written in Python
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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