Skip to content

Commit

Permalink
Merge branch 'dev' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
BrammyS committed Aug 8, 2021
2 parents 91a6889 + 9077bc8 commit 2ea7e0e
Show file tree
Hide file tree
Showing 59 changed files with 671 additions and 323 deletions.
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,7 @@ public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

// Configure Color-Chan.Discord.Commands
// EnableAutoSync is off by default. Turn this own if you dont want to send the slash command to discord manually.
var config = new SlashCommandConfiguration
{
EnableAutoSync = true // <-----
};
// Register all the commands in an Assembly.
await host.RegisterSlashCommandsAsync(Assembly.GetExecutingAssembly(), config).ConfigureAwait(false); // <-----
// Run the WebHost, and start accepting requests.
Expand All @@ -168,9 +163,18 @@ You will need to add your bot token, public key and application id, these can be
```csharp
public void ConfigureServices(IServiceCollection services)
{
// Configure Color-Chan.Discord
var config = new ColorChanConfigurations
{
SlashCommandConfigs = slashOptions =>
{
slashOptions.EnableAutoSync = true; // <---
}
};

// Replace the arguments with the data of your bot.
// Note: It is not recommended to hardcode them in, loading them from an environment variable or from a json file is better.
services.AddColorChanDiscord("TOKEN", "PUBLIC_KEY", 999999999999999); // <---
services.AddColorChanDiscord("TOKEN", "PUBLIC_KEY", 999999999999999, config); // <---
services.AddControllers();
}
Expand Down
24 changes: 7 additions & 17 deletions samples/Pong/Commands/PongCommands.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using System.Drawing;
#pragma warning disable 1998
using System.Threading.Tasks;
using Color_Chan.Discord.Commands;
using Color_Chan.Discord.Commands.Attributes;
using Color_Chan.Discord.Commands.Attributes.ProvidedRequirements;
using Color_Chan.Discord.Commands.Modules;
using Color_Chan.Discord.Core.Common.Models.Interaction;
using Color_Chan.Discord.Core.Results;

namespace Pong.Commands
{
Expand All @@ -18,24 +19,13 @@ public class PongCommands : SlashCommandModule
/// <returns>
/// An embedded response with "Pong!".
/// </returns>
[SlashCommandRateLimit(5, 10)] // Sets the rate limit for this command to 5 requests per 10 seconds per user.
[SlashCommand("ping", "Ping Pong!")]
public Task<IDiscordInteractionResponse> PongAsync()
public async Task<Result<IDiscordInteractionResponse>> PongAsync()
{
// Build the response embed.
var embedBuilder = new DiscordEmbedBuilder()
.WithTitle("Ping response")
.WithDescription("Pong!")
.WithColor(Color.Aqua)
.WithTimeStamp();

// Build the response with the embed.
var response = new SlashCommandResponseBuilder()
.WithEmbed(embedBuilder.Build())
.MakePrivate()
.Build();

// Return the response to Discord.
return Task.FromResult(response);
var message = "Pong!";
return FromSuccess(message);
}
}
}
10 changes: 2 additions & 8 deletions samples/Pong/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Reflection;
using System.Threading.Tasks;
using Color_Chan.Discord.Commands.Configurations;
using Color_Chan.Discord.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
Expand All @@ -13,13 +12,8 @@ public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

// Configure Color-Chan.Discord.Commands
// EnableAutoSync is off by default. Turn this own if you dont want to send the slash command to discord manually.
var config = new SlashCommandConfiguration
{
EnableAutoSync = true // <-----
};
await host.RegisterSlashCommandsAsync(Assembly.GetExecutingAssembly(), config).ConfigureAwait(false); // <-----
// Register all the commands in an Assembly.
await host.RegisterSlashCommandsAsync(Assembly.GetExecutingAssembly()).ConfigureAwait(false); // <-----

// Run the WebHost, and start accepting requests.
await host.RunAsync().ConfigureAwait(false);
Expand Down
13 changes: 12 additions & 1 deletion samples/Pong/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Color_Chan.Discord.Configurations;
using Color_Chan.Discord.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand All @@ -18,9 +19,19 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Configure Color-Chan.Discord
var config = new ColorChanConfigurations
{
SlashCommandConfigs = slashOptions =>
{
slashOptions.EnableAutoSync = true;
slashOptions.EnableAutoGetGuild = true;
}
};

// Replace the arguments with the data of your bot.
// Note: It is not recommended to hardcode them in, loading them from an environment variable or from a json file is better.
services.AddColorChanDiscord("TOKEN", "PUBLIC_KEY", 999999999999999); // <---
services.AddColorChanDiscord("TOKEN", "PUBLIC_KEY", 999999999999999, config); // <---

services.AddControllers();
}
Expand Down
121 changes: 19 additions & 102 deletions samples/RoleManager/Commands/RoleCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,23 @@
using System.Threading.Tasks;
using Color_Chan.Discord.Commands;
using Color_Chan.Discord.Commands.Attributes;
using Color_Chan.Discord.Commands.Attributes.ProvidedRequirements;
using Color_Chan.Discord.Commands.Modules;
using Color_Chan.Discord.Core.Common.API.DataModels.Application;
using Color_Chan.Discord.Core.Common.API.DataModels.Guild;
using Color_Chan.Discord.Core.Common.API.Params.Guild;
using Color_Chan.Discord.Core.Common.API.Rest;
using Color_Chan.Discord.Core.Common.Models.Interaction;
using Color_Chan.Discord.Core.Results;

namespace RoleManager.Commands
{
/// <summary>
/// The command module for all role related commands.
/// </summary>
[SlashCommandGroup("roles", "Gets, creates or updates roles.")]
[SlashCommandRateLimit(10, 30)] // Sets the rate limit for this command module to 10 requests per 30 seconds per user.
[SlashCommandRequireGuild] // Required all commands in this command module to be executed in a guild.
public class RoleCommands : SlashCommandModule
{
private readonly IDiscordRestGuild _restGuild;
Expand All @@ -38,35 +42,24 @@ public RoleCommands(IDiscordRestGuild restGuild)
/// </returns>
[SlashCommandGroup("add", "Adds a role.")]
[SlashCommand("default", "Adds a role with the default permissions.")]
public async Task<IDiscordInteractionResponse> AddDefaultRoleAsync
public async Task<Result<IDiscordInteractionResponse>> AddDefaultRoleAsync
(
[SlashCommandOption("name", "The name of the new role.", true)]
string roleName
)
{
var guildId = SlashContext.GuildId;

// Send an error message if the command was used in DMs.
var dmErrorResponse = CheckIfGuildIdExists();
if (dmErrorResponse is not null) return dmErrorResponse;

// Create the new role.
var roleConfig = new DiscordCreateGuildRole
{
Name = roleName,
Permissions = DiscordGuildPermission.None
};
var newRoleResponse = await _restGuild.CreateGuildRoleAsync(guildId!.Value, roleConfig).ConfigureAwait(false);
var newRoleResponse = await _restGuild.CreateGuildRoleAsync(SlashContext.GuildId!.Value, roleConfig).ConfigureAwait(false);

// Check if the role was successfully created.
if (!newRoleResponse.IsSuccessful)
{
var errorResponse = new SlashCommandResponseBuilder()
.WithContent("Failed to create the role.")
.MakePrivate()
.Build();

return errorResponse;
return FromSuccess("Failed to create the role.", true);
}

// Build the response embed.
Expand All @@ -75,14 +68,9 @@ string roleName
.WithDescription($"Role: {roleName} has been created.")
.WithColor(newRoleResponse.Entity!.Color)
.WithTimeStamp();

// Build the response with the embed.
var response = new SlashCommandResponseBuilder()
.WithEmbed(embedBuilder.Build())
.Build();


// Return the response to Discord.
return response;
return FromSuccess(embedBuilder.Build());
}

/// <summary>
Expand All @@ -92,34 +80,23 @@ string roleName
/// A <see cref="IDiscordInteractionResponse" /> with an embed containing whether or not the role has been deleted.
/// </returns>
[SlashCommand("delete", "Deletes a role!")]
public async Task<IDiscordInteractionResponse> DeleteRoleAsync
public async Task<Result<IDiscordInteractionResponse>> DeleteRoleAsync
(
[SlashCommandOption("role", "The role that will be deleted.", true, DiscordApplicationCommandOptionType.Role)]
ulong roleId
)
{
var guildId = SlashContext.GuildId;

// Send an error message if the command was used in DMs.
var dmErrorResponse = CheckIfGuildIdExists();
if (dmErrorResponse is not null) return dmErrorResponse;

// Get the role object.
var role = SlashContext.CommandRequest.Resolved?.Roles?.FirstOrDefault(x => x.Key == roleId).Value;

// Delete the role.
var auditLog = $"User: {SlashContext.Member?.User?.Username} requested this action";
var deleteResponse = await _restGuild.DeleteGuildRoleAsync(guildId!.Value, roleId, auditLog).ConfigureAwait(false);
var deleteResponse = await _restGuild.DeleteGuildRoleAsync(SlashContext.GuildId!.Value, roleId, auditLog).ConfigureAwait(false);

// Check if the role were successfully deleted.
if (!deleteResponse.IsSuccessful)
{
var errorResponse = new SlashCommandResponseBuilder()
.WithContent("Failed to delete the role.")
.MakePrivate()
.Build();

return errorResponse;
return FromSuccess("Failed to delete the role.", true);
}

// Build the response embed.
Expand All @@ -128,14 +105,9 @@ ulong roleId
.WithDescription("The role has been successfully deleted!")
.WithColor(role?.Color ?? Color.FromArgb(0))
.WithTimeStamp();

// Build the response with the embed.
var response = new SlashCommandResponseBuilder()
.WithEmbed(embedBuilder.Build())
.Build();


// Return the response to Discord.
return response;
return FromSuccess(embedBuilder.Build());
}

/// <summary>
Expand All @@ -145,26 +117,15 @@ ulong roleId
/// A <see cref="IDiscordInteractionResponse" /> with an embed containing the role names.
/// </returns>
[SlashCommand("lists", "Get a neat little list with all the roles!")]
public async Task<IDiscordInteractionResponse> ListRolesAsync()
public async Task<Result<IDiscordInteractionResponse>> ListRolesAsync()
{
var guildId = SlashContext.GuildId;

// Send an error message if the command was used in DMs.
var dmErrorResponse = CheckIfGuildIdExists();
if (dmErrorResponse is not null) return dmErrorResponse;

// Get the roles from the current guild.
var rolesResult = await _restGuild.GetGuildRolesAsync(guildId!.Value).ConfigureAwait(false);
var rolesResult = await _restGuild.GetGuildRolesAsync(SlashContext.GuildId!.Value).ConfigureAwait(false);

// Check if the roles were successfully loaded.
if (!rolesResult.IsSuccessful)
{
var errorResponse = new SlashCommandResponseBuilder()
.WithContent("Failed to get guild roles.")
.MakePrivate()
.Build();

return errorResponse;
return FromSuccess("Failed to get guild roles.", true);
}

// Build the response.
Expand All @@ -177,53 +138,9 @@ public async Task<IDiscordInteractionResponse> ListRolesAsync()
.WithDescription(description)
.WithColor(Color.HotPink)
.WithTimeStamp();

// Build the response with the embed.
var response = new SlashCommandResponseBuilder()
.WithEmbed(embedBuilder.Build())
.Build();

// Return the response to Discord.
return response;
}

/// <summary>
/// Checks if the guild id is null, since this could be null if it was used in DMs.
/// </summary>
/// <returns>
/// True if the commands was used in a guild.
/// </returns>
private bool RequestIsFromGuild()
{
return SlashContext.GuildId is not null;
}

/// <summary>
/// Checks if the command was used in a guild.
/// </summary>
/// <returns>
/// A <see cref="IDiscordInteractionResponse" /> if the commands was used in DMs.
/// null if the commands was used in a guild.
/// </returns>
private IDiscordInteractionResponse? CheckIfGuildIdExists()
{
if (RequestIsFromGuild()) return null;

// Build the response embed.
var errorEmbedBuilder = new DiscordEmbedBuilder()
.WithTitle("Error")
.WithDescription("This command can only be used in a server!")
.WithColor(Color.Red)
.WithTimeStamp();

// Build the response with the embed.
var errorResponse = new SlashCommandResponseBuilder()
.WithEmbed(errorEmbedBuilder.Build())
.MakePrivate()
.Build();


// Return the response to Discord.
return errorResponse;
return FromSuccess(embedBuilder.Build());
}
}
}
10 changes: 2 additions & 8 deletions samples/RoleManager/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Reflection;
using System.Threading.Tasks;
using Color_Chan.Discord.Commands.Configurations;
using Color_Chan.Discord.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
Expand All @@ -13,13 +12,8 @@ public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

// Configure Color-Chan.Discord.Commands
// EnableAutoSync is off by default. Turn this own if you dont want to send the slash command to discord manually.
var config = new SlashCommandConfiguration
{
EnableAutoSync = true // <-----
};
await host.RegisterSlashCommandsAsync(Assembly.GetExecutingAssembly(), config).ConfigureAwait(false); // <-----
// Register all the commands in an Assembly.
await host.RegisterSlashCommandsAsync(Assembly.GetExecutingAssembly()).ConfigureAwait(false); // <-----

// Run the WebHost, and start accepting requests.
await host.RunAsync().ConfigureAwait(false);
Expand Down
13 changes: 12 additions & 1 deletion samples/RoleManager/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Color_Chan.Discord.Configurations;
using Color_Chan.Discord.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand All @@ -18,9 +19,19 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Configure Color-Chan.Discord
var config = new ColorChanConfigurations
{
SlashCommandConfigs = slashOptions =>
{
slashOptions.EnableAutoSync = true;
slashOptions.EnableAutoGetGuild = true;
}
};

// Replace the arguments with the data of your bot.
// Note: It is not recommended to hardcode them in, loading them from an environment variable or from a json file is better.
services.AddColorChanDiscord("TOKEN", "PUBLIC_KEY", 999999999999999); // <---
services.AddColorChanDiscord("TOKEN", "PUBLIC_KEY", 999999999999999, config); // <---

services.AddControllers();
}
Expand Down
Loading

0 comments on commit 2ea7e0e

Please sign in to comment.