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,8 +1,8 @@
using Discord.WebSocket; using Discord.WebSocket;
using MediatR; using MediatR;
namespace Lunaris2.Handler.GoodByeCommand namespace Lunaris2.Handler.GoodByeCommand;
{
public record GoodbyeCommand(SocketSlashCommand Message) : IRequest; public record GoodbyeCommand(SocketSlashCommand Message) : IRequest;
public class GoodbyeHandler : IRequestHandler<GoodbyeCommand> public class GoodbyeHandler : IRequestHandler<GoodbyeCommand>
@@ -12,4 +12,3 @@ namespace Lunaris2.Handler.GoodByeCommand
await message.Message.RespondAsync($"Goodbye, {message.Message.User.Username}! :c"); await message.Message.RespondAsync($"Goodbye, {message.Message.User.Username}! :c");
} }
} }
}

View File

@@ -3,8 +3,8 @@ using Lunaris2.SlashCommand;
using MediatR; using MediatR;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Lunaris2.Handler.HelloCommand namespace Lunaris2.Handler.HelloCommand;
{
public record HelloCommand(SocketSlashCommand Message) : IRequest; public record HelloCommand(SocketSlashCommand Message) : IRequest;
public class HelloHandler : IRequestHandler<HelloCommand> public class HelloHandler : IRequestHandler<HelloCommand>
@@ -16,4 +16,3 @@ namespace Lunaris2.Handler.HelloCommand
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.GoodByeCommand;
using Lunaris2.Handler.MusicPlayer.JoinCommand; using Lunaris2.Handler.MusicPlayer.JoinCommand;
using Lunaris2.Handler.MusicPlayer.PlayCommand; using Lunaris2.Handler.MusicPlayer.PlayCommand;
using Lunaris2.Handler.MusicPlayer.SkipCommand;
using Lunaris2.Notification; using Lunaris2.Notification;
using Lunaris2.SlashCommand; using Lunaris2.SlashCommand;
using MediatR; using MediatR;
@@ -26,7 +26,8 @@ public class MessageReceivedHandler(ISender mediator) : INotificationHandler<Mes
case Command.Play.Name: case Command.Play.Name:
await mediator.Send(new PlayCommand(notification.Message), cancellationToken); await mediator.Send(new PlayCommand(notification.Message), cancellationToken);
break; break;
default: case Command.Skip.Name:
await mediator.Send(new SkipCommand(notification.Message), cancellationToken);
break; break;
} }
} }

View File

