Documentation: dislash.py
This library adds different interaction features to discord.py, such as buttons or slash commands.
It’s recommended to read Quickstart first.
Sections
Quickstart
Installation
Enter one of these commands to install the library:
pip install dislash.py
python -m pip install dislash.py
Or just clone the repo: https://github.com/EQUENOS/dislash.py
Creating a simple command
Let’s make a /hello command that will send “Hello!” to the chat.
from discord.ext import commands
from dislash import InteractionClient
bot = commands.Bot(command_prefix="!")
# test_guilds param is optional, this is a list of guild IDs
inter_client = InteractionClient(bot, test_guilds=[12345])
@inter_client.slash_command(description="Says Hello")
async def hello(ctx):
await ctx.send("Hello!")
bot.run("BOT_TOKEN")
Note
test_guilds
/ guild_ids
parameters.And here we go! We’ve just made a simple slash-command named /hello

More examples
Note
For more examples, see Examples
Examples
A simple slash command
from discord.ext import commands
from dislash import InteractionClient
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot)
@inter_client.slash_command(description="Sends Hello")
async def hello(interaction):
await interaction.reply("Hello!")
bot.run("BOT_TOKEN")
See also
Slash embed
Let’s make something more complicated than /hello. For example, a command that generates an embed.
import discord
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot)
test_guilds = [12345] # Insert ID of your guild here
@inter_client.slash_command(
guild_ids=test_guilds,
description="Builds a custom embed",
options=[
Option('title', 'Makes the title of the embed', OptionType.STRING),
Option('description', 'Makes the description', OptionType.STRING),
Option('color', 'The color of the embed', OptionType.STRING)
# Note that all args are optional
# because we didn't specify required=True in Options
]
)
async def embed(inter, title=None, description=None, color=None):
# Converting color
if color is not None:
try:
color = await commands.ColorConverter().convert(inter, color)
except:
color = None
if color is None:
color = discord.Color.default()
# Generating an embed
emb = discord.Embed(color=color)
if title is not None:
emb.title = title
if desc is not None:
emb.description = desc
# Sending the output
await inter.respond(embed=emb, hide_user_input=True)
bot.run("BOT_TOKEN")
See also
Here’s the result we’ve just achieved:

Slash user-info
It’s time to work with different argument types. This example shows how to easily make a /user-info command
import discord
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot)
test_guilds = [12345]
@inter_client.slash_command(
guild_ids=test_guilds,
name="user-info",
description="Shows user's profile",
options=[
Option("user", "Specify any user", OptionType.USER),
]
)
async def user_info(inter, user=None):
# Default user is the command author
user = user or inter.author
emb = discord.Embed(color=discord.Color.blurple())
emb.title = str(user)
emb.description = (
f"**Created at:** `{user.created_at}`\n"
f"**ID:** `{user.id}`"
)
emb.set_thumbnail(url=user.avatar_url)
await inter.respond(embed=emb)
bot.run("BOT_TOKEN")
Here’s how this slash command looks like in Discord:

Slash commands
Introduction
As you’ve already noticed, Discord makes all slash commands look like a part of the interface. This is possible because every slash command is registered before people can use it. Even though this library registers your commands automatically, you should still design every slash command yourself ;)
What are interactions?
The data you receive is called SlashInteraction
.
There’re 2 types of slash commands: global and local (per guild). Global commands are visible everywhere, including bot DMs. Per guild commands are only visible in corresponding guilds.
Note
Basic example
In this example we’re using the following objects and methods:
InteractionClient
to activate the extensionSlashClient.command
to make a commandSlashInteraction
represented byinter
(see the code below)
from discord.ext import commands
from dislash import InteractionClient
bot = commands.Bot(command_prefix="!")
# test_guilds param is an optional list of guild IDs
inter_client = InteractionClient(bot, test_guilds=[12345])
@inter_client.slash_command(description="Test command")
async def test(inter):
await inter.reply("Test")
bot.run("BOT_TOKEN")
A command with arguments
Let’s make a command that shows the avatar of the user. If user isn’t specified, it shows the avatar of the author.
In addition to all previous methods, we’re going to use these:
Option
to make an optionOptionType
to specify the option type
This is required for further command registration.
import discord
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot, test_guilds=[12345])
@inter_client.slash_command(
description="Shows the avatar of the user",
options=[
Option("user", "Enter the user", OptionType.USER)
# By default, Option is optional
# Pass required=True to make it a required arg
]
)
async def avatar(inter, user=None):
# If user is None, set it to inter.author
user = user or inter.author
# We are guaranteed to receive a discord.User object,
# because we specified the option type as Type.USER
emb = discord.Embed(
title=f"{user}'s avatar",
color=discord.Color.blue()
)
emb.set_image(url=user.avatar_url)
await inter.reply(embed=emb)
bot.run("BOT_TOKEN")
Slash subcommands
Creating subcommands is as easy as creating commands. The only difference is the decorator we use.
In addition to all previous methods, we’re going to use CommandParent.sub_command
(represented by say.sub_command
in the code)
from discord.ext import commands
from dislash import InteractionClient
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot, test_guilds=[12345])
@inter_client.slash_command(description="Has subcommands")
async def say(inter):
# This is just a parent for 2 subcommands
# It's not necessary to do anything here,
# but if you do, it runs for any subcommand nested below
pass
# For each subcommand you can specify individual options and other parameters,
# see the "Objects and methods" reference to learn more.
@say.sub_command(description="Says hello")
async def hello(inter):
await inter.reply("Hello!")
@say.sub_command(description="Says bye")
async def goodbye(inter):
await inter.reply("Bye!")
bot.run("BOT_TOKEN")
Subcommand groups
You can make a command with groups of subcommands using
CommandParent.sub_command_group
and SubCommandGroup.sub_command
Partial code:
@inter_client.slash_command(description="Has groups")
async def groups(inter):
pass
@groups.sub_command_group()
async def group_1(inter):
pass
@group_1.sub_command()
async def blue(inter):
# This will be displayed as
# /groups group_1 blue
pass
@group_1.sub_command()
async def green(inter):
# This will be displayed as
# /groups group_1 green
pass
@groups.sub_command_group()
async def group_2(inter):
# You got the idea
pass
bot.run("BOT_TOKEN")
Alternative option syntax
Sometimes defining options as an argument of the decorator may look confusing, especially when you introduce connectors.
This can be fixed using a fastapi-like paramater “descriptors” using OptionParam
.
An example of a command using OptionParam:
import discord
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, OptionParam, SlashInteraction
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot, test_guilds=[12345])
# before:
@inter_client.slash_command(
options=[
Option("target", description="The target user", type=OptionType.USER, required=True),
Option("action", description="-"),
Option("where", description="The location", type=OptionType.CHANNEL),
],
connectors={"where": "channel"}
)
async def complicated(
inter: SlashInteraction,
target: discord.User,
action: str = "hug",
channel: discord.TextChannel = None
):
if not isinstance(channel, discord.TextChannel):
handle_error() # remember that you could recieve channel categories
pass
# after:
@inter_client.slash_command()
async def simple(
inter: SlashInteraction,
target: discord.User = OptionParam(..., description="The target user"),
action: str = "hug",
channel: discord.TextChannel = OptionParam(None, name="where", description="The location"),
):
pass
As you can see the commands syntax is shorter and keeps the option attribute definitions close to the actual parameter.
Defaults
The default value should be provided as the first argument to OptionParam
. If the parameter is required you can either not provide it or set it to an ellipsis …
@inter_client.slash_command()
async def command(
inter: SlashInteraction,
a: float = OptionParam(desc="Required float"),
b: int = OptionParam(..., desc="Required int"),
c: str = OptionParam("default", desc="Optional str")
):
pass
Sometimes the default value cannot be hardcoded, such as an author or the current channel. In this case you can just pass in any callable.
author = lambda inter: inter.author
@inter_client.slash_command()
async def command(
inter: SlashInteraction,
user: discord.User = OptionParam(author),
channel: discord.abc.TextChannel = OptionParam(lambda i: i.channel),
):
pass
Converters
In some cases you may require the argument to be converted to a type not supported by slash commands. Simply pass a converter callable as the converter argument
@inter_client.slash_command()
async def command(
inter: SlashInteraction,
item: str = OptionParam(desc="An item that will be pluralized", converter=lambda arg: arg + 's')
):
pass
Choices
Choices are highly simplified using OptionParam
. Simply use either typing.Literal
or enum.Enum
.
# before:
@inter_client.slash_command(
options=[
Option(
"arg",
description="An argument picked from multiple choices",
type=OptionType.STRING,
required=True,
choices=[
OptionChoice("argument 1", "arg1"),
OptionChoice("argument 2", "arg2"),
OptionChoice("argument 3", "arg3"),
],
)
]
)
async def original(inter: SlashInteraction, arg: str):
pass
# ------------------------------
# using Enum:
class Arg(str, Enum):
# inheriting from str ensures the typing is correct
# underscores are replaced by spaces
argument_1 = "arg1"
argument_2 = "arg2"
argument_3 = "arg3"
@inter_client.slash_command()
async def enumerator(
inter: SlashInteraction,
arg: Arg = OptionParam(desc="An argument picked from multiple choices")
):
pass
# ------------------------------
# using one-line Enum:
from dislash import option_enum
# both of these options are valid:
OneLineArg = option_enum({"argument 1": "arg1", "argument 2": "arg2", "argument 3": "arg3"})
OneLineArg = option_enum(argument_1="arg1", argument_2="arg2", argument_3="arg3"})
@inter_client.slash_command()
async def oneline_enumerator(
inter: SlashInteraction,
arg: OneLineArg = OptionParam(desc="An argument picked from multiple choices")
):
pass
# ------------------------------
# using Literal:
@inter_client.slash_command()
async def literal(
inter: SlashInteraction,
arg: Literal["arg1", "arg2", "arg3"]
):
# this approach assumes the values and what the user is gonna be picking from are gonna be the same
# that's generally unlikely so you should always prefer enumerators
pass
Supported types for slash command argument
STRING - str
INTEGER - int
NUMBER - float
BOOLEAN - bool
USER - discord.abc.User, discord.User, discord.Member
CHANNEL - discord.abc.GuildChannel, discord.TextChannel, discord.VoiceChannel, discord.CategoryChannel, discord.StageChannel, discord.StoreChannel
ROLE - discord.Role
MENTIONABLE - discord.abc.Snowflake, Union[discord.Member, discord.Role]
Cogs
Sorting commands between cogs is a popular practice in bot development. This section shows how to build slash commands in cogs.
It’s as simple as this:
Example
from discord.ext import commands
from dislash import slash_command, ActionRow, Button, ButtonStyle
class mycog(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Example of a slash command in a cog
@slash_command(description="Says Hello")
async def hello(self, inter):
await inter.respond("Hello from cog!")
# Buttons in cogs (no changes basically)
@commands.command()
async def test(self, ctx):
row_of_buttons = ActionRow(
Button(
style=ButtonStyle.green,
label="Green button",
custom_id="green"
),
Button(
style=ButtonStyle.red,
label="Red button",
custom_id="red"
)
)
msg = await ctx.send("This message has buttons", components=[row_of_buttons])
# Wait for a button click
def check(inter):
return inter.author == ctx.author
inter = await msg.wait_for_button_click(check=check)
# Process the button click
inter.reply(f"Button: {inter.button.label}", type=ResponseType.UpdateMessage)
def setup(bot):
bot.add_cog(mycog(bot))
Differences
@slash_command
instead of@InteractionClient.slash_command
self
is a required first argumentself.bot
instead ofbot
InteractionClient
is accessible viaself.bot.slash
Events
from discord.ext import commands
from dislash import *
bot = commands.Bot(command_prefix="!")
slash = SlashClient(bot)
Here’re 3 different ways of working with dislash events:
@slash.event
async def on_event():
# ...
@bot.listen()
async def on_event():
# ...
# For cogs
@commands.Cog.listener()
async def on_event(self):
# ...
on_ready
- async events.on_ready()
An event which is activated when the dislash extension is ready and all slash commands are synced (if there’re any)
on_auto_register
- async events.on_auto_register(global_commands_patched, patched_guilds)
An event which is called after auto synchronisation of commands.
- Parameters
global_commands_patched (
bool
) – whether the global application commands were updatedpatched_guilds (
List[int]
) – the list of IDs of guilds where the commands were updated
on_dropdown
- async events.on_dropdown(interaction)
An event which is called on any menu click of your application.
- Parameters
interaction (
MessageInteraction
) – the interaction with the select menu
on_slash_command
- async events.on_slash_command(interaction)
An event which is called every time a slash command of your application is invoked.
- Parameters
interaction (
SlashInteraction
) – the interaction with a slash command
on_user_command
- async events.on_user_command(interaction)
An event which is called every time a user command of your application is invoked.
- Parameters
interaction (
ContextMenuInteraction
) – the interaction with a user command
on_message_command
- async events.on_message_command(interaction)
An event which is called every time a message command of your application is invoked.
- Parameters
interaction (
ContextMenuInteraction
) – the interaction with a message command
on_slash_command_error
- async events.on_slash_command_error(interaction, error)
An event which is called every time a slash command fails due to some error. This also includes
InteractionCheckFailure
- Parameters
interaction (
SlashInteraction
) – the interaction with a slash commanderror (
ApplicationCommandError
) – the error that was raised
on_user_command_error
- async events.on_user_command_error(interaction, error)
An event which is called every time a user command fails due to some error. This also includes
InteractionCheckFailure
- Parameters
interaction (
ContextMenuInteraction
) – the interaction with a user commanderror (
ApplicationCommandError
) – the error that was raised
on_message_command_error
- async events.on_message_command_error(interaction, error)
An event which is called every time a message command fails due to some error. This also includes
InteractionCheckFailure
- Parameters
interaction (
ContextMenuInteraction
) – the interaction with a message commanderror (
ApplicationCommandError
) – the error that was raised
Slash command checks
Introduction
This section contains documentation of decorator-based checks that dislash.py has.
Here’s a possible use case:
import dislash
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
inter_client = dislash.InteractionClient(bot)
@inter_client.slash_command(description="A command for admins")
@dislash.has_permissions(administrator=True)
async def hello(inter):
await inter.reply("Hello, administrator!")
bot.run("BOT_TOKEN")
If you want to respond with something like “You’re missing permissions!”,
you should add an error handler using on_slash_command_error(inter, error)
event,
learn more about it here: on_slash_command_error
Checks
- dislash.check(predicate)
A function that converts
predicate(interaction)
functions into application command decoratorsExample
def is_guild_owner(): def predicate(inter): return inter.author.id == inter.guild.owner_id return check(predicate) @is_guild_owner() @slash.command(description="Says Hello if you own the guild") async def hello(inter): await inter.reply("Hello, Mr.Owner!")
- dislash.check_any(*checks)
Similar to
commands.check_any
- dislash.cooldown(rate, per, type=<BucketType.default: 0>)
A decorator that adds a cooldown to a slash-command. Similar to discord.py cooldown decorator.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of
type
which must be of enum typeBucketType
.If a cooldown is triggered, then
CommandOnCooldown
is triggered inon_slash_command_error
in the local error handler.A command can only have a single cooldown.
- Parameters
rate (int) – The number of times a command can be used before triggering a cooldown.
per (float) – The amount of seconds to wait for a cooldown when it’s been triggered.
type (BucketType) – The type of cooldown to have.
- dislash.has_role(item)
Similar to
commands.has_role
- dislash.has_any_role(*items)
Similar to
commands.has_any_role
- dislash.has_permissions(**perms)
Similar to
commands.has_permissions
- dislash.has_guild_permissions(**perms)
Similar to
commands.has_guild_permissions
- dislash.dm_only()
Similar to
commands.dm_only
- dislash.guild_only()
Similar to
commands.guild_only
- dislash.is_owner()
Similar to
commands.is_owner
- dislash.is_nsfw()
Similar to
commands.is_nsfw
- dislash.bot_has_role(item)
Similar to
commands.bot_has_role
- dislash.bot_has_any_role(*items)
Similar to
commands.bot_has_any_role
- dislash.bot_has_permissions(**perms)
Similar to
commands.bot_has_permissions
- dislash.bot_has_guild_permissions(**perms)
Similar to
commands.bot_has_guild_permissions
Objects and methods
ActionRow
- class dislash.ActionRow(*components)
Represents an action row. Action rows are basically shelves for buttons.
- Parameters
components (
List[Button]
) – a list of up to 5 buttons to place in a row
- add_button(*, style: dislash.interactions.message_components.ButtonStyle, label: Optional[str] = None, emoji: Optional[str] = None, custom_id: Optional[str] = None, url: Optional[str] = None, disabled: bool = False)
- disable_buttons(*positions: int)
Sets
disabled
toTrue
for all buttons in this row.
- enable_buttons(*positions: int)
Sets
disabled
toFalse
for all buttons in this row.
- classmethod from_dict(data: dict)
- to_dict()
ApplicationCommand
- class dislash.ApplicationCommand(type: dislash.interactions.application_command.ApplicationCommandType, **kwargs)
Base class for application commands
ApplicationCommandError
- class dislash.ApplicationCommandError(message=None, *args)
The base exception type for all slash-command related errors.
This inherits from
discord.DiscordException
.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from
SlashClient
,on_slash_command_error()
.
ApplicationCommandInteractionData
- class dislash.ApplicationCommandInteractionData(*, data, guild, state)
ApplicationCommandPermissions
- class dislash.ApplicationCommandPermissions(raw_permissions: Optional[list] = None)
Represents application command permissions. Roughly equivalent to a list of
RawCommandPermission
Application command permissions are checked on the server side. Only local application commands can have this type of permissions.
- Parameters
raw_permissions (List[RawCommandPermission]) – a list of
RawCommandPermission
. However,from_pairs()
orfrom_ids()
might be more convenient.
- classmethod from_dict(data: dict)
- classmethod from_ids(role_perms: Optional[dict] = None, user_perms: Optional[dict] = None)
Creates
SlashCommandPermissions
from 2 dictionaries of IDs and permissions.- Parameters
role_perms (
dict
) – a dictionary of {role_id
:bool
}user_perms (
dict
) – a dictionary of {user_id
:bool
}
- classmethod from_pairs(permissions: dict)
Creates
SlashCommandPermissions
using instances ofdiscord.Role
anddiscord.User
- Parameters
permissions (
dict
) – a dictionary of {Role | User
:bool
}
- to_dict()
ApplicationCommandType
- class dislash.ApplicationCommandType
BadArgument
- class dislash.BadArgument(message=None, *args)
BaseInteraction
- class dislash.BaseInteraction(client, data: dict)
The base class for all interactions
- async create_response(content=None, *, type=None, embed=None, embeds=None, components=None, view=None, ephemeral=False, tts=False, allowed_mentions=None)
Creates an interaction response.
- Parameters
content (
str
) – response contenttype (
int
|ResponseType
) – sets the response type. SeeResponseType
embed (
discord.Embed
) – response embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachcomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationephemeral (
bool
) – if set toTrue
, your response will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.
- Raises
HTTPException – sending the response failed
InvalidArgument – Both
embed
andembeds
are specified
- async delete()
Deletes the original interaction response.
- async delete_after(delay: float)
- async edit(content=None, *, embed=None, embeds=None, components=None, allowed_mentions=None)
Edits the original interaction response.
- Parameters
content (
str
) – New message contentembed (
discord.Embed
) – New message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds of a new messagecomponents (
List[ActionRow]
) – a list of up to 5 action rowsallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.
- Returns
message – The message that was edited
- Return type
discord.Message
- async fetch_initial_response()
Fetches the original interaction response.
- async followup(content=None, *, embed=None, embeds=None, file=None, files=None, components=None, view=None, tts=False, ephemeral=False, allowed_mentions=None, username=None, avatar_url=None)
Sends a followup message.
- Parameters
content (
str
) – the followup message contentembed (
discord.Embed
) – the followup message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachfile (
discord.File
) – a file to attach to the messagefiles (List[
discord.File
]) – a list of files to attach to the messagecomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationephemeral (
bool
) – if set toTrue
, your message will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this messageusername (
str
) – override the default bot nameavatar_url (
str
) – override the default avatar of the bot
- async reply(content=None, *, embed=None, embeds=None, components=None, view=None, file=None, files=None, tts=False, hide_user_input=False, ephemeral=False, delete_after=None, allowed_mentions=None, type=None, fetch_response_message=True)
Creates an interaction response. What’s the difference between this method and
create_response()
? If the token is no longer valid, this method sends a usual channel message instead of creating an interaction response. Also, this method fetches the interaction response message and returns it, unlikecreate_response()
.- Parameters
content (
str
) – message contentembed (
discord.Embed
) – message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachcomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationfile (
discord.File
) – if it’s the first interaction reply, the file will be ignored due to API limitations. Everything else is the same as indiscord.TextChannel.send()
method.files (List[
discord.File
]) – same asfile
but for multiple files.hide_user_input (
bool
) – if set toTrue
, user’s input won’t be displayedephemeral (
bool
) – if set toTrue
, your response will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notdelete_after (
float
) – if specified, your reply will be deleted afterdelete_after
secondsallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.type (
int
|ResponseType
) – sets the response type. If it’s not specified, this method sets it according tohide_user_input
,content
andembed
params.fetch_response_message (
bool
) – whether to fetch and return the response message. Defaults toTrue
.
- Raises
HTTPException – sending the response failed
InvalidArgument – Both
embed
andembeds
are specified
- Returns
message – The response message that has been sent or
None
if the message is ephemeral- Return type
discord.Message
|None
BotMissingAnyRole
- class dislash.BotMissingAnyRole(missing_roles)
BotMissingPermissions
- class dislash.BotMissingPermissions(missing_perms, *args)
BotMissingRole
- class dislash.BotMissingRole(missing_role)
BucketType
MessageInteraction
- class dislash.MessageInteraction(client, data)
Represents a button interaction. Obtainable via
discord.Context.wait_for_button_click
and inon_button_click
event.- author
The user that clicked the button
- Type
discord.Member
|discord.User
- channel
The channel where the click happened
- Type
discord.Messageable
- guild
The guild where the click happened
- Type
discord.Guild
|None
- message
The message where the button was clicked
- Type
discord.Message
- async create_response(content=None, *, type=None, embed=None, embeds=None, components=None, view=None, ephemeral=False, tts=False, allowed_mentions=None)
Creates an interaction response.
- Parameters
content (
str
) – response contenttype (
int
|ResponseType
) – sets the response type. SeeResponseType
embed (
discord.Embed
) – response embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachcomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationephemeral (
bool
) – if set toTrue
, your response will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.
- Raises
HTTPException – sending the response failed
InvalidArgument – Both
embed
andembeds
are specified
- async delete()
Deletes the original interaction response.
- async delete_after(delay: float)
- async edit(content=None, *, embed=None, embeds=None, components=None, allowed_mentions=None)
Edits the original interaction response.
- Parameters
content (
str
) – New message contentembed (
discord.Embed
) – New message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds of a new messagecomponents (
List[ActionRow]
) – a list of up to 5 action rowsallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.
- Returns
message – The message that was edited
- Return type
discord.Message
- async fetch_initial_response()
Fetches the original interaction response.
- async followup(content=None, *, embed=None, embeds=None, file=None, files=None, components=None, view=None, tts=False, ephemeral=False, allowed_mentions=None, username=None, avatar_url=None)
Sends a followup message.
- Parameters
content (
str
) – the followup message contentembed (
discord.Embed
) – the followup message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachfile (
discord.File
) – a file to attach to the messagefiles (List[
discord.File
]) – a list of files to attach to the messagecomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationephemeral (
bool
) – if set toTrue
, your message will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this messageusername (
str
) – override the default bot nameavatar_url (
str
) – override the default avatar of the bot
- async reply(content=None, *, embed=None, embeds=None, components=None, view=None, file=None, files=None, tts=False, hide_user_input=False, ephemeral=False, delete_after=None, allowed_mentions=None, type=None, fetch_response_message=True)
Creates an interaction response. What’s the difference between this method and
create_response()
? If the token is no longer valid, this method sends a usual channel message instead of creating an interaction response. Also, this method fetches the interaction response message and returns it, unlikecreate_response()
.- Parameters
content (
str
) – message contentembed (
discord.Embed
) – message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachcomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationfile (
discord.File
) – if it’s the first interaction reply, the file will be ignored due to API limitations. Everything else is the same as indiscord.TextChannel.send()
method.files (List[
discord.File
]) – same asfile
but for multiple files.hide_user_input (
bool
) – if set toTrue
, user’s input won’t be displayedephemeral (
bool
) – if set toTrue
, your response will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notdelete_after (
float
) – if specified, your reply will be deleted afterdelete_after
secondsallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.type (
int
|ResponseType
) – sets the response type. If it’s not specified, this method sets it according tohide_user_input
,content
andembed
params.fetch_response_message (
bool
) – whether to fetch and return the response message. Defaults toTrue
.
- Raises
HTTPException – sending the response failed
InvalidArgument – Both
embed
andembeds
are specified
- Returns
message – The response message that has been sent or
None
if the message is ephemeral- Return type
discord.Message
|None
CheckAnyFailure
- class dislash.CheckAnyFailure(checks, errors)
ClickListener
- class dislash.ClickListener(message_id: int, timeout: Optional[float] = None)
Creates a nice click manager for a message. You can use this class, or call
discord.Message.create_click_listener(timeout)
in order to create an instance.Click manager allows to process button clicks under a specific message using decorator-based interface.
- Parameters
message_id (
int
) – the ID of the message with buttonstimeout (
float
) – the amount of seconds required after the last matched interaction for the click manager to finish working. Defaults toNone
, which means no timeout.
- from_user(user: discord.user.User, *, cancel_others: bool = False, reset_timeout: bool = True)
A decorator that makes the function below waiting for a click from the specified user.
Parameters are the same as in
matching_condition()
, exceptcheck
parameter is replaced with auser
to compare with.
- kill()
Kills the click manager. Only useful if the
timeout
param was specified asNone
.
- matching_condition(check, *, cancel_others: bool = False, reset_timeout: bool = True)
A decorator that makes the function below waiting for a click matching the specified conditions.
- Parameters
check (
function
) – the required condition. This function must take exactly one argument which is guaranteed to be an instance ofMessageInteraction
. This function must returnTrue
orFalse
.cancel_others (
bool
) – defaults toFalse
. Specifies whether to cancel all other local listeners or not. For example, if this parameter isFalse
, the library will activate all other listeners matching the interaction, untill all listeners are toggled or some of them cancels others.reset_timeout (
bool
) – defaults toTrue
. Specifies whether to restart the timer or not. By restarting the timer, you extend the lifespan of all local listeners.
- matching_id(custom_id: str, *, cancel_others: bool = False, reset_timeout: bool = True)
A decorator that makes the function below waiting for a click of the button matching the specified custom_id.
Parameters are the same as in
matching_condition()
, exceptcheck
parameter is replaced withcustom_id
.
- no_checks(*, cancel_others: bool = False, reset_timeout: bool = True)
A decorator that makes the function below waiting for any click.
Parameters are the same as in
matching_condition()
, except there’s nocheck
.
- not_from_user(user: discord.user.User, *, cancel_others: bool = False, reset_timeout: bool = True)
A decorator that makes the function below waiting for a click from a user not maching the specified one.
Parameters are the same as in
matching_condition()
, exceptcheck
parameter is replaced with auser
to compare with.
- timeout(func)
A decorator that makes the function below waiting for click listener timeout.
CommandOnCooldown
- class dislash.CommandOnCooldown(cooldown, retry_after)
Exception raised when the application command being invoked is on cooldown.
This inherits from ApplicationCommandError
## Attributes
cooldown: Cooldown (a class with attributes rate, per, and type)
retry_after: float (the amount of seconds to wait before you can retry again)
CommandParent
- class dislash.CommandParent(func, *, name=None, description=None, options=None, default_permission=True, guild_ids=None, connectors=None, auto_sync=True, **kwargs)
- error(func)
A decorator that makes the function below work as error handler for this command.
- get_cooldown_retry_after(inter)
Retrieves the amount of seconds before this slash command can be tried again.
- Parameters
inter (
SlashInteraction
) – The interaction to retrieve the cooldown from.- Returns
The amount of time left on this slash command’s cooldown in seconds. If this is
0.0
then the slash command isn’t on cooldown.- Return type
float
- async invoke(interaction)
- async invoke_children(interaction)
- is_on_cooldown(inter)
Checks whether the slash command is currently on cooldown.
- Parameters
inter (
SlashInteraction
) – The interaction to use when checking the commands cooldown status.- Returns
A boolean indicating if the slash command is on cooldown.
- Return type
bool
- reset_cooldown(inter)
Resets the cooldown on this slash command.
- Parameters
inter (
SlashInteraction
) – The interaction to reset the cooldown under.
- sub_command(name: Optional[str] = None, description: Optional[str] = None, options: Optional[list] = None, connectors: Optional[dict] = None, **kwargs)
A decorator that creates a subcommand under the base command.
- Parameters
name (
str
) – the name of the subcommand. Defaults to the function namedescription (
str
) – the description of the subcommandoptions (
list
) – the options of the subcommand for registration in APIconnectors (
dict
) – which function param states for each option. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template:{"option-name": "param_name", ...}
- sub_command_group(name=None, **kwargs)
A decorator that creates a subcommand group under the base command. Remember that the group must have at least one subcommand.
- Parameters
name (
str
) – the name of the subcommand group. Defaults to the function name
Component
- class dislash.Component(type: int)
The base class for message components
ComponentType
- class dislash.ComponentType
An enumerator for component types.
- ActionRow = 1
- Button = 2
- SelectMenu = 3
DiscordException
- class dislash.DiscordException
Base exception class for discord.py
Ideally speaking, this could be caught to handle any exceptions thrown from this library.
SlashInteraction
- class dislash.SlashInteraction(client, payload)
Every interaction with slash-commands is represented by instances of this class
- author
The member/user that used the slash-command.
- Type
discord.Member
|discord.User
- guild
The guild where interaction was created
- Type
discord.Guild
- channel
The channel where interaction was created
- Type
discord.TextChannel
- data
The arguments that were passed
- Type
InteractionData
- created_at
Then interaction was created
- Type
datetime.datetime
- expired
Whether the interaction token is still valid
- Type
bool
:
- async create_response(content=None, *, type=None, embed=None, embeds=None, components=None, view=None, ephemeral=False, tts=False, allowed_mentions=None)
Creates an interaction response.
- Parameters
content (
str
) – response contenttype (
int
|ResponseType
) – sets the response type. SeeResponseType
embed (
discord.Embed
) – response embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachcomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationephemeral (
bool
) – if set toTrue
, your response will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.
- Raises
HTTPException – sending the response failed
InvalidArgument – Both
embed
andembeds
are specified
- async delete()
Deletes the original interaction response.
- async delete_after(delay: float)
- async edit(content=None, *, embed=None, embeds=None, components=None, allowed_mentions=None)
Edits the original interaction response.
- Parameters
content (
str
) – New message contentembed (
discord.Embed
) – New message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds of a new messagecomponents (
List[ActionRow]
) – a list of up to 5 action rowsallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.
- Returns
message – The message that was edited
- Return type
discord.Message
- async fetch_initial_response()
Fetches the original interaction response.
- async followup(content=None, *, embed=None, embeds=None, file=None, files=None, components=None, view=None, tts=False, ephemeral=False, allowed_mentions=None, username=None, avatar_url=None)
Sends a followup message.
- Parameters
content (
str
) – the followup message contentembed (
discord.Embed
) – the followup message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachfile (
discord.File
) – a file to attach to the messagefiles (List[
discord.File
]) – a list of files to attach to the messagecomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationephemeral (
bool
) – if set toTrue
, your message will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this messageusername (
str
) – override the default bot nameavatar_url (
str
) – override the default avatar of the bot
- get(name: str, default=None)
Equivalent to
InteractionData.get
- get_option(name: str)
Equivalent to
InteractionData.get_option
- option_at(index: int)
Equivalent to
InteractionData.option_at
- async reply(content=None, *, embed=None, embeds=None, components=None, view=None, file=None, files=None, tts=False, hide_user_input=False, ephemeral=False, delete_after=None, allowed_mentions=None, type=None, fetch_response_message=True)
Creates an interaction response. What’s the difference between this method and
create_response()
? If the token is no longer valid, this method sends a usual channel message instead of creating an interaction response. Also, this method fetches the interaction response message and returns it, unlikecreate_response()
.- Parameters
content (
str
) – message contentembed (
discord.Embed
) – message embedembeds (
List[discord.Embed]
) – a list of up to 10 embeds to attachcomponents (
List[ActionRow]
) – a list of up to 5 action rowsview (
discord.ui.View
) – only usable with discord.py 2.0. Read more aboutView
in discord.py 2.0 official documentationfile (
discord.File
) – if it’s the first interaction reply, the file will be ignored due to API limitations. Everything else is the same as indiscord.TextChannel.send()
method.files (List[
discord.File
]) – same asfile
but for multiple files.hide_user_input (
bool
) – if set toTrue
, user’s input won’t be displayedephemeral (
bool
) – if set toTrue
, your response will only be visible to the command authortts (
bool
) – whether the message is text-to-speech or notdelete_after (
float
) – if specified, your reply will be deleted afterdelete_after
secondsallowed_mentions (
discord.AllowedMentions
) – controls the mentions being processed in this message.type (
int
|ResponseType
) – sets the response type. If it’s not specified, this method sets it according tohide_user_input
,content
andembed
params.fetch_response_message (
bool
) – whether to fetch and return the response message. Defaults toTrue
.
- Raises
HTTPException – sending the response failed
InvalidArgument – Both
embed
andembeds
are specified
- Returns
message – The response message that has been sent or
None
if the message is ephemeral- Return type
discord.Message
|None
InteractionCheckFailure
- class dislash.InteractionCheckFailure(message=None, *args)
InteractionClient
- class dislash.InteractionClient(client, *, test_guilds: Optional[List[int]] = None, sync_commands: bool = True, show_warnings: bool = True, modify_send: bool = True)
The main purpose of this class is to track
INTERACTION_CREATE
API event.- Parameters
client (
commands.Bot
|commands.AutoShardedBot
) – The discord.py Bot instanceshow_warnings (
bool
) – Whether to show the warnings or not. Defaults toTrue
modify_send (
bool
) – Whether to modifyMessageable.send
andMessage.edit
. Modified methods allow to specify thecomponents
parameter.
- client
an instance of any class inherited from
discord.Client
- Type
commands.Bot
|commands.AutoShardedBot
- application_id
the ID of the application your bot is related to
- Type
int
- global_commands
All registered global application commands
- Type
List[
ApplicationCommand
]
- slash_commands
All invokable slash commands from your code
- Type
Dict[str, CommandParent]
- user_commands
All invokable user commands from your code
- Type
Dict[str, InvokableUserCommand]
- message_commands
All invokable message commands from your code
- Type
Dict[str, InvokableMessageCommand]
- commands
All invokable application commands from your code
- Type
Dict[str, InvokableApplicationCommand]
- is_ready
Equals to
True
if SlashClient is ready, otherwise it’sFalse
- Type
bool
- async batch_edit_guild_command_permissions(guild_id: int, permissions: dict)
Batch edits permissions for all commands in a guild.
- Parameters
guild_id (
int
) – the ID of the guildpermissions (Dict[
int
,ApplicationCommandPermissions
]) – a dictionary of command IDs and permissions
- async batch_fetch_guild_command_permissions(guild_id: int)
Fetches command permissions for all commands in a guild.
- Parameters
guild_id (
int
) – the ID of the guild
- async delete_global_command(command_id: int)
Deletes the global application command
- Parameters
command_id (int) –
- async delete_global_command_named(name: str)
Deletes a global command matching the specified name.
- Parameters
name (str) – the name of the command to delete
- async delete_global_commands()
Deletes all global commands.
- async delete_guild_command(guild_id: int, command_id: int)
Deletes the local application command
- Parameters
guild_id (int) –
command_id (int) –
- async delete_guild_command_named(guild_id: int, name: str)
Deletes a local command matching the specified name.
- Parameters
guild_id (int) – ID of the guild where the command is registered
name (str) – the name of the command to edit
- async delete_guild_commands(guild_id: int)
Deletes all local commands in the specified guild.
- Parameters
guild_id (int) – the ID of the guild where you’re going to delete the commands
- dispatch(event_name, *args, **kwargs)
- async edit_global_command(command_id: int, app_command: dislash.interactions.application_command.ApplicationCommand, **kwargs)
Edits a global application command
- Parameters
command_id (int) –
app_command (ApplicationCommand) – replacement of the old data
- async edit_global_command_named(name: str, app_command: dislash.interactions.application_command.ApplicationCommand)
Edits a global command matching the specified name.
- Parameters
name (str) – the name of the command to edit
app_command (ApplicationCommand) – replacement of the old data
- async edit_guild_command(guild_id: int, command_id: int, app_command: dislash.interactions.application_command.ApplicationCommand, **kwargs)
Edits the local application command
- Parameters
guild_id (int) –
command_id (int) –
app_command (ApplicationCommand) – replacement of the old data
- async edit_guild_command_named(guild_id: int, name: str, app_command: dislash.interactions.application_command.ApplicationCommand)
Edits a local command matching the specified name.
- Parameters
guild_id (int) – ID of the guild where the command is registered
name (str) – the name of the command to edit
app_command (ApplicationCommand) – replacement of the old data
- async edit_guild_command_permissions(guild_id: int, command_id: int, permissions: dislash.interactions.application_command.ApplicationCommandPermissions)
Edits command permissions for a specific command in a guild.
- Parameters
guild_id (
int
) – the ID of the guildcommand_id (
int
) – the ID of the commandpermissions (
SlashCommandPermissions
|dict
) – new permissions to set. If you useSlashCommandPermissions.from_pairs
, you can pass the arg of that method straight into this function
- event(func)
Decorator
@slash.event async def on_ready(): print("SlashClient is ready")
All possible events:on_ready
,on_auto_register
,on_slash_command
,on_slash_command_error
- async fetch_global_command(command_id: int)
Requests a registered global command
- Parameters
command_id (int) –
- Returns
global_command
- Return type
- async fetch_global_command_named(name: str)
Fetches a global command that matches the specified name
- Parameters
name (str) – the name of the command to fetch
- async fetch_global_commands()
Requests a list of global registered commands from the API
- Returns
global_commands
- Return type
List[ApplicationCommand]
- async fetch_guild_command(guild_id: int, command_id: int)
Requests a registered guild command
- Parameters
guild_id (int) –
command_id (int) –
- Returns
guild_command
- Return type
- async fetch_guild_command_named(guild_id: int, name: str)
Fetches a guild command that matches the specified name
- Parameters
guild_id (int) – ID of the guild where the command is registered
name (str) – the name of the command to fetch
- async fetch_guild_command_permissions(guild_id: int, command_id: int)
Fetches command permissions for a specific command in a guild.
- Parameters
guild_id (
int
) – the ID of the guildcommand_id (
int
) – the ID of the command
- async fetch_guild_commands(guild_id: int)
Requests a list of registered commands for a specific guild
- Parameters
guild_id (int) –
- Returns
guild_commands
- Return type
List[ApplicationCommand]
- get_global_command(command_id: int)
Get a cached global command
- Parameters
command_id (int) – the ID of the command
- Returns
slash_command
- Return type
SlashCommand | None
- get_global_command_named(name: str)
Get a cached global command matching the specified name
- Parameters
name (str) – the name of the command
- Returns
slash_command
- Return type
SlashCommand | None
- get_guild_command(guild_id: int, command_id: int)
Get a cached guild command
- Parameters
guild_id (int) – the ID of the guild
command_id (int) – the ID of the command
- Returns
slash_command
- Return type
SlashCommand | None
- get_guild_command_named(guild_id: int, name: str)
Get a cached guild command matching the specified name
- Parameters
guild_id (int) – the ID of the guild
name (str) – the name of the command
- Returns
slash_command
- Return type
SlashCommand | None
- get_guild_commands(guild_id: int)
Get cached guild commands
- Parameters
guild_id (int) – the ID of the guild
- Returns
- Return type
~:class:List[ApplicationCommand]
- message_command(*args, **kwargs)
- async multiple_wait_for(events_and_checks: Dict[str, Any], timeout: Optional[float] = None)
Waits until one of the given events toggles and matches the relevant check.
Example:
result = None try: result = await client.multiple_wait_for( { "message": lambda msg: msg.author == ctx.author, "reaction_add": lambda react, user: user == ctx.author }, timeout=60 ) except asyncio.TimeoutError: await ctx.send("It took too long") if isinstance(result, discord.Message): # on_message was toggled await ctx.send(f"You said '{result.content}'") else: # on_reaction_add was toggled reaction, user = result await ctx.send(f"Your reaction: {reaction.emoji}")
- Parameters
events_and_checks (Dict[
str
,function | None
]) – a dictionary of event names and relevant checks, e.g.{"message": lambda m: m.author == ctx.author, "button_click": None}
timeout (
float
|None
) – the amount of seconds the bot should wait for any of the given events
- async overwrite_global_commands(app_commands: list)
Bulk overwrites all global application commands
- Parameters
app_commands (List[ApplicationCommand]) –
- async overwrite_guild_commands(guild_id: int, app_commands: list)
Bulk overwrites all guild application commands
- Parameters
guild_id (int) –
app_commands (List[ApplicationCommand]) –
- async register_global_command(app_command: dislash.interactions.application_command.ApplicationCommand)
Registers a global application command
- Parameters
app_command (ApplicationCommand) –
- async register_guild_command(guild_id: int, app_command: dislash.interactions.application_command.ApplicationCommand)
Registers a local application command
- Parameters
guild_id (
int
) –app_command (
ApplicationCommand
) –
- slash_command(*args, **kwargs)
A decorator that allows to build a slash command.
- Parameters
auto_sync (
bool
) – whether to automatically register the command or not. Defaults toTrue
name (
str
) – name of the slash command you want to respond to (equals to function name by default).description (
str
) – the description of the slash command. It will be visible in Discord.options (
List[Option]
) – the list of slash command options. The options will be visible in Discord.default_permission (
bool
) – whether the command is enabled by default when the app is added to a guild.guild_ids (
List[int]
) – if specified, the client will register a command in these guilds. Otherwise this command will be registered globally.connectors (
dict
) – which function param states for each option. If the name of an option already matches the corresponding function param, you don’t have to specify the connectors. Connectors template:{"option-name": "param_name", ...}
- teardown()
Cleanup the client by removing all registered listeners and caches.
- user_command(*args, **kwargs)
- async wait_for_button_click(check=None, timeout=None)
- async wait_for_dropdown(check=None, timeout=None)
InteractionDataOption
- class dislash.InteractionDataOption(*, data, resolved: dislash.interactions.app_command_interaction.Resolved)
Represents user’s input for a specific option
- name
The name of the option
- Type
str
- value
The value of the option
- Type
Any
- options
- Represents options of a sub-slash-command.{
name
:InteractionDataOption
, …}- Type
dict
- get(name: str, default=None)
Get the value of an option with the specified name
- Parameters
name (str) – the name of the option you want to get
default (any) – what to return in case nothing was found
- Returns
option_value (any) – The option type isn’t
SUB_COMMAND_GROUP
orSUB_COMMAND
option (InteractionDataOption |
default
) – Otherwise
- get_option(name: str)
Get the raw
InteractionDataOption
matching the specified name- Parameters
name (str) – The name of the option you want to get
- Returns
option
- Return type
InteractionDataOption |
None
- option_at(index: int)
Similar to
InteractionData.option_at
InteractionType
- class dislash.InteractionType
InvokableApplicationCommand
- class dislash.InvokableApplicationCommand(func, *, name=None, **kwargs)
- error(func)
A decorator that makes the function below work as error handler for this command.
- get_cooldown_retry_after(inter)
Retrieves the amount of seconds before this slash command can be tried again.
- Parameters
inter (
SlashInteraction
) – The interaction to retrieve the cooldown from.- Returns
The amount of time left on this slash command’s cooldown in seconds. If this is
0.0
then the slash command isn’t on cooldown.- Return type
float
- is_on_cooldown(inter)
Checks whether the slash command is currently on cooldown.
- Parameters
inter (
SlashInteraction
) – The interaction to use when checking the commands cooldown status.- Returns
A boolean indicating if the slash command is on cooldown.
- Return type
bool
- reset_cooldown(inter)
Resets the cooldown on this slash command.
- Parameters
inter (
SlashInteraction
) – The interaction to reset the cooldown under.
InvokableMessageCommand
- class dislash.InvokableMessageCommand(func, *, name=None, guild_ids=None, **kwargs)
- error(func)
A decorator that makes the function below work as error handler for this command.
- get_cooldown_retry_after(inter)
Retrieves the amount of seconds before this slash command can be tried again.
- Parameters
inter (
SlashInteraction
) – The interaction to retrieve the cooldown from.- Returns
The amount of time left on this slash command’s cooldown in seconds. If this is
0.0
then the slash command isn’t on cooldown.- Return type
float
- async invoke(interaction)
- is_on_cooldown(inter)
Checks whether the slash command is currently on cooldown.
- Parameters
inter (
SlashInteraction
) – The interaction to use when checking the commands cooldown status.- Returns
A boolean indicating if the slash command is on cooldown.
- Return type
bool
- reset_cooldown(inter)
Resets the cooldown on this slash command.
- Parameters
inter (
SlashInteraction
) – The interaction to reset the cooldown under.
InvokableUserCommand
- class dislash.InvokableUserCommand(func, *, name=None, guild_ids=None, **kwargs)
- error(func)
A decorator that makes the function below work as error handler for this command.
- get_cooldown_retry_after(inter)
Retrieves the amount of seconds before this slash command can be tried again.
- Parameters
inter (
SlashInteraction
) – The interaction to retrieve the cooldown from.- Returns
The amount of time left on this slash command’s cooldown in seconds. If this is
0.0
then the slash command isn’t on cooldown.- Return type
float
- async invoke(interaction)
- is_on_cooldown(inter)
Checks whether the slash command is currently on cooldown.
- Parameters
inter (
SlashInteraction
) – The interaction to use when checking the commands cooldown status.- Returns
A boolean indicating if the slash command is on cooldown.
- Return type
bool
- reset_cooldown(inter)
Resets the cooldown on this slash command.
- Parameters
inter (
SlashInteraction
) – The interaction to reset the cooldown under.
SelectOption
- class dislash.SelectOption(label: str, value: str, description: Optional[str] = None, emoji: Optional[str] = None, default: bool = False)
This class represents an option in a select menu.
- Parameters
label (
str
) – the user-facing name of the option, max 25 charactersvalue (
str
) – the dev-define value of the option, max 100 charactersdescription (
str
) – an additional description of the option, max 50 charactersemoji (
str
) – well add an emoji to the optiondefault (
bool
) – will render this option as selected by default
- classmethod from_dict(data: dict)
- to_dict()
MessageCommand
MissingAnyRole
- class dislash.MissingAnyRole(missing_roles)
MissingPermissions
- class dislash.MissingPermissions(missing_perms, *args)
MissingRole
- class dislash.MissingRole(missing_role)
NSFWChannelRequired
- class dislash.NSFWChannelRequired(channel)
NoPrivateMessage
- class dislash.NoPrivateMessage(message=None)
NotGuildOwner
- class dislash.NotGuildOwner(message=None, *args)
NotOwner
- class dislash.NotOwner(message=None, *args)
Option
- class dislash.Option(name: str, description: Optional[str] = None, type: Optional[int] = None, required: bool = False, choices: Optional[List[dislash.interactions.application_command.OptionChoice]] = None, options: Optional[list] = None)
- Parameters
name (
str
) – option’s namedescription (
str
) – option’s descriptiontype (
Type
) – the option type, e.g.Type.USER
, see OptionTyperequired (
bool
) – whether this option is required or notchoices (List[
OptionChoice
]) – the list of option choices, type OptionChoiceoptions (List[
Option
]) – the list of sub options. You can only specify this parameter if thetype
isType.SUB_COMMAND
orType.SUB_COMMAND_GROUP
- add_choice(name: str, value: Any)
Adds an OptionChoice to the list of current choices
Parameters are the same as for
OptionChoice
- add_option(name: str, description: Optional[str] = None, type: Optional[int] = None, required: bool = False, choices: Optional[List[dislash.interactions.application_command.OptionChoice]] = None, options: Optional[list] = None)
Adds an option to the current list of options
Parameters are the same as for
Option
- classmethod from_dict(payload: dict)
- to_dict()
OptionChoice
- class dislash.OptionChoice(name: str, value: Any)
- Parameters
name (str) – the name of the option-choice (visible to users)
value (str or int) – the value of the option-choice
OptionType
- class dislash.OptionType
- SUB_COMMAND = 1
- SUB_COMMAND_GROUP = 2
- STRING = 3
- INTEGER = 4
- BOOLEAN = 5
- USER = 6
- CHANNEL = 7
- ROLE = 8
- MENTIONABLE = 9
- NUMBER = 10
PrivateMessageOnly
- class dislash.PrivateMessageOnly(message=None)
RawCommandPermission
- class dislash.RawCommandPermission(id: int, type: int, permission: bool)
Represents command permissions for a role or a user.
- id
ID of a target
- Type
int
- type
1 if target is a role; 2 if target is a user
- Type
int
- permission
allow or deny the access to the command
- Type
bool
- classmethod from_dict(data: dict)
- classmethod from_pair(target: Union[discord.role.Role, discord.user.User], permission: bool)
- to_dict()
ResponseType
- class dislash.ResponseType
All possible response type values. Used in
Interaction.reply
- Pong = 1
ACK a Ping
- ChannelMessageWithSource = 4
Respond to an interaction with a message
- AcknowledgeWithSource = 5
ACK an interaction and edit a response later, the user sees a loading state
- DeferredUpdateMessage = 6
For components, ACK an interaction and edit the original message later; the user does not see a loading state
- UpdateMessage = 7
For components, edit the message the component was attached to
SlashCommand
- class dislash.SlashCommand(name: str, description: str, options: Optional[list] = None, default_permission: bool = True, **kwargs)
A base class for building slash-commands.
- Parameters
- add_option(name: str, description: Optional[str] = None, type: Optional[int] = None, required: bool = False, choices: Optional[List[dislash.interactions.application_command.OptionChoice]] = None, options: Optional[list] = None)
Adds an option to the current list of options
Parameters are the same as for
Option
- classmethod from_dict(payload: dict)
- to_dict(*, hide_name=False)
SlashInteractionData
- class dislash.SlashInteractionData(*, data, guild, state)
- id
The id of the interaction
- Type
int
- name
The name of activated slash-command
- Type
str
- options
- Represents options of the slash-command.{
name
:InteractionDataOption
, …}- Type
dict
- resolved
The collection of related objects, such as users, members, roles, channels and messages
- Type
Resolved
- get(name: str, default=None)
Get the value of an option with the specified name
- Parameters
name (str) – the name of the option you want to get
default (any) – what to return in case nothing was found
- Returns
option_value (any) – The option type isn’t
SUB_COMMAND_GROUP
orSUB_COMMAND
option (
InteractionDataOption
|default
) – Otherwise
- get_option(name: str)
Get the raw
InteractionDataOption
matching the specified name- Parameters
name (str) – The name of the option you want to get
- Returns
option
- Return type
InteractionDataOption
|None
- option_at(index: int)
Get an option by it’s index
- Parameters
index (int) – the index of the option you want to get
- Returns
option – the option located at the specified index
- Return type
InteractionDataOption
|None
SubCommand
- class dislash.SubCommand(func, *, name=None, description=None, options=None, connectors=None, **kwargs)
- error(func)
A decorator that makes the function below work as error handler for this command.
- get_cooldown_retry_after(inter)
Retrieves the amount of seconds before this slash command can be tried again.
- Parameters
inter (
SlashInteraction
) – The interaction to retrieve the cooldown from.- Returns
The amount of time left on this slash command’s cooldown in seconds. If this is
0.0
then the slash command isn’t on cooldown.- Return type
float
- is_on_cooldown(inter)
Checks whether the slash command is currently on cooldown.
- Parameters
inter (
SlashInteraction
) – The interaction to use when checking the commands cooldown status.- Returns
A boolean indicating if the slash command is on cooldown.
- Return type
bool
- reset_cooldown(inter)
Resets the cooldown on this slash command.
- Parameters
inter (
SlashInteraction
) – The interaction to reset the cooldown under.
SubCommandGroup
- class dislash.SubCommandGroup(func, *, name=None, **kwargs)
- error(func)
A decorator that makes the function below work as error handler for this command.
- get_cooldown_retry_after(inter)
Retrieves the amount of seconds before this slash command can be tried again.
- Parameters
inter (
SlashInteraction
) – The interaction to retrieve the cooldown from.- Returns
The amount of time left on this slash command’s cooldown in seconds. If this is
0.0
then the slash command isn’t on cooldown.- Return type
float
- is_on_cooldown(inter)
Checks whether the slash command is currently on cooldown.
- Parameters
inter (
SlashInteraction
) – The interaction to use when checking the commands cooldown status.- Returns
A boolean indicating if the slash command is on cooldown.
- Return type
bool
- reset_cooldown(inter)
Resets the cooldown on this slash command.
- Parameters
inter (
SlashInteraction
) – The interaction to reset the cooldown under.
- sub_command(name: Optional[str] = None, description: Optional[str] = None, options: Optional[list] = None, connectors: Optional[dict] = None, **kwargs)
A decorator that creates a subcommand in the subcommand group.
Parameters are the same as in
CommandParent.sub_command