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.

patterncog.py 10KB

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