Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- print("Connecting...")
- class JailClient(Bot):
- _db = None
- _Users = None
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- # create the background task and run it in the background
- self.bg_task = self.loop.create_task(self.check_jail_status())
- self._db = TinyDB('data.json')
- self._Users = Query()
- async def check_jail_status(self):
- await self.wait_until_ready()
- guild = self.get_guild(GUILD_ID) # guild ID goes here
- try:
- jail_role = discord.utils.get(guild.roles, name=JAIL_ROLE)
- if jail_role is None:
- print('Error, role \'thin ice\' not found')
- return
- while not self.is_closed():
- now = datetime.datetime.now().timestamp()
- # get jailed
- q = self._db.search((self._Users.expired_at > now) | (self._Users.expire_at == 0))
- #if they does not have a role and jailed, set it
- if q:
- for member in q:
- real_member = guild.get_member(member['id'])
- has_role = discord.utils.get(real_member.roles, name=JAIL_ROLE)
- if has_role is None:
- await real_member.add_roles(jail_role, reason='Роль восстановлена')
- q = self._db.search((self._Users.expired_at <= now) & (self._Users.expire_at != 0))
- if q:
- for member in q:
- real_member = guild.get_member(member['id'])
- self._db.remove(self._Users.id==real_member.id)
- # remove that role
- await real_member.remove_roles(jail_role, reason='Наказание истекло')
- await asyncio.sleep(1) # task runs every 60 seconds
- except Exception as e:
- print('check_jail_status error, ', e)
- async def on_ready(self):
- print("Bot online!")
- print("Discord.py API version: ", discord.__version__)
- print("Name: {}".format(client.user.name))
- print("ID: {}".format(client.user.id))
- print("Currently active on " + str(len(client.guilds)) + " servers.")
- print("")
- async def on_member_update(self, before, after):
- try:
- if len(before.roles) != len(after.roles): # роли изменились
- had_jail_role = discord.utils.get(before.roles, name=JAIL_ROLE)
- has_jail_role = discord.utils.get(after.roles, name=JAIL_ROLE)
- if had_jail_role and has_jail_role is None:
- # remove from database if it is there
- self._db.remove(self._Users.id==after.id)
- except discord.Forbidden as e:
- print('[on_member_update] Forbidden, bot hasn\'t access to that, check permissions, ', e)
- except discord.HTTPException as e:
- print('[on_member_update] Error on adding/removing role. HTTP Exception, ', e)
- except Exception as e:
- print('[on_member_update] Unrecognized error: ', e)
- async def can_target(self, ctx, target : discord.Member, notify: bool):
- if (ctx.author.top_role.position <= target.top_role.position and ctx.author.id != target.id):
- if notify:
- output = '{}, The nerve, the audacity. {}'.format(ctx.author.mention, target.mention)
- output = discord.Embed(title='Access Denied', type='rich', description=output, colour=discord.Colour.red())
- await ctx.send(embed=output)
- await ctx.message.delete()
- return False
- return True
- @commands.command(name='jail', help='Keep this place safe, from that user')
- @commands.guild_only()
- @commands.has_role(WARDEN_ROLE)
- @asyncio.coroutine
- def jail(ctx, victim: discord.Member, length: int, reason: str = None):
- try:
- if length < 0:
- yield from ctx.author.send(embed=discord.Embed(title='Error', type='rich', description="There term cannot be < 0", colour=discord.Colour.red()))
- return
- if victim.bot:
- yield from ctx.send(embed=discord.Embed(title='Are you stupid? Are you dumb?', type='rich', description="", colour=discord.Colour.red()))
- return
- can_target = yield from client.can_target(ctx, victim, True)
- if not can_target:
- return
- jailrole = discord.utils.get(ctx.guild.roles, name=JAIL_ROLE)
- if jailrole:
- now = datetime.datetime.now().timestamp()
- expired_at = datetime.datetime.now() + datetime.timedelta(minutes=length)
- if reason:
- reason = (reason[:75] + '..') if len(reason) > 75 else reason
- # role founded, check in database, if user has role and in database
- if jailrole in victim.roles and client._db.contains(client._Users.id == victim.id):
- if reason:
- client._db.update({'created_at': now, 'expired_at': 0 if length == 0 else expired_at.timestamp(), 'reason': reason}, client._Users.id == victim.id)
- else:
- client._db.update({'created_at': now, 'expired_at': 0 if length == 0 else expired_at.timestamp()}, client._Users.id == victim.id)
- lengthstr = 'for ' + str(length) + ' minutes' if length > 0 else 'forever'
- embed = discord.Embed(title='Jail length updated', type='rich', description="User {} was jailed {}".format(victim.mention, lengthstr), colour=discord.Colour.blue())
- if reason:
- embed.add_field(name="New reason:", value="{}".format(reason))
- yield from ctx.send(embed=embed)
- else: #user not in database and does not have a role
- 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 })
- yield from victim.add_roles(jailrole, reason='Sent to jail {}#{}'.format(ctx.author.name, ctx.author.discriminator))
- lengthstr = 'for ' + str(length) + ' minutes' if length > 0 else 'for life'
- embed = discord.Embed(title='Jail', type='rich', description="User {} was jailed {}".format(victim.mention, lengthstr), colour=discord.Colour.orange())
- embed.add_field(name="Reason:", value="{}".format("N/A" if reason is None else reason))
- yield from ctx.send(embed=embed)
- else:
- print('Role \'thin ice\' not found')
- except discord.Forbidden as e:
- print('Forbidden, bot hasn\'t access to that, check permissions, ', e)
- except discord.HTTPException as e:
- print('Error on adding/removing role. HTTP Exception, ', e)
- except Exception as e:
- print('Unrecognized error: ', e)
- @commands.command(name='unjail', help='Unjail member')
- @commands.guild_only()
- @commands.has_role(WARDEN_ROLE)
- @asyncio.coroutine
- def unjail(ctx, victim: discord.Member):
- try:
- if victim.bot:
- yield from ctx.send(embed=discord.Embed(title='You do not have permission to do that!', type='rich', description="", colour=discord.Colour.red()))
- return
- can_target = yield from client.can_target(ctx, victim, True)
- if not can_target:
- return
- # Remove from database and then remove role
- client._db.remove(client._Users.id==victim.id)
- jail_role = discord.utils.get(victim.roles, name=JAIL_ROLE)
- if jail_role is None:
- yield from ctx.send(embed=discord.Embed(title='Jail', type='rich', description="User {} Not in jail".format(victim.mention), colour=discord.Colour.red()))
- return
- # remove that role
- yield from ctx.send(embed=discord.Embed(title='Jail', type='rich', description="User {} was released".format(victim.mention), colour=discord.Colour.dark_green()))
- yield from victim.remove_roles(jail_role, reason='Released {}#{}'.format(ctx.author.name, ctx.author.discriminator))
- except discord.Forbidden as e:
- print('Forbidden, bot hasn\'t access to that, check permissions, ', e)
- except discord.HTTPException as e:
- print('Error on adding/removing role. HTTP Exception, ', e)
- except Exception as e:
- print('Unrecognized error: ', e)
- @commands.command(name='checkjail', help='Check member', description='Check jail status of member')
- @commands.guild_only()
- @commands.has_role(WARDEN_ROLE)
- @asyncio.coroutine
- def checkjail(ctx, victim: discord.Member):
- try:
- if victim.bot:
- yield from ctx.send(embed=discord.Embed(title='You do not have the sufficient permissions.', type='rich', description="", colour=discord.Colour.red()))
- return
- can_target = yield from client.can_target(ctx, victim, True)
- if not can_target:
- return
- jailrole = discord.utils.get(ctx.guild.roles, name=JAIL_ROLE)
- if jailrole and (jailrole in victim.roles) and client._db.contains(client._Users.id == victim.id):
- # role founded, check in database, if user has role and in database
- clientinfo = client._db.search(client._Users.id == victim.id)
- if not clientinfo or not len(clientinfo):
- print("error, no info found for victim {} and him jail status".format(victim.id))
- clientinfo = clientinfo[0]
- created_at = datetime.datetime.fromtimestamp(int(clientinfo['created_at']))
- created_at_str = created_at.strftime('%d-%m-%Y %H:%M:%S')
- if clientinfo['expired_at'] > 0:
- expired_at = datetime.datetime.fromtimestamp(int(clientinfo['expired_at']))
- expired_at_str = expired_at.strftime('%d-%m-%Y %H:%M:%S')
- else:
- expired_at_str = 'в след. жизни'
- if clientinfo['expired_at'] > 0:
- length = relativedelta(expired_at, created_at)
- length_str = "на "
- if length.days > 0:
- length_str += "{} дней ".format(length.days)
- if length.hours > 0:
- length_str += "{} часов ".format(length.hours)
- if length.minutes > 0:
- length_str += "{} минут ".format(length.minutes)
- if length.seconds > 0:
- length_str += "{} секунд".format(length.seconds)
- else:
- length_str = "пожизненно"
- embed = discord.Embed(title='Информация о {}#{}'.format(victim.name, victim.discriminator), type='rich', description="Пользователь {} был посажен {}".format(victim.mention, length_str))
- embed.add_field(name="Осужден:", value="{}".format(created_at_str))
- embed.add_field(name="Будет освобожден:", value="{}".format(expired_at_str))
- embed.add_field(name="Причина:", value="{}".format(clientinfo['reason']), inline=False)
- yield from ctx.send(embed=embed)
- else:
- yield from ctx.send(embed=discord.Embed(title='Тюрьма', type='rich', description="Пользователь {} чист перед законом".format(victim.mention)))
- except discord.Forbidden as e:
- print('Forbidden, bot hasn\'t access to that, check permissions, ', e)
- except discord.HTTPException as e:
- print('Error on adding/removing role. HTTP Exception, ', e)
- except Exception as e:
- print('Unrecognized error: ', e)
- # Start bot
- client = JailClient(description='Warden bot', command_prefix=',')
- client.add_command(jail)
- client.add_command(unjail)
- client.add_command(checkjail)
- @client.check_once
- def check_role(ctx):
- return discord.utils.get(ctx.message.author.roles, name=WARDEN_ROLE) is not None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement