Example #1
0
 def predicate(ctx):
     if ctx.message.author.id == load_config.owner:
         return True
     else:
         admin_roles = gs.get(ctx.guild).perm_roles["admin"]
         mod_roles = gs.get(ctx.guild).perm_roles["mod"]
         for role in ctx.author.roles:
             if role.id in mod_roles or role.id in admin_roles:
                 return True
     return False
Example #2
0
File: gss.py Project: PaPiix/roxbot
	async def perms(self, ctx, role):
		"""Shell command to do the perm assigning. Only should be invoked by another command."""
		# Just in case some c**t looks at the source code and thinks they can give themselves Admin.
		if role.id not in self.acceptable_roles:
			print("lol no")
			return False
		settings = guild_settings.get(ctx.guild)
		member = ctx.author
		required_score = settings.gss["required_score"]
		days = int(settings.gss["required_days"])
		data = self.tatsumaki_api_call(member, ctx.guild)
		if not data:
			return await ctx.send("Tatsumaki API call returned nothing. Maybe the API is down?")

		if role in member.roles:
			await member.remove_roles(role, reason="Requested removal of {0.name}".format(role))
			return await ctx.send("You already had {0.name}. It has now been removed.".format(role))

		time = datetime.datetime.now() - ctx.author.joined_at

		if time > datetime.timedelta(days=days) and int(data["score"]) >= required_score:
			await member.add_roles(role, reason="Requested {0.name}".format(role))
			await ctx.send("You have now have the {0.name} role".format(role))
		else:
			return await ctx.send(
				"You do not meet the requirements for this role. You need at least {} score with <@!172002275412279296> and to have been in the server for {} days.".format(required_score, days)
			)
Example #3
0
    async def add(self, ctx, command, output, prefix_required="0"):
        "Adds a custom command to the list of custom commands."
        settings = guild_settings.get(ctx.guild)
        command = command.lower()
        output = output
        zero = settings.custom_commands["0"]
        one = settings.custom_commands["1"]

        if ctx.message.mentions or ctx.message.mention_everyone or ctx.message.role_mentions:
            return await ctx.send(
                "Custom Commands cannot mention people/roles/everyone.")
        elif len(output) > 1800:
            return await ctx.send("The output is too long")
        elif command in self.bot.commands and prefix_required == "1":
            return await ctx.send(
                "This is already the name of a built in command.")
        elif command in zero or command in one:
            return await ctx.send("Custom Command already exists.")
        elif prefix_required != "1" and prefix_required != "0":
            return await ctx.send("No prefix setting set.")
        elif len(command.split(" ")) > 1 and prefix_required == "1":
            return await ctx.send(
                "Custom commands with a prefix can only be one word with no spaces."
            )

        settings.custom_commands[prefix_required][command] = output
        settings.update(settings.custom_commands, "custom_commands")
        return await ctx.send("{} has been added with the output: '{}'".format(
            command, output))
Example #4
0
 async def printsettings(self, ctx, option=None):
     "OWNER OR ADMIN ONLY: Prints the servers settings file."
     config = guild_settings.get(ctx.guild)
     em = discord.Embed(colour=0xDEADBF)
     em.set_author(name="{} settings for {}.".format(
         self.bot.user.name, ctx.message.guild.name),
                   icon_url=self.bot.user.avatar_url)
     if option in config.settings:
         settingcontent = ""
         for x in config.settings[option].items():
             settingcontent += str(x).strip("()") + "\n"
         em.add_field(name=option, value=settingcontent, inline=False)
         return await ctx.send(embed=em)
     else:
         for settings in config.settings:
             if settings != "custom_commands" and settings != "warnings":
                 settingcontent = ""
                 for x in config.settings[settings].items():
                     settingcontent += str(x).strip("()") + "\n"
                 em.add_field(name=settings,
                              value=settingcontent,
                              inline=False)
             elif settings == "custom_commands":
                 em.add_field(
                     name="custom_commands",
                     value=
                     "For Custom Commands, use the custom list command.",
                     inline=False)
         return await ctx.send(embed=em)
Example #5
0
    async def list(self, ctx, debug="0"):
        "Lists all custom commands for this server."
        if debug != "0" and debug != "1":
            debug = "0"
        settings = guild_settings.get(ctx.guild)
        l = settings.custom_commands
        listzero = ""
        listone = ""

        for command in l["0"]:
            if debug == "1":
                command += " - {}".format(l["0"][command])
            listzero = listzero + "- " + command + "\n"
        for command in l["1"]:
            if debug == "1":
                command += " - {}".format(l["1"][command])
            listone = listone + "- " + command + "\n"
        if not listone:
            listone = "There are no commands setup.\n"
        if not listzero:
            listzero = "There are no commands setup.\n"

        # TODO: Sort out a way to shorten this if it goes over 2000 characters.

        em = discord.Embed(title="Here is the list of Custom Commands",
                           color=load_config.embedcolour)
        em.add_field(name="Commands that require Prefix:",
                     value=listone,
                     inline=False)
        em.add_field(name="Commands that don't:", value=listzero, inline=False)
        return await ctx.send(embed=em)
Example #6
0
	async def on_member_remove(self, member):
		# TODO: Add some way of detecting whether a user left/was kicked or was banned.
		logging = guild_settings.get(member.guild).logging
		if logging["enabled"]:
			channel = self.bot.get_channel(logging["channel"])
			embed = discord.Embed(description="{} left the server".format(member), colour=embedcolour)
			return await channel.send(embed=embed)
Example #7
0
    async def add(self, ctx, user: discord.User = None, *, warning=""):
        """Adds a warning to a user."""
        # Warning in the settings is a dictionary of user ids. The user ids are equal to a list of dictionaries.
        settings = gs.get(ctx.guild)
        warning_limit = 2
        warning_dict = {
            "warned-by": ctx.author.id,
            "date": time.time(),
            "warning": warning
        }
        user_id = str(user.id)

        if not user_id in settings.warnings:
            settings.warnings[user_id] = []

        settings.warnings[user_id].append(warning_dict)
        settings.update(settings.warnings, "warnings")

        amount_warnings = len(settings.warnings[user_id])
        if amount_warnings > warning_limit:
            await ctx.author.send(
                "{} has been reported {} time(s). This is a reminder that this is over the set limit of {}."
                .format(str(user), amount_warnings, warning_limit))

        return await ctx.send("Reported {}.".format(str(user)))
Example #8
0
    async def remove(self, ctx, user: discord.User = None, index=None):
        """Removes one or all of the warnings for a user."""
        user_id = str(user.id)
        settings = gs.get(ctx.guild)

        if index:
            try:
                index = int(index)
                index -= 1
                settings.warnings[user_id].pop(index)
                if not settings.warnings[user_id]:
                    settings.warnings.pop(user_id)

                settings.update(settings.warnings, "warnings")
                return await ctx.send("Removed Warning {} from {}".format(
                    index + 1, str(user)))

            except Exception as e:
                if isinstance(e, IndexError):
                    return await ctx.send(":warning: Index Error.")
                elif isinstance(e, KeyError):
                    return await ctx.send(
                        "Could not find user in warning list.")
                elif isinstance(e, ValueError):
                    return await ctx.send("Please enter a valid index number.")
                else:
                    raise e
        else:
            try:
                settings.warnings.pop(user_id)
                settings.update(settings.warnings, "warnings")
                return await ctx.send("Removed all warnings for {}".format(
                    str(user)))
            except KeyError:
                return await ctx.send("Could not find user in warning list.")
Example #9
0
    async def edit(self, ctx, option, mentions=None):
        """Adds or removes users to the whitelist. Exactly the same as the blacklist command in usage."""
        whitelist_count = 0
        settings = guild_settings.get(ctx.guild)

        if not ctx.message.mentions and option != 'list':
            return await ctx.send("You haven't mentioned anyone to whitelist.")

        if option not in ['+', '-', 'add', 'remove', 'list']:
            return await ctx.send(
                'Invalid option "%s" specified, use +, -, add, or remove' %
                option,
                expire_in=20)

        if option in ['+', 'add']:
            for user in ctx.message.mentions:
                settings.twitch["whitelist"]["list"].append(user.id)
                whitelist_count += 1
            settings.update(settings.twitch, "twitch")
            return await ctx.send(
                '{} user(s) have been added to the whitelist'.format(
                    whitelist_count))

        elif option in ['-', 'remove']:
            for user in ctx.message.mentions:
                if user.id in settings.twitch["whitelist"]["list"]:
                    settings.twitch["whitelist"]["list"].remove(user.id)
                    whitelist_count += 1
            settings.update(settings.twitch, "twitch")
            return await ctx.send(
                '{} user(s) have been removed to the whitelist'.format(
                    whitelist_count))

        elif option == 'list':
            return await ctx.send(settings.twitch["whitelist"]["list"])
