Package: slash-util
slash_util is a library that adds new features to discord.pyInstallationBEFORE ANYTHINGYou must install discord.py 2.0 from GitHub:pip install -U git+https://github.com/Rapptz/discord.pyThis script will NOT work without it. Seethis messagefor more information on discord.py 2.0You can now install slash_util from PyPI:pip install -U slash-utilFeaturesApplication Commands (slash commands + message/user context menu commands)New Modal interactionApplication CommandsDefining parametersA few different parameter types can be specified in accordance with the discord api.These parameters may only be used insideslash commands, not within context menu commands.strfor stringsintorRange[min, max]for ints (seeRangesfor more information)floatorRange[min, max]for floats (seeRangesfor more information)boolfor booleansdiscord.Userordiscord.Memberfor membersdiscord.Rolefor rolesdiscord.Attachmentfor attaching files (seeAttachmentsfor more information)typing.Literalfor option choices (seeLiteralsfor more information)For defining channel parameters, they are documented inChannelsParameters can also be optional, seeOptionalRangesRanges are a way to specify minimum and maximum values forintsandfloats. They can be defined inside a type hint, for example:@slash_util.slash_command()asyncdefmy_command(self,ctx,number:slash_util.Range[0,10]):# `number` will only be an int within this rangeawaitctx.send(f"Your number was{number}!",ephemeral=True)If you specify a float in either parameter, the value will be a float.ChannelsChannels can be defined usingdiscord.TextChannel,VoiceChannelorCategoryChannel.
You can specify multiple channel types viatyping.Union:@slash_util.slash_command()asyncdefmy_command(self,ctx,channel:typing.Union[discord.TextChannel,discord.VoiceChannel]):awaitctx.send(f'{channel.mention}is not a category!',ephemeral=True)AttachmentsNEW: Discord now lets you upload attachments to slash commands.slash_utilsupports this via thediscord.Attachmenttype hint, for example:@slash_util.slash_command()asyncdefmy_command(self,ctx,attachment:discord.Attachment):awaitctx.send("Your file:",file=awaitattachment.to_file())LiteralsAtyping.Literalis a special type hint that requires the passed parameter to be equal to one of the listed values.
The passed literals must be all the same type, which must be eitherstr,intorfloat.
These will be used to create a list of options for the user to select from.
For example, given the following:fromtypingimportLiteral@slash_util.slash_command()asyncdefshop(self,ctx,buy_sell:Literal['buy','sell'],amount:Literal[1,2],item:str):awaitctx.send(f'{buy_sell.capitalize()}ing{amount}{item}(s)!')Thebuy_sellparameter must be either the literal string"buy"or"sell"and amount must be the int1or2.OptionalA parameter can be optional by assigning a default value to it.@slash_util.slash_command()asyncdefadd(self,ctx,a:int,b:int,c:int=0):total=a+b+cawaitctx.send(f"{a}+{b}+{c}={total}")If thecparameter isn't given, it will be defaulted to 0. This will also show up to the user as an optional argument.The default value isn't type restricted as well, this is to supportNonetypes but this could be used to give any other type. This means the above example can be rewritten in two ways -@slash_util.slash_command()asyncdefadd(self,ctx,a:int,b:int,c:int=None):...@slash_util.slash_command()asyncdefadd(self,ctx,a:int,b:int,c:int='0'):...Same as before, only thecparameter will give a different value in the two examples. The first one will giveNoneand the second will give a string'0'. If the user givescthen it is restricted to integers.ModalsDiscord recently added a new interaction type - Modals. These aren't supported with discord.py, and I've decided to implement them in my library.importslash_util@slash_util.slash_command()asyncdefmodal(self,ctx):modal=slash_util.Modal(title="Hello, world!",items=[slash_util.TextInput(custom_id="name",label="What is your name?",style=slash_util.TextInputStyle.short),# custom_id is important!slash_util.TextInput(custom_id="about",label="Tell us about yourself!",style=slash_util.TextInputStyle.paragraph)])awaitctx.send(modal=modal)try:interaction=awaitmodal.wait(timeout=60.0)exceptasyncio.TimeoutError:awaitctx.send("You didn't respond in time...")returnresponse=modal.response# this will be a dict with the custom_ids above as the keys, and the user responses as the valuesname=response['name']awaitinteraction.response.send_message(f"Hello,{name}!")Examplesslash_utildefines a bot subclass to automatically handle posting updated commands to discords api. This isn't required but highly recommended to use.classMyBot(slash_util.Bot):def__init__(self):super().__init__(command_prefix="!")# command prefix only applies to message based commandsself.load_extension("cogs.my_cog")# important!if__name__=='__main__':MyBot().run("token")Sample cog:classMyCog(slash_util.Cog):@slash_util.slash_command()# sample slash commandasyncdefslash(self,ctx:slash_util.Context,number:int):awaitctx.send(f"You selected #{number}!",ephemeral=True)@slash_util.message_command(name="Quote")# sample command for message context menusasyncdefquote(self,ctx:slash_util.Context,message:discord.Message):# these commands may only have a single Message parameterawaitctx.send(f'>{message.clean_content}\n-{message.author}')@slash_util.user_command(name='Bonk')# sample command for user context menusasyncdefbonk(self,ctx:slash_util.Context,user:discord.Member):# these commands may only have a single Member parameterawaitctx.send(f'{ctx.author}BONKS{user}:hammer:')defsetup(bot):bot.add_cog(MyCog(bot))