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.

179 lines
6.2KB

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