DSharpPlus как сделать slashcommand'у которую будет видеть только вызваший команду пользователь?
Assistant
To create a Slash Command that can only be seen by the user who invoked it using DSharpPlus, you can utilize the or methods from the class and set the property to . Then, you will need to overwrite the command permissions for the user who invoked it using the method.
User
на русском
Assistant
Чтобы создать Slash Command, которую сможет видеть только пользователь, вызвавший ее при использовании DSharpPlus, вы можете использовать методы или из класса и установить свойство в значение . Затем вам нужно будет перезаписать разрешения команды для пользователя, который вызвал ее, с помощью метода .
CreateGlobalCommandAsync()
CreateGuildCommandAsync()
DiscordClient
DefaultPermission
false
EditGuildCommandPermissionsAsync()
Here is an example of how you can achieve this:
csharp
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.SlashCommands;
using System.Threading.Tasks;
public class MyBot
{
private DiscordClient discord;
private SlashCommandsExtension slashCommands;
public MyBot()
{
discord = new DiscordClient(new DiscordConfiguration()
{
Token = "YOUR_BOT_TOKEN_GOES_HERE",
TokenType = TokenType.Bot
});
var commandsConfig = new SlashCommandsConfiguration()
{
Services = BuildServices() // optional, only if you need dependency injection
};
slashCommands = discord.UseSlashCommands(commandsConfig);
discord.Ready += OnReady;
discord.ConnectAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
private async Task OnReady(DiscordClient sender, ReadyEventArgs e)
{
// Register a global slash command with default permissions set to false
var command = await slashCommands.CreateGlobalCommandAsync("mycommand", "My Slash Command")
.ConfigureAwait(false);
await command.EditPermissionsAsync(new[]
{
new DiscordSlashCommandPermission
{
Id = e.Client.CurrentUser.Id,
Type = SlashCommandPermissionType.User,
Permission = true
}
}).ConfigureAwait(false);
}
private IServiceProvider BuildServices()
{
// Implement your DI container setup here if necessary
return null;
}
}
In this example, the OnReady event handler is used to create a global slash command called "mycommand" with a description of "My Slash Command". The EditPermissionsAsync() method is then called to allow only the bot user (the response) to interact with the command.
Note: Remember to replace "YOUR_BOT_TOKEN_GOES_HERE" with your actual bot token before running the code.
CreateGlobalCommandAsync()
CreateGuildCommandAsync()
DiscordClient
DefaultPermission
false
EditGuildCommandPermissionsAsync()
Вот пример, как это можно сделать:
csharp
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.SlashCommands;
using System.Threading.Tasks;
public class MyBot
{
private DiscordClient discord;
private SlashCommandsExtension slashCommands;
public MyBot()
{
discord = new DiscordClient(new DiscordConfiguration()
{
Token = "ВАШ_ТОКЕН_БОТА_ЗДЕСЬ",
TokenType = TokenType.Bot
});
var commandsConfig = new SlashCommandsConfiguration()
{
Services = BuildServices() // необязательно, только если вам нужна инъекция зависимостей
};
slashCommands = discord.UseSlashCommands(commandsConfig);
discord.Ready += OnReady;
discord.ConnectAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
private async Task OnReady(DiscordClient sender, ReadyEventArgs e)
{
// Зарегистрируйте глобальную Slash Command со значениями разрешений по умолчанию, установленными в false
var command = await slashCommands.CreateGlobalCommandAsync("mycommand", "Моя Slash Command")
.ConfigureAwait(false);
await command.EditPermissionsAsync(new[]
{
new DiscordSlashCommandPermission
{
Id = e.Client.CurrentUser.Id,
Type = SlashCommandPermissionType.User,
Permission = true
}
}).ConfigureAwait(false);
}
private IServiceProvider BuildServices()
{
// Реализуйте настройку вашего контейнера DI здесь, если необходимо
return null;
}
}
В этом примере обработчик события OnReady используется для создания глобальной Slash Command с названием "mycommand" и описанием "Моя Slash Command". Затем вызывается метод EditPermissionsAsync(), чтобы разрешить взаимодействие только боту (ответу) с командой.
Примечание: Не забудьте заменить "ВАШ_ТОКЕН_БОТА_ЗДЕСЬ" на фактический токен вашего бота перед запуском кода.