Reference
Components V2, modals and slash commands for discord.py, through direct Discord API calls.
Buttons
create_buttonCreates a button. Values passed indatatravel inside thecustom_idand come back on click.create_link_buttonButton that opens a URL. No event reaches the bot.create_premium_buttonPurchase button for one of your application's SKUs (Discord monetization).
Select menus
create_channel_select_menuChannel select menu, filterable by type.create_entity_select_menuGeneric entity select menu: users (5), roles (6), mentionables (7) or channels (8).create_mentionable_select_menuSelect menu mixing users and roles.create_role_select_menuRole select menu.create_select_menuText select menu (25 options max). Options accept dicts, tuples or strings.create_user_select_menuUser or member select menu.default_valuePre-selected value of an entity select menu.select_optionOption for a select menu, a radio group or a checkbox group.
Builders
ActionRowBuilderAction row builder.ContainerBuilderChainable container V2 builder. Every method returns the builder; finish withbuild().FileBuilderAttached file builder.MediaGalleryBuilderGallery builder;add()appends an image with alt text or spoiler.SectionBuilderSection builder: texts on the left, button or thumbnail on the right.SeparatorBuilderSeparator builder.TextDisplayBuilderText block builder.ThumbnailBuilderThumbnail builder.actionRowShortcut forActionRowBuilder(*components).containerShortcut forContainerBuilder(...).fileComponentShortcut forFileBuilder(filename, spoiler).mediaGalleryShortcut forMediaGalleryBuilder(*urls).sectionShortcut forSectionBuilderwith its texts.separatorShortcut forSeparatorBuilder(divider, spacing).textDisplayShortcut forTextDisplayBuilder(content).thumbnailShortcut forThumbnailBuilder(url, description, spoiler).
Components V2
create_action_rowAction row (type 1): up to 5 buttons or a single select menu.create_button_rowRow of buttons. Same ascreate_action_row.create_containerContainer (type 17): the card grouping components V2. A string becomes a text block.create_fileAttached file shown in the message (type 13). Send the file itself withfiles=.create_media_galleryGallery of 1 to 10 images or videos (type 12).create_media_itemGallery item: media, alt text and spoiler.create_modal_rowModal row in the legacy format (ActionRow + TextInput).create_sectionSection (type 9): 1 to 3 texts with an accessory, button or thumbnail.create_select_rowRow holding a select menu.create_separatorSeparator (type 14): divider line and vertical spacing.create_text_display_componentMarkdown text block (type 10), up to 4000 characters.create_thumbnailThumbnail (type 11), used as the accessory of a section.disable_all_componentsCopy of the components with every button and select disabled, at any depth.
Modal fields
create_checkboxSingle yes or no checkbox. Always optional.create_checkbox_groupCheckbox group (1 to 10 options, multiple choices).create_file_upload_componentFile upload inside a modal (0 to 10 files), filterable by type.create_label_componentLabel (type 18): title and description around a modal field. The modern format recommended by Discord.create_modalComplete modal as a dict. Bare fields are wrapped in a Label automatically.create_radio_groupRadio group (2 to 10 options, single choice).create_text_inputModal text field, short or paragraph.
Types and constants
ButtonStyleButton styles:Primary(1),Secondary(2),Success(3),Danger(4),Link(5) andPremium(6).ComponentTypeType numbers of every Discord component, from action row (1) to checkbox (23).SeparatorSpacingSeparator spacing:Small(1) orLarge(2).TextInputStyleText input style:Short(single line) orParagraph(multiple lines).create_componentRaw component:{"type": component_type, **fields}. Handy for a type the module does not cover yet.
Building modals
ModalBuilderModern modal builder: every field sits in a Label with a title and description. 5 components max.
Reading values
ModalSubmitSubmitted values keyed bycustom_id. Text and radio asstr, checkbox asbool, everything else aslist.get_modal_valuesModal values as a{custom_id: value}dict.parse_modalReads the values of a submitted modal. Same asparse_values.parse_valuesReads the values of a modal or a select menu, with entities and files resolved.
Sending and replying
defer_interactionAcknowledges now to answer later (15 minutes). On a component,update=Trueshows nothing.delete_original_responseDeletes the original response, or a followup withmessage_id.edit_messageEdits an existing message. Attachments are kept whenattachmentsis omitted.edit_original_responseEdits the original response, or a followup withmessage_id.get_original_responseFetches the original response (API dict), for example to get its ID.respondResponds to the interaction, or sends a followup if it was already answered.respond_to_interactionInitial interaction response. Withupdate=True, edits the message of the clicked component.send_followupFollowup message after a response or a defer.send_messageSends a message to a channel, a thread, a context, a member's DMs, or as an interaction response.send_modalOpens a modal. Accepts aModalBuilder, acreate_modaldict or the three separate arguments.update_messageEdits the message of the clicked component. Shortcut forrespond_to_interaction(..., update=True).
Updating components
DisableAllHandleDisable timer:refresh(),cancel(),force_disable(),is_active().add_componentInserts components into a builder or a container dict.disable_allDisables every component of a message, now or after a delay.disable_all_by_message_idLikedisable_all, from a channel and a message ID.disable_buttonsCopy of the components with buttons and selects disabled; Link buttons stay active.remove_componentRemoves the matching components; rows left empty disappear too.row_updateTransforms every component of one or more rows with a function.row_update_oneLikerow_update, but only when exactly one row matches.update_componentReloads the message, then updates every matching component.update_component_oneLikeupdate_component, but only when exactly one component matches.
Payloads
MessageFlagsMessage flags:EPHEMERAL,IS_COMPONENTS_V2,SUPPRESS_EMBEDS,SUPPRESS_NOTIFICATIONSand the other API flags.build_message_payloadBuilds a message payload for any endpoint. AddsIS_COMPONENTS_V2and turnscontentinto a text block when needed.parse_allowed_mentionsNormalizes allowed mentions: discord.py object, API payload, discord.js style or boolean switches.
Routing
InteractionRouterRoutes buttons, select menus and modals to handlers by thebase_idof theircustom_id.
Signed custom_id
build_signed_custom_idcustom_idsigned with HMAC-SHA256, with optional expiry. Cannot be forged without the secret.create_auto_rowsPlaces buttons and select menus into valid rows automatically.create_signed_buttonButton with a signedcustom_id.parse_signed_custom_idVerifies a signedcustom_id. Returns(base_id, data, valid, reason).respond_or_followupInitial response when possible, otherwise a followup.
Shortcuts
quick_buttonOne-line button.quick_containerComplete container in one call: title, lines, thumbnail, section button or row of buttons.quick_rowRow of buttons:quick_row(b1, b2)orquick_row([b1, b2]).quick_send_containerSends aquick_containerdirectly.
custom_id
build_custom_idbase_id:dataas compact JSON in url-safe base64. Raises past 100 characters.decode_dataDecodescustom_iddata; returns{}when invalid.encode_dataEncodes a dict as compact JSON in url-safe base64 without padding.get_base_custom_idPart of acustom_idbefore the first:.parse_custom_idSplits acustom_idinto(base_id, data). Also reads the legacy format.
HTTP
CallbackTypeInteraction response types: message (4), deferred (5, 6), update (7), autocomplete (8), modal (9).
Slash commands
SlashCommandA declared command. Created by@slash.command().SlashCommandManagerEntry point for slash commands: declaration, execution, autocomplete and sync. Alias:SlashManager.SlashGroupCommand group:/group subcommandor/group subgroup subcommand.optionDecorator: adds an option to the command. Writing order is kept.optionsDecorator: adds several options at once.
Context
SlashContextCommand context: interaction, author, channel, options and response methods.create_contextCreates aSlashContext(internal use or tests).
Options
AttachmentOptionAttachment option (created byAttachment).BooleanOptionBoolean option (created byBoolean).ChannelOptionChannel option (created byChannel).ChoiceFixed choice of an option.IntegerOptionInteger option (created byInteger).MentionableOptionMentionable option (created byMentionable).NumberOptionDecimal option (created byNumber).OptionBaseCommon base of options.RoleOptionRole option (created byRole).StringOptionText option (created byString).UserOptionUser option (created byUser).ChannelTypesChannel types and ready-made groups:TEXT_CHANNELS,VOICE_CHANNELS,THREAD_CHANNELS,ALL_TEXT.OptionTypeAPI option types.AttachmentAttachment option.file_typesfilters on Discord's side,allowed_extensionsandmax_sizeon the bot's side.BooleanTrue or false option.ChannelChannel option, filterable by type.IntegerInteger option with bounds, step, choices and autocomplete.MentionableUser or role option.NumberDecimal option with bounds and rounding.RoleRole option. The value arrives asdiscord.Role.StringText option with length, choices, regex and autocomplete.UserUser option. The value arrives asdiscord.Member(ordiscord.Useroutside guilds).
Permissions
PermissionConfigEvery restriction of a command, filled by the decorators.IntegrationTypeInstallation types:GUILD_INSTALL,USER_INSTALL.InteractionContextUsage contexts:GUILD,BOT_DM,PRIVATE_CHANNEL.PermissionsDiscord permission flags, up toPIN_MESSAGESandBYPASS_SLOWMODE.allowed_channelsRestricts the command to some channels.allowed_guildsRestricts the command to some guilds.blocked_channelsForbids the command in some channels.bot_has_permissionsRequires bot permissions in the channel.checkAdds a custom async check(interaction) -> bool.check_permissionsChecks every restriction. Returns(allowed, message).contextsWhere the command can be used: guilds, DMs with the bot, private groups.default_permissionsHides the command from members lacking these permissions, directly in Discord.dm_onlyCommand usable in direct messages only.guild_onlyCommand usable in guilds only.has_permissionsRequires user permissions in the channel:@has_permissions(manage_messages=True).integration_typesInstallation types: guild, user, or both.nsfwCommand restricted to NSFW channels.owner_onlyCommand restricted to the bot owners.require_rolesRequires one of the given roles, or all of them withrequire_all=True.time_restrictedRestricts the command to some hours (UTC).user_installableCommand installable by users and usable everywhere.
Cooldowns
CooldownBucketSliding window of a cooldown.acquire()checks and consumes in one step.DynamicCooldownCooldown whose duration is computed on every call.SharedCooldownCooldown shared between several commands.CooldownTypeCooldown scopes.channel_cooldownPer-channel cooldown.cooldownRate-limits a command:@cooldown(1, 5)allows one use every 5 seconds per user.global_cooldownCooldown shared by everyone.guild_cooldownPer-guild cooldown.member_cooldownPer-member cooldown (user within a guild).user_cooldownPer-user cooldown.
Autocomplete
AutocompleteContextAutocomplete context: current input (value), option and other filled options.AutocompleteRegistryInternal registry of autocomplete functions.autocomplete_handlerMarks a function as the autocomplete of a command.chainCombines several autocompletes, without duplicates.conditionalPicks an autocomplete depending on the context.filter_choicesFilters and ranks choices against the input: exact, prefix, contains, then fuzzy.from_coroutineAutocomplete from an async function, with optional caching.from_dictAutocomplete from a{label: value}dict.from_listAutocomplete from a list of strings.
Middlewares
MiddlewareBefore, after and error hooks, filterable per command.MiddlewareStackStack of middlewares sorted by priority.MiddlewarePhaseMiddleware execution phases.analytics_middlewareSends one usage event per command to your function.error_handler_middlewareGlobal error handling with a message to the user.logging_middlewareLogs every command, its options and its duration.maintenance_middlewareMaintenance mode: blocks commands except for some users.ratelimit_middlewareGlobal anti-spam: maximum commands per minute.timing_middlewareReports commands slower than a threshold.
Localization
LocalizationTranslations for command names, descriptions and choices.LocalizedStringTranslated string built on the fly:L("Bonjour").en_US("Hello").TranslationSetTranslations of one key in several locales.create_common_localizationLocalizationpre-filled with the common translations.LShortcut forLocalizedString.
Sync
CommandSyncFine-grained sync: targeted read, create, update and delete of commands.SyncResultSync report: created, updated, deleted, errors.SyncModeSync strategies.
Errors
AutocompleteErrorAn autocomplete failed.BotMissingPermissionsMissing bot permissions.CheckFailureA@checkfailed.CommandDisabledCommand disabled.CommandNotFoundUnknown command.CommandOnCooldownCommand on cooldown;retry_aftergives the wait in seconds.InvalidOptionOption value rejected by validation.MaxConcurrencyToo many simultaneous runs.MiddlewareErrorA middleware failed.MissingPermissionsMissing user permissions.NotInGuildCommand restricted to guilds.NotOwnerCommand restricted to owners.NSFWChannelRequiredCommand restricted to NSFW channels.SlashCommandErrorBase of every slash command error.
Pseudo containers (deprecated)
PseudoContainerBuilderDeprecated: container imitation built with embeds. Usecontainer().PseudoSectionBuilderDeprecated.PseudoTextDisplayBuilderDeprecated.pseudoContainerDeprecated: usecontainer().pseudoSectionDeprecated: usesection().pseudoTextDisplayDeprecated: usetextDisplay().
Other
COMMON_TRANSLATIONSCommon ready-made translations.LOCALESLocale codes supported by Discord.