示例#1
0
 async def per(self, ctx, *, length: TimedeltaConverter):
     """How long of a timeframe to keep track of command spamming."""
     duration_seconds = length.total_seconds()
     await self.config.per.set(duration_seconds)
     await ctx.send(
         f"The spam filter has been set to check commands during a  {humanize_timedelta(seconds=duration_seconds)} period."
     )
     await self.gen_cache()
示例#2
0
 async def length(self, ctx, *, length: TimedeltaConverter):
     """How long to blacklist a user from using commands."""
     duration_seconds = length.total_seconds()
     await self.config.mute_length.set(duration_seconds)
     await ctx.send(
         f"The spam filter blacklist timer has been set to {humanize_timedelta(seconds=duration_seconds)}."
     )
     await self.gen_cache()
示例#3
0
 async def delay(
     self,
     ctx,
     seconds: TimedeltaConverter(minimum=timedelta(seconds=15),
                                 maximum=timedelta(seconds=900),
                                 default_unit="seconds"),
 ):
     """Set the delay used to check for new content."""
     time = seconds.total_seconds()
     await self.config.delay.set(time)
     await ctx.tick()
     await ctx.send("This delay will come into effect on the next loop.")
示例#4
0
 async def delay(
     self,
     ctx,
     time: TimedeltaConverter(minimum=timedelta(seconds=15),
                              maximum=timedelta(hours=3),
                              default_unit="seconds"),
 ):
     """Set the delay used to check for new content."""
     seconds = time.total_seconds()
     await self.config.delay.set(seconds)
     await ctx.tick()
     await ctx.send(
         f"The {humanize_timedelta(seconds=seconds)} delay will come into effect on the next loop."
     )
示例#5
0
 async def time(
     self,
     ctx,
     *,
     time: TimedeltaConverter(
         minimum=timedelta(),
         maximum=timedelta(minutes=60),
         default_unit="seconds",
         allowed_units=["seconds", "minutes"],
     ),
 ):
     """Set the time before snipes expire"""
     duration = time.total_seconds()
     await self.config.guild(ctx.guild).timeout.set(duration)
     await ctx.tick()
示例#6
0
    async def per(self, ctx, *, length: TimedeltaConverter):
        """How long of a timeframe to keep track of command spamming.

        Accepts: seconds, minutes, hours, days, weeks
        Examples:
            `[p]antispamset per 1d2h30m`
            `[p]antispamset per 1 day 2 hours 30 minutes`
        """
        if not length:
            return await ctx.send("You must provide a value greater than 0.")
        duration_seconds = length.total_seconds()
        await self.config.per.set(duration_seconds)
        await ctx.send(
            f"The spam filter has been set to check commands during a {humanize_timedelta(seconds=duration_seconds).rstrip('s')} period."
        )
        await self.gen_cache()
示例#7
0
    async def length(self, ctx, *, length: TimedeltaConverter):
        """How long to blacklist a user from using commands.

        Accepts: seconds, minutes, hours, days, weeks
        Examples:
            `[p]antispamset length 1d2h30m`
            `[p]antispamset length 1 day 2 hours 30 minutes`
        """
        if not length:
            return await ctx.send("You must provide a value greater than 0.")
        duration_seconds = length.total_seconds()
        await self.config.mute_length.set(duration_seconds)
        await ctx.send(
            f"The spam filter blacklist timer has been set to {humanize_timedelta(seconds=duration_seconds)}."
        )
        await self.gen_cache()
示例#8
0
    async def deletetime(
        self,
        ctx: commands.Context,
        *,
        time: TimedeltaConverter(
            minimum=timedelta(),
            maximum=timedelta(minutes=60),
            default_unit="seconds",
            allowed_units=["seconds", "minutes"],
        ),
    ):
        """
        Set the time for snipes to be removed automatically.

        Takes seconds or minutes, use the whole unit name with the amount.
        Defaults to seconds if no unit name used.
        """
        duration = time.total_seconds()
        await self.config.timer.set(duration)
        await ctx.tick()
