Пример #1
0
class Approval(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.modlog = Logger(__name__, bot.modlogs_channel)

    @commands.has_permissions(manage_roles=True)
    @commands.command()
    async def approve(self, ctx, member: Member):
        """Approve members"""

        if self.bot.approved_role in member.roles:
            await ctx.send("Member already approved")
            return

        try:
            await member.add_roles(self.bot.approved_role)
            dm_msg = "You have been approved. Welcome to {}!".format(
                ctx.guild.name)
            try:
                await member.send(dm_msg)
            except Forbidden:
                if not member.bot:
                    await ctx.send("User had DMs disabled")
            await ctx.send(":thumbsup: {} has been approved".format(member))
            self.modlog.approval(
                f"{ctx.message.author.name} approved {member.mention} [{member.name}]"
            )
        except errors.Forbidden:
            await ctx.send("💢 I dont have permission to do this.")

    @commands.has_permissions(manage_roles=True)
    @commands.command()
    async def unapprove(self, ctx, member: Member):
        """Unapprove members"""

        if not self.bot.approved_role in member.roles:
            await ctx.send("Member not approved")
            return

        try:
            await member.remove_roles(self.bot.approved_role)
            await ctx.send(":thumbsdown: {} has been unapproved".format(member)
                           )
            self.modlog.approval(
                f"{ctx.message.author.name} unapproved {member.mention} [{member.name}]"
            )
        except errors.Forbidden:
            await ctx.send("💢 I dont have permission to do this.")
Пример #2
0
async def on_ready():

    for guild in bot.guilds:
        bot.guild = guild

    # Roles

    bot.owner_role = discord.utils.get(guild.roles, name=botcfg.OwnerRole)
    bot.admin_role = discord.utils.get(guild.roles, name=botcfg.AdminRole)
    bot.mod_role = discord.utils.get(guild.roles, name=botcfg.ModRole)

    if botcfg.approvalSystemEnabled:
        bot.approved_role = discord.utils.get(guild.roles,
                                              name=botcfg.approvedRole)

    bot.messagelogs_channel = discord.utils.get(
        guild.channels, name=botcfg.messagelogs_channel)
    bot.memberlogs_channel = discord.utils.get(guild.channels,
                                               name=botcfg.memberlogs_channel)
    bot.modlogs_channel = discord.utils.get(guild.channels,
                                            name=botcfg.modlogs_channel)

    logger = Logger(__name__, bot.modlogs_channel)

    # Notify user if an addon fails to load.
    for addon in botcfg.addons:
        try:
            bot.load_extension("addons." + addon)
        except Exception as e:
            logger.warn("Failed to load {}:\n{}".format(
                addon, "".join(format_exception(type(e), e, e.__traceback__))))

    # Notify user if a spacecog fails to load.
    for addon in botcfg.cogs:
        try:
            bot.load_extension("cogs." + addon)
        except Exception as e:
            logger.warn("Failed to load {}:\n{}".format(
                addon, "".join(format_exception(type(e), e, e.__traceback__))))

    print(
        f"Client logged in as {bot.user.name}, in the following guild : {guild.name}"
    )
Пример #3
0
class Moderation(commands.Cog):
    """
    Moderation commands
    """
    def __init__(self, bot):
        self.bot = bot
        self.modlog = Logger(__name__, bot.modlogs_channel)

    @commands.has_permissions(kick_members=True)
    @commands.command()
    async def kick(self, ctx, member: Member, *, reason: str = None):
        """Kick a member. (Staff Only)"""
        if member == ctx.message.author:
            await ctx.send("You cannot kick yourself")
            self.modlog.info(
                f"{ctx.message.author.name} tried kicking themselfs")
            return

        elif member == ctx.me:
            await ctx.send("Unable to kick myself")
            self.modlog.info(
                f"{ctx.message.author.name} tried kicking {member.name} (Bot)")
            return

        elif self.bot.owner_role in member.roles:
            await ctx.send("Unable to kick Owner")
            self.modlog.info(
                f"{ctx.message.author.name} tried kicking {member.name} (Missing Permissions)"
            )
            return

        elif self.bot.admin_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send("Unable to kick Admin")
            self.modlog.info(
                f"{ctx.message.author.name} tried kicking {member.name} (Missing Permissions)"
            )
            return

        msg = f"You have been kicked from {ctx.guild.name}"
        if reason:
            msg += f" for the following reason:\n{reason}"

        try:
            await member.send(msg)
        except Forbidden:
            if not member.bot:
                await ctx.send("User had DMs disabled")

        try:
            await member.kick()
        except Forbidden:
            await ctx.send("Unable to kick Member")
            return

        await ctx.send(f"{member.name} has been kicked")
        self.modlog.info(f"{ctx.message.author.name} kicked {member.name}")

    @commands.has_permissions(ban_members=True)
    @commands.command()
    async def ban(self, ctx, member: Member, *, reason: str = None):
        """Ban a member. (Staff Only)"""
        if member == ctx.message.author:
            await ctx.send("You cannot ban yourself")
            self.modlog.info(
                f"{ctx.message.author.name} tried banning themselfs")
            return

        elif member == ctx.me:
            await ctx.send("Unable to ban myself")
            self.modlog.info(
                f"{ctx.message.author.name} tried banning {member.name} (Bot)")
            return

        elif self.bot.owner_role in member.roles:
            await ctx.send("Unable to ban Owner")
            self.modlog.info(
                f"{ctx.message.author.name} tried banning {member.name} (Missing Permissions)"
            )
            return

        elif self.bot.admin_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send("Unable to ban Admin")
            self.modlog.info(
                f"{ctx.message.author.name} tried banning {member.name} (Missing Permissions)"
            )
            return

        msg = f"You have been banned from {ctx.guild.name}"
        if reason:
            msg += f" for the following reason:\n{reason}"

        try:
            await member.send(msg)
        except Forbidden:
            if not member.bot:
                await ctx.send("User had DMs disabled")

        try:
            await member.ban(delete_message_days=0)
        except Forbidden:
            await ctx.send("Unable to ban Member")
            return

        await ctx.send(f"{member.name} has been banned")
        self.modlog.info(f"{ctx.message.author.name} banned {member.name}")
Пример #4
0
 def __init__(self, bot):
     self.bot = bot
     self.modlog = Logger(__name__, bot.modlogs_channel)
Пример #5
0
class Memberlogs(commands.Cog):
    """
    Logs member-related stuff
    """
    def __init__(self, bot):
        self.bot = bot
        self.memberlog = Logger(__name__, bot.memberlogs_channel)

    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        if before.nick != after.nick:
            self.memberlog.info(
                f"Nickname Changed: {before.nick} --> {after.nick} ({after.mention})"
            )

        if before.name != after.name:
            self.memberlog.info(
                f"Username change: {before.name}#{before.discriminator} --> {after.name}#{after.discriminator} ({after.mention})"
            )

        if before.roles != after.roles:
            before_roles = []
            after_roles = []

            for role in before.roles:
                before_roles.append(role.name)

            for role in after.roles:
                after_roles.append(role.name)

            if before.roles > after.roles:
                set_difference = set(after_roles) - set(before_roles)
                x = set_difference.pop()
                role_string = "+ " + x
                self.memberlog.info(
                    f"Change in roles for {after.name}:\n {role_string}")
            else:
                set_difference = set(before_roles) - set(after_roles)
                x = set_difference.pop()
                role_string = "- " + x
                self.memberlog.info(
                    f"Change in roles for {after.name}:\n {role_string}")

        else:
            pass

    if enableJoinLogs == True:

        @commands.Cog.listener()
        async def on_member_join(self, member):
            emb = Embed(title="Member Joined", colour=Colour.green())
            emb.add_field(name="Member:", value=member.name, inline=True)
            emb.set_thumbnail(url=member.avatar_url)

            await self.bot.memberlogs_channel.send("", embed=emb)

    if enableLeaveLogs == True:

        @commands.Cog.listener()
        async def on_member_remove(self, member):
            emb = Embed(title="Member Left", colour=Colour.green())
            emb.add_field(name="Member:", value=member.name, inline=True)
            emb.set_thumbnail(url=member.avatar_url)

            await self.bot.memberlogs_channel.send("", embed=emb)
Пример #6
0
 def __init__(self, bot):
     self.bot = bot
     self.logger = Logger(__name__, bot.memberlogs_channel)
Пример #7
0
class Warn(commands.Cog):
    """
    Warning system
    """
    def __init__(self, bot):
        self.bot = bot
        self.logger = Logger(__name__, bot.memberlogs_channel)

    async def dm(self, member: Member, message: str):
        """DM the user and catch an eventual exception."""
        try:
            await member.send(message)
        except:
            pass

    @commands.has_permissions(manage_roles=True)
    @commands.command()
    async def warn(self, ctx, member: Member, *, reason: str = ""):
        if member == ctx.message.author:
            await ctx.send("You cannot warn yourself!")
            return

        elif member == ctx.me:
            await ctx.send("I can't warn myself!")
            return

        elif self.bot.owner_role in member.roles:
            await ctx.send("I can't warn an owner!")
            return

        elif self.bot.admin_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send("You can't warn an admin unless you are an owner!")
            return

        try:
            with open("data/warns.json", "r") as config:
                js = load(config)
        except FileNotFoundError:
            with open("data/warns.json", "w") as config:
                config.write('{}')
                js = {}

        userid = str(member.id)
        if userid not in js:
            amount_of_warns = 1
            js[userid] = {"warns": []}
        else:
            amount_of_warns = len(js[userid]["warns"]) + 1

        member_name = "{}#{}".format(member.name, member.discriminator)
        timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime())
        author_name = "{}#{}".format(ctx.message.author.name,
                                     ctx.message.author.discriminator)

        js[userid]["amount"] = amount_of_warns
        js[userid]["warns"].append({
            "name": member_name,
            "timestamp": timestamp,
            "reason": reason,
            "author": author_name,
            "author_id": ctx.message.author.id,
        })

        try:
            await member.send(
                f"You have been warned in {ctx.guild.name} for the following reason: {reason}. This is warning #{amount_of_warns}."
            )
        except Forbidden:
            if not member.bot:
                await ctx.send("User had DMs disabled")
        await ctx.send(
            f"🚩 {member} has been warned. This is warning #{amount_of_warns}."
        )

        self.logger.info(
            f"{ctx.message.author.name} warned {member.name} for {reason}. (#{amount_of_warns})."
        )

        if amount_of_warns == 1:
            try:
                await member.send("This is your first warning.")
            except Forbidden:
                pass

        elif amount_of_warns == 2:
            try:
                await member.send(
                    "This is your second warning.\nYour next warn will result in being kicked from the server."
                )
            except Forbidden:
                pass
        elif amount_of_warns == 3:
            try:
                await member.send(
                    "This is your third warning, so you have been kicked. Please "
                    "note that **the next warn will result in another kick!**")
            except Forbidden:
                pass
            await member.kick(reason="Third warn, {}".format(reason))

        elif amount_of_warns == 4:
            try:
                await member.send(
                    "You have been kicked from the server. This is your fourth and "
                    "final warning. **__The next warning will result in an automatic"
                    " ban.__**")
            except Forbidden:
                pass
            await member.kick(reason="Fourth warn: {}".format(reason))

        elif amount_of_warns >= 5:
            try:
                await self.dm(
                    member, "You have reached your fifth warning. You are now "
                    "banned from this server.")
            except Forbidden:
                pass
            await member.ban(delete_message_days=0,
                             reason="Fifth warn: {}".format(reason))

        with open("data/warns.json", "w") as f:
            dump(js, f, sort_keys=True, indent=4, separators=(',', ': '))

    @commands.has_permissions(manage_roles=True)
    @commands.command(aliases=["delwarn"])
    async def deletewarn(self, ctx, member: Member, number: int):
        author = ctx.message.author
        if member == author:
            await ctx.send("You cannot delete your own warns")
            return

        elif self.bot.owner_role in member.roles:
            await ctx.send("Can't remove warns from an owner!")
            return

        elif self.bot.admin_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send(
                "You cannot remove warns from an admin unless you are an owner!"
            )
            return
        elif number <= 0:
            await ctx.send("Warn number must be a positive number!")
            return

        with open("data/warns.json", "r") as f:
            js = load(f)  # https://hastebin.com/ejizaxasav.scala

        userid = str(member.id)
        if userid not in js:
            js[userid] = {"warns": []}
            await ctx.send("{} doesn't have any warns.".format(member.name))
            return
        else:
            amount_of_warns = len(js[userid]["warns"]) - 1

        js[userid]["amount"] = amount_of_warns
        js[userid]["warns"].pop(number - 1)
        await ctx.send(
            "🚩 I've deleted the {} warn of {}. The user now has {} warns."
            "".format(number, member, amount_of_warns))
        try:
            await member.send(
                "One of your warns in {} has been removed.".format(
                    ctx.guild.name))
        except Forbidden:
            pass

        self.logger.info(
            f"{ctx.message.author.name} removed warn #{number} from {member.name}"
        )

        with open("data/warns.json", "w") as f:
            dump(js, f, sort_keys=True, indent=4, separators=(',', ': '))

    @commands.command()
    async def listwarns(self, ctx, member: Member = None):
        """
        List your own warns or someone else's warns.
        Only the staff can view someone else's warns
        """
        if not member:
            member = ctx.message.author

        has_perms = self.bot.owner_role or self.bot.admin_role or self.bot.mod_role in ctx.message.author.roles

        if not has_perms and member != ctx.message.author:
            return await ctx.send(
                "{} You don't have permission to list other member's warns!"
                "".format(ctx.message.author.mention))

        with open("data/warns.json", "r") as f:
            js = load(f)

        userid = str(member.id)
        if userid not in js:
            return await ctx.send("No warns found!")
        embed = Embed(color=member.colour)
        embed.set_author(name="List of warns for {} :".format(member),
                         icon_url=member.avatar_url)

        for nbr, warn in enumerate(js[userid]["warns"]):
            content = "{}".format(warn["reason"])
            author = await self.bot.fetch_user(warn["author_id"])
            content += "\n*Warn author : {} ({})*".format(
                warn["author"], author.mention)
            embed.add_field(name="\n\n#{}: {}".format(nbr + 1,
                                                      warn["timestamp"]),
                            value=content,
                            inline=False)

        await ctx.send("", embed=embed)
