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.

urlspamcog.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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=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. name='URL spam',
  55. short_description='Manages URL spam detection.',
  56. )
  57. self.add_setting(URLSpamCog.SETTING_ENABLED)
  58. self.add_setting(URLSpamCog.SETTING_ACTION)
  59. self.add_setting(URLSpamCog.SETTING_JOIN_AGE)
  60. self.add_setting(URLSpamCog.SETTING_DECEPTIVE_ACTION)
  61. @Cog.listener()
  62. async def on_message(self, message: Message):
  63. """Event listener"""
  64. if message.author is None or \
  65. message.author.bot or \
  66. message.guild is None or \
  67. message.channel is None or \
  68. message.content is None:
  69. return
  70. if not self.get_guild_setting(message.guild, self.SETTING_ENABLED):
  71. return
  72. await self.check_message_recency(message)
  73. await self.check_deceptive_links(message)
  74. async def check_message_recency(self, message: Message):
  75. """Checks if the message was sent too recently by a new user"""
  76. action = self.get_guild_setting(message.guild, self.SETTING_ACTION)
  77. join_seconds = self.get_guild_setting(message.guild, self.SETTING_JOIN_AGE)
  78. min_join_age = timedelta(seconds=join_seconds)
  79. if action == 'nothing':
  80. return
  81. if not self.__contains_url(message.content):
  82. return
  83. join_age = message.created_at - message.author.joined_at
  84. join_age_str = describe_timedelta(join_age)
  85. if join_age < min_join_age:
  86. context = URLSpamContext(message)
  87. needs_attention = False
  88. if action == 'modwarn':
  89. needs_attention = not self.was_warned_recently(message.author)
  90. self.log(message.guild, f'New user {message.author.name} ' + \
  91. f'({message.author.id}) posted URL {join_age_str} after ' + \
  92. 'joining.' + (' Mods alerted.' if needs_attention else ''))
  93. elif action == 'delete':
  94. await message.delete()
  95. context.is_deleted = True
  96. self.log(message.guild, f'New user {message.author.name} ' + \
  97. f'({message.author.id}) posted URL {join_age_str} after ' + \
  98. 'joining. Message deleted.')
  99. elif action == 'kick':
  100. await message.delete()
  101. context.is_deleted = True
  102. await message.author.kick(
  103. reason=f'Rocketbot: Posted a link {join_age_str} after joining')
  104. context.is_kicked = True
  105. self.log(message.guild, f'New user {message.author.name} ' + \
  106. f'({message.author.id}) posted URL {join_age_str} after ' + \
  107. 'joining. User kicked.')
  108. elif action == 'ban':
  109. await message.author.ban(
  110. reason=f'Rocketbot: User posted a link {join_age_str} after joining',
  111. delete_message_days=1)
  112. context.is_deleted = True
  113. context.is_kicked = True
  114. context.is_banned = True
  115. self.log(message.guild, f'New user {message.author.name} ' + \
  116. f'({message.author.id}) posted URL {join_age_str} after ' + \
  117. 'joining. User banned.')
  118. bm = BotMessage(
  119. message.guild,
  120. f'User {message.author.mention} posted a URL ' + \
  121. f'{join_age_str} after joining: {message.jump_url}',
  122. type = BotMessage.TYPE_MOD_WARNING if needs_attention else BotMessage.TYPE_INFO,
  123. context = context)
  124. bm.quote = discordutils.remove_markdown(message.clean_content)
  125. await bm.set_reactions(BotMessageReaction.standard_set(
  126. did_delete=context.is_deleted,
  127. did_kick=context.is_kicked,
  128. did_ban=context.is_banned))
  129. await self.post_message(bm)
  130. if needs_attention:
  131. self.record_warning(message.author)
  132. async def check_deceptive_links(self, message: Message):
  133. """
  134. Checks if the message contains deceptive URL Markdown, e.g.
  135. `[nicewebsite.com](https://evilwebsite.com)'`
  136. """
  137. action = self.get_guild_setting(message.guild, self.SETTING_DECEPTIVE_ACTION)
  138. if action is None or action == 'nothing':
  139. return
  140. if not self.contains_deceptive_links(message.content):
  141. return
  142. mod_text = f'User {message.author.name} ({message.author.id}) posted a deceptive link. {message.jump_url}'
  143. quoted = '> ' + escape_markdown(message.content).replace('\n', '\n> ')
  144. mod_text += f'\n\n{quoted}'
  145. self.log(message.guild, f'{message.author.name} posted deceptive link - action: {action}')
  146. if 'modwarn' in action:
  147. if 'delete' in action:
  148. mod_text += '\n\nMessage deleted'
  149. else:
  150. mod_text += f'\n\n{message.jump_url}'
  151. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_MOD_WARNING, suppress_embeds=True)
  152. await self.post_message(bm)
  153. if 'delete' in action:
  154. await message.delete()
  155. elif 'chatwarn' in action:
  156. if 'delete' in action:
  157. response = f':warning: Links with deceptive labels are prohibited :warning:'
  158. else:
  159. response = f':warning: Message contains a deceptively labeled link! Click carefully. :warning:'
  160. await message.reply(response, mention_author=False)
  161. if 'delete' in action:
  162. await message.delete()
  163. elif action == 'delete':
  164. mod_text += f'\n\nDeleting message'
  165. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_INFO, suppress_embeds=True)
  166. await self.post_message(bm)
  167. await message.delete()
  168. elif action == 'kick':
  169. mod_text += f'\n\nUser kicked'
  170. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_MOD_WARNING, suppress_embeds=True)
  171. await self.post_message(bm)
  172. await message.delete()
  173. await message.author.kick(
  174. reason=f'Rocketbot: User posted a deceptive link')
  175. elif action == 'ban':
  176. mod_text += f'\n\nUser banned'
  177. bm = BotMessage(message.guild, mod_text, BotMessage.TYPE_MOD_WARNING, suppress_embeds=True)
  178. await self.post_message(bm)
  179. await message.author.ban(
  180. reason=f'Rocketbot: User posted a deceptive link',
  181. delete_message_days=1)
  182. def contains_deceptive_links(self, content: str) -> bool:
  183. # Strip Markdown that can safely contain URL sequences
  184. content = re.sub(r'`[^`]+`', '', content) # `inline code`
  185. content = re.sub(r'```.+?```', '', content, re.DOTALL) # ``` code block ```
  186. matches = re.findall(r'\[([^]]+)]\(([^)]+)\)', content)
  187. for match in matches:
  188. original_label: str = match[0].strip()
  189. original_link: str = match[1].strip()
  190. label: str = original_label
  191. link: str = original_link
  192. if link.startswith('<') and link.endswith('>'):
  193. link = link[1:-1]
  194. if self.is_url(label):
  195. if label != link:
  196. return True
  197. elif self.is_casual_url(label):
  198. # Trim www. for easier comparisons.
  199. if link.startswith('https://www.'):
  200. link = 'https://' + link[12:]
  201. if link.startswith('http://www.'):
  202. link = 'http://' + link[11:]
  203. if link.endswith('/'):
  204. link = link[:-1]
  205. if label.startswith('www.'):
  206. label = label[4:]
  207. if label.endswith('/'):
  208. label = label[:-1]
  209. if link.startswith('https://') and 'https://' + label != link:
  210. return True
  211. elif link.startswith('http://') and 'http://' + label != link:
  212. return True
  213. return False
  214. def is_url(self, s: str) -> bool:
  215. """Tests if a string is strictly a URL"""
  216. ipv6_host_pattern = r'\[[0-9a-fA-F:]+\]'
  217. ipv4_host_pattern = r'[0-9\.]+'
  218. hostname_pattern = r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+'
  219. host_pattern = r'(?:' + ipv6_host_pattern + '|' + ipv4_host_pattern + '|' + hostname_pattern + ')'
  220. port_pattern = '(?::[0-9]+)?'
  221. path_pattern = r'(?:/[^ \]\)]*)?'
  222. pattern = r'^http[s]?://' + host_pattern + port_pattern + path_pattern + '$'
  223. return re.match(pattern, s, re.IGNORECASE) is not None
  224. def is_casual_url(self, s: str) -> bool:
  225. """Tests if a string is a "casual URL" with no scheme included"""
  226. ipv6_host_pattern = r'\[[0-9a-fA-F:]+\]'
  227. ipv4_host_pattern = r'[0-9\.]+'
  228. hostname_pattern = r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+'
  229. host_pattern = r'(?:' + ipv6_host_pattern + '|' + ipv4_host_pattern + '|' + hostname_pattern + ')'
  230. port_pattern = '(?::[0-9]+)?'
  231. path_pattern = r'(?:/[^ \]\)]*)?'
  232. pattern = r'^' + host_pattern + port_pattern + path_pattern + '$'
  233. return re.match(pattern, s, re.IGNORECASE) is not None
  234. async def on_mod_react(self,
  235. bot_message: BotMessage,
  236. reaction: BotMessageReaction,
  237. reacted_by: Member) -> None:
  238. context: URLSpamContext = bot_message.context
  239. if context is None:
  240. return
  241. sm: Message = context.spam_message
  242. if reaction.emoji == CONFIG['trash_emoji']:
  243. if not context.is_deleted:
  244. await sm.delete()
  245. context.is_deleted = True
  246. self.log(sm.guild, f'URL spam by {sm.author.name} deleted ' + \
  247. f'by {reacted_by.name}')
  248. elif reaction.emoji == CONFIG['kick_emoji']:
  249. if not context.is_deleted:
  250. await sm.delete()
  251. context.is_deleted = True
  252. if not context.is_kicked:
  253. await sm.author.kick(
  254. reason=f'Rocketbot: Kicked for URL spam by {reacted_by.name}')
  255. context.is_kicked = True
  256. self.log(sm.guild, f'URL spammer {sm.author.name} kicked ' + \
  257. f'by {reacted_by.name}')
  258. elif reaction.emoji == CONFIG['ban_emoji']:
  259. if not context.is_banned:
  260. await sm.author.ban(
  261. reason=f'Rocketbot: Banned for URL spam by {reacted_by.name}',
  262. delete_message_days=1)
  263. context.is_deleted = True
  264. context.is_kicked = True
  265. context.is_banned = True
  266. self.log(sm.guild, f'URL spammer {sm.author.name} banned ' + \
  267. f'by {reacted_by.name}')
  268. else:
  269. return
  270. await bot_message.set_reactions(BotMessageReaction.standard_set(
  271. did_delete=context.is_deleted,
  272. did_kick=context.is_kicked,
  273. did_ban=context.is_banned))
  274. @classmethod
  275. def __contains_url(cls, text: str) -> bool:
  276. p = re.compile(r'https?://\S+')
  277. return p.search(text) is not None