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

urlspamcog.py 11KB

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