Example #10
0
	async def log(self, guild, command_name, **kwargs):
		logging = guild_settings.get(guild).logging
		if logging["enabled"]:
			channel = self.bot.get_channel(logging["channel"])
			embed=discord.Embed(title="{} command logging".format(command_name), colour=embedcolour)
			for key, value in kwargs.items():
				embed.add_field(name=key, value=value)
			return await channel.send(embed=embed)
Example #11
0
 def predicate(ctx):
     if ctx.author.id == load_config.owner:
         return True
     else:
         for role in ctx.author.roles:
             if role.id in gs.get(ctx.guild).perm_roles["admin"]:
                 return True
     return False
Example #12
0
def nsfw_predicate(ctx):
    nsfw = gs.get(ctx.guild).nsfw
    if not nsfw["channels"] and nsfw["enabled"]:
        return nsfw["enabled"] == 1
    elif nsfw["enabled"] and nsfw["channels"]:
        return ctx.channel.id in nsfw["channels"]
    else:
        return False
Example #13
0
	async def on_member_join(self, member):
		logging = guild_settings.get(member.guild).logging
		if logging["enabled"]:
			channel = self.bot.get_channel(logging["channel"])
			embed = discord.Embed(title="{} joined the server".format(member), colour=embedcolour)
			embed.add_field(name="ID", value=member.id)
			embed.add_field(name="Mention", value=member.mention)
			embed.add_field(name="Date Account Created", value="{:%a %Y/%m/%d %H:%M:%S} UTC".format(member.created_at))
			embed.add_field(name="Date Joined", value="{:%a %Y/%m/%d %H:%M:%S} UTC".format(member.joined_at))
			embed.set_thumbnail(url=member.avatar_url)
			return await channel.send(embed=embed)
Example #14
0
	async def on_member_remove(self, member):
		"""
		The same but the opposite
		"""
		settings = guild_settings.get(member.guild)
		channel = settings.goodbyes["goodbye-channel"]
		if not settings.goodbyes["enabled"]:
			return
		else:
			channel = self.bot.get_channel(channel)
			return await channel.send(embed=discord.Embed(
				description="{}#{} has left or been beaned.".format(member.name, member.discriminator), colour=0xDEADBF))
Example #15
0
    async def aesthetics(self, ctx, *, convert):
        """Converts text to be more  a e s t h e t i c s"""
        WIDE_MAP = dict((i, i + 0xFEE0) for i in range(0x21, 0x7F))
        WIDE_MAP[0x20] = 0x3000
        converted = str(convert).translate(WIDE_MAP)

        logging = guild_settings.get(ctx.guild).logging
        if logging["enabled"]:
            await Logging(self.bot).log(ctx.guild,
                                        "aesthetics",
                                        user=ctx.author,
                                        argument_given=convert)
        return await ctx.send(converted)
Example #16
0
 async def remove(self, ctx, command):
     "Removes a custom command."
     settings = guild_settings.get(ctx.guild)
     command = command.lower()
     if command in settings.custom_commands["1"]:
         settings.custom_commands["1"].pop(command)
         settings.update(settings.custom_commands, "custom_commands")
         return await ctx.send("Removed {} custom command".format(command))
     elif command in settings.custom_commands["0"]:
         settings.custom_commands["0"].pop(command)
         settings.update(settings.custom_commands, "custom_commands")
         return await ctx.send("Removed {} custom command".format(command))
     else:
         return await ctx.send("Custom Command doesn't exist.")
Example #17
0
    async def list(self, ctx, *, user: discord.User = None):
        """Lists all or just the warnings for one user."""
        settings = gs.get(ctx.guild)

        if user == None:
            output = ""
            for member in settings.warnings:
                # Remove users with no warning here instead of remove cause im lazy
                if not settings.warnings[member]:
                    settings.warnings.pop(member)
                else:
                    member_obj = discord.utils.get(ctx.guild.members,
                                                   id=int(member))
                    if member_obj:
                        output += "{}: {} Warning(s)\n".format(
                            str(member_obj), len(settings.warnings[member]))
                    else:
                        output += "{}: {} Warning(s)\n".format(
                            member, len(settings.warnings[member]))
            return await ctx.send(output)

        user_id = str(user.id)

        if not settings.warnings[user_id]:
            settings.warnings.pop(user_id)
            settings.update(settings.warnings, "warnings")
        if not user_id in settings.warnings:
            return await ctx.send(
                "This user doesn't have any warning on record.")

        em = discord.Embed(title="Warnings for {}".format(str(user)),
                           colour=0XDEADBF)
        em.set_thumbnail(url=user.avatar_url)
        x = 1
        userlist = settings.warnings[user_id]
        for warning in userlist:
            try:
                warned_by = str(await
                                self.bot.get_user_info(warning["warned-by"]))
            except discord.ext.commands.CommandInvokeError:
                warned_by = warning["warned-by"]
            date = datetime.datetime.fromtimestamp(
                warning["date"]).strftime('%c')
            warn_reason = warning["warning"]
            em.add_field(name="Warning %s" % x,
                         value="Warned by: {}\nTime: {}\nReason: {}".format(
                             warned_by, date, warn_reason))
            x += 1
        return await ctx.send(embed=em)
