text: # Copyright (C) 2019 The Raphielscape Company LLC.
  #
  # Licensed under the Raphielscape Public License, Version 1.c (the "License");
  # you may not use this file except in compliance with the License.
  """
  Userbot module to help you manage a group
  """
  
  from asyncio import sleep
  from os import remove
  from telethon import events
  import asyncio
  
  from telethon.errors import (BadRequestError, ChatAdminRequiredError,
                               UserAdminInvalidError)
  from telethon.errors.rpcerrorlist import (UserIdInvalidError,
                                            MessageTooLongError)
  from telethon.tl.functions.channels import (EditAdminRequest,
                                              EditBannedRequest)
  
  from telethon.tl.types import (ChannelParticipantsAdmins, ChatAdminRights,
                                 ChatBannedRights, MessageEntityMentionName,
                                 MessageMediaPhoto)
  
  from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP, bot 
  from userbot.utils import  errors_handler, admin_cmd
  
  # =================== CONSTANT ===================
  
  NO_ADMIN = "`I am not an admin nub nibba!`"
  NO_PERM = "`I don't have sufficient permissions! This is so sed. Alexa play despacito`"
  NO_SQL = "`Running on Non-SQL mode!`"
  
  
  
  BANNED_RIGHTS = ChatBannedRights(
      until_date=None,
      view_messages=True,
      send_messages=True,
      send_media=True,
      send_stickers=True,
      send_gifs=True,
      send_games=True,
      send_inline=True,
      embed_links=True,
  )
  
  UNBAN_RIGHTS = ChatBannedRights(
      until_date=None,
      send_messages=None,
      send_media=None,
      send_stickers=None,
      send_gifs=None,
      send_games=None,
      send_inline=None,
      embed_links=None,
  )
  
  MUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True)
  
  UNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False)
  # ================================================
  
  
  @borg.on(admin_cmd(pattern="(ban|unban) ?(.*)", allow_sudo=True))
  async def _(event):
      # Space weirdness in regex required because argument is optional and other
      # commands start with ".unban"
      if event.fwd_from:
          return
      start = datetime.now()
      to_ban_id = None
      rights = None
      input_cmd = event.pattern_match.group(1)
      if input_cmd == "ban":
          rights = BANNED_RIGHTS
      elif input_cmd == "unban":
          rights = UNBAN_RIGHTS
      input_str = event.pattern_match.group(2)
      reply_msg_id = event.reply_to_msg_id
      if reply_msg_id:
          r_mesg = await event.get_reply_message()
          to_ban_id = r_mesg.from_id
      elif input_str and "all" not in input_str:
          to_ban_id = int(input_str)
      else:
          return False
      try:
          await borg(EditBannedRequest(event.chat_id, to_ban_id, rights))
      except (Exception) as exc:
          await event.edit(str(exc))
      else:
          await event.edit(f"{input_cmd}ned Successfully!")
  
  
  @borg.on(admin_cmd(pattern="pgs ?(.*)", allow_sudo=True))
  async def _(event):
      if event.fwd_from:
          return
      if event.reply_to_msg_id:
          i = 1
          msgs = []
          from_user = None
          input_str = event.pattern_match.group(1)
          if input_str:
              from_user = await borg.get_entity(input_str)
              logger.info(from_user)
          async for message in borg.iter_messages(
              event.chat_id,
              min_id=event.reply_to_msg_id,
              from_user=from_user
          ):
              i = i + 1
              msgs.append(message)
              if len(msgs) == 100:
                  await borg.delete_messages(event.chat_id, msgs, revoke=True)
                  msgs = []
          if len(msgs) <= 100:
              await borg.delete_messages(event.chat_id, msgs, revoke=True)
              msgs = []
              await event.delete()
          else:
              await event.edit("**PURGE** Failed!")
  
  
  @borg.on(admin_cmd(pattern="(ban|unban) ?(.*)"))
  async def _(event):
      # Space weirdness in regex required because argument is optional and other
      # commands start with ".unban"
      if event.fwd_from:
          return
      start = datetime.now()
      to_ban_id = None
      rights = None
      input_cmd = event.pattern_match.group(1)
      if input_cmd == "ban":
          rights = BANNED_RIGHTS
      elif input_cmd == "unban":
          rights = UNBAN_RIGHTS
      input_str = event.pattern_match.group(2)
      reply_msg_id = event.reply_to_msg_id
      if reply_msg_id:
          r_mesg = await event.get_reply_message()
          to_ban_id = r_mesg.from_id
      elif input_str and "all" not in input_str:
          to_ban_id = int(input_str)
      else:
          return False
      try:
          await borg(EditBannedRequest(event.chat_id, to_ban_id, rights))
      except (Exception) as exc:
          await event.edit(str(exc))
      else:
          await event.edit(f"{input_cmd}ned Successfully!")
  
  
  async def get_user_from_event(event):
      """ Get the user from argument or replied message. """
      args = event.pattern_match.group(1).split(' ', 1)
      extra = None
      if event.reply_to_msg_id:
          previous_message = await event.get_reply_message()
          user_obj = await event.client.get_entity(previous_message.from_id)
          extra = event.pattern_match.group(1)
      elif args:
          user = args[0]
          if len(args) == 2:
              extra = args[1]
  
          if user.isnumeric():
              user = int(user)
  
          if not user:
              await event.edit("`Pass the user's username, id or reply!`")
              return
  
          if event.message.entities is not None:
              probable_user_mention_entity = event.message.entities[0]
  
              if isinstance(probable_user_mention_entity,
                            MessageEntityMentionName):
                  user_id = probable_user_mention_entity.user_id
                  user_obj = await event.client.get_entity(user_id)
                  return user_obj
          try:
              user_obj = await event.client.get_entity(user)
          except (TypeError, ValueError) as err:
              await event.edit(str(err))
              return None
  
      return user_obj, extra
  
  
  async def get_user_from_id(user, event):
      if isinstance(user, str):
          user = int(user)
  
      try:
          user_obj = await event.client.get_entity(user)
      except (TypeError, ValueError) as err:
          await event.edit(str(err))
          return None
  
      return user_obj
    
    
    
  CMD_HELP.update({
      "ban":
      ".ban reply to the user/.ban username/.ban userid\
      \nbans the user in the group\
      \n\n.unban reply to the user/.unban username/.unban userid\
      \nunbans the user in the group\
  "
  })   
  