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.

157 lines
5.3KB

  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):
  12. self.bot = Bot
  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.timestamp
  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.timestamp - self.users[channel.id][author.id] < timer:
  31. await message.delete()
  32. else:
  33. self.users[message.channel.id][author.id] = message.timestamp
  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. if time == "off" and self.slow_mode: # Turn Slow Mode off
  42. self.slow_mode = False
  43. self.slow_mode_channels.pop(ctx.channel.id)
  44. self.users.pop(ctx.channel.id)
  45. return await ctx.send("Slowmode off")
  46. elif time.isdigit() and not self.slow_mode: # Turn Slow Mode On
  47. self.users[ctx.channel.id] = {}
  48. self.slow_mode_channels[ctx.channel.id] = int(time)
  49. self.slow_mode = True
  50. return await ctx.send("Slowmode on :snail: ({} seconds)".format(time))
  51. elif time.isdigit and self.slow_mode: # Change value of Slow Mode timer
  52. self.slow_mode_channels[ctx.channel.id] = int(time)
  53. return await ctx.send("Slowmode set to :snail: ({} seconds)".format(time))
  54. else:
  55. pass
  56. @checks.is_admin_or_mod()
  57. @group()
  58. async def warn(self, ctx):
  59. if ctx.invoked_subcommand is None:
  60. return await ctx.send('Missing Argument')
  61. @warn.command()
  62. async def add(self, ctx, user: discord.User = None, *, warning = ""):
  63. # Warning in the config is a dictionary of user ids. The user ids are equal to a list of dictionaries.
  64. self.servers = self.con.load_config()
  65. warning_limit = 2
  66. id = str(ctx.guild.id)
  67. warning_dict = {
  68. "warned-by": ctx.author.id,
  69. "date": time.time(),
  70. "warning": warning
  71. }
  72. if not user.id in self.servers[id]["warnings"]:
  73. self.servers[id]["warnings"][user.id] = []
  74. self.servers[id]["warnings"][user.id].append(warning_dict)
  75. self.con.update_config(self.servers)
  76. amount_warnings = len(self.servers[id]["warnings"][user.id])
  77. if amount_warnings > warning_limit:
  78. await ctx.author.send("{} has been reported {} time(s). This is a reminder that this is over the set limit of {}.".format(
  79. str(user), amount_warnings, warning_limit))
  80. return await ctx.send("Reported {}.".format(user.name+"#"+user.discriminator))
  81. @warn.command()
  82. async def list(self, ctx, *, user: discord.User = None):
  83. async with ctx.channel.typing():
  84. if user == None:
  85. output = ""
  86. for user in self.servers[str(ctx.guild.id)]["warnings"]:
  87. user_obj = await self.bot.get_user_info(user)
  88. output += "{}#{}: {} Warning(s)\n".format(user_obj.name, user_obj.discriminator, len(self.servers[str(ctx.guild.id)]["warnings"][user]))
  89. return await ctx.send(output)
  90. if not user.id in self.servers[str(ctx.guild.id)]["warnings"]:
  91. return await ctx.send("This user doesn't have any warning on record.")
  92. em = discord.Embed(title="Warnings for {}".format(str(user)), colour=0XDEADBF)
  93. em.set_thumbnail(url=user.avatar_url)
  94. x = 1
  95. userlist = self.servers[str(ctx.guild.id)]["warnings"][user.id]
  96. for warning in userlist:
  97. try:
  98. warned_by = str(await self.bot.get_user_info(warning["warned-by"]))
  99. except:
  100. warned_by = warning["warned-by"]
  101. date = datetime.datetime.fromtimestamp(warning["date"]).strftime('%c')
  102. warn_reason = warning["warning"]
  103. em.add_field(name="Warning %s"%x, value="Warned by: {}\nTime: {}\nReason: {}".format(warned_by, date, warn_reason))
  104. x += 1
  105. return await ctx.send(embed=em)
  106. @warn.command()
  107. async def remove(self, ctx, user: discord.User = None, index = None):
  108. self.servers = self.con.load_config()
  109. if index:
  110. try:
  111. index = int(index)
  112. index -= 1
  113. self.servers[str(ctx.guild.id)]["warnings"][user.id].pop(index)
  114. self.con.update_config(self.servers)
  115. return await ctx.send("Removed Warning {} from {}".format(index+1, str(user)))
  116. except Exception as e:
  117. if isinstance(e, IndexError):
  118. return await ctx.send(":warning: Index Error.")
  119. elif isinstance(e, KeyError):
  120. return await ctx.send("Could not find user in warning list.")
  121. elif isinstance(e, ValueError):
  122. return await ctx.send("Please enter a valid index number.")
  123. else:
  124. raise e
  125. else:
  126. try:
  127. self.servers[str(ctx.guild.id)]["warnings"].pop(user.id)
  128. self.con.update_config(self.servers)
  129. return await ctx.send("Removed all warnings for {}".format(str(user)))
  130. except KeyError:
  131. return await ctx.send("Could not find user in warning list.")
  132. def setup(Bot):
  133. Bot.add_cog(Admin(Bot))