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.

patterncog.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. """
  2. Cog for matching messages against guild-configurable criteria and taking
  3. automated actions on them.
  4. """
  5. from datetime import datetime
  6. from discord import Guild, Member, Message, utils as discordutils
  7. from discord.ext import commands
  8. from config import CONFIG
  9. from rocketbot.cogs.basecog import BaseCog, BotMessage, BotMessageReaction
  10. from rocketbot.cogsetting import CogSetting
  11. from rocketbot.pattern import PatternCompiler, PatternDeprecationError, \
  12. PatternError, PatternStatement
  13. from rocketbot.storage import Storage
  14. class PatternContext:
  15. """
  16. Data about a message that has matched a configured statement and what
  17. actions have been carried out.
  18. """
  19. def __init__(self, message: Message, statement: PatternStatement):
  20. self.message = message
  21. self.statement = statement
  22. self.is_deleted = False
  23. self.is_kicked = False
  24. self.is_banned = False
  25. class PatternCog(BaseCog, name='Pattern Matching'):
  26. """
  27. Highly flexible cog for performing various actions on messages that match
  28. various critera. Patterns can be defined by mods for each guild.
  29. """
  30. SETTING_PATTERNS = CogSetting('patterns', None)
  31. def __get_patterns(self, guild: Guild) -> dict[str, PatternStatement]:
  32. """
  33. Returns a name -> PatternStatement lookup for the guild.
  34. """
  35. patterns: dict[str, PatternStatement] = Storage.get_state_value(guild,
  36. 'PatternCog.patterns')
  37. if patterns is None:
  38. jsons: list[dict] = self.get_guild_setting(guild, self.SETTING_PATTERNS)
  39. pattern_list: list[PatternStatement] = []
  40. for json in jsons:
  41. try:
  42. ps = PatternStatement.from_json(json)
  43. pattern_list.append(ps)
  44. try:
  45. ps.check_deprecations()
  46. except PatternDeprecationError as e:
  47. self.log(guild, f'Pattern {ps.name}: {e}')
  48. except PatternError as e:
  49. self.log(guild, f'Error decoding pattern "{json["name"]}": {e}')
  50. patterns = { p.name:p for p in pattern_list}
  51. Storage.set_state_value(guild, 'PatternCog.patterns', patterns)
  52. return patterns
  53. @classmethod
  54. def __save_patterns(cls,
  55. guild: Guild,
  56. patterns: dict[str, PatternStatement]) -> None:
  57. to_save: list[dict] = list(map(PatternStatement.to_json, patterns.values()))
  58. cls.set_guild_setting(guild, cls.SETTING_PATTERNS, to_save)
  59. @classmethod
  60. def __get_last_matched(cls, guild: Guild, name: str) -> datetime:
  61. last_matched: dict[name, datetime] = Storage.get_state_value(guild, 'PatternCog.last_matched')
  62. if last_matched:
  63. return last_matched.get(name)
  64. return None
  65. @classmethod
  66. def __set_last_matched(cls, guild: Guild, name: str, time: datetime) -> None:
  67. last_matched: dict[name, datetime] = Storage.get_state_value(guild, 'PatternCog.last_matched')
  68. if last_matched is None:
  69. last_matched = {}
  70. Storage.set_state_value(guild, 'PatternCog.last_matched', last_matched)
  71. last_matched[name] = time
  72. @commands.Cog.listener()
  73. async def on_message(self, message: Message) -> None:
  74. 'Event listener'
  75. if message.author is None or \
  76. message.author.bot or \
  77. message.channel is None or \
  78. message.guild is None or \
  79. message.content is None or \
  80. message.content == '':
  81. return
  82. if message.author.permissions_in(message.channel).ban_members:
  83. # Ignore mods
  84. return
  85. patterns = self.__get_patterns(message.guild)
  86. for statement in sorted(patterns.values(), key=lambda s : s.priority, reverse=True):
  87. other_fields = {
  88. 'last_matched': self.__get_last_matched(message.guild, statement.name),
  89. }
  90. if statement.expression.matches(message, other_fields):
  91. self.__set_last_matched(message.guild, statement.name, message.created_at)
  92. await self.__trigger_actions(message, statement)
  93. break
  94. async def __trigger_actions(self,
  95. message: Message,
  96. statement: PatternStatement) -> None:
  97. context = PatternContext(message, statement)
  98. should_post_message = False
  99. message_type: int = BotMessage.TYPE_DEFAULT
  100. action_descriptions = []
  101. self.log(message.guild, f'Message from {message.author.name} matched ' + \
  102. f'pattern "{statement.name}"')
  103. for action in statement.actions:
  104. if action.action == 'ban':
  105. await message.author.ban(
  106. reason='Rocketbot: Message matched custom pattern named ' + \
  107. f'"{statement.name}"',
  108. delete_message_days=0)
  109. context.is_banned = True
  110. context.is_kicked = True
  111. action_descriptions.append('Author banned')
  112. self.log(message.guild, f'{message.author.name} banned')
  113. elif action.action == 'delete':
  114. await message.delete()
  115. context.is_deleted = True
  116. action_descriptions.append('Message deleted')
  117. self.log(message.guild, f'{message.author.name}\'s message deleted')
  118. elif action.action == 'kick':
  119. await message.author.kick(
  120. reason='Rocketbot: Message matched custom pattern named ' + \
  121. f'"{statement.name}"')
  122. context.is_kicked = True
  123. action_descriptions.append('Author kicked')
  124. self.log(message.guild, f'{message.author.name} kicked')
  125. elif action.action == 'modinfo':
  126. should_post_message = True
  127. message_type = BotMessage.TYPE_INFO
  128. action_descriptions.append('Message logged')
  129. elif action.action == 'modwarn':
  130. should_post_message = not self.was_warned_recently(message.author)
  131. message_type = BotMessage.TYPE_MOD_WARNING
  132. action_descriptions.append('Mods alerted')
  133. elif action.action == 'reply':
  134. await message.reply(
  135. f'{action.arguments[0]}',
  136. mention_author=False)
  137. action_descriptions.append('Autoreplied')
  138. self.log(message.guild, f'autoreplied to {message.author.name}')
  139. if should_post_message:
  140. bm = BotMessage(
  141. message.guild,
  142. f'User {message.author.name} tripped custom pattern ' + \
  143. f'`{statement.name}`.\n\nAutomatic actions taken:\n• ' + \
  144. ('\n• '.join(action_descriptions)),
  145. type=message_type,
  146. context=context)
  147. self.record_warning(message.author)
  148. bm.quote = discordutils.remove_markdown(message.clean_content)
  149. await bm.set_reactions(BotMessageReaction.standard_set(
  150. did_delete=context.is_deleted,
  151. did_kick=context.is_kicked,
  152. did_ban=context.is_banned))
  153. await self.post_message(bm)
  154. async def on_mod_react(self,
  155. bot_message: BotMessage,
  156. reaction: BotMessageReaction,
  157. reacted_by: Member) -> None:
  158. context: PatternContext = bot_message.context
  159. if reaction.emoji == CONFIG['trash_emoji']:
  160. await context.message.delete()
  161. context.is_deleted = True
  162. elif reaction.emoji == CONFIG['kick_emoji']:
  163. await context.message.author.kick(
  164. reason='Rocketbot: Message matched custom pattern named ' + \
  165. f'"{context.statement.name}". Kicked by {reacted_by.name}.')
  166. context.is_kicked = True
  167. elif reaction.emoji == CONFIG['ban_emoji']:
  168. await context.message.author.ban(
  169. reason='Rocketbot: Message matched custom pattern named ' + \
  170. f'"{context.statement.name}". Banned by {reacted_by.name}.',
  171. delete_message_days=1)
  172. context.is_banned = True
  173. await bot_message.set_reactions(BotMessageReaction.standard_set(
  174. did_delete=context.is_deleted,
  175. did_kick=context.is_kicked,
  176. did_ban=context.is_banned))
  177. @commands.group(
  178. brief='Manages message pattern matching',
  179. )
  180. @commands.has_permissions(ban_members=True)
  181. @commands.guild_only()
  182. async def pattern(self, context: commands.Context):
  183. 'Message pattern matching command group'
  184. if context.invoked_subcommand is None:
  185. await context.send_help()
  186. @pattern.command(
  187. brief='Adds a custom pattern',
  188. description='Adds a custom pattern. Patterns use a simplified ' + \
  189. 'expression language. Full documentation found here: ' + \
  190. 'https://git.rixafrix.com/ialbert/python-app-rocketbot/src/' + \
  191. 'branch/master/patterns.md',
  192. usage='<pattern_name> <expression...>',
  193. ignore_extra=True
  194. )
  195. async def add(self, context: commands.Context, name: str):
  196. 'Command handler'
  197. pattern_str = PatternCompiler.expression_str_from_context(context, name)
  198. try:
  199. statement = PatternCompiler.parse_statement(name, pattern_str)
  200. statement.check_deprecations()
  201. patterns = self.__get_patterns(context.guild)
  202. patterns[name] = statement
  203. self.__save_patterns(context.guild, patterns)
  204. await context.message.reply(
  205. f'{CONFIG["success_emoji"]} Pattern `{name}` added.',
  206. mention_author=False)
  207. except PatternError as e:
  208. await context.message.reply(
  209. f'{CONFIG["failure_emoji"]} Error parsing statement. {e}',
  210. mention_author=False)
  211. @pattern.command(
  212. brief='Removes a custom pattern',
  213. usage='<pattern_name>'
  214. )
  215. async def remove(self, context: commands.Context, name: str):
  216. 'Command handler'
  217. patterns = self.__get_patterns(context.guild)
  218. if patterns.get(name) is not None:
  219. del patterns[name]
  220. self.__save_patterns(context.guild, patterns)
  221. await context.message.reply(
  222. f'{CONFIG["success_emoji"]} Pattern `{name}` deleted.',
  223. mention_author=False)
  224. else:
  225. await context.message.reply(
  226. f'{CONFIG["failure_emoji"]} No pattern named `{name}`.',
  227. mention_author=False)
  228. @pattern.command(
  229. brief='Lists all patterns'
  230. )
  231. async def list(self, context: commands.Context) -> None:
  232. 'Command handler'
  233. patterns = self.__get_patterns(context.guild)
  234. if len(patterns) == 0:
  235. await context.message.reply('No patterns defined.', mention_author=False)
  236. return
  237. msg = ''
  238. for name, statement in sorted(patterns.items()):
  239. msg += f'Pattern `{name}` (priority={statement.priority}):\n```\n{statement.original}\n```\n'
  240. await context.message.reply(msg, mention_author=False)
  241. @pattern.command(
  242. brief='Sets a pattern\'s priority level',
  243. description='Sets the priority for a pattern. Messages are checked ' +
  244. 'against patterns with the highest priority first. Patterns with ' +
  245. 'the same priority may be checked in arbitrary order. Default ' +
  246. 'priority is 100.',
  247. )
  248. async def setpriority(self, context: commands.Context, name: str, priority: int) -> None:
  249. 'Command handler'
  250. patterns = self.__get_patterns(context.guild)
  251. statement = patterns.get(name)
  252. if statement is None:
  253. await context.message.reply(
  254. f'{CONFIG["failure_emoji"]} No such pattern `{name}`',
  255. mention_author=False)
  256. return
  257. statement.priority = priority
  258. self.__save_patterns(context.guild, patterns)
  259. await context.message.reply(
  260. f'{CONFIG["success_emoji"]} Priority for pattern `{name}` ' + \
  261. f'updated to `{priority}`.',
  262. mention_author=False)