Skip to content

Commit

Permalink
update examples for dcs 10.5
Browse files Browse the repository at this point in the history
  • Loading branch information
Lulalaby committed Dec 20, 2023
1 parent 1852aae commit 5f3f4d4
Show file tree
Hide file tree
Showing 62 changed files with 4,193 additions and 250 deletions.
3,957 changes: 3,957 additions & 0 deletions .editorconfig

Large diffs are not rendered by default.

67 changes: 67 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
*.cs diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
*.sln merge=binary
*.csproj merge=binary
*.vbproj merge=binary
*.vcxproj merge=binary
*.vcproj merge=binary
*.dbproj merge=binary
*.fsproj merge=binary
*.lsproj merge=binary
*.wixproj merge=binary
*.modelproj merge=binary
*.sqlproj merge=binary
*.wwaproj merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

DisCatSharp.Docs/obj/.cache/build/** binary
DisCatSharp.Docs/obj/.cache/build/**/** binary
DisCatSharp.Docs/obj/.cache/build/**/* binary
1 change: 0 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,5 @@ jobs:
dotnet-version: |
8.0.100
7.0.404
6.x
- name: Build library
run: dotnet build -c Release -v normal
1 change: 0 additions & 1 deletion .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ jobs:
dotnet-version: |
8.0.100
7.0.404
6.x
- name: Autobuild
uses: github/codeql-action/autobuild@v3
Expand Down
8 changes: 4 additions & 4 deletions ApplicationCommands/ApplicationCommands.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Authors>Lala Sabathil &lt;aiko@aitsys.dev&gt;, Lunar Starstrum, QuantuChi</Authors>
<Company>Aiko IT Systems</Company>
<PackageId>DisCatSharp.Examples.ApplicationCommands</PackageId>
<Product>DisCatSharp.Examples.ApplicationCommands</Product>
<Description>DisCatSharp ApplicationCommands Example Bot</Description>
<Copyright>2021 AITSYS</Copyright>
<Copyright>2021-2024 AITSYS</Copyright>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryUrl>https://github.com/Aiko-IT-Systems/DisCatSharp.Examples</RepositoryUrl>
<RepositoryType>git</RepositoryType>
Expand All @@ -23,8 +23,8 @@
<NoWarn>1701;1702;DV2001</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DisCatSharp" Version="10.4.2-nightly-057" />
<PackageReference Include="DisCatSharp.ApplicationCommands" Version="10.4.2-nightly-057" />
<PackageReference Include="DisCatSharp" Version="10.5.0-nightly-001" />
<PackageReference Include="DisCatSharp.ApplicationCommands" Version="10.5.0-nightly-001" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
Expand Down
2 changes: 1 addition & 1 deletion ApplicationCommands/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("Usage", "CA2254:Template should be a static expression", Justification = "<Pending>", Scope = "member", Target = "~M:DisCatSharp.Examples.ApplicationCommands.Program.MainAsync(System.String[])~System.Threading.Tasks.Task")]
[assembly: SuppressMessage("Usage", "CA2254:Template should be a static expression", Justification = "<Pending>", Scope = "member", Target = "~M:DisCatSharp.Examples.ApplicationCommands.Program.MainAsync(System.String[])~System.Threading.Tasks.Task")]
2 changes: 1 addition & 1 deletion ApplicationCommands/src/Commands/MessageCopy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ public static async Task CommandAsync(ContextMenuContext context)
// CHALLENGE: Copy embeds/components to the new message
// CHALLENGE #2: Send message via webhook (with username and avatar of the original message author)
}
}
}
2 changes: 1 addition & 1 deletion ApplicationCommands/src/Commands/Ping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ public static async Task CommandAsync(InteractionContext context)

// CHALLENGE: Turns this into a lambda
}
}
}
4 changes: 1 addition & 3 deletions ApplicationCommands/src/Commands/RoleInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,8 @@ await context.CreateResponseAsync(InteractionResponseType.DeferredChannelMessage

// If the guild has a custom guild icon, set the embed's thumbnail to that icon.
if (context.Guild.IconUrl != null)
{
// CHALLENGE: Replace the jpg to the highest resolution png file using the Discord API.
embedBuilder.WithThumbnail(context.Guild.IconUrl);
}

// Add fields to the embed, giving general information about the role that isn't typically available through the normal client.
embedBuilder.AddField(new("Color", discordRole.Color.ToString(), true));
Expand All @@ -88,4 +86,4 @@ await context.CreateResponseAsync(InteractionResponseType.DeferredChannelMessage
// Change our previous "thinking" response to our actual result.
await context.EditResponseAsync(messageBuilder);
}
}
}
2 changes: 1 addition & 1 deletion ApplicationCommands/src/Commands/RollRandom.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,4 @@ public static async Task CommandAsync(InteractionContext context, [Option("rando
break;
}
}
}
}
2 changes: 1 addition & 1 deletion ApplicationCommands/src/Commands/Slap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,4 @@ public static async Task CommandAsync(ContextMenuContext context)
};
await context.EditResponseAsync(discordWebhookBuilder);
}
}
}
19 changes: 8 additions & 11 deletions ApplicationCommands/src/Commands/Tags.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class RealTags : ApplicationCommandsModule
/// <summary>
/// Tags will be cleared when the bot restarts.
/// </summary>
public static List<Tag> Tags { get; private set; } = new();
public static List<Tag> Tags { get; private set; } = [];

/// <summary>
/// Sends a premade message.
Expand Down Expand Up @@ -95,7 +95,7 @@ public static async Task SendAsync(InteractionContext context, [Autocomplete(typ
return;
}

var tag = Tags.FirstOrDefault(listTag => listTag.GuildId == context.Guild.Id && listTag.Name == tagName.ToLowerInvariant());
var tag = Tags.FirstOrDefault(listTag => listTag.GuildId == context.Guild.Id && listTag.Name.Equals(tagName, System.StringComparison.InvariantCultureIgnoreCase));

// The tag already exists, we can't allow duplicates to happen.
if (tag != null)
Expand Down Expand Up @@ -139,7 +139,7 @@ public static async Task DeleteAsync(InteractionContext context, [Option("name",
return;
}

var tag = Tags.FirstOrDefault(listTag => listTag.GuildId == context.Guild.Id && listTag.Name == tagName.ToLowerInvariant());
var tag = Tags.FirstOrDefault(listTag => listTag.GuildId == context.Guild.Id && listTag.Name.Equals(tagName, System.StringComparison.InvariantCultureIgnoreCase));
if (tag == null)
{
discordInteractionResponseBuilder.Content = $"Error: Tag {tagName.Sanitize().InlineCode()} not found!";
Expand Down Expand Up @@ -181,12 +181,9 @@ internal class TagsAutocompleteProvider : IAutocompleteProvider
public async Task<IEnumerable<DiscordApplicationCommandAutocompleteChoice>> Provider(AutocompleteContext context)
#pragma warning restore 1998
{
if (context.FocusedOption == null)
{
return null;
}

return Tags.RealTags.Tags.Where(listTag => listTag.GuildId == context.Interaction.Guild.Id)
.Select(item => new DiscordApplicationCommandAutocompleteChoice(item.Name, item.Name)).ToList();
return context.FocusedOption == null
? null
: Tags.RealTags.Tags.Where(listTag => listTag.GuildId == context.Interaction.Guild.Id)
.Select(item => new DiscordApplicationCommandAutocompleteChoice(item.Name, item.Name)).ToList();
}
}
}
5 changes: 2 additions & 3 deletions ApplicationCommands/src/Commands/Tell.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class Tell : ApplicationCommandsModule
/// Check if this command is executed in the guild.
/// </summary>
/// <param name="context">Interaction context</param>
public async override Task<bool> BeforeSlashExecutionAsync(InteractionContext context)
public override async Task<bool> BeforeSlashExecutionAsync(InteractionContext context)
{
if (context.Guild == null)
{
Expand All @@ -46,7 +46,6 @@ await context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSour
InteractionContext context,
[Option("victim", "Who the bot is messaging.")] DiscordUser victim,
[Choice("ModMail", "Please contact ModMail."), Choice("Behaviour", "Please stop being rude."), Choice("Advertisement", "Please stop advertising."), Choice("SFW", "Please keep things SFW."), Option("Phrase", "What to message to the victim.")]

string phrase
)
{
Expand Down Expand Up @@ -81,4 +80,4 @@ string phrase
await context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, discordInteractionResponseBuilder);
return;
}
}
}
18 changes: 5 additions & 13 deletions ApplicationCommands/src/Commands/TriggerHelp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,16 @@ await context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSour

// If the guild has a custom guild icon, set the embed's thumbnail to that icon.
if (context.Guild != null && context.Guild.IconUrl != null)
{
// CHALLENGE: Replace the jpg to the highest resolution png file using the Discord API.
discordEmbedBuilder.WithThumbnail(context.Guild.IconUrl);
}

// Iterate through each of the command's parameters, selecting only the ones that have the Option attribute.
foreach (var parameter in command.GetParameters())
{
var parameterChoice = parameter.GetCustomAttribute<OptionAttribute>(false);
// If the option attribute doesn't exist on the method argument, skip it.
if (parameterChoice == null)
{
continue;
}

// Add the argument's description to the embed, specifying if it's optional or required.
discordEmbedBuilder.AddField(new((parameter.IsOptional ? "(Optional) " : "(Required) ") + parameterChoice.Name, $"**Type:** {parameter.ParameterType.Name}\n**Description:** {parameterChoice.Description}"));
Expand All @@ -83,7 +79,7 @@ await context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSour
/// </summary>
public class TriggerHelpChoiceProvider : IChoiceProvider
{
internal static readonly Dictionary<string, MethodInfo> Commands = new();
internal static readonly Dictionary<string, MethodInfo> Commands = [];

/// <summary>
/// Adding all commands and subcommands to Commands field.
Expand All @@ -95,8 +91,7 @@ public static void SearchCommands(Type type, string commandName = "")
// Get all nested group commands in the type variable/class
var nestedTypes = type.GetNestedTypes().Where(innerType => innerType?.GetCustomAttribute<SlashCommandGroupAttribute>() != null).ToList();
// If any nested group commands are available
if (nestedTypes.Any())
{
if (nestedTypes.Count != 0)
// Iterate through each subgroup command
foreach (var nestedType in nestedTypes)
{
Expand All @@ -109,12 +104,11 @@ public static void SearchCommands(Type type, string commandName = "")
// There are still nested classes, throw it back into the recursive loop.
SearchCommands(nestedType, commandName);
}
}
else
{
// Get all slash commands in the class
var commands = type.GetMethods().Where(method => method.GetCustomAttribute<SlashCommandAttribute>() != null).ToList();
if (!commands.Any())
if (commands.Count == 0)
return;

foreach (var command in commands)
Expand Down Expand Up @@ -145,17 +139,15 @@ public Task<IEnumerable<DiscordApplicationCommandOptionChoice>> Provider()

// Find all command or subgroup commands from the classes
foreach (var command in commandClasses)
{
SearchCommands(command);
}

// SearchCommands registers the commands into a Dictionary<string, MethodInfo>. Since we only need the command name, we can just select the keys.
List<DiscordApplicationCommandOptionChoice> discordApplicationCommandOptionChoices = Commands.Keys.Select(commandName => new DiscordApplicationCommandOptionChoice(commandName, commandName)).ToList();
var discordApplicationCommandOptionChoices = Commands.Keys.Select(commandName => new DiscordApplicationCommandOptionChoice(commandName, commandName)).ToList();

// Sort the options alphabetically, in case Discord doesn't do that for us already.
discordApplicationCommandOptionChoices.Sort((DiscordApplicationCommandOptionChoice x, DiscordApplicationCommandOptionChoice y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));

// Return our commands to the help function.
return Task.FromResult(discordApplicationCommandOptionChoices.AsEnumerable());
}
}
}
4 changes: 2 additions & 2 deletions ApplicationCommands/src/Commands/UserInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class UserInfo : ApplicationCommandsModule
/// context menu commands use BeforeContextMenuExecutionAsync/AfterContextMenuExecutionAsync
/// </summary>
/// <param name="context">Context menu context</param>
public async override Task<bool> BeforeContextMenuExecutionAsync(ContextMenuContext context)
public override async Task<bool> BeforeContextMenuExecutionAsync(ContextMenuContext context)
{
if (context.Guild != null)
return true;
Expand Down Expand Up @@ -60,4 +60,4 @@ public static async Task CommandAsync(ContextMenuContext context)

// CHALLENGE: Copy embeds/components to the new message
}
}
}
4 changes: 1 addition & 3 deletions ApplicationCommands/src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,7 @@ public static async Task MainAsync(string[] args)
// If the guild ID is not provided, then register global commands.
ulong? guildId = null;
if (args.Length > 1)
{
guildId = ulong.Parse(args[1]);
}

// In order not to list all the commands when adding, you can create a list of all commands with this.
/*Type appCommandModule = typeof(ApplicationCommandsModule);
Expand Down Expand Up @@ -148,4 +146,4 @@ private static Task Context_ContextMenuCommandErroredAsync(ApplicationCommandsEx
Log.Logger.Error("Context: {ExceptionMessage} | CN: {ContextCommandName} | IID: {ContextInteractionId}", e.Exception.Message, e.Context.CommandName, e.Context.InteractionId);
return Task.CompletedTask;
}
}
}
2 changes: 1 addition & 1 deletion ApplicationCommands/src/Tag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ public class Tag

// When the tag was created at.
public DateTime CreatedAt { get; } = DateTime.UtcNow;
}
}
4 changes: 1 addition & 3 deletions Basics/AppCommands/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ public static async Task ShutdownAsync(InteractionContext ctx)
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Shutting down!"));
}
else
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("You are not allowed to execute this request!"));
}
}

/// <summary>
Expand Down Expand Up @@ -94,4 +92,4 @@ public static async Task AvatarAsync(ContextMenuContext ctx)
}.WithFooter($"Requested by {ctx.Member.DisplayName}", ctx.Member.AvatarUrl).WithAuthor($"{ctx.TargetUser.Username}", ctx.TargetUser.AvatarUrl, ctx.TargetUser.AvatarUrl);
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().AddEmbed(embed.Build()));
}
}
}
Loading

0 comments on commit 5f3f4d4

Please sign in to comment.