Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.92 KB | None | 0 0
  1. print("Connecting...")
  2.  
  3. class JailClient(Bot):
  4. _db = None
  5. _Users = None
  6.  
  7. def __init__(self, *args, **kwargs):
  8. super().__init__(*args, **kwargs)
  9.  
  10. # create the background task and run it in the background
  11. self.bg_task = self.loop.create_task(self.check_jail_status())
  12.  
  13. self._db = TinyDB('data.json')
  14. self._Users = Query()
  15.  
  16. async def check_jail_status(self):
  17. await self.wait_until_ready()
  18.  
  19. guild = self.get_guild(GUILD_ID) # guild ID goes here
  20. try:
  21. jail_role = discord.utils.get(guild.roles, name=JAIL_ROLE)
  22. if jail_role is None:
  23. print('Error, role \'thin ice\' not found')
  24. return
  25. while not self.is_closed():
  26. now = datetime.datetime.now().timestamp()
  27. # get jailed
  28. q = self._db.search((self._Users.expired_at > now) | (self._Users.expire_at == 0))
  29. #if they does not have a role and jailed, set it
  30. if q:
  31. for member in q:
  32. real_member = guild.get_member(member['id'])
  33. has_role = discord.utils.get(real_member.roles, name=JAIL_ROLE)
  34. if has_role is None:
  35. await real_member.add_roles(jail_role, reason='Роль восстановлена')
  36. q = self._db.search((self._Users.expired_at <= now) & (self._Users.expire_at != 0))
  37. if q:
  38. for member in q:
  39. real_member = guild.get_member(member['id'])
  40. self._db.remove(self._Users.id==real_member.id)
  41. # remove that role
  42. await real_member.remove_roles(jail_role, reason='Наказание истекло')
  43. await asyncio.sleep(1) # task runs every 60 seconds
  44. except Exception as e:
  45. print('check_jail_status error, ', e)
  46.  
  47.  
  48. async def on_ready(self):
  49. print("Bot online!")
  50. print("Discord.py API version: ", discord.__version__)
  51.  
  52. print("Name: {}".format(client.user.name))
  53. print("ID: {}".format(client.user.id))
  54. print("Currently active on " + str(len(client.guilds)) + " servers.")
  55. print("")
  56.  
  57. async def on_member_update(self, before, after):
  58. try:
  59. if len(before.roles) != len(after.roles): # роли изменились
  60. had_jail_role = discord.utils.get(before.roles, name=JAIL_ROLE)
  61. has_jail_role = discord.utils.get(after.roles, name=JAIL_ROLE)
  62. if had_jail_role and has_jail_role is None:
  63. # remove from database if it is there
  64. self._db.remove(self._Users.id==after.id)
  65. except discord.Forbidden as e:
  66. print('[on_member_update] Forbidden, bot hasn\'t access to that, check permissions, ', e)
  67. except discord.HTTPException as e:
  68. print('[on_member_update] Error on adding/removing role. HTTP Exception, ', e)
  69. except Exception as e:
  70. print('[on_member_update] Unrecognized error: ', e)
  71.  
  72. async def can_target(self, ctx, target : discord.Member, notify: bool):
  73. if (ctx.author.top_role.position <= target.top_role.position and ctx.author.id != target.id):
  74. if notify:
  75. output = '{}, The nerve, the audacity. {}'.format(ctx.author.mention, target.mention)
  76. output = discord.Embed(title='Access Denied', type='rich', description=output, colour=discord.Colour.red())
  77. await ctx.send(embed=output)
  78. await ctx.message.delete()
  79. return False
  80. return True
  81.  
  82.  
  83. @commands.command(name='jail', help='Keep this place safe, from that user')
  84. @commands.guild_only()
  85. @commands.has_role(WARDEN_ROLE)
  86. @asyncio.coroutine
  87. def jail(ctx, victim: discord.Member, length: int, reason: str = None):
  88. try:
  89. if length < 0:
  90. yield from ctx.author.send(embed=discord.Embed(title='Error', type='rich', description="There term cannot be < 0", colour=discord.Colour.red()))
  91. return
  92. if victim.bot:
  93. yield from ctx.send(embed=discord.Embed(title='Are you stupid? Are you dumb?', type='rich', description="", colour=discord.Colour.red()))
  94. return
  95. can_target = yield from client.can_target(ctx, victim, True)
  96. if not can_target:
  97. return
  98. jailrole = discord.utils.get(ctx.guild.roles, name=JAIL_ROLE)
  99. if jailrole:
  100. now = datetime.datetime.now().timestamp()
  101. expired_at = datetime.datetime.now() + datetime.timedelta(minutes=length)
  102. if reason:
  103. reason = (reason[:75] + '..') if len(reason) > 75 else reason
  104. # role founded, check in database, if user has role and in database
  105. if jailrole in victim.roles and client._db.contains(client._Users.id == victim.id):
  106. if reason:
  107. client._db.update({'created_at': now, 'expired_at': 0 if length == 0 else expired_at.timestamp(), 'reason': reason}, client._Users.id == victim.id)
  108. else:
  109. client._db.update({'created_at': now, 'expired_at': 0 if length == 0 else expired_at.timestamp()}, client._Users.id == victim.id)
  110. lengthstr = 'for ' + str(length) + ' minutes' if length > 0 else 'forever'
  111. embed = discord.Embed(title='Jail length updated', type='rich', description="User {} was jailed {}".format(victim.mention, lengthstr), colour=discord.Colour.blue())
  112. if reason:
  113. embed.add_field(name="New reason:", value="{}".format(reason))
  114. yield from ctx.send(embed=embed)
  115. else: #user not in database and does not have a role
  116. client._db.insert({'id': victim.id, 'created_at': now, 'expired_at': 0 if length == 0 else expired_at.timestamp(), 'reason': 'N/A' if reason is None else reason })
  117. yield from victim.add_roles(jailrole, reason='Sent to jail {}#{}'.format(ctx.author.name, ctx.author.discriminator))
  118. lengthstr = 'for ' + str(length) + ' minutes' if length > 0 else 'for life'
  119. embed = discord.Embed(title='Jail', type='rich', description="User {} was jailed {}".format(victim.mention, lengthstr), colour=discord.Colour.orange())
  120. embed.add_field(name="Reason:", value="{}".format("N/A" if reason is None else reason))
  121. yield from ctx.send(embed=embed)
  122. else:
  123. print('Role \'thin ice\' not found')
  124. except discord.Forbidden as e:
  125. print('Forbidden, bot hasn\'t access to that, check permissions, ', e)
  126. except discord.HTTPException as e:
  127. print('Error on adding/removing role. HTTP Exception, ', e)
  128. except Exception as e:
  129. print('Unrecognized error: ', e)
  130.  
  131. @commands.command(name='unjail', help='Unjail member')
  132. @commands.guild_only()
  133. @commands.has_role(WARDEN_ROLE)
  134. @asyncio.coroutine
  135. def unjail(ctx, victim: discord.Member):
  136. try:
  137. if victim.bot:
  138. yield from ctx.send(embed=discord.Embed(title='You do not have permission to do that!', type='rich', description="", colour=discord.Colour.red()))
  139. return
  140. can_target = yield from client.can_target(ctx, victim, True)
  141. if not can_target:
  142. return
  143.  
  144. # Remove from database and then remove role
  145. client._db.remove(client._Users.id==victim.id)
  146.  
  147. jail_role = discord.utils.get(victim.roles, name=JAIL_ROLE)
  148. if jail_role is None:
  149. yield from ctx.send(embed=discord.Embed(title='Jail', type='rich', description="User {} Not in jail".format(victim.mention), colour=discord.Colour.red()))
  150. return
  151. # remove that role
  152. yield from ctx.send(embed=discord.Embed(title='Jail', type='rich', description="User {} was released".format(victim.mention), colour=discord.Colour.dark_green()))
  153. yield from victim.remove_roles(jail_role, reason='Released {}#{}'.format(ctx.author.name, ctx.author.discriminator))
  154.  
  155. except discord.Forbidden as e:
  156. print('Forbidden, bot hasn\'t access to that, check permissions, ', e)
  157. except discord.HTTPException as e:
  158. print('Error on adding/removing role. HTTP Exception, ', e)
  159. except Exception as e:
  160. print('Unrecognized error: ', e)
  161.  
  162. @commands.command(name='checkjail', help='Check member', description='Check jail status of member')
  163. @commands.guild_only()
  164. @commands.has_role(WARDEN_ROLE)
  165. @asyncio.coroutine
  166. def checkjail(ctx, victim: discord.Member):
  167. try:
  168. if victim.bot:
  169. yield from ctx.send(embed=discord.Embed(title='You do not have the sufficient permissions.', type='rich', description="", colour=discord.Colour.red()))
  170. return
  171. can_target = yield from client.can_target(ctx, victim, True)
  172. if not can_target:
  173. return
  174.  
  175. jailrole = discord.utils.get(ctx.guild.roles, name=JAIL_ROLE)
  176. if jailrole and (jailrole in victim.roles) and client._db.contains(client._Users.id == victim.id):
  177. # role founded, check in database, if user has role and in database
  178. clientinfo = client._db.search(client._Users.id == victim.id)
  179. if not clientinfo or not len(clientinfo):
  180. print("error, no info found for victim {} and him jail status".format(victim.id))
  181. clientinfo = clientinfo[0]
  182. created_at = datetime.datetime.fromtimestamp(int(clientinfo['created_at']))
  183. created_at_str = created_at.strftime('%d-%m-%Y %H:%M:%S')
  184. if clientinfo['expired_at'] > 0:
  185. expired_at = datetime.datetime.fromtimestamp(int(clientinfo['expired_at']))
  186. expired_at_str = expired_at.strftime('%d-%m-%Y %H:%M:%S')
  187. else:
  188. expired_at_str = 'в след. жизни'
  189. if clientinfo['expired_at'] > 0:
  190. length = relativedelta(expired_at, created_at)
  191. length_str = "на "
  192. if length.days > 0:
  193. length_str += "{} дней ".format(length.days)
  194. if length.hours > 0:
  195. length_str += "{} часов ".format(length.hours)
  196. if length.minutes > 0:
  197. length_str += "{} минут ".format(length.minutes)
  198. if length.seconds > 0:
  199. length_str += "{} секунд".format(length.seconds)
  200. else:
  201. length_str = "пожизненно"
  202. embed = discord.Embed(title='Информация о {}#{}'.format(victim.name, victim.discriminator), type='rich', description="Пользователь {} был посажен {}".format(victim.mention, length_str))
  203. embed.add_field(name="Осужден:", value="{}".format(created_at_str))
  204. embed.add_field(name="Будет освобожден:", value="{}".format(expired_at_str))
  205. embed.add_field(name="Причина:", value="{}".format(clientinfo['reason']), inline=False)
  206. yield from ctx.send(embed=embed)
  207. else:
  208. yield from ctx.send(embed=discord.Embed(title='Тюрьма', type='rich', description="Пользователь {} чист перед законом".format(victim.mention)))
  209. except discord.Forbidden as e:
  210. print('Forbidden, bot hasn\'t access to that, check permissions, ', e)
  211. except discord.HTTPException as e:
  212. print('Error on adding/removing role. HTTP Exception, ', e)
  213. except Exception as e:
  214. print('Unrecognized error: ', e)
  215.  
  216. # Start bot
  217.  
  218. client = JailClient(description='Warden bot', command_prefix=',')
  219. client.add_command(jail)
  220. client.add_command(unjail)
  221. client.add_command(checkjail)
  222.  
  223. @client.check_once
  224. def check_role(ctx):
  225. return discord.utils.get(ctx.message.author.roles, name=WARDEN_ROLE) is not None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement