Experimental Discord bot written in Python
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

joinraidcog.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import weakref
  2. from datetime import datetime, timedelta
  3. from discord import Guild, Member
  4. from discord.ext import commands
  5. from cogs.basecog import BaseCog, BotMessage, BotMessageReaction, CogSetting
  6. from config import CONFIG
  7. from rscollections import AgeBoundList
  8. from storage import Storage
  9. class JoinRaidContext:
  10. """
  11. Data about a join raid.
  12. """
  13. def __init__(self, join_members: list):
  14. self.join_members = list(join_members)
  15. self.kicked_members = set()
  16. self.banned_members = set()
  17. self.warning_message_ref = None
  18. def last_join_time(self) -> datetime:
  19. 'Returns when the most recent member join was, in UTC'
  20. return self.join_members[-1].joined_at
  21. class JoinRaidCog(BaseCog, name='Join Raids'):
  22. """
  23. Cog for monitoring member joins and detecting potential bot raids.
  24. """
  25. SETTING_ENABLED = CogSetting('enabled', bool,
  26. brief='join raid detection',
  27. description='Whether this cog is enabled for a guild.')
  28. SETTING_JOIN_COUNT = CogSetting('joincount', int,
  29. brief='number of joins to trigger a warning',
  30. description='The number of joins occuring within the time ' + \
  31. 'window to trigger a mod warning.',
  32. usage='<count:int>',
  33. min_value=2)
  34. SETTING_JOIN_TIME = CogSetting('jointime', float,
  35. brief='time window length to look for joins',
  36. description='The number of seconds of join history to look ' + \
  37. 'at when counting recent joins. If joincount or more ' + \
  38. 'joins occur within jointime seconds a mod warning is issued.',
  39. usage='<seconds:float>',
  40. min_value=1.0,
  41. max_value=900.0)
  42. STATE_KEY_RECENT_JOINS = "JoinRaidCog.recent_joins"
  43. STATE_KEY_LAST_RAID = "JoinRaidCog.last_raid"
  44. def __init__(self, bot):
  45. super().__init__(bot)
  46. self.add_setting(JoinRaidCog.SETTING_ENABLED)
  47. self.add_setting(JoinRaidCog.SETTING_JOIN_COUNT)
  48. self.add_setting(JoinRaidCog.SETTING_JOIN_TIME)
  49. @commands.group(
  50. brief='Manages join raid detection and handling',
  51. )
  52. @commands.has_permissions(ban_members=True)
  53. @commands.guild_only()
  54. async def joinraid(self, context: commands.Context):
  55. 'Join raid detection command group'
  56. if context.invoked_subcommand is None:
  57. await context.send_help()
  58. async def on_mod_react(self,
  59. bot_message: BotMessage,
  60. reaction: BotMessageReaction,
  61. reacted_by: Member) -> None:
  62. guild: Guild = bot_message.guild
  63. raid: JoinRaidContext = bot_message.context
  64. if reaction.emoji == CONFIG['kick_emoji']:
  65. to_kick = set(raid.join_members) - raid.kicked_members
  66. for member in to_kick:
  67. await member.kick(
  68. reason=f'Rocketbot: Part of join raid. Kicked by {reacted_by.name}.')
  69. raid.kicked_members |= to_kick
  70. await self.__update_warning_message(raid)
  71. self.log(guild, f'Join raid users kicked by {reacted_by.name}.')
  72. elif reaction.emoji == CONFIG['ban_emoji']:
  73. to_ban = set(raid.join_members) - raid.banned_members
  74. for member in to_ban:
  75. await member.ban(
  76. reason=f'Rocketbot: Part of join raid. Banned by {reacted_by.name}.',
  77. delete_message_days=0)
  78. raid.banned_members |= to_ban
  79. await self.__update_warning_message(raid)
  80. self.log(guild, f'Join raid users banned by {reacted_by.name}')
  81. @commands.Cog.listener()
  82. async def on_member_join(self, member: Member) -> None:
  83. 'Event handler'
  84. guild: Guild = member.guild
  85. if not self.get_guild_setting(guild, self.SETTING_ENABLED):
  86. return
  87. min_count = self.get_guild_setting(guild, self.SETTING_JOIN_COUNT)
  88. seconds = self.get_guild_setting(guild, self.SETTING_JOIN_TIME)
  89. timespan: timedelta = timedelta(seconds=seconds)
  90. last_raid: JoinRaidContext = Storage.get_state_value(guild, self.STATE_KEY_LAST_RAID)
  91. recent_joins: AgeBoundList = Storage.get_state_value(guild, self.STATE_KEY_RECENT_JOINS)
  92. if recent_joins is None:
  93. recent_joins = AgeBoundList(timespan, lambda i, member : member.joined_at)
  94. Storage.set_state_value(guild, self.STATE_KEY_RECENT_JOINS, recent_joins)
  95. if last_raid:
  96. if member.joined_at - last_raid.last_join_time() > timespan:
  97. # Last raid is over
  98. Storage.set_state_value(guild, self.STATE_KEY_LAST_RAID, None)
  99. recent_joins.append(member)
  100. return
  101. # Add join to existing raid
  102. last_raid.join_members.append(member)
  103. await self.__update_warning_message(last_raid)
  104. else:
  105. # Add join to the general, non-raid recent join list
  106. recent_joins.append(member)
  107. if len(recent_joins) >= min_count:
  108. self.log(guild, '\u0007Join raid detected')
  109. last_raid = JoinRaidContext(recent_joins)
  110. Storage.set_state_value(guild, self.STATE_KEY_LAST_RAID, last_raid)
  111. recent_joins.clear()
  112. msg = BotMessage(guild,
  113. text='',
  114. type=BotMessage.TYPE_MOD_WARNING,
  115. context=last_raid)
  116. last_raid.warning_message_ref = weakref.ref(msg)
  117. await self.__update_warning_message(last_raid)
  118. await self.post_message(msg)
  119. async def on_setting_updated(self, guild: Guild, setting: CogSetting) -> None:
  120. if setting is self.SETTING_JOIN_TIME:
  121. seconds = self.get_guild_setting(guild, self.SETTING_JOIN_TIME)
  122. timespan: timedelta = timedelta(seconds=seconds)
  123. recent_joins: AgeBoundList = Storage.get_state_value(guild,
  124. self.STATE_KEY_RECENT_JOINS)
  125. if recent_joins:
  126. recent_joins.max_age = timespan
  127. recent_joins.purge_old_elements()
  128. async def __update_warning_message(self, context: JoinRaidContext) -> None:
  129. if context.warning_message_ref is None:
  130. return
  131. bot_message = context.warning_message_ref()
  132. if bot_message is None:
  133. return
  134. text = 'JOIN RAID DETECTED\n\n' + \
  135. 'The following members joined in close succession:\n'
  136. for member in context.join_members:
  137. text += '\n• '
  138. if member in context.banned_members:
  139. text += f'~~{member.mention} ({member.id})~~ - banned'
  140. elif member in context.kicked_members:
  141. text += f'~~{member.mention} ({member.id})~~ - kicked'
  142. else:
  143. text += f'{member.mention} ({member.id})'
  144. text += '\n_(list updates automatically)_'
  145. await bot_message.set_text(text)
  146. member_count = len(context.join_members)
  147. kick_count = len(context.kicked_members)
  148. ban_count = len(context.banned_members)
  149. await bot_message.set_reactions(BotMessageReaction.standard_set(
  150. did_kick=kick_count >= member_count,
  151. did_ban=ban_count >= member_count,
  152. user_count=member_count))