示例#9
0
    async def slottime(self, ctx: commands.Context, *,
                       duration: TimedeltaConverter(default_unit="seconds")):
        """Set the cooldown for the slot machine.

        Examples:
            - `[p]economyset slottime 10`
            - `[p]economyset slottime 10m`

        **Arguments**

        - `<duration>` The new duration to wait in between uses of the slot machine. Default is 5 seconds.
        Accepts: seconds, minutes, hours, days, weeks (if no unit is specified, the duration is assumed to be given in seconds)
        """
        seconds = int(duration.total_seconds())
        guild = ctx.guild
        if await bank.is_global():
            await self.config.SLOT_TIME.set(seconds)
        else:
            await self.config.guild(guild).SLOT_TIME.set(seconds)
        await ctx.send(_("Cooldown is now {num} seconds.").format(num=seconds))
示例#10
0
 async def time(
     self,
     ctx,
     *,
     time: TimedeltaConverter(
         minimum=timedelta(),
         maximum=timedelta(minutes=60),
         default_unit="seconds",
         allowed_units=["seconds", "minutes"],
     ),
 ):
     """ 
     Set the time before snipes expire.  
     
     Takes seconds or minutes, use the whole unit name with the amount.  
     Defaults to seconds if no unit name used.   
     """
     duration = time.total_seconds()
     await self.config.guild(ctx.guild).timeout.set(duration)
     await ctx.tick()
示例#11
0
    async def start(
            self,
            ctx: commands.Context,
            channel: Optional[discord.TextChannel],
            time: TimedeltaConverter(default_unit="minutes"),
            *,
            prize: str,
    ):
        """
        Start a giveaway.

        This by default will DM the winner and also DM a user if they cannot enter the giveaway.
        """
        channel = channel or ctx.channel
        end = datetime.now(timezone.utc) + time
        embed = discord.Embed(
            title=f"{prize}",
            description=
            f"\nReact with 🎉 to enter\n\n**Hosted by:** {ctx.author.mention}\n\nEnds: <t:{int(end.timestamp())}:R>",
            color=await ctx.embed_color(),
        )
        msg = await channel.send(embed=embed)
        giveaway_obj = Giveaway(
            ctx.guild.id,
            channel.id,
            msg.id,
            end,
            prize,
            "🎉",
            **{
                "congratulate": True,
                "notify": True
            },
        )
        self.giveaways[msg.id] = giveaway_obj
        await msg.add_reaction("🎉")
        giveaway_dict = deepcopy(giveaway_obj.__dict__)
        giveaway_dict["endtime"] = giveaway_dict["endtime"].timestamp()
        await self.config.custom(GIVEAWAY_KEY, str(ctx.guild.id),
                                 str(msg.id)).set(giveaway_dict)
示例#12
0
    async def paydaytime(self, ctx: commands.Context, *,
                         duration: TimedeltaConverter(default_unit="seconds")):
        """Set the cooldown for the payday command.

        Examples:
            - `[p]economyset paydaytime 86400`
            - `[p]economyset paydaytime 1d`

        **Arguments**

        - `<duration>` The new duration to wait in between uses of payday. Default is 5 minutes.
        Accepts: seconds, minutes, hours, days, weeks (if no unit is specified, the duration is assumed to be given in seconds)
        """
        seconds = int(duration.total_seconds())
        guild = ctx.guild
        if await bank.is_global():
            await self.config.PAYDAY_TIME.set(seconds)
        else:
            await self.config.guild(guild).PAYDAY_TIME.set(seconds)
        await ctx.send(
            _("Value modified. At least {num} seconds must pass between each payday."
              ).format(num=seconds))
示例#13
0
    async def convert(self, ctx, argument):
        argument = argument.replace("—", "--")
        parser = NoExitParser(description="Giveaway Created", add_help=False)

        # Required Arguments

        parser.add_argument("--prize", "--p", dest="prize", nargs="*", default=[])

        timer = parser.add_mutually_exclusive_group()
        timer.add_argument("--duration", "--d", dest="duration", nargs="*", default=[])
        timer.add_argument("--end", "--e", dest="end", nargs="*", default=[])

        # Optional Arguments
        parser.add_argument("--channel", dest="channel", default=None, nargs="?")
        parser.add_argument("--roles", "--r", "--restrict", dest="roles", nargs="*", default=[])
        parser.add_argument("--multiplier", "--m", dest="multi", default=None, type=int, nargs="?")
        parser.add_argument("--multi-roles", "--mr", nargs="*", dest="multi-roles", default=[])
        parser.add_argument("--joined", dest="joined", default=None, type=int, nargs="?")
        parser.add_argument("--created", dest="created", default=None, type=int, nargs="?")
        parser.add_argument("--blacklist", dest="blacklist", nargs="*", default=[])
        parser.add_argument("--winners", dest="winners", default=None, type=int, nargs="?")
        parser.add_argument("--mentions", dest="mentions", nargs="*", default=[])
        parser.add_argument("--description", dest="description", default=[], nargs="*")
        parser.add_argument("--emoji", dest="emoji", default=None, nargs="*")

        # Setting arguments
        parser.add_argument("--multientry", action="store_true")
        parser.add_argument("--notify", action="store_true")
        parser.add_argument("--congratulate", action="store_true")
        parser.add_argument("--announce", action="store_true")
        parser.add_argument("--ateveryone", action="store_true")
        parser.add_argument("--athere", action="store_true")
        parser.add_argument("--show-requirements", action="store_true")

        # Integrations
        parser.add_argument("--cost", dest="cost", default=None, type=int, nargs="?")
        parser.add_argument("--level-req", dest="levelreq", default=None, type=int, nargs="?")
        parser.add_argument("--rep-req", dest="repreq", default=None, type=int, nargs="?")
        parser.add_argument("--tatsu-level", default=None, type=int, nargs="?")
        parser.add_argument("--tatsu-rep", default=None, type=int, nargs="?")
        parser.add_argument("--mee6-level", default=None, type=int, nargs="?")
        parser.add_argument("--amari-level", default=None, type=int, nargs="?")
        parser.add_argument("--amari-weekly-xp", default=None, type=int, nargs="?")

        try:
            vals = vars(parser.parse_args(argument.split(" ")))
        except Exception as error:
            raise BadArgument(
                "Could not parse flags correctly, ensure flags are correctly used."
            ) from error

        if not vals["prize"]:
            raise BadArgument("You must specify a prize. Use `--prize` or `-p`")  #

        if not any([vals["duration"], vals["end"]]):
            raise BadArgument(
                "You must specify a duration or end date. Use `--duration` or `-d` or `--end` or `-e`"
            )

        nums = [vals["cost"], vals["joined"], vals["created"], vals["winners"]]
        for val in nums:
            if val is None:
                continue
            if val < 1:
                raise BadArgument("Number must be greater than 0")

        valid_multi_roles = []
        for role in vals["multi-roles"]:
            try:
                role = await RoleConverter().convert(ctx, role)
                valid_multi_roles.append(role.id)
            except BadArgument:
                raise BadArgument(f"The role {role} does not exist within this server.")
        vals["multi-roles"] = valid_multi_roles

        valid_exclusive_roles = []
        for role in vals["roles"]:
            try:
                role = await RoleConverter().convert(ctx, role)
                valid_exclusive_roles.append(role.id)
            except BadArgument:
                raise BadArgument(f"The role {role} does not exist within this server.")
        vals["roles"] = valid_exclusive_roles

        valid_blacklist_roles = []
        for role in vals["blacklist"]:
            try:
                role = await RoleConverter().convert(ctx, role)
                valid_blacklist_roles.append(role.id)
            except BadArgument:
                raise BadArgument(f"The role {role} does not exist within this server.")
        vals["blacklist"] = valid_blacklist_roles = []

        valid_mentions = []
        for role in vals["mentions"]:
            try:
                role = await RoleConverter().convert(ctx, role)
                valid_mentions.append(role.id)
            except BadArgument:
                raise BadArgument(f"The role {role} does not exist within this server.")
        vals["mentions"] = valid_mentions

        if vals["channel"]:
            try:
                vals["channel"] = await TextChannelConverter().convert(ctx, vals["channel"])
            except BadArgument:
                raise BadArgument("Invalid channel.")

        if vals["levelreq"] or vals["repreq"]:
            cog = ctx.bot.get_cog("Leveler")
            if not cog:
                raise BadArgument("Leveler cog not loaded.")
            if not hasattr(cog, "db"):
                raise BadArgument(
                    "This may be the wrong leveling cog. Ensure you are using Fixators."
                )

        if vals["tatsu_level"] or vals["tatsu_rep"]:
            token = await ctx.bot.get_shared_api_tokens("tatsumaki")
            if not token.get("authorization"):
                raise BadArgument(
                    f"You do not have a valid Tatsumaki API token. Check `{ctx.clean_prefix}gw integrations` for more info."
                )

        if vals["amari_level"] or vals["amari_weekly_xp"]:
            token = await ctx.bot.get_shared_api_tokens("amari")
            if not token.get("authorization"):
                raise BadArgument(
                    f"You do not have a valid Amari API token. Check `{ctx.clean_prefix}gw integrations` for more info."
                )

        if (vals["multi"] or vals["multi-roles"]) and not (vals["multi"] and vals["multi-roles"]):
            raise BadArgument(
                "You must specify a multiplier and roles. Use `--multiplier` or `-m` and `--multi-roles` or `-mr`"
            )

        if (
            (vals["ateveryone"] or vals["athere"])
            and not ctx.channel.permissions_for(ctx.me).mention_everyone
            and not ctx.channel.permissions_for(ctx.author).mention_everyone
        ):
            raise BadArgument(
                "You do not have permission to mention everyone. Please ensure the bot and you have `Mention Everyone` permission."
            )

        if vals["description"]:
            vals["description"] = " ".join(vals["description"])
            if len(vals["description"]) > 1000:
                raise BadArgument("Description must be less than 1000 characters.")

        if vals["emoji"]:
            vals["emoji"] = " ".join(vals["emoji"]).rstrip().lstrip()
            custom = False
            try:
                vals["emoji"] = await EmojiConverter().convert(ctx, vals["emoji"])
                custom = True
            except Exception:
                vals["emoji"] = str(vals["emoji"]).replace("\N{VARIATION SELECTOR-16}", "")
            try:
                await ctx.message.add_reaction(vals["emoji"])
                await ctx.message.remove_reaction(vals["emoji"], ctx.me)
            except Exception:
                raise BadArgument("Invalid emoji.")
            if custom:
                vals["emoji"] = vals["emoji"].id

        vals["prize"] = " ".join(vals["prize"])
        if vals["duration"]:
            tc = TimedeltaConverter()
            try:
                vals["duration"] = await tc.convert(ctx, " ".join(vals["duration"]))
            except BadArgument:
                raise BadArgument("Invalid duration. Use `--duration` or `-d`")
        else:
            try:
                time = dateparser.parse(" ".join(vals["end"]))
                if time.tzinfo is None:
                    time = time.replace(tzinfo=timezone.utc)
                if datetime.now(timezone.utc) > time:
                    raise BadArgument("End date must be in the future.")
                time = time - datetime.now(timezone.utc)
                vals["duration"] = time
            except Exception:
                raise BadArgument(
                    "Invalid end date. Use `--end` or `-e`. Ensure to pass a timezone, otherwise it defaults to UTC."
                )

        return vals