Experimental Discord bot written in Python
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

basecog.py 9.8KB

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