You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

182 lines
5.9KB

  1. import datetime
  2. import time
  3. from Roxbot import checks
  4. import discord
  5. from Roxbot.settings import guild_settings as gs
  6. from discord.ext.commands import bot, group, guild_only, bot_has_permissions
  7. class Admin():
  8. """
  9. Admin Commands for those admins
  10. """
  11. def __init__(self, bot_client):
  12. self.bot = bot_client
  13. self.slow_mode = False
  14. self.slow_mode_channels = {}
  15. self.users = {}
  16. async def on_message(self, message):
  17. # Slow Mode Code
  18. channel = message.channel
  19. author = message.author
  20. if not author == self.bot.user:
  21. if self.slow_mode and channel.id in self.slow_mode_channels:
  22. if author.id not in self.users[channel.id]:
  23. # If user hasn't sent a message in this channel after slow mode was turned on
  24. self.users[channel.id][author.id] = message.created_at
  25. else:
  26. # Else, check when their last message was and if time is smaller than the timer, delete the message.
  27. timer = datetime.timedelta(seconds=self.slow_mode_channels[channel.id])
  28. if message.created_at - self.users[channel.id][author.id] < timer:
  29. await message.delete()
  30. else:
  31. self.users[message.channel.id][author.id] = message.created_at
  32. else:
  33. pass
  34. @guild_only()
  35. @checks.is_admin_or_mod()
  36. @bot_has_permissions(manage_messages=True)
  37. @bot.command()
  38. async def slowmode(self, ctx, time):
  39. """Puts the current channel in slowmode.
  40. Usage:
  41. ;slowmode [time/"off"]
  42. time = time of the cooldown between messages a user has.
  43. off = turns off slowmode for this channel"""
  44. if time == "off" and self.slow_mode: # Turn Slow Mode off
  45. self.slow_mode = False
  46. self.slow_mode_channels.pop(ctx.channel.id)
  47. self.users.pop(ctx.channel.id)
  48. return await ctx.send("Slowmode off")
  49. elif time.isdigit() and not self.slow_mode: # Turn Slow Mode On
  50. self.users[ctx.channel.id] = {}
  51. self.slow_mode_channels[ctx.channel.id] = int(time)
  52. self.slow_mode = True
  53. return await ctx.send("Slowmode on :snail: ({} seconds)".format(time))
  54. elif time.isdigit and self.slow_mode: # Change value of Slow Mode timer
  55. self.slow_mode_channels[ctx.channel.id] = int(time)
  56. return await ctx.send("Slowmode set to :snail: ({} seconds)".format(time))
  57. else:
  58. pass
  59. @checks.is_admin_or_mod()
  60. @group()
  61. async def warn(self, ctx):
  62. """Group of commands handling warnings"""
  63. if ctx.invoked_subcommand is None:
  64. return await ctx.send('Missing Argument')
  65. @warn.command()
  66. async def add(self, ctx, user: discord.User = None, *, warning = ""):
  67. """Adds a warning to a user."""
  68. # Warning in the settings is a dictionary of user ids. The user ids are equal to a list of dictionaries.
  69. settings = gs.get(ctx.guild)
  70. warning_limit = 2
  71. warning_dict = {
  72. "warned-by": ctx.author.id,
  73. "date": time.time(),
  74. "warning": warning
  75. }
  76. user_id = str(user.id)
  77. if not user_id in settings.warnings:
  78. settings.warnings[user_id] = []
  79. settings.warnings[user_id].append(warning_dict)
  80. settings.update(settings.warnings, "warnings")
  81. amount_warnings = len(settings.warnings[user_id])
  82. if amount_warnings > warning_limit:
  83. await ctx.author.send("{} has been reported {} time(s). This is a reminder that this is over the set limit of {}.".format(
  84. str(user), amount_warnings, warning_limit))
  85. return await ctx.send("Reported {}.".format(str(user)))
  86. @warn.command()
  87. async def list(self, ctx, *, user: discord.User = None):
  88. """Lists all or just the warnings for one user."""
  89. settings = gs.get(ctx.guild)
  90. if user == None:
  91. output = ""
  92. for member in settings.warnings:
  93. # Remove users with no warning here instead of remove cause im lazy
  94. if not settings.warnings[member]:
  95. settings.warnings.pop(member)
  96. else:
  97. member_obj = discord.utils.get(ctx.guild.members, id=int(member))
  98. if member_obj:
  99. output += "{}: {} Warning(s)\n".format(str(member_obj), len(
  100. settings.warnings[member]))
  101. else:
  102. output += "{}: {} Warning(s)\n".format(member, len(
  103. settings.warnings[member]))
  104. return await ctx.send(output)
  105. user_id = str(user.id)
  106. if not settings.warnings[user_id]:
  107. settings.warnings.pop(user_id)
  108. settings.update(settings.warnings, "warnings")
  109. if not user_id in settings.warnings:
  110. return await ctx.send("This user doesn't have any warning on record.")
  111. em = discord.Embed(title="Warnings for {}".format(str(user)), colour=0XDEADBF)
  112. em.set_thumbnail(url=user.avatar_url)
  113. x = 1
  114. userlist = settings.warnings[user_id]
  115. for warning in userlist:
  116. try:
  117. warned_by = str(await self.bot.get_user_info(warning["warned-by"]))
  118. except discord.ext.commands.CommandInvokeError:
  119. warned_by = warning["warned-by"]
  120. date = datetime.datetime.fromtimestamp(warning["date"]).strftime('%c')
  121. warn_reason = warning["warning"]
  122. em.add_field(name="Warning %s"%x, value="Warned by: {}\nTime: {}\nReason: {}".format(warned_by, date, warn_reason))
  123. x += 1
  124. return await ctx.send(embed=em)
  125. @warn.command()
  126. async def remove(self, ctx, user: discord.User = None, index = None):
  127. """Removes one or all of the warnings for a user."""
  128. user_id = str(user.id)
  129. settings = gs.get(ctx.guild)
  130. if index:
  131. try:
  132. index = int(index)
  133. index -= 1
  134. settings.warnings[user_id].pop(index)
  135. if not settings.warnings[user_id]:
  136. settings.warnings.pop(user_id)
  137. settings.update(settings.warnings, "warnings")
  138. return await ctx.send("Removed Warning {} from {}".format(index+1, str(user)))
  139. except Exception as e:
  140. if isinstance(e, IndexError):
  141. return await ctx.send(":warning: Index Error.")
  142. elif isinstance(e, KeyError):
  143. return await ctx.send("Could not find user in warning list.")
  144. elif isinstance(e, ValueError):
  145. return await ctx.send("Please enter a valid index number.")
  146. else:
  147. raise e
  148. else:
  149. try:
  150. settings.warnings.pop(user_id)
  151. settings.update(settings.warnings, "warnings")
  152. return await ctx.send("Removed all warnings for {}".format(str(user)))
  153. except KeyError:
  154. return await ctx.send("Could not find user in warning list.")
  155. def setup(bot_client):
  156. bot_client.add_cog(Admin(bot_client))