Example #1
0
    async def admin_log(self,
                        ctx: Context,
                        enabled: bool,
                        channel: TextChannel = None):
        """Enable/disable to-channel logging and set the log channel.
        MUST HAVE SERVER ADMINISTRATOR PERMISSION
        """
        sid = str(ctx.guild.id)

        # Initialize the server in the database if required
        if sid not in db:
            db[sid] = {}

        # Set the config values based on user input (or lack thereof for log channel)
        db[sid]["log"] = enabled

        if channel is not None:
            db[sid]["log_channel"] = str(channel.id)
        else:
            if "log_channel" not in db[sid]:
                db[sid]["log_channel"] = str(ctx.message.channel.id)
            channel = ctx.message.channel

        update_db(sql_db, db, "admin")

        embed = Embed(title="Log Settings", color=0xff0000)
        embed.add_field(name="Enabled", value=str(enabled))
        embed.add_field(name="Log Channel", value=channel.mention)

        await ctx.send(embed=embed)
Example #2
0
    async def unmute(self, ctx: Context, target: Member):
        """Unmute a member early.
        Level 4 required
        """
        sid = str(ctx.guild.id)
        uid = str(target.id)
        mute_role = None

        # Try to get the mute role from the server
        try:
            mute_role = ctx.guild.get_role(int(db[sid]["mute_role"]))
        except KeyError:
            await ctx.send(":anger: This server has no mute role set.")
            return

        if sid not in mute_db:
            await ctx.send(":anger: This server has no mutes.")
            return

        if uid not in mute_db[sid]:
            await ctx.send(":anger: This member is not muted.")
            return

        await target.send(
            f":speaking_head: You have been unmuted in {ctx.guild.name}.")
        await ctx.send(f":speaking_head: Unmuted {target.name}.")

        # Remove the mute role and delete the entry from the database
        await target.remove_roles(mute_role)
        del mute_db[sid][uid]

        update_db(sql_db, mute_db, "mutes")
Example #3
0
 async def role_add(self, ctx, *, role_name: Role):
     """Add an assignable role."""
     s_id = ctx.message.server.id
     if s_id not in roles:
         roles[s_id] = []
     roles[s_id].append(role_name.name)
     update_db(roles, "roles")
     await self.bot.say("\U00002705")
Example #4
0
 async def account_remove(self, uid: str):
     """Remove an acconut."""
     if uid not in accounts:
         await self.bot.say(f"\U00002754 No account with ID {uid} exists.")
         return
     del accounts[uid]
     update_db(accounts, "accounts")
     await self.bot.say("\U00002705")
Example #5
0
 async def account_update(self, uid: str, level: int):
     """Change an account's level."""
     if uid not in accounts:
         await self.bot.say(f"\U00002754 No accounts with ID {uid} exists.")
         return
     accounts[uid]["level"] = level
     update_db(accounts, "accounts")
     await self.bot.say("\U00002705")
Example #6
0
 async def account_update(self, uid: str, level: int):
     """Change an account's level."""
     if uid not in accounts:
         await self.bot.say(f"\U00002754 No accounts with ID {uid} exists.")
         return
     accounts[uid]["level"] = level
     update_db(accounts, "accounts")
     await self.bot.say("\U00002705")
Example #7
0
 async def account_remove(self, uid: str):
     """Remove an acconut."""
     if uid not in accounts:
         await self.bot.say(f"\U00002754 No account with ID {uid} exists.")
         return
     del accounts[uid]
     update_db(accounts, "accounts")
     await self.bot.say("\U00002705")
Example #8
0
 async def role_add(self, ctx, *, role_name: Role):
     """Add an assignable role."""
     s_id = ctx.message.server.id
     if s_id not in roles:
         roles[s_id] = []
     roles[s_id].append(role_name.name)
     update_db(roles, "roles")
     await self.bot.say("\U00002705")
Example #9
0
 async def account_add(self, uid: str, level: int):
     """Add an account."""
     if uid in accounts:
         await self.bot.say("\U00002754 Account already exists.")
         return
     accounts[uid] = {}
     accounts[uid]["level"] = level
     update_db(accounts, "accounts")
     await self.bot.say("\U00002705")
Example #10
0
 async def account_add(self, uid: str, level: int):
     """Add an account."""
     if uid in accounts:
         await self.bot.say("\U00002754 Account already exists.")
         return
     accounts[uid] = {}
     accounts[uid]["level"] = level
     update_db(accounts, "accounts")
     await self.bot.say("\U00002705")