Пример #8
0
class Lockdown(commands.Cog):
    """
    Lockdown System
    """
    def __init__(self, bot):
        self.bot = bot
        self.lockmsg = ":lock: Channel locked."
        self.unlockmsg = ":unlock: Channel Unlocked"
        self.modlog = Logger(__name__, bot.modlogs_channel)

    @commands.has_permissions(manage_messages=True)
    @commands.command(aliases=["lock"])
    async def lockdown(self, ctx, *, reason=""):
        """
        Lock down a channel
        """
        await ctx.channel.set_permissions(ctx.guild.default_role,
                                          send_messages=False)
        if reason:
            await ctx.send(self.lockmsg + f" The given reason is: {reason}")
        else:
            await ctx.send(self.lockmsg)
        self.modlog.info(
            f"{ctx.message.author.name} locked {ctx.message.channel.name}")

    @commands.has_permissions(manage_messages=True)
    @commands.command(aliases=["rlock"])
    async def remotelockdown(self, ctx, channel: TextChannel, *, reason=""):
        """
        Lock down a channel
        """
        await channel.set_permissions(ctx.guild.default_role,
                                      send_messages=False)
        await ctx.send(self.lockmsg)
        if reason:
            await channel.send(self.lockmsg +
                               f" The given reason is: {reason}")
        else:
            await channel.send(self.lockmsg)
        self.modlog.info(
            f"{ctx.message.author.name} locked {ctx.message.channel.name}")

    @commands.has_permissions(manage_messages=True)
    @commands.command()
    async def unlock(self, ctx):
        """
        Unlock a channel
        """
        await ctx.channel.set_permissions(ctx.guild.default_role,
                                          send_messages=True)
        await ctx.send(":unlock: Channel Unlocked")
        self.modlog.info(
            f"{ctx.message.author.name} locked {ctx.message.channel.name}")

    @commands.has_permissions(manage_messages=True)
    @commands.command(aliases=["runlock"])
    async def remoteunlock(self, ctx, channel: TextChannel):
        """
        Unlock a channel
        """
        await channel.set_permissions(ctx.guild.default_role,
                                      send_messages=True)
        await channel.send(self.unlockmsg)
        await ctx.send(self.unlockmsg)
        self.modlog.info(
            f"{ctx.message.author.name} locked {ctx.message.channel.name}")
