Experimental Discord bot written in Python
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

basecog.py 8.2KB

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