Add Embed

This commit is contained in:
Myx
2024-04-14 21:43:25 +02:00
parent 2d7ec0829e
commit 0bc2a9be56
19 changed files with 347 additions and 228 deletions

View File

@@ -1,15 +1,14 @@
using Discord.WebSocket;
using MediatR;
namespace Lunaris2.Handler.GoodByeCommand
{
public record GoodbyeCommand(SocketSlashCommand Message) : IRequest;
namespace Lunaris2.Handler.GoodByeCommand;
public class GoodbyeHandler : IRequestHandler<GoodbyeCommand>
public record GoodbyeCommand(SocketSlashCommand Message) : IRequest;
public class GoodbyeHandler : IRequestHandler<GoodbyeCommand>
{
public async Task Handle(GoodbyeCommand message, CancellationToken cancellationToken)
{
public async Task Handle(GoodbyeCommand message, CancellationToken cancellationToken)
{
await message.Message.RespondAsync($"Goodbye, {message.Message.User.Username}! :c");
}
await message.Message.RespondAsync($"Goodbye, {message.Message.User.Username}! :c");
}
}

View File

@@ -3,17 +3,16 @@ using Lunaris2.SlashCommand;
using MediatR;
using Newtonsoft.Json;
namespace Lunaris2.Handler.HelloCommand
{
public record HelloCommand(SocketSlashCommand Message) : IRequest;
namespace Lunaris2.Handler.HelloCommand;
public class HelloHandler : IRequestHandler<HelloCommand>
public record HelloCommand(SocketSlashCommand Message) : IRequest;
public class HelloHandler : IRequestHandler<HelloCommand>
{
public async Task Handle(HelloCommand message, CancellationToken cancellationToken)
{
public async Task Handle(HelloCommand message, CancellationToken cancellationToken)
{
Console.WriteLine(JsonConvert.SerializeObject(Command.GetAllCommands()));
Console.WriteLine(JsonConvert.SerializeObject(Command.GetAllCommands()));
await message.Message.RespondAsync($"Hello, {message.Message.User.Username}!");
}
await message.Message.RespondAsync($"Hello, {message.Message.User.Username}!");
}
}

View File

@@ -1,7 +1,7 @@
using Discord.Commands;
using Lunaris2.Handler.GoodByeCommand;
using Lunaris2.Handler.MusicPlayer.JoinCommand;
using Lunaris2.Handler.MusicPlayer.PlayCommand;
using Lunaris2.Handler.MusicPlayer.SkipCommand;
using Lunaris2.Notification;
using Lunaris2.SlashCommand;
using MediatR;
@@ -26,7 +26,8 @@ public class MessageReceivedHandler(ISender mediator) : INotificationHandler<Mes
case Command.Play.Name:
await mediator.Send(new PlayCommand(notification.Message), cancellationToken);
break;
default:
case Command.Skip.Name:
await mediator.Send(new SkipCommand(notification.Message), cancellationToken);
break;
}
}

View File

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

@@ -1,4 +1,3 @@
using Discord;
using Discord.WebSocket;
using MediatR;
using Victoria.Node;

View File

@@ -0,0 +1,52 @@
using Discord;
using Discord.WebSocket;
using Lunaris2.Handler.MusicPlayer;
public static class MessageModule
{
private static Dictionary<ulong, List<ulong>> guildMessageIds = new Dictionary<ulong, List<ulong>>();
public static async Task SendMessageAsync(this SocketSlashCommand context, string message, DiscordSocketClient client)
{
var guildId = await StoreForRemoval(context, client);
await context.RespondAsync(message);
var sentMessage = await context.GetOriginalResponseAsync();
guildMessageIds[guildId].Add(sentMessage.Id);
}
public static async Task SendMessageAsync(this SocketSlashCommand context, Embed message, DiscordSocketClient client)
{
var guildId = await StoreForRemoval(context, client);
await context.RespondAsync(embed: message);
var sentMessage = await context.GetOriginalResponseAsync();
guildMessageIds[guildId].Add(sentMessage.Id);
}
private static async Task<ulong> StoreForRemoval(SocketSlashCommand context, DiscordSocketClient client)
{
var guildId = context.GetGuild(client).Id;
if (guildMessageIds.ContainsKey(guildId))
{
foreach (var messageId in guildMessageIds[guildId])
{
var messageToDelete = await context.Channel.GetMessageAsync(messageId);
if (messageToDelete != null)
await messageToDelete.DeleteAsync();
}
guildMessageIds[guildId].Clear();
}
else
{
guildMessageIds.Add(guildId, []);
}
return guildId;
}
}

View File

@@ -0,0 +1,44 @@
using Discord;
using Discord.WebSocket;
using Victoria;
using Victoria.Player;
namespace Lunaris2.Handler.MusicPlayer;
public class MusicEmbed
{
private Embed SendMusicEmbed(
string imageUrl,
string title,
string length,
string artist,
string queuedBy,
string? nextInQueue)
{
return new EmbedBuilder()
.WithAuthor("Lunaris", "https://media.tenor.com/GqAwMt01UXgAAAAi/cd.gif")
.WithTitle(title)
.WithDescription($"Length: {length}\nArtist: {artist}\nQueued by: {queuedBy}\nNext in queue: {nextInQueue}")
.WithColor(Color.Magenta)
.WithThumbnailUrl(imageUrl)
.Build();
}
public async Task NowPlayingEmbed(
LavaPlayer<LavaTrack> player,
SocketSlashCommand context,
DiscordSocketClient client)
{
var artwork = await player.Track.FetchArtworkAsync();
var getNextTrack = player.Vueue.Count > 1 ? player.Vueue.ToArray()[1].Title : "No songs in queue.";
var embed = SendMusicEmbed(
artwork,
player.Track.Title,
player.Track.Duration.ToString(),
player.Track.Author,
context.User.Username,
getNextTrack);
await context.SendMessageAsync(embed, client);
}
}

View File

