Add Join and Play handlers, Expand Command Builder functionality

This commit is contained in:
Myx
2024-04-14 16:06:18 +02:00
parent f7b54ca80c
commit 95ab1281a4
16 changed files with 293 additions and 20 deletions

View File

@@ -1,4 +1,7 @@
using Discord.Commands;
using Lunaris2.Handler.GoodByeCommand;
using Lunaris2.Handler.MusicPlayer.JoinCommand;
using Lunaris2.Handler.MusicPlayer.PlayCommand;
using Lunaris2.Notification;
using Lunaris2.SlashCommand;
using MediatR;
@@ -17,6 +20,12 @@ public class MessageReceivedHandler(ISender mediator) : INotificationHandler<Mes
case Command.Goodbye.Name:
await mediator.Send(new GoodbyeCommand(notification.Message), cancellationToken);
break;
case Command.Join.Name:
await mediator.Send(new JoinCommand(notification.Message), cancellationToken);
break;
case Command.Play.Name:
await mediator.Send(new PlayCommand(notification.Message), cancellationToken);
break;
default:
break;
}

View File

@@ -0,0 +1,61 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Victoria.Node;
namespace Lunaris2.Handler.MusicPlayer
{
public static class Extensions
{
public static SocketGuild GetGuild(this SocketSlashCommand message, DiscordSocketClient client)
{
if (message.GuildId == null)
{
throw new Exception("Guild ID is null!");
}
return client.GetGuild(message.GuildId.Value);
}
public static IVoiceState GetVoiceState(this SocketSlashCommand message)
{
var voiceState = message.User as IVoiceState;
if (voiceState?.VoiceChannel == null)
{
throw new Exception("You must be connected to a voice channel!");
}
return voiceState;
}
public static async Task RespondAsync(this SocketSlashCommand message, string content)
{
await message.RespondAsync(content, ephemeral: true);
}
public static async Task EnsureConnected(this LavaNode lavaNode)
{
if(!lavaNode.IsConnected)
await lavaNode.ConnectAsync();
}
public static async Task JoinVoiceChannel(this SocketSlashCommand context, LavaNode lavaNode)
{
try
{
var textChannel = context.Channel as ITextChannel;
await lavaNode.JoinAsync(context.GetVoiceState().VoiceChannel, textChannel);
await context.RespondAsync($"Joined {context.GetVoiceState().VoiceChannel.Name}!");
}
catch (Exception exception) {
Console.WriteLine(exception);
}
}
public static string GetOptionValueByName(this SocketSlashCommand command, string optionName)
{
return command.Data.Options.FirstOrDefault(option => option.Name == optionName)?.Value.ToString() ?? string.Empty;
}
}
}

View File

@@ -0,0 +1,34 @@
using Discord;
using Discord.WebSocket;
using MediatR;
using Victoria.Node;
namespace Lunaris2.Handler.MusicPlayer.JoinCommand;
public record JoinCommand(SocketSlashCommand Message) : IRequest;
public class JoinHandler : IRequestHandler<JoinCommand>
{
private readonly LavaNode _lavaNode;
private readonly DiscordSocketClient _client;
public JoinHandler(LavaNode lavaNode, DiscordSocketClient client)
{
_lavaNode = lavaNode;
_client = client;
}
public async Task Handle(JoinCommand command, CancellationToken cancellationToken)
{
var context = command.Message;
await _lavaNode.EnsureConnected();
if (_lavaNode.HasPlayer(context.GetGuild(_client))) {
await context.RespondAsync("I'm already connected to a voice channel!");
return;
}
await context.JoinVoiceChannel(_lavaNode);
}
}

View File

@@ -0,0 +1,110 @@
using Discord;
using Discord.WebSocket;
using Lunaris2.SlashCommand;
using MediatR;
using Victoria.Node;
using Victoria.Node.EventArgs;
using Victoria.Player;
using Victoria.Responses.Search;
namespace Lunaris2.Handler.MusicPlayer.PlayCommand;
public record PlayCommand(SocketSlashCommand Message) : IRequest;
public class PlayHandler : IRequestHandler<PlayCommand>
{
private readonly LavaNode _lavaNode;
private readonly DiscordSocketClient _client;
public PlayHandler(LavaNode lavaNode, DiscordSocketClient client)
{
_lavaNode = lavaNode;
_client = client;
}
public async Task Handle(PlayCommand command, CancellationToken cancellationToken)
{
var context = command.Message;
await _lavaNode.EnsureConnected();
var songName = context.GetOptionValueByName(Option.Input);
if (string.IsNullOrWhiteSpace(songName)) {
await context.RespondAsync("Please provide search terms.");
return;
}
var player = await GetPlayer(context);
if (player == null)
return;
var searchResponse = await _lavaNode.SearchAsync(
Uri.IsWellFormedUriString(songName, UriKind.Absolute)
? SearchType.Direct
: SearchType.YouTube, songName);
if (!await HandleSearchResponse(searchResponse, player, context, songName))
return;
await PlayTrack(player);
_lavaNode.OnTrackEnd += OnTrackEnd;
}
private async Task OnTrackEnd(TrackEndEventArg<LavaPlayer<LavaTrack>, LavaTrack> arg)
{
var player = arg.Player;
if (!player.Vueue.TryDequeue(out var nextTrack))
{
await player.TextChannel.SendMessageAsync("Queue completed!");
return;
}
await player.PlayAsync(nextTrack);
}
private async Task PlayTrack(LavaPlayer<LavaTrack> player)
{
if (player.PlayerState is PlayerState.Playing or PlayerState.Paused) {
return;
}
player.Vueue.TryDequeue(out var lavaTrack);
await player.PlayAsync(lavaTrack);
}
private async Task<LavaPlayer<LavaTrack>?> GetPlayer(SocketSlashCommand context)
{
var voiceState = context.User as IVoiceState;
if (voiceState?.VoiceChannel != null)
return await _lavaNode.JoinAsync(voiceState.VoiceChannel, context.Channel as ITextChannel);
await context.RespondAsync("You must be connected to a voice channel!");
return null;
}
private async Task<bool> HandleSearchResponse(SearchResponse searchResponse, LavaPlayer<LavaTrack> player, SocketSlashCommand context, string songName)
{
if (searchResponse.Status is SearchStatus.LoadFailed or SearchStatus.NoMatches) {
await context.RespondAsync($"I wasn't able to find anything for `{songName}`.");
return false;
}
if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) {
player.Vueue.Enqueue(searchResponse.Tracks);
await context.RespondAsync($"Enqueued {searchResponse.Tracks.Count} songs.");
}
else {
var track = searchResponse.Tracks.FirstOrDefault()!;
player.Vueue.Enqueue(track);
await context.RespondAsync($"Enqueued {track?.Title}");
}
return true;
}
}

View File

@@ -8,16 +8,17 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.14.1" />
<PackageReference Include="Discord.Net.Commands" Version="3.14.1" />
<PackageReference Include="Discord.Net.Core" Version="3.14.1" />
<PackageReference Include="Discord.Net.Interactions" Version="3.14.1" />
<PackageReference Include="Discord.Net.Rest" Version="3.14.1" />
<PackageReference Include="Discord.Net" Version="3.13.1" />
<PackageReference Include="Discord.Net.Commands" Version="3.13.1" />
<PackageReference Include="Discord.Net.Core" Version="3.13.1" />
<PackageReference Include="Discord.Net.Interactions" Version="3.13.1" />
<PackageReference Include="Discord.Net.Rest" Version="3.13.1" />
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Victoria" Version="6.0.23.324" />
</ItemGroup>
<ItemGroup>

View File

@@ -24,8 +24,8 @@ public class DiscordEventListener(DiscordSocketClient client, IServiceScopeFacto
await Task.CompletedTask;
}
private Task OnMessageReceivedAsync(SocketSlashCommand arg)
private async Task OnMessageReceivedAsync(SocketSlashCommand arg)
{
return Mediator.Publish(new MessageReceivedNotification(arg), _cancellationToken);
await Mediator.Publish(new MessageReceivedNotification(arg), _cancellationToken);
}
}

View File

@@ -8,11 +8,15 @@ using Lunaris2.SlashCommand;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Victoria;
using Victoria.Node;
using RunMode = Discord.Commands.RunMode;
namespace Lunaris2
{
public class Program
{
public static LavaNode _lavaNode;
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
@@ -27,8 +31,10 @@ namespace Lunaris2
GatewayIntents = GatewayIntents.All
};
var commandServiceConfig = new CommandServiceConfig{ DefaultRunMode = RunMode.Async };
var client = new DiscordSocketClient(config);
var commands = new CommandService();
var commands = new CommandService(commandServiceConfig);
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
@@ -38,7 +44,21 @@ namespace Lunaris2
.AddSingleton(commands)
.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()))
.AddSingleton<DiscordEventListener>()
.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>()));
.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>()))
.AddLavaNode(x =>
{
x.SelfDeaf = false;
x.Hostname = "lavalink.devamop.in";
x.Port = 80;
x.Authorization = "DevamOP";
})
// .AddLavaNode(x =>
// {
// x.SelfDeaf = false;
// x.Hostname = "localhost";
// x.Port = 2333;
// })
.AddSingleton<LavaNode>();
client.Ready += () => Client_Ready(client);
client.Log += Log;
@@ -53,6 +73,8 @@ namespace Lunaris2
.GetAwaiter()
.GetResult();
_lavaNode = services.BuildServiceProvider().GetRequiredService<LavaNode>();
var listener = services
.BuildServiceProvider()
.GetRequiredService<DiscordEventListener>();
@@ -63,10 +85,10 @@ namespace Lunaris2
.GetResult();
});
private static Task Client_Ready(DiscordSocketClient client)
private static async Task Client_Ready(DiscordSocketClient client)
{
await _lavaNode.ConnectAsync();
client.RegisterCommands();
return Task.CompletedTask;
}
private static Task Log(LogMessage arg)

View File

@@ -1,5 +1,12 @@
using Discord;
namespace Lunaris2.SlashCommand;
public static class Option
{
public const string Input = "input";
}
public static class Command
{
public static class Hello
@@ -14,6 +21,29 @@ public static class Command
public const string Description = "Say goodbye to the bot!";
}
public static class Join
{
public const string Name = "join";
public const string Description = "Join the voice channel!";
}
public static class Play
{
public const string Name = "play";
public const string Description = "Play a song!";
public static readonly List<SlashCommandOptionBuilder> Options = new()
{
new SlashCommandOptionBuilder
{
Name = "input",
Description = "The song you want to play",
Type = ApplicationCommandOptionType.String,
IsRequired = true
},
};
}
public static string[] GetAllCommands()
{
return typeof(Command)

View File

@@ -1,13 +1,15 @@
using Discord;
using Discord.Net;
using Discord.WebSocket;
using Newtonsoft.Json;
namespace Lunaris2.SlashCommand;
public class SlashCommandBuilder(string commandName, string commandDescription)
public class SlashCommandBuilder(string commandName, string commandDescription, List<SlashCommandOptionBuilder> commandOptions = null)
{
private string CommandName { get; set; } = commandName;
private string CommandDescription { get; set; } = commandDescription;
private List<SlashCommandOptionBuilder> CommandOptions { get; set; }
public async Task CreateSlashCommand(DiscordSocketClient client)
{
@@ -21,6 +23,8 @@ public class SlashCommandBuilder(string commandName, string commandDescription)
globalCommand.WithName(CommandName);
globalCommand.WithDescription(CommandDescription);
commandOptions.ForEach(option => globalCommand.AddOption(option));
try
{
await client.CreateGlobalApplicationCommandAsync(globalCommand.Build());
@@ -46,12 +50,12 @@ public class SlashCommandBuilder(string commandName, string commandDescription)
}
}
private async Task<bool> CommandExists(IEnumerable<SocketApplicationCommand> registeredCommands)
private Task<bool> CommandExists(IEnumerable<SocketApplicationCommand> registeredCommands)
{
if (!registeredCommands.Any(command => command.Name == CommandName && command.Description == CommandDescription))
return false;
return Task.FromResult(false);
Console.WriteLine($"Command {CommandName} already exists.");
return true;
return Task.FromResult(true);
}
}

View File

@@ -1,3 +1,4 @@
using Discord;
using Discord.WebSocket;
namespace Lunaris2.SlashCommand;
@@ -8,11 +9,13 @@ public static class SlashCommandRegistration
{
RegisterCommand(client, Command.Hello.Name, Command.Hello.Description);
RegisterCommand(client, Command.Goodbye.Name, Command.Goodbye.Description);
RegisterCommand(client, Command.Join.Name, Command.Join.Description);
RegisterCommand(client, Command.Play.Name, Command.Play.Description, Command.Play.Options);
}
private static void RegisterCommand(DiscordSocketClient client, string commandName, string commandDescription)
private static void RegisterCommand(DiscordSocketClient client, string commandName, string commandDescription, List<SlashCommandOptionBuilder> commandOptions = null)
{
var command = new SlashCommandBuilder(commandName, commandDescription);
var command = new SlashCommandBuilder(commandName, commandDescription, commandOptions);
_ = command.CreateSlashCommand(client);
}
}

View File

@@ -16,7 +16,6 @@ lavalink:
# defaultPluginRepository: "https://maven.lavalink.dev/releases" # optional, defaults to the Lavalink release repository
# defaultPluginSnapshotRepository: "https://maven.lavalink.dev/snapshots" # optional, defaults to the Lavalink snapshot repository
server:
password: "youshallnotpass"
sources:
youtube: true
bandcamp: true

View File

@@ -1,7 +1,7 @@
services:
lavalink:
# pin the image version to Lavalink v4
image: ghcr.io/lavalink-devs/lavalink:4
image: ghcr.io/lavalink-devs/lavalink:3.7.10
container_name: lavalink
restart: unless-stopped
environment:

Binary file not shown.