Example #18
0
    async def enable(self, ctx):
        """Enables the twitch shilling whitelist. Repeat the command to disable.
		Usage:
			;whitelist enable"""
        settings = guild_settings.get(ctx.guild)
        if not settings.twitch["whitelist"]["enabled"]:
            settings.twitch["whitelist"]["enabled"] = 1
            settings.update(settings.twitch, "twitch")
            return await ctx.send(
                "Whitelist for Twitch shilling has been enabled.")
        else:
            settings.twitch["whitelist"]["enabled"] = 0
            settings.update(settings.twitch, "twitch")
            return await ctx.send(
                "Whitelist for Twitch shilling has been disabled.")
Example #19
0
    async def on_member_update(self, member_b, member_a):
        """Twitch Shilling Part"""
        twitch = guild_settings.get(member_b.guild).twitch
        if blacklisted(member_b) or not twitch["enabled"]:
            return

        if member_a.activitiy:
            if member_a.activity.type == ActivityType.streaming and member_b.activity.type != ActivityType.streaming:
                if not twitch["whitelist"]["enabled"] or member_a.id in twitch[
                        "whitelist"]["list"]:
                    channel = self.bot.get_channel(twitch["channel"])
                    return await channel.send(
                        ":video_game:** {} is live!** :video_game:\n{}\n{}".
                        format(member_a.name, member_a.game.name,
                               member_a.game.url))
Example #20
0
	async def on_member_join(self, member):
		"""
		Greets users when they join a server.
		"""
		settings = guild_settings.get(member.guild)
		if not settings.greets["enabled"]:
			return

		if settings.greets["custom-message"]:
			message = settings.greets["custom-message"]
		else:
			message = settings.greets["default-message"]
		em = discord.Embed(
			title="Welcome to {}!".format(member.guild),
			description='Hey {}! Welcome to **{}**! {}'.format(member.mention, member.guild, message),
			colour=0xDEADBF)
		em.set_thumbnail(url=member.avatar_url)

		channel = self.bot.get_channel(settings.greets["welcome-channel"])
		return await channel.send(embed=em)
Example #21
0
    async def on_message(self, message):
        settings = guild_settings.get(message.guild)
        msg = message.content.lower()
        channel = message.channel

        if blacklisted(message.author) or type(
                message.channel) != discord.TextChannel:
            return
        if message.author == self.bot.user:
            return

        if msg.startswith(self.bot.command_prefix):
            if msg.split(self.bot.command_prefix
                         )[1] in settings.custom_commands["1"]:
                return await channel.send(
                    settings.custom_commands["1"][msg.split(
                        self.bot.command_prefix)[1]])
        else:
            for command in settings.custom_commands["0"]:
                if msg == command:
                    return await channel.send(
                        settings.custom_commands["0"][command])
Example #22
0
    async def edit(self, ctx, command, edit):
        "Edits an existing custom command."
        settings = guild_settings.get(ctx.guild)
        zero = settings.custom_commands["0"]
        one = settings.custom_commands["1"]

        if ctx.message.mentions or ctx.message.mention_everyone or ctx.message.role_mentions:
            return await ctx.send(
                "Custom Commands cannot mention people/roles/everyone.")

        if command in zero:
            settings.custom_commands["0"][command] = edit
            settings.update(settings.custom_commands, "custom_commands")
            return await ctx.send("Edit made. {} now outputs {}".format(
                command, edit))
        elif command in one:
            settings.custom_commands["1"][command] = edit
            settings.update(settings.custom_commands, "custom_commands")
            return await ctx.send("Edit made. {} now outputs {}".format(
                command, edit))
        else:
            return await ctx.send("That Custom Command doesn't exist.")
Example #23
0
    async def logging(self, ctx, selection, *, changes=None):
        """Edits the logging settings.

		Options:
			enable/disable: Enable/disables logging.
			channel: sets the channel.
		"""
        selection = selection.lower()
        settings = guild_settings.get(ctx.guild)

        if selection == "enable":
            settings.logging["enabled"] = 1
            await ctx.send("'logging' was enabled!")
        elif selection == "disable":
            settings.logging["enabled"] = 0
            await ctx.send("'logging' was disabled :cry:")
        elif selection == "channel":
            channel = self.get_channel(ctx, changes)
            settings.logging["channel"] = channel.id
            await ctx.send("{} has been set as the logging channel!".format(
                channel.mention))
        else:
            return await ctx.send("No valid option given.")
        return self.guild_settings.update(settings.logging, "logging")
Example #24
0
 def tag_blacklist(self, ctx):
     blacklist = ""
     for tag in gs.get(ctx.guild).nsfw["blacklist"]:
         blacklist += "-{} ".format(tag)
     return blacklist
Example #25
0
def isnt_anal():
    return commands.check(lambda ctx: gs.get(ctx.guild).is_anal[
        "y/n"] and nsfw_predicate(ctx) or not gs.get(ctx.guild).is_anal["y/n"])
Example #26
0
 async def settings(self, ctx):
     if ctx.invoked_subcommand is None:
         return await ctx.send('Missing Argument')
     self.guild_settings = guild_settings.get(ctx.guild)
Example #27
0
 async def on_command_error(self, ctx, error):
     self.owner = self.bot.get_user(self.bot.owner_id)
     err_colour = 0x992d22
     if self.dev:
         raise error
     elif isinstance(error, commands.CommandInvokeError):
         embed = discord.Embed(title='Command Error', colour=err_colour)
         embed.description = str(error)
         embed.add_field(name='Server', value=ctx.guild)
         embed.add_field(name='Channel', value=ctx.channel.mention)
         embed.add_field(name='User', value=ctx.author)
         embed.add_field(name='Message', value=ctx.message.content)
         embed.timestamp = datetime.datetime.utcnow()
         await ctx.send(embed=embed)
     else:
         if isinstance(error, commands.NoPrivateMessage):
             embed = discord.Embed(
                 description=
                 "This command cannot be used in private messages.")
         elif isinstance(error, commands.DisabledCommand):
             embed = discord.Embed(description="This command is disabled.")
         elif isinstance(error, commands.MissingRequiredArgument):
             embed = discord.Embed(description="Argument missing.")
         elif isinstance(error, commands.BadArgument):
             embed = discord.Embed(
                 description=
                 "Invalid Argument given. Please check arguments given.")
         elif isinstance(error, commands.TooManyArguments):
             embed = discord.Embed(description="Too many arguments given.")
         elif isinstance(error, commands.CommandNotFound):
             cc = guild_settings.get(
                 ctx.guild
             ).custom_commands  # Delete this when we update this system.
             if ctx.invoked_with in cc["1"]:
                 embed = None
             elif len(
                     ctx.message.content
             ) < 6:  # Should avoid puncutation emoticons while also not being big enough to trigger for mispelt commands,
                 embed = None
             else:
                 embed = discord.Embed(
                     description="That Command doesn't exist.")
         elif isinstance(error, commands.BotMissingPermissions):
             embed = discord.Embed(
                 description="I am missing the following permissions: {}".
                 format(str(error.missing_perms).strip("[]")))
         elif isinstance(error, commands.MissingPermissions):
             embed = discord.Embed(
                 description="You are missing the following permissions: {}"
                 .format(str(error.missing_perms).strip("[]")))
         elif isinstance(error, commands.NotOwner):
             embed = discord.Embed(
                 description=
                 "You do not have permission to do this. You are not Roxie!"
             )
         elif isinstance(error, commands.CommandOnCooldown):
             embed = discord.Embed(
                 description=
                 "This command is on cooldown, please wait {} seconds before trying again."
                 .format(error.retry_after))
         elif isinstance(error, commands.CheckFailure):
             embed = discord.Embed(
                 description=
                 "You do not have permission to do this. Back off, thot!")
         else:
             embed = discord.Embed(
                 description=
                 "Placeholder embed. If you see this please message {}.".
                 format(str(self.owner)))
         if embed:
             embed.colour = err_colour
             await ctx.send(embed=embed)