@@ -1,4 +1,5 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Lunaris2.SlashCommand;
using MediatR;
@@ -13,29 +14,36 @@ public record PlayCommand(SocketSlashCommand Message) : IRequest;
public class PlayHandler : IRequestHandler<PlayCommand>
{
private readonly MusicEmbed _musicEmbed;
private readonly LavaNode _lavaNode;
private readonly DiscordSocketClient _client;
private SocketSlashCommand _context;
public PlayHandler(LavaNode lavaNode, DiscordSocketClient client)
public PlayHandler(
LavaNode lavaNode,
DiscordSocketClient client,
MusicEmbed musicEmbed)
{
_lavaNode = lavaNode;
_client = client;
_musicEmbed = musicEmbed;
}
[Command(RunMode = RunMode.Async)]
public async Task Handle(PlayCommand command, CancellationToken cancellationToken)
{
var context = command.Message;
_context = command.Message;
await _lavaNode.EnsureConnected();
var songName = context.GetOptionValueByName(Option.Input);
var songName = _context.GetOptionValueByName(Option.Input);
if (string.IsNullOrWhiteSpace(songName)) {
await context.RespondAsync("Please provide search terms.");
await _context.RespondAsync("Please provide search terms.");
return;
}
var player = await GetPlayer(context);
var player = await GetPlayer();
if (player == null)
return;
@@ -45,10 +53,12 @@ public class PlayHandler : IRequestHandler<PlayCommand>
? SearchType.Direct
: SearchType.YouTube, songName);
if (!await HandleSearchResponse(searchResponse, player, context, songName))
if (!await SearchResponse(searchResponse, player, songName))
return;
await PlayTrack(player);
await _musicEmbed.NowPlayingEmbed(player, _context, _client);
_lavaNode.OnTrackEnd += OnTrackEnd;
}
@@ -57,15 +67,14 @@ public class PlayHandler : IRequestHandler<PlayCommand>
{
var player = arg.Player;
if (!player.Vueue.TryDequeue(out var nextTrack))
{
await player.TextChannel.SendMessageAsync("Queue completed!");
return;
}
await player.PlayAsync(nextTrack);
await _musicEmbed.NowPlayingEmbed(player, _context, _client);
}
private async Task PlayTrack(LavaPlayer<LavaTrack> player)
private static async Task PlayTrack(LavaPlayer<LavaTrack> player)
{
if (player.PlayerState is PlayerState.Playing or PlayerState.Paused) {
return;
@@ -75,34 +84,34 @@ public class PlayHandler : IRequestHandler<PlayCommand>
await player.PlayAsync(lavaTrack);
}
private async Task<LavaPlayer<LavaTrack>?> GetPlayer(SocketSlashCommand context)
private async Task<LavaPlayer<LavaTrack>?> GetPlayer()
{
var voiceState = context.User as IVoiceState;
var voiceState = _context.User as IVoiceState;
if (voiceState?.VoiceChannel != null)
return await _lavaNode.JoinAsync(voiceState.VoiceChannel, context.Channel as ITextChannel);
return await _lavaNode.JoinAsync(voiceState.VoiceChannel, _context.Channel as ITextChannel);
await context.RespondAsync("You must be connected to a voice channel!");
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)
private async Task<bool> SearchResponse(
SearchResponse searchResponse, LavaPlayer<LavaTrack> player,
string songName)
{
if (searchResponse.Status is SearchStatus.LoadFailed or SearchStatus.NoMatches) {
await context.RespondAsync($"I wasn't able to find anything for `{songName}`.");
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.");
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

@@ -0,0 +1,48 @@
using Discord.WebSocket;
using MediatR;
using Victoria.Node;
using Victoria.Player;
namespace Lunaris2.Handler.MusicPlayer.SkipCommand;
public record SkipCommand(SocketSlashCommand Message) : IRequest;
public class SkipHandler : IRequestHandler<SkipCommand>
{
private readonly LavaNode _lavaNode;
private readonly DiscordSocketClient _client;
private readonly MusicEmbed _musicEmbed;
public SkipHandler(LavaNode lavaNode, DiscordSocketClient client, MusicEmbed musicEmbed)
{
_lavaNode = lavaNode;
_client = client;
_musicEmbed = musicEmbed;
}
public async Task Handle(SkipCommand message, CancellationToken cancellationToken)
{
var context = message.Message;
await _lavaNode.EnsureConnected();
if (!_lavaNode.TryGetPlayer(context.GetGuild(_client), out var player)) {
await context.RespondAsync("I'm not connected to a voice channel.");
return;
}
if (player.PlayerState != PlayerState.Playing) {
await context.RespondAsync("Woaaah there, I can't skip when nothing is playing.");
return;
}
try {
await player.SkipAsync();
await _musicEmbed.NowPlayingEmbed(player, context, _client);
}
catch (Exception exception) {
await context.RespondAsync("There is not more tracks to skip.");
Console.WriteLine(exception);
}
}
}

9
Bot/Helper/RunAsync.cs Normal file
View File

@@ -0,0 +1,9 @@
namespace Lunaris2.Helper;
public static class Async
{
public static void Run(Func<Task> task)
{
_ = Task.Run(task);
}
}

View File

@@ -1,15 +0,0 @@
using System.Threading.Tasks;
using Discord.WebSocket;
using Lunaris2.SlashCommand;
namespace Lunaris2.Helpers
{
public static class ClientReadyHandler
{
public static Task Client_Ready(this DiscordSocketClient client)
{
client.RegisterCommands();
return Task.CompletedTask;
}
}
}

View File

@@ -1,12 +0,0 @@
using Discord.Commands;
namespace Lunaris2.Helpers
{
public static class CommandServiceSetup
{
public static CommandService Setup()
{
return new CommandService();
}
}
}

View File

@@ -1,17 +0,0 @@
using Discord;
using Discord.WebSocket;
namespace Lunaris2.Helpers
{
public static class DiscordSocketClientSetup
{
public static DiscordSocketClient Setup()
{
var config = new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.All
};
return new DiscordSocketClient(config);
}
}
}

View File

@@ -1,13 +0,0 @@
using Discord;
namespace Lunaris2.Helpers
{
public static class LogHandler
{
public static Task Log(LogMessage arg)
{
Console.WriteLine(arg);
return Task.CompletedTask;
}
}
}

View File

@@ -5,6 +5,7 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UserSecretsId>ec2f340f-a44c-4869-ab79-a12ba9459d80</UserSecretsId>
</PropertyGroup>
<ItemGroup>

View File

@@ -3,6 +3,7 @@ using Discord;
using Discord.Commands;
using Discord.Interactions;
using Discord.WebSocket;
using Lunaris2.Handler.MusicPlayer;
using Lunaris2.Notification;
using Lunaris2.SlashCommand;
using Microsoft.Extensions.Configuration;
@@ -12,89 +13,83 @@ using Victoria;
using Victoria.Node;
using RunMode = Discord.Commands.RunMode;
namespace Lunaris2
namespace Lunaris2;
public class Program
{
public class Program
private static LavaNode? _lavaNode;
public static void Main(string[] args)
{
public static LavaNode _lavaNode;
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
var config = new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.All
};
var commandServiceConfig = new CommandServiceConfig{ DefaultRunMode = RunMode.Async };
var client = new DiscordSocketClient(config);
var commands = new CommandService(commandServiceConfig);
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
services.AddSingleton(client)
.AddSingleton(commands)
.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()))
.AddSingleton<DiscordEventListener>()
.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;
client
.LoginAsync(TokenType.Bot, configuration["Token"])
.GetAwaiter()
.GetResult();
client
.StartAsync()
.GetAwaiter()
.GetResult();
_lavaNode = services.BuildServiceProvider().GetRequiredService<LavaNode>();
var listener = services
.BuildServiceProvider()
.GetRequiredService<DiscordEventListener>();
listener
.StartAsync()
.GetAwaiter()
.GetResult();
});
private static async Task Client_Ready(DiscordSocketClient client)
{
await _lavaNode.ConnectAsync();
client.RegisterCommands();
}
private static Task Log(LogMessage arg)
{
Console.WriteLine(arg);
return Task.CompletedTask;
}
CreateHostBuilder(args).Build().Run();
}
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
var config = new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.All
};
var commandServiceConfig = new CommandServiceConfig{ DefaultRunMode = RunMode.Async };
var client = new DiscordSocketClient(config);
var commands = new CommandService(commandServiceConfig);
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
services.AddSingleton(client)
.AddSingleton(commands)
.AddMediatR(configuration => configuration.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()))
.AddSingleton<DiscordEventListener>()
.AddSingleton(service => new InteractionService(service.GetRequiredService<DiscordSocketClient>()))
.AddLavaNode(nodeConfiguration =>
{
nodeConfiguration.SelfDeaf = false;
nodeConfiguration.Hostname = configuration["LavaLinkHostname"];
nodeConfiguration.Port = Convert.ToUInt16(configuration["LavaLinkPort"]);
nodeConfiguration.Authorization = configuration["LavaLinkPassword"];
})
.AddSingleton<LavaNode>()
.AddSingleton<MusicEmbed>();
client.Ready += () => Client_Ready(client);
client.Log += Log;
client
.LoginAsync(TokenType.Bot, configuration["Token"])
.GetAwaiter()
.GetResult();
client
.StartAsync()
.GetAwaiter()
.GetResult();
_lavaNode = services.BuildServiceProvider().GetRequiredService<LavaNode>();
var listener = services
.BuildServiceProvider()
.GetRequiredService<DiscordEventListener>();
listener
.StartAsync()
.GetAwaiter()
.GetResult();
});
private static async Task Client_Ready(DiscordSocketClient client)
{
await _lavaNode.ConnectAsync();
client.RegisterCommands();
}
private static Task Log(LogMessage arg)
{
Console.WriteLine(arg);
return Task.CompletedTask;
}
}

View File

@@ -27,12 +27,24 @@ public static class Command
public const string Description = "Join the voice channel!";
}
public static class Skip
{
public const string Name = "skip";
public const string Description = "Skip the current song!";
}
public static class Stop
{
public const string Name = "stop";
public const string Description = "Stop the music!";
}
public static class Play
{
public const string Name = "play";
public const string Description = "Play a song!";
public static readonly List<SlashCommandOptionBuilder> Options = new()
public static readonly List<SlashCommandOptionBuilder>? Options = new()
{
new SlashCommandOptionBuilder
{

View File

@@ -5,11 +5,14 @@ using Newtonsoft.Json;
namespace Lunaris2.SlashCommand;
public class SlashCommandBuilder(string commandName, string commandDescription, List<SlashCommandOptionBuilder> commandOptions = null)
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; }
private List<SlashCommandOptionBuilder>? CommandOptions { get; set; } = commandOptions;
public async Task CreateSlashCommand(DiscordSocketClient client)
{
@@ -23,7 +26,7 @@ public class SlashCommandBuilder(string commandName, string commandDescription,
globalCommand.WithName(CommandName);
globalCommand.WithDescription(CommandDescription);
commandOptions.ForEach(option => globalCommand.AddOption(option));
CommandOptions?.ForEach(option => globalCommand.AddOption(option));
try
{

View File

@@ -10,10 +10,16 @@ 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.Skip.Name, Command.Skip.Description);
RegisterCommand(client, Command.Play.Name, Command.Play.Description, Command.Play.Options);
RegisterCommand(client, Command.Stop.Name, Command.Stop.Description);
}
private static void RegisterCommand(DiscordSocketClient client, string commandName, string commandDescription, List<SlashCommandOptionBuilder> commandOptions = null)
private static void RegisterCommand(
DiscordSocketClient client,
string commandName,
string commandDescription,
List<SlashCommandOptionBuilder>? commandOptions = null)
{
var command = new SlashCommandBuilder(commandName, commandDescription, commandOptions);
_ = command.CreateSlashCommand(client);