Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.36 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. from .utils import checks
  4. import asyncio
  5. import logging
  6. # Data stuffies
  7. from __main__ import send_cmd_help
  8. from cogs.utils.dataIO import dataIO
  9. import os
  10. import time
  11. import copy
  12. # Tabulate, cause its tabulate
  13. try:
  14. from tabulate import tabulate
  15. except:
  16. raise Exception('Run "pip install tabulate" in your CMD/Linux Terminal')
  17. log = logging.getLogger('red.punish')
  18.  
  19.  
  20. class Punish:
  21. """Adds the ability to punish users."""
  22.  
  23. # --- Format
  24. # {
  25. # Server : {
  26. # UserIDs : {
  27. # Until :
  28. # Givenby :
  29. # NumberOfSandwiches :
  30. # }
  31. # }
  32. # }
  33. # ---
  34.  
  35. def __init__(self, bot):
  36. self.bot = bot
  37. self.location = 'data/punish/settings.json'
  38. self.json = dataIO.load_json(self.location)
  39. self.min = ['m', 'min', 'mins', 'minutes', 'minute']
  40. self.hour = ['h', 'hour', 'hours']
  41. self.day = ['d', 'day', 'days']
  42. self.task = bot.loop.create_task(self.check_time())
  43.  
  44. def __unload(self):
  45. self.task.cancel()
  46. log.debug('Stopped task')
  47.  
  48. def _timestamp(self, t, unit):
  49. if unit in self.min:
  50. return t * 60 + int(time.time())
  51. elif unit in self.hour:
  52. return t * 60 * 60 + int(time.time())
  53. elif unit in self.day:
  54. return t * 60 * 60 * 24 + int(time.time())
  55. else:
  56. raise Exception('Invalid Unit')
  57.  
  58. @commands.command(pass_context=True, no_pm=True)
  59. @checks.mod_or_permissions(manage_messages=True)
  60. async def punish(self, ctx, user: discord.Member, t: int=1, unit='hour'):
  61. """Places a user in timeout for a period of time.
  62.  
  63. Valid unit of times are minutes, hours & days.
  64. Example usage: !punish @Kowlin 3 hours"""
  65. server = ctx.message.server
  66. # --- CREATING ROLE ---
  67. if 'Punished' not in [r.name for r in server.roles]:
  68. await self.bot.say('The Punished role doesn\'t exist! Creating it now!')
  69. log.debug('Creating Punished role in {}'.format(server.id))
  70. try:
  71. perms = discord.Permissions.none()
  72. await self.bot.create_role(server, name='Punished', permissions=perms)
  73. await self.bot.say("Role created! Setting channel permissions!\nPlease ensure that your moderator roles are ABOVE the Punished role!\nPlease wait until the user has been added to the Timeout role!")
  74. try:
  75. r = discord.utils.get(server.roles, name='Punished')
  76. perms = discord.PermissionOverwrite()
  77. perms.send_messages = False
  78. for c in server.channels:
  79. if c.type.name == 'text':
  80. await self.bot.edit_channel_permissions(c, r, perms)
  81. await asyncio.sleep(1.5)
  82. except discord.Forbidden:
  83. await self.bot.say("A error occured while making channel permissions.\nPlease check your channel permissions for the Punished role!")
  84. except discord.Forbidden:
  85. await self.bot.say("I cannot create a role. Please assign Manage Roles to me!")
  86. role = discord.utils.get(server.roles, name='Punished')
  87. # --- DONE CREATING ROLE! ---
  88. # --- JSON SERVER LOGIC ---
  89. if server.id not in self.json:
  90. log.debug('Adding server({}) in Json'.format(server.id))
  91. self.json[server.id] = {}
  92. dataIO.save_json(self.location, self.json)
  93. # --- DONE JSON SERVER LOGIC! ---
  94. # --- ASSIGNING TIMESTAMPS AND ROLE ---
  95. try:
  96. if user.id == ctx.message.author.id:
  97. await self.bot.say('Please don\'t punish yourself :(')
  98. elif user.id not in self.json[server.id] and role not in user.roles:
  99. # USER NOT IN PUNISH, NO ROLE
  100. until = self._timestamp(t, unit)
  101. self.json[server.id][user.id] = {'until': until, 'givenby': ctx.message.author.id}
  102. dataIO.save_json(self.location, self.json)
  103. await self.bot.add_roles(user, role)
  104. await self.bot.say('``{}`` is now Punished for {} {} by ``{}``.'.format(user.display_name, str(t), unit, ctx.message.author.display_name))
  105. elif user.id in self.json[server.id] and role not in user.roles:
  106. # USER IN PUNISH, NO ROLE
  107. await self.bot.add_roles(user, role)
  108. await self.bot.say('Role reapplied on {}'.format(user.display_name))
  109. elif user.id not in self.json[server.id] and role in user.roles:
  110. # USER NOT IN PUNISH, HAS ROLE
  111. until = self._timestamp(t, unit)
  112. self.json[server.id][user.id] = {'until': until, 'givenby': ctx.message.author.id}
  113. dataIO.save_json(self.location, self.json)
  114. await self.bot.say('``{}`` is now Punished for {} {} by ``{}``.'.format(user.display_name, str(t), unit, ctx.message.author.display_name))
  115. else:
  116. # USER IN PUNISH, HAS ROLE
  117. await self.bot.say('``{}`` is already punished. Please use ``unpunish`` to unpunish the user.'.format(user.display_name))
  118. except:
  119. await self.bot.say('Invalid unit')
  120.  
  121. @commands.command(pass_context=True, no_pm=True)
  122. @checks.mod_or_permissions(manage_messages=True)
  123. async def unpunish(self, ctx, user: discord.Member):
  124. """Unpunishes a punished user"""
  125. if user.id in self.json[ctx.message.server.id]:
  126. r = discord.utils.get(ctx.message.server.roles, name='Punished')
  127. del self.json[ctx.message.server.id][user.id]
  128. await self.bot.remove_roles(user, r)
  129. dataIO.save_json(self.location, self.json)
  130. await self.bot.say('``{}`` is now unpunished.'.format(user.display_name))
  131.  
  132. @commands.command(pass_context=True, no_pm=True)
  133. async def muted(self, ctx):
  134. """Shows the list of punished users"""
  135. # Populate a list with other lists, they act as tables
  136. server = ctx.message.server
  137. table = []
  138. if server.id in self.json:
  139. for user in self.json[server.id]:
  140. temp = []
  141. # Get the user display_name
  142. user_obj = discord.utils.get(server.members, id=user)
  143. log.debug(user_obj)
  144. if user_obj is None:
  145. temp.append('ID: {}'.format(user))
  146. else:
  147. temp.append(user_obj.display_name)
  148. # Get the time in minutes or hours, (hopefully)
  149. remaining = self.json[server.id][user]['until'] - int(time.time())
  150. if remaining < 60:
  151. temp.append('<1 Minute')
  152. elif remaining < 120:
  153. temp.append('1 Minute')
  154. elif remaining < 3600:
  155. remaining = remaining / 60
  156. temp.append('{} Minutes'.format(int(remaining)))
  157. elif remaining < 86400:
  158. remaining = remaining / 60 / 60
  159. temp.append('{} Hours'.format(int(remaining)))
  160. else:
  161. remaining = remaining / 60 / 60 / 24
  162. temp.append('{} Days'.format(int(remaining)))
  163. # Get the givenby
  164. given_obj = discord.utils.get(server.members, id=self.json[server.id][user]['givenby'])
  165. if given_obj is None:
  166. temp.append('ID: {}'.format(self.json[server.id][user]['givenby']))
  167. else:
  168. temp.append(given_obj.display_name)
  169. table.append(temp)
  170. header = ['Member', 'Time Remaining', 'Given By']
  171. await self.bot.say('```\n{}```'.format(tabulate(table, headers=header, tablefmt='simple')))
  172. else:
  173. await self.bot.say('No punishments are given out on this server.')
  174.  
  175. # Look for new channels, and slap the role in there face!
  176. async def new_channel(self, c):
  177. if 'Punished' in [r.name for r in c.server.roles]:
  178. if c.type.name == 'text':
  179. perms = discord.PermissionOverwrite()
  180. perms.send_messages = False
  181. r = discord.utils.get(c.server.roles, name='Punished')
  182. await self.bot.edit_channel_permissions(c, r, perms)
  183. log.debug('Punished role created on channel: {}'.format(c.id))
  184.  
  185. async def check_time(self):
  186. while True:
  187. await asyncio.sleep(30)
  188. json = copy.deepcopy(self.json)
  189. log.debug('First Timer')
  190. for server in json:
  191. server_obj = discord.utils.get(self.bot.servers, id=server)
  192. role_obj = discord.utils.get(server_obj.roles, name='Punished')
  193. log.debug('Server Object = {}'.format(server_obj))
  194. for user in json[server]:
  195. user_obj = discord.utils.get(server_obj.members, id=user)
  196. log.debug('User Object = {}'.format(user_obj))
  197. if json[server][user]['until'] < int(time.time()):
  198. log.debug('Expired user ({})'.format(user))
  199. await self.bot.remove_roles(user_obj, role_obj)
  200. del self.json[server][user]
  201. dataIO.save_json(self.location, self.json)
  202. log.debug('after loops')
  203.  
  204. async def new_member(self, member):
  205. if member.server.id in self.json:
  206. if member.id in self.json[member.server.id]:
  207. r = discord.utils.get(member.server.roles, name='Punished')
  208. await self.bot.add_roles(member, r)
  209. log.debug('User ({}) joined while punished.'.format(member.id))
  210.  
  211.  
  212. def check_folder():
  213. if not os.path.exists('data/punish'):
  214. log.debug('Creating folder: data/punish')
  215. os.makedirs('data/punish')
  216.  
  217.  
  218. def check_file():
  219. f = 'data/punish/settings.json'
  220. if dataIO.is_valid_json(f) is False:
  221. log.debug('Creating json: settings.json')
  222. dataIO.save_json(f, {})
  223.  
  224.  
  225. def setup(bot):
  226. check_folder()
  227. check_file()
  228. n = Punish(bot)
  229. bot.add_cog(n)
  230. bot.add_listener(n.new_member, 'on_member_join')
  231. bot.add_listener(n.new_channel, 'on_channel_create')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement