Slash util - A simple script to add application command support to discord.py v2.0

Overview

slash_util is a simple wrapper around slash commands for discord.py

This is written by an official discord.py helper to try and stop people using third party forks or otherwise. If any help is required, please ping Maya#9000 in one of the help channels. To any other helpers reading this, this script is exempt from rule 14.

Table of contents

Installation

BEFORE ANYTHING You must install discord.py 2.0 from GitHub:

pip install -U git+https://github.com/Rapptz/discord.py

This script will NOT work without it. See this message for more information on discord.py 2.0

  1. Go to the slash_util.py file

  2. Click the following button img

  3. Copy the entire text and paste it into your own file, then proceed to import it into files you need.

Defining parameters

A few different parameter types can be specified in accordance with the discord api.

These parameters may only be used inside slash commands, not within context menu commands.

  • str for strings
  • int or Range[min, max] for ints (see Ranges for more information)
  • float or Range[min, max] for floats (see Ranges for more information)
  • bool for booleans
  • discord.User or discord.Member for members
  • discord.Role for roles

For defining channel parameters, they are documented in Channels

Ranges

Ranges are a way to specify minimum and maximum values for ints and floats. They can be defined inside a type hint, for example:

@slash_util.slash_command()
async def my_command(self, ctx, number: slash_util.Range[0, 10]):
  # `number` will only be an int within this range
  await ctx.send(f"Your number was {number}!", ephemeral=True)

If you specify a float in either parameter, the value will be a float.

Channels

Channels can be defined using discord.TextChannel, VoiceChannel or CategoryChannel. You can specify multiple channel types via typing.Union:

@slash_util.slash_command()
async def my_command(self, ctx, channel: typing.Union[discord.TextChannel, discord.VoiceChannel]):
  await ctx.send(f'{channel.mention} is not a category!', ephemeral=True)

Examples

slash_util defines a bot subclass to automatically handle posting updated commands to discords api. This isn't required but highly recommended to use.

class MyBot(slash_util.Bot):
    def __init__(self):
        super().__init__(command_prefix="!")  # command prefix only applies to message based commands

        self.load_extension("cogs.my_cog")  # important!
        
if __name__ == '__main__':
    MyBot().run("token")

Sample cog:

class MyCog(slash_util.ApplicationCog):
    @slash_util.slash_command()  # sample slash command
    async def slash(self, ctx: slash_util.Context, number: int):
        await ctx.send(f"You selected #{number}!", ephemeral=True)
    
    @slash_util.message_command(name="Quote")  # sample command for message context menus
    async def quote(self, ctx: slash_util.Context, message: discord.Message):  # these commands may only have a single Message parameter
        await ctx.send(f'> {message.clean_content}\n- {message.author}')
    
    @slash_util.user_command(name='Bonk')  # sample command for user context menus
    async def bonk(self, ctx: slash_util.Context, user: discord.Member):  # these commands may only have a single Member parameter
        await ctx.send(f'{ctx.author} BONKS {user} :hammer:')

def setup(bot):
    bot.add_cog(MyCog(bot))

See the api documentation below for more information on attributes, functions and more.

API Documentation

deco @slash_command(**kwargs)

Defines a function as a slash-type application command.

Parameters:

  • name: str
    • The display name of the command. If unspecified, will use the functions name.
  • guild_id: Optional[int]
    • The guild ID this command will belong to. If unspecified, the command will be uploaded globally.
  • description: str
    • The description of the command. If unspecified, will use the functions docstring, or "No description provided" otherwise.
deco @message_command(**kwargs)

Defines a function as a message-type application command.

Parameters:

  • name: str
    • The display name of the command. If unspecified, will use the functions name.
  • guild_id: Optional[int]
    • The guild ID this command will belong to. If unspecified, the command will be uploaded globally.
deco @user_command(**kwargs)

Defines a function as a user-type application command.

Parameters:

  • name: str
    • The display name of the command. If unspecified, will use the functions name.
  • guild_id: Optional[int]
    • The guild ID this command will belong to. If unspecified, the command will be uploaded globally.
deco @describe(**kwargs: str)

Sets the description for the specified parameters of the slash command. Sample usage:

@slash_util.slash_command()
@describe(channel="The channel to ping")
async def mention(self, ctx: slash_util.Context, channel: discord.TextChannel):
    await ctx.send(f'{channel.mention}')

If this decorator is not used, parameter descriptions will be set to "No description provided." instead.

class Range(min: NumT | None, max: NumT)

Defines a minimum and maximum value for float or int values. The minimum value is optional.

async def number(self, ctx, num: slash_util.Range[0, 10], other_num: slash_util.Range[10]):
    ...
class Bot(command_prefix, help_command=<default-help-command>, description=None, **options)

None

Methods:

get_application_command(self, name: str)

Gets and returns an application command by the given name.

Parameters:

  • name: str
    • The name of the command.

Returns:

  • Command
    • The relevant command object
  • None
    • No command by that name was found.

async delete_all_commands(self, guild_id: int | None = None)

Deletes all commands on the specified guild, or all global commands if no guild id was given.

Parameters:

  • guild_id: Optional[str]
    • The guild ID to delete from, or None to delete global commands.

async delete_command(self, id: int, guild_id: int | None = None)

Deletes a command with the specified ID. The ID is a snowflake, not the name of the command.

Parameters:

  • id: int
    • The ID of the command to delete.
  • guild_id: Optional[str]
    • The guild ID to delete from, or None to delete a global command.

async sync_commands(self)

Uploads all commands from cogs found and syncs them with discord. Global commands will take up to an hour to update. Guild specific commands will update immediately.

class Context(bot: BotT, command: Command[CogT], interaction: discord.Interaction)

The command interaction context.

Attributes

Methods:

async send(self, content=..., **kwargs)

Responds to the given interaction. If you have responded already, this will use the follow-up webhook instead. Parameters embed and embeds cannot be specified together. Parameters file and files cannot be specified together.

Parameters:

  • content: str
    • The content of the message to respond with
  • embed: discord.Embed
    • An embed to send with the message. Incompatible with embeds.
  • embeds: List[discord.Embed]
    • A list of embeds to send with the message. Incompatible with embed.
  • file: discord.File
    • A file to send with the message. Incompatible with files.
  • files: List[discord.File]
    • A list of files to send with the message. Incompatible with file.
  • ephemeral: bool
    • Whether the message should be ephemeral (only visible to the interaction user).
    • Note: This field is ignored if the interaction was deferred.

Returns

async def defer(self, *, ephemeral: bool = False) -> None:

Defers the given interaction.

This is done to acknowledge the interaction. A secondary action will need to be sent within 15 minutes through the follow-up webhook.

Parameters:

  • ephemeral: bool
    • Indicates whether the deferred message will eventually be ephemeral. Defaults to False

Returns

  • None

Raises

property cog(self)

The cog this command belongs to.

property guild(self)

The guild this interaction was executed in.

property message(self)

The message that executed this interaction.

property channel(self)

The channel the interaction was executed in.

property author(self)

The user that executed this interaction.

class ApplicationCog(*args: Any, **kwargs: Any)

The cog that must be used for application commands.

Attributes:

Comments
  • Implement chat-type command checks.

    Implement chat-type command checks.

    This PR implements chat-type command checks, as per the title, using the same internal code as discord.py.

    I haven't had the chance to test this PR so if anyone is willing to do so before I get the chance then that would be appreciated. As far as I know everything should work fine though.

    Closes #6

    merged 
    opened by Axelancerr 3
  • Add optional parameters to README.md

    Add optional parameters to README.md

    This pull request just adds optional parameters to README.md. I wanted to add this to let new developers know that optional parameters are supported.

    There might be a better example that I couldn't think of. But I believe a + b + c with c being optional is the best. Mainly if someone test out the code they'll see c being set to 0 when its not given.

    opened by catzoo 2
  • slash_util.Bot.get_context() raising `TypeError` on custom class

    slash_util.Bot.get_context() raising `TypeError` on custom class

    Hi! I'm trying to migrate from discord.py 2.0 to slash_util, but in my class which I use to add an attribute to my context (and it works on 2.0) is raising a TypeError: __init__() got an unexpected keyword argument 'prefix' This is my current code. The only things I've changed were commands.Bot to slash_util.Bot and commands.Context to slash_util.Context.

    class Noether(slash_util.Bot):
        async def get_context(self, message, *, cls=slash_util.Context):
            ctx = await super().get_context(message, cls=cls) 
            # ... more code
    

    And this is the full traceback:

    Ignoring exception in on_message
    Traceback (most recent call last):
      File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 351, in _run_event
        await coro(*args, **kwargs)
      File "bot.py", line 404, in on_message
        await bot.process_commands(message)
      File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 1030, in process_commands
        ctx = await self.get_context(message)
      File "bot.py", line 54, in get_context
        ctx = await super().get_context(message, cls=cls)
      File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 935, in get_context
        ctx = cls(prefix=None, view=view, bot=self, message=message)
    TypeError: __init__() got an unexpected keyword argument 'prefix'
    

    I also tried and saw that changing slash_util.Context back to commands.Context makes it work, but that would be pointless since I could not use most of the features of the library.

    invalid 
    opened by Eleiber 1
  • Add Autocomplete Options

    Add Autocomplete Options

    This PR adds the ability to use autocomplete on command options. I'm not sure I'm satisfied with the interface, but it's the best I could come up with. Inspired by dpy's converters, sort of.

    Discord: lukesaltweather#1111

    I tested:

    • Whether user, message and "old" slash commands still work

    • Several sorts of callables passed to the decorator, so async method, sync method, classes with async methods (the code that handles calling the autocomplete and convert methods has basically been copied from the converter section of dpy)

    opened by lukesaltweather 1
  • Bot events don't work anymore

    Bot events don't work anymore

    bot events don't work anymore: @bot.event def on_ready(): # something returns error: TypeError: event() missing 1 required positional argument: 'coro' And bot is my slash_util init cog

    invalid 
    opened by TimBitBox 1
  • Add support for discord.Attachment options

    Add support for discord.Attachment options

    Finally. Added support for option type 11 discord.Attachment. It was tested. (See #9)

    (idk why I added that much commits. Ignore them)

    (I am not good at using GitHub/changing source code, if I have anything that I can improve, pls tell me. Thanks.) (next time I will test the code first on my local computer before I commit.)

    opened by ChesterWOV-DPY 1
  • Support new Attachment parameter

    Support new Attachment parameter

    Will be accomplished as the following:

    @slash_util.slash_command()
    async def slash(self, ctx, file: discord.Attachment):
        # basically equivalent to checking the message attachments i guess?
    
    enhancement 
    opened by XuaTheGrate 1
  • Fixing a TypeError when sending files.

    Fixing a TypeError when sending files.

    When you tried to send a file without deferring the interaction first you would get TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'file'. This PR is just to fix that by deferring the interaction response if the file or files kwarg has been passed and it hasn't been deferred before.

    opened by LeoCx1000 1
  • Adding support for Literal option choices.

    Adding support for Literal option choices.

    Here is my implementation of literal options I had made a few weeks ago in my gist fork, glad to be finally able to make PRs. here's an example:

    import typing
    AllowedWords = typing.Literal['First', 'Second', 'Third', 'Fourth']
    
    @slash_util.slash_command(name="test", guild_id=774561547930304536)
    async def test(self, ctx: slash_utils.Context, option: AllowedWords):
        await ctx.send(f"option: {option}")
    

    example example2

    I apologize for this lack of documentation 😦 and sorry if this was already PRed, I had some struggles understanding the interface

    opened by LeoCx1000 1
  • Add defer method to context and update documentation

    Add defer method to context and update documentation

    Added a defer method to the context object. This hasn't been tested yet so that would be good before merging. Also I updated documentation and tried to copy the current style but some changes may need to be made there.

    Also removed the attribute _responded of context. Now uses InteractionResponse.is_done()

    opened by mysistersbrother 1
Owner
Maya
Maya
A discord bot wrapper for python have slash command

A discord bot wrapper for python have slash command

null 4 Dec 4, 2021
A Python wrapper for discord slash-commands, designed to extend discord.py.

dislash.py An extending library for discord.py that allows to build awesome slash-commands. ⭐

null 173 Dec 19, 2022
Discord music bot using discord.py, slash commands, and yt-dlp.

bop Discord music bot using discord.py, slash commands, and yt-dlp. Features Play music from YouTube videos and playlists Queue system with shuffle Sk

Hizkia Felix 3 Aug 11, 2022
Attempting to create a framework for Discord Slash commands... yes

discord_slash.py Attempting to create a framework for Discord Slash commands... yes Installation pip install slashpy Documentation Coming soon™ Why is

AlexFlipnote 11 Mar 24, 2021
A Slash Commands Discord Bot created using Pycord!

Hey, I am Slash Bot. A Bot which works with Slash Commands! Prerequisites Python 3+ Check out. the requirements.txt and install all the pakages. Insta

Saumya Patel 18 Nov 15, 2022
Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar seu próprio token, e lembrando, é um bot básico, não se utiliza Cogs nem slash commands nele!

BotDiscordPython Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar s

Matheus Muguet 4 Feb 5, 2022
Your custom slash commands Discord bot!

Slashy - Your custom slash-commands bot Hey, I'm Slashy - your friendly neighborhood custom-command bot! The code for this bot exists because I'm like

Omar Zunic 8 Dec 20, 2022
Your custom slash commands Discord bot!

Slashy - Your custom slash-commands bot Hey, I'm Slashy - your friendly neighborhood custom-command bot! The code for this bot exists because I'm like

Omar Zunic 3 Jan 8, 2022
An example of using discordpy 2.0.0a to create a bot that supports slash commands

DpySlashBotExample An example of using discordpy 2.0.0a to create a bot that supports slash commands. This is not a fully complete bot, just an exampl

null 7 Oct 17, 2022
A python library for creating Slack slash commands using AWS Lambda Functions

slashbot Slashbot makes it easy to create slash commands using AWS Lambda functions. These can be handy for creating a secure way to execute automated

Eric Brassell 17 Oct 21, 2022
An example Music Bot written in Disnake and uses slash commands to operate.

Music Bot An example music bot that is written in Disnake [Maintained discord.py Fork] Disnake Disnake is a maintained and updated fork of discord.py.

null 6 Jan 8, 2022
Linky bot, A open-source discord bot that allows you to add links to ur website, youtube url, etc for the people all around discord to see!

LinkyBot Linky bot, An open-source discord bot that allows you to add links to ur website, youtube url, etc for the people all around discord to see!

AlexyDaCoder 1 Sep 20, 2022
Discord bot script for sending multiple media files to a discord channel according to discord limitations.

Discord Bulk Image Sending Bot Send bulk images to Discord channel. This is a bot script that will allow you to send multiple images to Discord channe

Nikola Arbov 1 Jan 13, 2022
Support for Competitive Coding badges to add in Github readme or portfolio websites.

Support for Competitive Coding badges to add in Github readme or portfolio websites.

Akshat Aggarwal 2 Feb 14, 2022
A simple, fast, and awesome discord nuke bot! The only thing you need to add is your bot token.

SimpleNukeBot A simple, fast, and awesome discord nuke bot! The only thing you need to add is your bot token. Instructions: All you need to do is crea

Bisc 1 Apr 18, 2022
Discord-Token-Formatter - A simple script to convert discord tokens from email token to token only format

Discord-Token-Formatter A simple script to convert discord tokens from email:pas

null 2 Oct 23, 2022
Free and Open Source Group Voice chat music player for telegram ❤️ with button support youtube playback support

Free and Open Source Group Voice chat music player for telegram ❤️ with button support youtube playback support

Sehath Perera 1 Jan 8, 2022
Cytotron - A unique discord bot like never before. Add it to your server to keep it active, motiviated, and amazing!!

Cytotron - Take your server to the next level Most of the details are in the website. Go to https://cytotron-bot.gq for more information. If that link

LeviathanProgramming 6 Jun 13, 2021
A discord bot consuming Notion API to add, retrieve data to Notion databases.

Notion-DiscordBot A discord bot consuming Notion API to add and retrieve data from Notion databases. Instructions to use the bot: Pre-Requisites: a)In

Servatom 57 Dec 29, 2022