Перейти к содержимому

Как зарегать слэш команду боту дискорд

  • автор:

Name already in use

discord-py-guide / slash-commands.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

1 contributor

Users who have contributed to this file

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Если вы только начали изучать работу с библиотекой, то рекомендую сначала изучить основное руководство или хотя бы основы prefix-команд

На этом этапе надо отметить, что discord-py — устаревшая библиотека, которая не обновляется под новые фишки дискорда. Поэтому для работы со slash-командами, кнопками и выпадающими списками стоит удалить старую библиотеку и установить ее форк PyCord :

В целом, вся структура классов, их свойств и методов в PyCord осталась такой же как в discord-py , поэтому ничего менять и переписывать не нужно. Поэтому к PyCord подойдет документация от discord-py , но я все же рекомендую пользоваться документацией именно от PyCord

Для реализации slash-команд, в качестве объекта бота можно использвать все тот же класс discord.ext.commands.Bot .

Для slash-команд, остаются актуальными все свойства prefix-команд. Разве что, декоратор @bot.command() меняется на @bot.slash_command()

Декоратор @bot.slash_command() принимает некоторые необязательные аргументы. Рассмотрим следующие:

  • name : название команды
  • description : описание команды
  • guild_ids : список id серверов, на которых эта команда будет доступна. Поскольку slash-команды синхронизируются с дискордом, данный параметр также имеет смысл указывать для ускорения процесса синхронизации. (Подробный разбор проблемы)

Теперь приступим к созданию команды. В декоратор можно сразу передать параметры названия и описания:

Конечно, там есть много других параметров, описание которых можно найти в документации по discord.SlashCommand

Далее создаем функцию команды. Поскольку дискорд обрабатывает команды интерактивно,

необходимо что-то делать с контекстом выполнения команды:

Либо его можно удалить ( await ctx.delete() ):

Результат:

Либо отправить ответ сразу ( await ctx.respond() ):

Результат:

Если не сделать что-то с конекстом, то дискорд не дождавшись ответа от бота, выдаст ошибку. Например, вот такая команда, которая ничего не возвращает, а просто осуществляет вывод в консоль

Действительно выведет сообщение в консоль, но вот обработка команды в дискорде будет выглядеть так:

Выглядит так, будто при выполнении произошла ошибка, но на деле это просто дискорд не получил ответа от бота. Однако это может произойти даже если команда подразумевает ответ. Например, если идут какие-то долгие вычисления, дискорд может просто не дождаться ответа и команда не выполнится. В таких случаях контекст стоит либо удалять, как показано в примере выше, либо использовать метод контекста defer() .

Из описания следует, что он нужен как раз для таких ситуаций: «Откладывает ответ на взаимодействие. Обычно это используется, когда взаимодействие подтверждено, а дополнительное действие будет выполнено позже.«

Результат:

Разумеется, использовать метод await ctx.defer() имеет смысл только если вы собираетесь что-то отвечать на команду. Если же никакого ответа не подразумевается, то лучше просто удалять контекст. Иначе бот просто бесконечно будет «думать» как на скрине выше.

Работа с аргументами

Работа с аргументами у slash-команд устроена иначе, нежели у prefix-команд. Чтобы PyCord распознал аргумент и передал его в дискорд, нужно в качестве аннотации типа аргумента команды указать экземпляр класса discord.Option

Для начала импортируем класс в код

Конструктор класса Option принимает некоторые параметры. В основном указывают следующие:

  • тип аргумента
  • name : название аргумента (Наследуется от имени переменной, если оно не указано в качестве параметра.)
  • description : описание аргумента
  • required : обязательно ли указывать этот аргумент при вызове команды ( True / False )
  • default : стандартное значение аргумента, если он не был указан

Также есть следующие:

  • min_value : минимальное число, которое пользователь может ввести в качестве аргумента (если тип аргумента — int / float )
  • max_value : тоже самое, что и min_value , только это верхняя граница — максимальное число
  • choices : список ( list ) значений аргумента, которые пользователь может выбрать
  • min_length : минимальная длина строки, которую пользователь должен ввести в качестве значения аргумента

Есть и другие параметры, про которые все также можно почитать в документации к discord.Option . Некоторые из них будут разобраны позже.

Таким образом, получение любого аргумента будет выглядеть так:

Теперь давайте попробуем получить от пользователя следующие аргументы:

  1. Число в диапазоне от 1 до 10
  2. Значение типа bool
  3. Участника сервера ( discord.Member )
  4. Текст из нескольких слов
  5. Слово из списка для выбора

Реализация аргументов будет выглядеть так:

Результат:

  • Аргументы можно указывать в разном порядке
  • Встроенная проверка не даст ввести некорректное значение
  • Необязательные ( required=False ) параметры можно не указывать

На выходе получаем:

Пользовательские типы аргументов

Предположим, вам нужно получить от пользователя bool -значение. Чтобы не указывать в описании аргумента за что отвечает True , а за что False , можно написать свой тип аргумента, который будет предлагать пользователю выбор Да / Нет (Вместо True / False ), затем автоматически конвертировать выбор в bool .

Для этого создадим новый класс, который будет наследоваться от discord.ext.commands.Converter .

Класс должен переопределять метод convert , принимающий аргументы:

  • cls — объект этого класса
  • ctx — контекст выполнения команды
  • arg — значение аргумента

Данный метод будет конвертировать полученную строку ( str ) ‘Да’ / ‘Нет’ в bool в зависимоси от значения.

Также внутри класса можно сразу создать поле choices , содержащее варианты выбора:

Теперь подставим его в качестве типа аргумента. В параметр choices передадим значение поля класса:

Результат:

Разумеется, можно делать и более сложные конвертации во что угодно, буквально ограничиваясь своей фантазией и необходимостью. Вот пример преобразования слова в число:

Slash Commands

In this guide, you will learn more about implementing slash commands to your bot.

Slash commands are type of interactive application commands. It let’s users to interact with your bot by typing /<command name> .

preview

General information

Discord allows up to 200 slash commands (100 global & 100 guild based commands).

To use slash commands, you need to invite the bot with applications.commands scope.

Creating/modifying/deleting global slash commands might take up to 1 hour.

Creating a guild slash command is instant but it won’t appear unless you have registered them in the current guild using $registerGuildCommands[(slash command name;. )] function.

�� Guild slash commands don’t appear in DMs unlike global slash commands.

Getting started

Before you start, you need 2.0.18 version of the app or later.

Inviting the bot

  • Visit Discord Developer official website and select your bot application.
  • Click hamburger icon ≡ on top-left of the website and choose OAuth2 tab.
  • In OAuth2 tab, click URL Generator sub-tab.
  • Choose bot & application.commands in scopes and desired bot permissions.
  • Copy the generated url below and invite your bot into your server.
  • Open BDFD app and select your bot.
  • Press Add invite bot to server button in dashboard tab.
  • Click Edit invite link scopes and enable "Slash commands" if its disabled.
  • Now, go back & press "Add your bot to your server"
  • Finally, invite the bot into your server.

Creating a slash command

  • Create or modify an existing command.
  • Click "Slash command trigger".
  • Choose "Enable global slash command" or "Enable guild slash command" as per your preference.
  • Fill-up necessary data and save it.

�� Slash commands can have a maximum of 4000 characters (combined name, description, and value properties) per slash.

Example

Screenshot_20220717_170852 Screenshot_20220717_170915Screenshot_20220717_171511

Slash options

Slash options are great way to get an user’s input in slash commands.

To create a slash option,

  • Open your slash command edit trigger page.
  • Click "Add" button in Options section.
  • Fill-up necessary data and save the changes.

�� Slash commands can have up to maximum 25 options per slash.

Slash options types

  • Text — Accepts any string data input.
  • Integer — Accepts only integer value input. For example: 3, -70 etc.
  • Number — Accepts only number value input. For example: 5.3, -35, 23 etc.
  • Boolean — Accepts either true or false input.
  • User — It allows to mention any user.
  • Channel — It allows to mention any channel.
  • Role — It allows to mention any role.
  • Mentionable — It allows to mention any user or role.
  • Attachments — It allows to upload attachments.

Retrieving value from options

To retrieve a value from an option, use $message[<option name>] .

�� If you want this function to work both in normal and slash command,
then you can use $message[<arg number>;<option name>] .

Example

Screenshot_20220717_175245 Screenshot_20220717_175635Screenshot_20220717_175649

Pre-defined choices

To create choices in options,

  • In your slash command edit trigger page, create an option and fill-up the necessary data.
  • Toggle "Enabled" in Predefined choices section.
  • Then, click "Add a new choice" button.
  • Type your choice name and value.
  • Click "Add" and save the changes.

�� A slash command can have upto maximum 25 choices per option.

Retrieving choices

You can retrieve user’s option choices using $if statements.

Format

⚠️ Above code snippet requires BDScript 2 in order to execute since it contains $elseif .

# Creating slash commands

open in new window , which provide users a first-class way of interacting directly with your application.

Slash commands provide a huge number of benefits over manual message parsing, including:

  • Integration with the Discord client interface.
  • Automatic command detection and parsing of the associated options/arguments.
  • Typed argument inputs for command options, e.g. "String", "User", or "Role".
  • Validated or dynamic choices for command options.
  • In-channel private responses (ephemeral messages).
  • Pop-up form-style inputs for capturing additional information.

# Before you continue

Assuming you've followed the guide so far, your project directory should look something like this:

For fully functional slash commands, there are three important pieces of code that need to be written. They are:

  1. The individual command files, containing their definitions and functionality.
  2. The command handler, which dynamically reads the files and executes the commands.
  3. The command deployment script, to register your slash commands with Discord so they appear in the interface.

These steps can be done in any order, but all are required before the commands are fully functional.

On this page, you'll complete Step 1. Make sure to also complete the other pages linked above!

# Individual command files

Create a new folder named commands , which is where you'll store all of your command files. You'll be using the SlashCommandBuilder

open in new window class to construct the command definitions.

At a minimum, the definition of a slash command must have a name and a description. Slash command names must be between 1-32 characters and contain no capital letters, spaces, or symbols other than — and _ . Using the builder, a simple ping command definition would look like this:

A slash command also requires a function to run when the command is used, to respond to the interaction. Using an interaction response method confirms to Discord that your bot successfully received the interaction, and has responded to the user. Discord enforces this to ensure that all slash commands provide a good user experience (UX). Failing to respond will cause Discord to show that the command failed, even if your bot is performing other actions as a result.

The simplest way to acknowledge and respond to an interaction is the interaction.reply() method. Other methods of replying are covered on the Response methods page later in this section.

Put these two together by creating a commands/ping.js file for your first command. Inside this file, you're going to define and export two items.

  • The data property, which will provide the command definition shown above for registering to Discord.
  • The execute method, which will contain the functionality to run from our event handler when the command is used.

These are placed inside module.exports so they can be read by other files; namely the command loader and command deployment scripts mentioned earlier.

  • commands/ping.js

open in new window is how you export data in Node.js so that you can require()

If you need to access your client instance from inside a command file, you can access it via interaction.client . If you need to access external files, packages, etc., you should require() them at the top of the file.

That's it for your basic ping command. Below are examples of two more commands we're going to build upon throughout the guide, so create two more files for these before you continue reading.

  • commands/user.js
  • commands/server.js
# Next steps

You can implement additional commands by creating additional files in the commands folder, but these three are the ones we're going to use for the examples as we go on. For now let's move on to the code you'll need for command handling, to load the files and respond to incoming interactions.

# Resulting code

If you want to compare your code to the code we've constructed so far, you can review it over on the GitHub repository here

Creating your first slash commands.

There are two kinds of Slash Commands: global commands and guild commands. Global commands are available for every guild that adds your app. An individual app's global commands are also available in DMs if that app has a bot that shares a mutual guild with the user.

Guild commands are specific to the guild you specify when making them. Guild commands are not available in DMs. Command names are unique per application within each scope (global and guild). That means:

  • Your app cannot have two global commands with the same name
  • Your app cannot have two guild commands within the same name on the same guild
  • Your app can have a global and guild command with the same name
  • Multiple apps can have commands with the same names

Note: Apps can have a maximum of 100 global commands, and an additional 100 guild-specific commands per guild.

Note: Global commands will take up to 1 hour to create, delete or modify on guilds. If you need to update a command quickly for testing you can create it as a guild command.

If you don't have the code for a bot ready yet please follow this guide.

SlashCommandBuilder

The slash command builder will help you create slash commands. The builder has these available fields and methods:

Name Type Description
MaxNameLength const int The maximum length of a name for a slash command allowed by Discord.
MaxDescriptionLength const int The maximum length of a commands description allowed by Discord.
MaxOptionsCount const int The maximum count of command options allowed by Discord
Name string The name of this slash command.
Description string A 1-100 length description of this slash command
Options List<SlashCommandOptionBuilder> The options for this command.
DefaultPermission bool Whether the command is enabled by default when the app is added to a guild.
WithName Function Sets the field name.
WithDescription Function Sets the description of the current command.
WithDefaultPermission Function Sets the default permission of the current command.
AddOption Function Adds an option to the current slash command.
Build Function Builds the builder into a SlashCommandCreationProperties class used to make slash commands

Slash command names must be all lowercase!

Creating a Slash Command

Let's use the slash command builder to make a global and guild command.

Slash commands only need to be created once. They do not have to be 'created' on every startup or connection. The example simple shows creating them in the ready event as it's simpler than creating normal bot commands to register slash commands. The global commands take up to an hour to register every time the CreateGlobalApplicationCommandAsync() is called for a given command.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *