Experimental Discord bot written in Python
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

urlspamcog.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. """
  2. Cog for detecting URLs posted by new users.
  3. """
  4. import re
  5. from datetime import timedelta
  6. from typing import Literal
  7. from discord import Member, Message, utils as discordutils
  8. from discord.ext.commands import Cog
  9. from discord.utils import escape_markdown
  10. from config import CONFIG
  11. from rocketbot.cogs.basecog import BaseCog, BotMessage, BotMessageReaction, CogSetting
  12. from rocketbot.utils import describe_timedelta
  13. class URLSpamContext:
  14. """
  15. Data about a suspected spam message containing a URL.
  16. """
  17. def __init__(self, spam_message: Message):
  18. self.spam_message = spam_message
  19. self.is_deleted = False
  20. self.is_kicked = False
  21. self.is_banned = False
  22. class URLSpamCog(BaseCog, name='URL Spam'):
  23. """
  24. Detects users posting URLs who just joined recently: a common spam pattern.
  25. Can be configured to take immediate action or just warn the mods.
  26. """
  27. SETTING_ENABLED = CogSetting('enabled', bool,
  28. brief='URL spam detection',
  29. description='Whether URLs posted soon after joining are flagged.')
  30. SETTING_ACTION = CogSetting('action', Literal['nothing', 'modwarn', 'delete', 'kick', 'ban'],
  31. brief='action to take on spam',
  32. description='The action to take on detected URL spam.',
  33. enum_values={'nothing', 'modwarn', 'delete', 'kick', 'ban'})
  34. SETTING_JOIN_AGE = CogSetting('joinage', timedelta,
  35. brief='seconds since member joined',
  36. description='The minimum seconds since the user joined the ' + \
  37. 'server before they can post URLs. URLs posted by users ' + \
  38. 'who joined too recently will be flagged. Keep in mind ' + \
  39. 'many servers have a minimum 10 minute cooldown before ' + \
  40. 'new members can say anything. Setting to 0 effectively ' + \
  41. 'disables URL spam detection.',
  42. usage='<seconds:int>',
  43. min_value=timedelta(seconds=0))
  44. SETTING_DECEPTIVE_ACTION = CogSetting('deceptiveaction', Literal['nothing', 'modwarn', 'modwarndelete', 'chatwarn', 'chatwarndelete', 'delete', 'kick', 'ban'],
  45. brief='action to take on deceptive link markdown',
  46. description='The action to take on chat messages with links ' + \
  47. 'where the text looks like a different URL than the actual link.',
  48. enum_values={'nothing', 'modwarn', 'modwarndelete',
  49. 'chatwarn', 'chatwarndelete', 'delete', 'kick', 'ban'})
  50. def __init__(self, bot):
  51. super().__init__(
  52. bot,
  53. config_prefix='urlspam',
  54. short_description='Manages URL spam detection.',
  55. )
  56. self.add_setting(URLSpamCog.SETTING_ENABLED)
  57. self.add_setting(URLSpamCog.SETTING_ACTION)
  58. self.add_setting(URLSpamCog.SETTING_JOIN_AGE)
  59. self.add_setting(URLSpamCog.SETTING_DECEPTIVE_ACTION)
  60. @Cog.listener()
  61. async def on_message(self, message: Message):
  62. """Event listener"""
  63. if message.author is None or \
  64. message.author.bot or \
  65. message.guild is None or \
  66. message.channel is None or \
  67. message.content is None:
  68. return
  69. if not self.get_guild_setting(message.guild, self.SETTING_ENABLED):
  70. return
  71. await self.check_message_recency(message)
  72. await self.check_deceptive_links(message)
  73. async def check_message_recency(self, message: Message):
  74. """Checks if the message was sent too recently by a new user"""
  75. action = self.get_guild_setting(message.guild, self.SETTING_ACTION)
  76. join_seconds = self.get_guild_setting(message.guild, self.SETTING_JOIN_AGE)
  77. min_join_age = timedelta(seconds=join_seconds)
  78. if action == 'nothing':
  79. return
  80. if not self.__contains_url(message.content):
  81. return
  82. join_age = message.created_at - message.author.joined_at
  83. join_age_str = describe_timedelta(join_age)
  84. if join_age < min_join_age:
  85. context = URLSpamContext(message)
  86. needs_attention = False
  87. if action == 'modwarn':
  88. needs_attention = not self.was_warned_recently(message.author)
  89. self.log(message.guild, f'New user {message.author.name} ' + \
  90. f'({message.author.id}) posted URL {join_age_str} after ' + \
  91. 'joining.' + (' Mods alerted.' if needs_attention else ''))
  92. elif action == 'delete':
  93. await message.delete()
  94. context.is_deleted = True
  95. self.log(message.guild, f'New user {message.author.name} ' + \
  96. f'({message.author.id}) posted URL {join_age_str} after ' + \
  97. 'joining. Message deleted.')
  98. elif action == 'kick':
  99. await message.delete()
  100. context.is_deleted = True
  101. await message.author.kick(
  102. reason=f'Rocketbot: Posted a link {join_age_str} after joining')
  103. context.is_kicked = True
  104. self.log(message.guild, f'New user {message.author.name} ' + \
  105. f'({message.author.id}) posted URL {join_age_str} after ' + \
  106. 'joining. User kicked.')
  107. elif action == 'ban':
  108. await message.author.ban(
  109. reason=f'Rocketbot: User posted a link {join_age_str} after joining',
  110. delete_message_days=1)
  111. context.is_deleted = True
  112. context.is_kicked = True
  113. context.is_banned = True
  114. self.log(message.guild, f'New user {message.author.name} ' + \
  115. f'({message.author.id}) posted URL {join_age_str} after ' + \
  116. 'joining. User banned.')
  117. bm = BotMessage(
  118. message.guild,
  119. f'User {message.author.mention} posted a URL ' + \
  120. f'{join_age_str} after joining: {message.jump_url}',
  121. type = BotMessage.TYPE_MOD_WARNING if needs_attention else BotMessage.TYPE_INFO,
  122. context = context)
  123. bm.quote = discordutils.remove_markdown(message.clean_content)
  124. await bm.set_reactions(BotMessageReaction.standard_set(
  125. did_delete=context.is_deleted,
  126. did_kick=context.is_kicked,
  127. did_ban=context.is_banned))
  128. await self.post_message(bm)
  129. if needs_attention:
  130. self.record_warning(message.author)
  131. async def check_deceptive_links(self, message: Message):
  132. """
  133. Checks if the message contains deceptive URL Markdown, e.g.
  134. `[nicewebsite.com](https://evilwebsite.com)'`
  135. """
  136. action = self.get_guild_setting(message.guild, self.SETTING_DECEPTIVE_ACTION)
  137. if action is None or action == 'nothing':
  138. return
  139. if not self.contains_deceptive_links(message.content):
  140. return
  141. mod_text = f'User {message.author.name} ({message.author.id}) posted a deceptive link. {message.jump_url}'
  142. quoted = '> ' + escape_markdown(message.content).replace('\n', '\n> ')
  143. mod_text += f'\n\n{quoted}'
  144. self.log(message.guild, f'{message.author.name} posted deceptive link - action: {action}')
  145. if 'modwarn' in action:
  146. if 'delete' in action:
  147. mod_text += '\n\nMessage deleted'
  148. else:
  149. mod_text += f'\n\n{message.jump_url}'
  150. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_MOD_WARNING, suppress_embeds=True)
  151. await self.post_message(bm)
  152. if 'delete' in action:
  153. await message.delete()
  154. elif 'chatwarn' in action:
  155. if 'delete' in action:
  156. response = f':warning: Links with deceptive labels are prohibited :warning:'
  157. else:
  158. response = f':warning: Message contains a deceptively labeled link! Click carefully. :warning:'
  159. await message.reply(response, mention_author=False)
  160. if 'delete' in action:
  161. await message.delete()
  162. elif action == 'delete':
  163. mod_text += f'\n\nDeleting message'
  164. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_INFO, suppress_embeds=True)
  165. await self.post_message(bm)
  166. await message.delete()
  167. elif action == 'kick':
  168. mod_text += f'\n\nUser kicked'
  169. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_MOD_WARNING, suppress_embeds=True)
  170. await self.post_message(bm)
  171. await message.delete()
  172. await message.author.kick(
  173. reason=f'Rocketbot: User posted a deceptive link')
  174. elif action == 'ban':
  175. mod_text += f'\n\nUser banned'
  176. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_MOD_WARNING, suppress_embeds=True)
  177. await self.post_message(bm)
  178. await message.author.ban(
  179. reason=f'Rocketbot: User posted a deceptive link',
  180. delete_message_days=1)
  181. def contains_deceptive_links(self, content: str) -> bool:
  182. # Strip Markdown that can safely contain URL sequences
  183. content = re.sub(r'`[^`]+`', '', content) # `inline code`
  184. content = re.sub(r'```.+?```', '', content, re.DOTALL) # ``` code block ```
  185. matches = re.findall(r'\[([^]]+)]\(([^)]+)\)', content)
  186. for match in matches:
  187. original_label: str = match[0].strip()
  188. original_link: str = match[1].strip()
  189. label: str = original_label
  190. link: str = original_link
  191. if link.startswith('<') and link.endswith('>'):
  192. link = link[1:-1]
  193. if self.is_url(label):
  194. if label != link:
  195. return True
  196. elif self.is_casual_url(label):
  197. # Trim www. for easier comparisons.
  198. if link.startswith('https://www.'):
  199. link = 'https://' + link[12:]
  200. if link.startswith('http://www.'):
  201. link = 'http://' + link[11:]
  202. if link.endswith('/'):
  203. link = link[:-1]
  204. if label.startswith('www.'):
  205. label = label[4:]
  206. if label.endswith('/'):
  207. label = label[:-1]
  208. if link.startswith('https://') and 'https://' + label != link:
  209. return True
  210. elif link.startswith('http://') and 'http://' + label != link:
  211. return True
  212. return False
  213. def is_url(self, s: str) -> bool:
  214. """Tests if a string is strictly a URL"""
  215. ipv6_host_pattern = r'\[[0-9a-fA-F:]+\]'
  216. ipv4_host_pattern = r'[0-9\.]+'
  217. hostname_pattern = r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+'
  218. host_pattern = r'(?:' + ipv6_host_pattern + '|' + ipv4_host_pattern + '|' + hostname_pattern + ')'
  219. port_pattern = '(?::[0-9]+)?'
  220. path_pattern = r'(?:/[^ \]\)]*)?'
  221. pattern = r'^http[s]?://' + host_pattern + port_pattern + path_pattern + '$'
  222. return re.match(pattern, s, re.IGNORECASE) is not None
  223. def is_casual_url(self, s: str) -> bool:
  224. """Tests if a string is a "casual URL" with no scheme included"""
  225. ipv6_host_pattern = r'\[[0-9a-fA-F:]+\]'
  226. ipv4_host_pattern = r'[0-9\.]+'
  227. hostname_pattern = r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+'
  228. host_pattern = r'(?:' + ipv6_host_pattern + '|' + ipv4_host_pattern + '|' + hostname_pattern + ')'
  229. port_pattern = '(?::[0-9]+)?'
  230. path_pattern = r'(?:/[^ \]\)]*)?'
  231. pattern = r'^' + host_pattern + port_pattern + path_pattern + '$'
  232. return re.match(pattern, s, re.IGNORECASE) is not None
  233. async def on_mod_react(self,
  234. bot_message: BotMessage,
  235. reaction: BotMessageReaction,
  236. reacted_by: Member) -> None:
  237. context: URLSpamContext = bot_message.context
  238. if context is None:
  239. return
  240. sm: Message = context.spam_message
  241. if reaction.emoji == CONFIG['trash_emoji']:
  242. if not context.is_deleted:
  243. await sm.delete()
  244. context.is_deleted = True
  245. self.log(sm.guild, f'URL spam by {sm.author.name} deleted ' + \
  246. f'by {reacted_by.name}')
  247. elif reaction.emoji == CONFIG['kick_emoji']:
  248. if not context.is_deleted:
  249. await sm.delete()
  250. context.is_deleted = True
  251. if not context.is_kicked:
  252. await sm.author.kick(
  253. reason=f'Rocketbot: Kicked for URL spam by {reacted_by.name}')
  254. context.is_kicked = True
  255. self.log(sm.guild, f'URL spammer {sm.author.name} kicked ' + \
  256. f'by {reacted_by.name}')
  257. elif reaction.emoji == CONFIG['ban_emoji']:
  258. if not context.is_banned:
  259. await sm.author.ban(
  260. reason=f'Rocketbot: Banned for URL spam by {reacted_by.name}',
  261. delete_message_days=1)
  262. context.is_deleted = True
  263. context.is_kicked = True
  264. context.is_banned = True
  265. self.log(sm.guild, f'URL spammer {sm.author.name} banned ' + \
  266. f'by {reacted_by.name}')
  267. else:
  268. return
  269. await bot_message.set_reactions(BotMessageReaction.standard_set(
  270. did_delete=context.is_deleted,
  271. did_kick=context.is_kicked,
  272. did_ban=context.is_banned))
  273. @classmethod
  274. def __contains_url(cls, text: str) -> bool:
  275. p = re.compile(r'https?://\S+')
  276. return p.search(text) is not None