Example #11
0
 async def admin_set(self, ctx):
     """Set the logging channel for admin commands.
     
     The channel this command is invoked in will become the channel that all
     bot administration actions (kicks, bans, softbans, and unbans) are logged
     to.
     """
     admin["servers"][ctx.message.server.id] = ctx.message.channel.id
     update_db(admin, "admin")
     await self.bot.say("\U00002705")
Example #12
0
 async def role_remove(self, ctx, *, role_name: Role):
     """Remove an assignable role."""
     s_id = ctx.message.server.id
     if s_id not in roles:
         await self.bot.say("\U00002757 This server has no assignable roles.")
         return
     roles[s_id].remove(role_name.name)
     if len(roles[s_id]) == 0:
         del roles[s_id]
     update_db(roles, "roles")
     await self.bot.say("\U00002705")
Example #13
0
 async def role_remove(self, ctx, *, role_name: Role):
     """Remove an assignable role."""
     s_id = ctx.message.server.id
     if s_id not in roles:
         await self.bot.say(
             "\U00002757 This server has no assignable roles.")
         return
     roles[s_id].remove(role_name.name)
     if len(roles[s_id]) == 0:
         del roles[s_id]
     update_db(roles, "roles")
     await self.bot.say("\U00002705")
Example #14
0
    async def groups_create(self, ctx: Context, name: str, *,
                            description: str):
        """Create a group for you and your friends!
        Name must NOT include spaces!
        """
        sid = str(ctx.guild.id)

        if sid not in db:
            db[sid] = {}

        # Try to make a role, text, and voice channel for the group
        try:
            role = await ctx.guild.create_role(name=name, reason=GP)
            # Set overwrites for the category
            ow = {
                ctx.guild.default_role:
                PermissionOverwrite(read_messages=False),
                role: PermissionOverwrite(read_messages=True)
            }
            category = await ctx.guild.create_category(name=name,
                                                       reason=GP,
                                                       overwrites=ow)
            text = await ctx.guild.create_text_channel(name=name.lower(),
                                                       reason=GP,
                                                       category=category,
                                                       topic=description)
            voice = await ctx.guild.create_voice_channel(name=name,
                                                         reason=GP,
                                                         category=category)

            db[sid] = {
                name: {
                    "info": {
                        "description": description,
                        "category": str(category.id),
                        "text_channel": str(text.id),
                        "voice_channel": str(voice.id),
                        "role": str(role.id)
                    }
                }
            }
            update_db(sql_db, db, "servers")

            await ctx.author.add_roles(role, reason="Group created.")

        except Exception as e:
            await ctx.send(f":anger: Something went wrong: `{e}`")
            return

        await ctx.send(":white_check_mark: Group created!")
        await text.send(
            f"Welcome to your group {ctx.author.mention}! Try the `group invite` command!"
        )
Example #15
0
    async def mute(self, ctx: Context, target: Member, length: int, span: str,
                   *, reason: str):
        """Set a member to the mute role.
        For timing, plural and non-plural spans are accepted (Day, days, minutes, etc).
        Use "max" as the span for psuedo-permanence (10 years).
        Level 4 required
        """
        sid = str(ctx.guild.id)
        uid = str(target.id)
        mute_role = None

        # Try to get the mute role from the server
        try:
            mute_role = ctx.guild.get_role(int(db[sid]["mute_role"]))
        except KeyError:
            await ctx.send(":anger: Server has no mute role set.")
            return

        # Initialize the server in the mute database if required
        if sid not in mute_db:
            mute_db[sid] = {}

        # Get the current UTC time, a future time from time_parser, and the difference
        now = datetime.now(tz=timezone.utc)
        future = await time_parser(span, length, now)
        length = future - now
        time = pretty_timedelta(length)

        embed = await embed_builder("Muted", target, reason, length)

        await target.send(embed=embed)
        await ctx.send(
            f":white_check_mark: {target.name} muted for {reason}, expires in {time}"
        )

        # Set the user to the muted role
        await target.add_roles(mute_role)

        # Add the mute to the database
        mute = {
            "issued_by": str(ctx.author.id),
            "reason": reason,
            "expires": str(future.timestamp())
        }

        mute_db[sid][uid] = mute

        update_db(sql_db, mute_db, "mutes")
        await self.log_to_channel(ctx, target, reason)
Example #16
0
    async def admin_role(self, ctx: Context, role: Role):
        """Set the mute role for the server.
        MUST HAVE SERVER ADMINISTRATOR PERMISSION
        """
        sid = str(ctx.guild.id)

        # Initialize the server in the database if required
        if sid not in db:
            db[sid] = {}

        # Set the mute role
        db[sid]["mute_role"] = str(role.id)

        update_db(sql_db, db, "admin")

        await ctx.send(f":white_check_mark: Mute role set to: {role.name}.")