Пример #9
0
 def __init__(self, bot):
     self.bot = bot
     self.lockmsg = ":lock: Channel locked."
     self.unlockmsg = ":unlock: Channel Unlocked"
     self.modlog = Logger(__name__, bot.modlogs_channel)
Пример #10
0
class Mute(commands.Cog):
    """
    Mute System
    """
    def __init__(self, bot):
        self.bot = bot
        self.role = get(bot.guild.roles, name=MuteRole)
        self.modlog = Logger(__name__, bot.modlogs_channel)

    @commands.has_permissions(manage_roles=True)
    @commands.command()
    async def mute(self, ctx, member: Member, *, reason: str = None):
        if member == ctx.message.author:
            self.modlog.info(
                f"{ctx.message.author.name} tried muting themselfs")
            await ctx.send("You cannot mute yourself")
            return

        elif member == ctx.me:
            await ctx.send("Unable to mute myself")
            self.modlog.info(
                f"{ctx.message.author.name} tried muting {member.name} (Bot)")
            return

        elif self.bot.owner_role in member.roles:
            await ctx.send("Unable to mute Owner")
            self.modlog.info(
                f"{ctx.message.author.name} tried muting {member.name} (Missing Permissions)"
            )
            return

        elif self.bot.admin_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send("Unable to mute Admin")
            self.modlog.info(
                f"{ctx.message.author.name} tried muting {member.name} (Missing Permissions)"
            )
            return

        elif self.role in member.roles:
            await ctx.send("User is already muted")
            self.modlog.info(
                f"{ctx.message.author.name} tried muting {member.name} (Already Muted)"
            )
            return

        await member.add_roles(self.role)

        msg = f"You have been muted in {ctx.guild.name}"
        if reason:
            msg += f" for the following reason: {reason}"

        try:
            await member.send(msg)
        except Forbidden:
            if not member.bot:
                await ctx.send("User had DMs disabled")
        if reason:
            self.modlog.info(
                f"{ctx.message.author.name} muted {member.name} for reason: {reason}"
            )
        else:
            self.modlog.info(f"{ctx.message.author.name} muted {member.name}")
        await ctx.send(f"{member} has been muted.")

    @commands.has_permissions(manage_roles=True)
    @commands.command()
    async def unmute(self, ctx, member: Member):
        if member == ctx.message.author:
            await ctx.send("You cannot unmute yourself")
            self.modlog.info(
                f"{ctx.message.author.name} tried unmuting themselfs")
            return

        elif self.bot.owner_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send("Unable to unmute Owner")
            self.modlog.info(
                f"{ctx.message.author.name} tried unmuting {member.name} (Missing Permissions)"
            )
            return

        elif self.bot.admin_role in member.roles and not self.bot.owner_role in ctx.message.author.roles:
            await ctx.send("Unable to unmute Admin")
            self.modlog.info(
                f"{ctx.message.author.name} tried unmuting {member.name} (Missing Permissions)"
            )
            return

        elif not self.role in member.roles:
            self.modlog.info(
                f"{ctx.message.author.name} tried unmuting {member.name} (Not Muted)"
            )
            await ctx.send("User is not muted")
            return

        await member.remove_roles(self.role)
        try:
            await member.send(f"You have been unmuted in {ctx.guild.name}")
        except Forbidden:
            if not member.bot:
                await ctx.send("User had DMs disabled")
        self.modlog.info(f"{ctx.message.author.name} unmuted {member.name}")
        await ctx.send(f"{member} has been unmuted.")
Пример #11
0
 def __init__(self, bot):
     self.bot = bot
     self.role = get(bot.guild.roles, name=MuteRole)
     self.modlog = Logger(__name__, bot.modlogs_channel)