@@ -2,8 +2,8 @@ using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using Victoria.Node; using Victoria.Node;
namespace Lunaris2.Handler.MusicPlayer namespace Lunaris2.Handler.MusicPlayer;
{
public static class Extensions public static class Extensions
{ {
public static SocketGuild GetGuild(this SocketSlashCommand message, DiscordSocketClient client) public static SocketGuild GetGuild(this SocketSlashCommand message, DiscordSocketClient client)
@@ -57,4 +57,3 @@ namespace Lunaris2.Handler.MusicPlayer
return command.Data.Options.FirstOrDefault(option => option.Name == optionName)?.Value.ToString() ?? string.Empty; 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 Discord.WebSocket;
using MediatR; using MediatR;
using Victoria.Node; 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;
using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Lunaris2.SlashCommand; using Lunaris2.SlashCommand;
using MediatR; using MediatR;
@@ -13,29 +14,36 @@ public record PlayCommand(SocketSlashCommand Message) : IRequest;
public class PlayHandler : IRequestHandler<PlayCommand> public class PlayHandler : IRequestHandler<PlayCommand>
{ {
private readonly MusicEmbed _musicEmbed;
private readonly LavaNode _lavaNode; private readonly LavaNode _lavaNode;
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private SocketSlashCommand _context;
public PlayHandler(LavaNode lavaNode, DiscordSocketClient client) public PlayHandler(
LavaNode lavaNode,
DiscordSocketClient client,
MusicEmbed musicEmbed)
{ {
_lavaNode = lavaNode; _lavaNode = lavaNode;
_client = client; _client = client;
_musicEmbed = musicEmbed;
} }
[Command(RunMode = RunMode.Async)]
public async Task Handle(PlayCommand command, CancellationToken cancellationToken) public async Task Handle(PlayCommand command, CancellationToken cancellationToken)
{ {
var context = command.Message; _context = command.Message;
await _lavaNode.EnsureConnected(); await _lavaNode.EnsureConnected();
var songName = context.GetOptionValueByName(Option.Input); var songName = _context.GetOptionValueByName(Option.Input);
if (string.IsNullOrWhiteSpace(songName)) { if (string.IsNullOrWhiteSpace(songName)) {
await context.RespondAsync("Please provide search terms."); await _context.RespondAsync("Please provide search terms.");
return; return;
} }
var player = await GetPlayer(context); var player = await GetPlayer();
if (player == null) if (player == null)
return; return;
@@ -45,11 +53,13 @@ public class PlayHandler : IRequestHandler<PlayCommand>
? SearchType.Direct ? SearchType.Direct
: SearchType.YouTube, songName); : SearchType.YouTube, songName);
if (!await HandleSearchResponse(searchResponse, player, context, songName)) if (!await SearchResponse(searchResponse, player, songName))
return; return;
await PlayTrack(player); await PlayTrack(player);
await _musicEmbed.NowPlayingEmbed(player, _context, _client);
_lavaNode.OnTrackEnd += OnTrackEnd; _lavaNode.OnTrackEnd += OnTrackEnd;
} }
@@ -57,15 +67,14 @@ public class PlayHandler : IRequestHandler<PlayCommand>
{ {
var player = arg.Player; var player = arg.Player;
if (!player.Vueue.TryDequeue(out var nextTrack)) if (!player.Vueue.TryDequeue(out var nextTrack))
{
await player.TextChannel.SendMessageAsync("Queue completed!");
return; return;
}
await player.PlayAsync(nextTrack); 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) { if (player.PlayerState is PlayerState.Playing or PlayerState.Paused) {
return; return;
@@ -75,34 +84,34 @@ public class PlayHandler : IRequestHandler<PlayCommand>
await player.PlayAsync(lavaTrack); 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) 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; 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) { 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; return false;
} }
if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) { if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) {
player.Vueue.Enqueue(searchResponse.Tracks); player.Vueue.Enqueue(searchResponse.Tracks);
await context.RespondAsync($"Enqueued {searchResponse.Tracks.Count} songs."); await _context.RespondAsync($"Enqueued {searchResponse.Tracks.Count} songs.");
} }
else { else {
var track = searchResponse.Tracks.FirstOrDefault()!; var track = searchResponse.Tracks.FirstOrDefault()!;
player.Vueue.Enqueue(track); player.Vueue.Enqueue(track);
await context.RespondAsync($"Enqueued {track?.Title}");
} }
return true; 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> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UserSecretsId>ec2f340f-a44c-4869-ab79-a12ba9459d80</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@@ -3,6 +3,7 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.Interactions; using Discord.Interactions;
using Discord.WebSocket; using Discord.WebSocket;
using Lunaris2.Handler.MusicPlayer;
using Lunaris2.Notification; using Lunaris2.Notification;
using Lunaris2.SlashCommand; using Lunaris2.SlashCommand;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@@ -12,11 +13,11 @@ using Victoria;
using Victoria.Node; using Victoria.Node;
using RunMode = Discord.Commands.RunMode; using RunMode = Discord.Commands.RunMode;
namespace Lunaris2 namespace Lunaris2;
{
public class Program public class Program
{ {
public static LavaNode _lavaNode; private static LavaNode? _lavaNode;
public static void Main(string[] args) public static void Main(string[] args)
{ {
CreateHostBuilder(args).Build().Run(); CreateHostBuilder(args).Build().Run();
@@ -42,23 +43,18 @@ namespace Lunaris2
services.AddSingleton(client) services.AddSingleton(client)
.AddSingleton(commands) .AddSingleton(commands)
.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly())) .AddMediatR(configuration => configuration.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()))
.AddSingleton<DiscordEventListener>() .AddSingleton<DiscordEventListener>()
.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>())) .AddSingleton(service => new InteractionService(service.GetRequiredService<DiscordSocketClient>()))
.AddLavaNode(x => .AddLavaNode(nodeConfiguration =>
{ {
x.SelfDeaf = false; nodeConfiguration.SelfDeaf = false;
x.Hostname = "lavalink.devamop.in"; nodeConfiguration.Hostname = configuration["LavaLinkHostname"];
x.Port = 80; nodeConfiguration.Port = Convert.ToUInt16(configuration["LavaLinkPort"]);
x.Authorization = "DevamOP"; nodeConfiguration.Authorization = configuration["LavaLinkPassword"];
}) })
// .AddLavaNode(x => .AddSingleton<LavaNode>()
// { .AddSingleton<MusicEmbed>();
// x.SelfDeaf = false;
// x.Hostname = "localhost";
// x.Port = 2333;
// })
.AddSingleton<LavaNode>();
client.Ready += () => Client_Ready(client); client.Ready += () => Client_Ready(client);
client.Log += Log; client.Log += Log;
@@ -97,4 +93,3 @@ namespace Lunaris2
return Task.CompletedTask; return Task.CompletedTask;
} }
} }
}

View File

@@ -27,12 +27,24 @@ public static class Command
public const string Description = "Join the voice channel!"; 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 static class Play
{ {
public const string Name = "play"; public const string Name = "play";
public const string Description = "Play a song!"; public const string Description = "Play a song!";
public static readonly List<SlashCommandOptionBuilder> Options = new() public static readonly List<SlashCommandOptionBuilder>? Options = new()
{ {
new SlashCommandOptionBuilder new SlashCommandOptionBuilder
{ {

View File

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

View File

@@ -10,10 +10,16 @@ public static class SlashCommandRegistration
RegisterCommand(client, Command.Hello.Name, Command.Hello.Description); RegisterCommand(client, Command.Hello.Name, Command.Hello.Description);
RegisterCommand(client, Command.Goodbye.Name, Command.Goodbye.Description); RegisterCommand(client, Command.Goodbye.Name, Command.Goodbye.Description);
RegisterCommand(client, Command.Join.Name, Command.Join.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.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); var command = new SlashCommandBuilder(commandName, commandDescription, commandOptions);
_ = command.CreateSlashCommand(client); _ = command.CreateSlashCommand(client);