Example #17
0
async def clear_channels(bot, location = None):
    for chan in groups["channels"][:]:
        channel = bot.get_channel(chan)
        if len(channel.voice_members) == 0:
            try:
                await bot.delete_channel(channel)
                await asyncio.sleep(0.25)
            except:
                if location is None:
                    continue
                await bot.send_message(location,
                    f"\U00002757 Unable to delete channel {channel.name}")
            finally:
                groups["channels"].remove(chan)
    if location is None:
        return
    update_db(groups, "groups")
Example #18
0
    async def warn(self, ctx: Context, target: Member, length: int, span: str,
                   *, reason: str):
        """Warn a member.
        For timing, plural and non-plural spans are accepted (Day, days, minutes, etc).
        Use "max" as the span for psuedo-permanence (10 years).
        Level 4 required
        """
        sid = str(ctx.guild.id)
        uid = str(target.id)
        warn_count = 1

        # Initialize the server in the warn database if required
        if sid not in warn_db:
            warn_db[sid] = {}

        # Add 1 to the amount of warns the user may already have
        if uid in warn_db[sid]:
            for _ in warn_db[sid][uid]:
                warn_count += 1

        # Get the current UTC time, a future time from time_parser, and the difference
        now = datetime.now(tz=timezone.utc)
        future = await time_parser(span, length, now)
        length = future - now

        embed = await embed_builder("Warned", target, reason, length)

        await target.send(embed=embed)
        await target.send(f":warning: This is warning #{warn_count}.")
        await ctx.send(
            f":warning: Warning {warn_count} issued to {target.name} for {reason}"
        )

        # Add the warn to the database
        if uid not in warn_db[sid]:
            warn_db[sid][uid] = {}

        warning = {
            "issued_by": str(ctx.author.id),
            "reason": reason,
            "expires": str(future.timestamp())
        }
        warn_db[sid][uid][str(warn_count)] = warning

        update_db(sql_db, warn_db, "warns")
        await self.log_to_channel(ctx, target, reason)
Example #19
0
 async def group_create(self, ctx, *, name: str = None):
     """Create a group channel.
     
     If a name is passed as an argument the channel will be set to that name
     with the prefix and suffix added. Otherwise the user's discriminator will
     be used as the channel name.
     """
     if name is None:
         name = ctx.message.author.discriminator
     name = f"{self.prefix}{name}{self.suffix}"
     try:
         channel = await self.bot.create_channel(ctx.message.server, name,
             type=ChannelType.voice)
         await self.bot.say("\U00002705 Channel created.")
         groups["channels"].append(channel.id)
         update_db(groups, "groups")
     except:
         await self.bot.say("\U00002757")
Example #20
0
async def clear_channels(bot, location=None):
    for chan in groups["channels"][:]:
        channel = bot.get_channel(chan)
        if len(channel.voice_members) == 0:
            try:
                await bot.delete_channel(channel)
                await asyncio.sleep(0.25)
            except:
                if location is None:
                    continue
                await bot.send_message(
                    location,
                    f"\U00002757 Unable to delete channel {channel.name}")
            finally:
                groups["channels"].remove(chan)
    if location is None:
        return
    update_db(groups, "groups")
Example #21
0
 async def group_create(self, ctx, *, name: str = None):
     """Create a group channel.
     
     If a name is passed as an argument the channel will be set to that name
     with the prefix and suffix added. Otherwise the user's discriminator will
     be used as the channel name.
     """
     if name is None:
         name = ctx.message.author.discriminator
     name = f"{self.prefix}{name}{self.suffix}"
     try:
         channel = await self.bot.create_channel(ctx.message.server,
                                                 name,
                                                 type=ChannelType.voice)
         await self.bot.say("\U00002705 Channel created.")
         groups["channels"].append(channel.id)
         update_db(groups, "groups")
     except:
         await self.bot.say("\U00002757")
Example #22
0
async def warn_check(bot: commands.Bot):
    ts = datetime.now(tz=timezone.utc).timestamp()

    # No servers registered
    if len(warn_db) <= 0:
        return

    for sid in warn_db:
        # No warns in the server
        if len(warn_db[sid]) <= 0:
            continue

        guild = bot.get_guild(int(sid))

        # Each warn in the server
        for uid in warn_db[sid]:
            for i, w in warn_db[sid][uid].items():
                if ts >= float(w["expires"]):
                    del warn_db[sid][uid][i]
                    update_db(sql_db, warn_db, "warns")
                    print(f"[ADMIN][WARN][REMOVE] {uid}.{i} in <{guild.name}>")
Example #23
0
    async def role_remove(self, ctx: Context, *, role_get: Role):
        """Remove a role from the assignable roles list.
        Level 10 required
        """
        sid = str(ctx.guild.id)

        if sid not in db:
            await ctx.send(":anger: There are no assignable roles on this server.")
            return

        if role_get.name not in db[sid]:
            await ctx.send(":anger: That is not an assignable role on this server.")
        else:
            try:
                del db[sid][role_get.name]

                await ctx.send(
                    f":white_check_mark: Removed {role_get.name} from assignable roles."
                )
                update_db(sql_db, db, "servers")
            except Exception as e:
                await ctx.send(f":anger: Error removing role: {e}")
Example #24
0
    async def role_add(self, ctx: Context, role_get: Role, *,
                       description: str):
        """Add/update a role on the assignable roles list.
        Level 10 required
        """
        sid = str(ctx.guild.id)
        rid = str(role_get.id)
        name = role_get.name

        if sid not in db:
            db[sid] = {}

        try:
            role_info = {"id": rid, "description": description}

            db[sid][name] = role_info

            await ctx.send(
                f":white_check_mark: Added {name} to assignable roles.")
            update_db(sql_db, db, "servers")
        except Exception as e:
            await ctx.send(f":anger: Error adding role: {e}")
Example #25
0
async def mute_check(bot: commands.Bot):
    ts = datetime.now(tz=timezone.utc).timestamp()

    # No servers registered
    if len(mute_db) <= 0:
        return

    for sid in mute_db:
        # No mutes in this server
        if len(mute_db[sid]) <= 0:
            continue

    # Each mute in the server
    for uid, info in mute_db[sid].items():
        if ts >= float(info["expires"]):
            guild = bot.get_guild(int(sid))

            # Get the mute role
            try:
                role = guild.get_role(int(db[sid]["mute_role"]))
            # Delete the mute from the database if we're unable to get the mute role
            except KeyError:
                del mute_db[sid][uid]
                break

            # Else get the member and remove the mute role
            target = guild.get_member(int(uid))

            if role in target.roles:
                await target.remove_roles(role, reason="Auto mute remove.")
                await target.send(
                    f":speaking_head: Your mute in {guild.name} has expired.")
            else:
                del mute_db[sid][uid]
                break

            del mute_db[sid][uid]
            update_db(sql_db, mute_db, "mutes")
            print(f"[ADMIN][MUTE][REMOVE] {target.id} in <{guild.name}>")
Example #26
0
    async def tempban(self,
                      ctx: Context,
                      target: Member,
                      length: int,
                      span: str,
                      *,
                      reason: str = None):
        """Temporarily ban a member from the server.
        For timing, plural and non-plural spans are accepted (Day, days, minutes, etc).
        Use "max" as the span for psuedo-permanence (10 years).
        Level 8 required
        """
        sid = str(ctx.guild.id)

        # Initialize the server in the tempban database if required
        if sid not in tempban_db:
            tempban_db[sid] = {}

        # Get the current UTC time, a future time from time_parser, and the difference
        now = datetime.now(tz=timezone.utc)
        future = await time_parser(span, length, now)
        length = future - now

        embed = await embed_builder("Temporarily Banned", target, reason,
                                    length)

        await target.send(embed=embed)

        await target.ban(reason=reason, delete_message_days=0)

        # Add the tempban to the database
        tempban_db[sid][target.id] = {
            "issued_by": str(ctx.author.id),
            "reason": reason,
            "expires": str(future.timestamp())
        }

        update_db(sql_db, tempban_db, "temp_bans")
        await self.log_to_channel(ctx, target, reason)
Example #27
0
async def tempban_check(bot: commands.Bot):
    ts = datetime.now(tz=timezone.utc).timestamp()

    # No servers registered
    if len(tempban_db) <= 0:
        return

    for sid in tempban_db:
        # No tempbans in this server
        if len(tempban_db[sid]) <= 0:
            continue

        # Each tempban in the server
        for uid in tempban_db[sid]:
            info = tempban_db[sid][uid]

            if ts >= float(info["expires"]):
                guild = bot.get_guild(int(sid))
                await guild.unban(bot.get_user(uid))

                del tempban_db[sid][uid]
                update_db(sql_db, tempban_db, "temp_bans")
                print(
                    f"[ADMIN][TEMPBAN][REMOVE] {target.id} in <{guild.name}>")