diff --git a/Documentation/.eslintrc.cjs b/Documentation/.eslintrc.cjs deleted file mode 100644 index ec366045d..000000000 --- a/Documentation/.eslintrc.cjs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -module.exports = { - env: { - browser: true - }, - ignorePatterns: ['**/*.js'], - extends: ['standard', 'eslint:recommended', 'plugin:@typescript-eslint/recommended'], - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint'], - root: true, - rules: { - 'space-before-function-paren': ['warn', 'never'], - } -}; diff --git a/Documentation/.eslintrc.json b/Documentation/.eslintrc.json new file mode 100644 index 000000000..5021f0b18 --- /dev/null +++ b/Documentation/.eslintrc.json @@ -0,0 +1,26 @@ +{ + "env": { + "browser": true, + "es2024": true, + "node": true + }, + "extends": ["standard", "plugin:@typescript-eslint/recommended"], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": 2024, + "sourceType": "module" + }, + "plugins": ["@typescript-eslint"], + "rules": { + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/explicit-function-return-types": "off", + "no-unused-vars": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { + "argsIgnorePattern": "^_", + "varsIgnorePattern": "^_" + } + ] + } +} diff --git a/Documentation/.gitignore b/Documentation/.gitignore index 193c07815..f4846c600 100644 --- a/Documentation/.gitignore +++ b/Documentation/.gitignore @@ -1,6 +1,6 @@ -############### -# folder # -############### +############## +# folder # +############## /**/DROP/ /**/TEMP/ /**/packages/ diff --git a/Documentation/build-templates.js b/Documentation/build-templates.js index 2c25bc260..5fa91f909 100644 --- a/Documentation/build-templates.js +++ b/Documentation/build-templates.js @@ -2,7 +2,6 @@ import { build as _build } from "esbuild"; import { copy } from "esbuild-plugin-copy"; -import { sassPlugin } from "esbuild-sass-plugin"; import { cpSync, rmSync } from "fs"; import { join } from "path"; @@ -40,10 +39,10 @@ async function buildNetCordTemplate() { entryPoints: [ `${template}/src/docfx.ts`, `${template}/src/search-worker.ts`, + `${template}/src/json-link-data.ts`, ], external: ["./main.js"], plugins: [ - sassPlugin(), copy({ assets: { from: [`${template}/src/*.js`], @@ -66,7 +65,12 @@ async function buildNetCordTemplate() { loader, }; - await _build(config); + try { + await _build(config); + } catch (error) { + console.error("Template build failed:", error.message); + process.exit(1); + } } function copyToDist() { diff --git a/Documentation/docfx.json b/Documentation/docfx.json index 0cc07512f..efb48ba00 100644 --- a/Documentation/docfx.json +++ b/Documentation/docfx.json @@ -36,6 +36,9 @@ "resource": [ { "files": [ "images/**", "favicon.ico", "logo.svg", "robots.txt" ] + }, + { + "files": [ "guides/**/BareBones/**", "guides/**/Barebones/**", "guides/**/GenericHosts/**" ] } ], "overwrite": [ @@ -44,6 +47,11 @@ "exclude": [ "obj/**", "_site/**" ] } ], + "warningLevel": "warn", + "lruSize": 1000, + "xrefService": [ + "https://xref.docs.microsoft.com/query?project=dotnet&uid={uid}" + ], "dest": "_site", "template": [ "default", "templates/NetCord" ], "markdownEngineName": "markdig", @@ -58,7 +66,9 @@ "_enableSearch": true, "_disableFooter": true, "_noindex": true, - "_lang": "en" + "_lang": "en", + "_jsonLinkData": true, + "_canonicalUrlPattern": "https://netcord.dev/{path}" }, "fileMetadata": { "_noindex": { @@ -68,6 +78,8 @@ "!docs/**": false } }, - "xref": [ "https://learn.microsoft.com/en-us/dotnet/.xrefmap.json" ] + "xref": [ + "https://learn.microsoft.com/en-us/dotnet/.xrefmap.json" + ] } } diff --git a/Documentation/guides/.markdownlint.json b/Documentation/guides/.markdownlint.json new file mode 100644 index 000000000..49a215fe4 --- /dev/null +++ b/Documentation/guides/.markdownlint.json @@ -0,0 +1,32 @@ +{ + "default": true, + "MD003": { + "style": "atx" + }, + "MD004": { + "style": "dash" + }, + "MD007": { + "indent": 2 + }, + "MD013": false, + "MD024": { + "siblings_only": true + }, + "MD025": { + "front_matter_title": "" + }, + "MD033": { + "allowed_elements": ["antml:function_calls", "antml:invoke", "antml:parameter"] + }, + "MD041": false, + "MD046": { + "style": "fenced" + }, + "MD049": { + "style": "underscore" + }, + "MD050": { + "style": "asterisk" + } +} diff --git a/Documentation/guides/advanced-topics/caching-strategies.md b/Documentation/guides/advanced-topics/caching-strategies.md new file mode 100644 index 000000000..c0a161e1a --- /dev/null +++ b/Documentation/guides/advanced-topics/caching-strategies.md @@ -0,0 +1,36 @@ +--- +title: Optimizing Discord Bot Performance with Caching Strategies +description: Implement efficient caching for Discord entities. Learn cache configuration, memory management, and performance optimization in NetCord. +omitAppTitle: true +--- + +# Caching Strategies + +> [!NOTE] +> Content for this section is under development. + +## Cache Interface {#cache-interface} + +IGatewayClientCache. + +## Concurrent vs Immutable {#concurrent-vs-immutable} + +ConcurrentGatewayClientCache, ImmutableGatewayClientCache. + +## Custom Cache {#custom-cache} + +Implementing custom caching. + +--- + +## Navigation + +← **Previous:** @"advanced-topics/rate-limiting?text=Rate Limiting" | **Next:** @"advanced-topics/connection-resilience?text=Connection Resilience" → + +## See Also + +- @"advanced-topics/rate-limiting?text=Rate Limiting" - Cache reduces rate limit hits +- @"advanced-topics/sharding?text=Sharding" - Cache across shards +- @"discord-entities/overview?text=Discord Entities" - Entity caching +- @"dotnet-integration/configuration?text=Configuration" - Cache configuration +- @"events/intents?text=Intents" - Control cached data diff --git a/Documentation/guides/advanced-topics/connection-resilience.md b/Documentation/guides/advanced-topics/connection-resilience.md new file mode 100644 index 000000000..1fb588d4d --- /dev/null +++ b/Documentation/guides/advanced-topics/connection-resilience.md @@ -0,0 +1,36 @@ +--- +title: Building Resilient Discord Bot Connections with NetCord +description: Handle disconnections and maintain reliable gateway connections. Learn reconnection strategies, session resumption, and connection monitoring. +omitAppTitle: true +--- + +# Connection Resilience + +> [!NOTE] +> Content for this section is under development. + +## Reconnect Strategies {#reconnect-strategies} + +Built-in strategies. + +## Custom Strategy {#custom-strategy} + +Implementing custom reconnection logic. + +## Disconnect Handling {#disconnect-handling} + +Disconnected event. + +--- + +## Navigation + +← **Previous:** @"advanced-topics/caching-strategies?text=Caching Strategies" | **Next:** @"migration/index?text=Migration Guide" → + +## See Also + +- @"dotnet-integration/configuration?text=Configuration" - Configure retry policies +- @"dotnet-integration/logging?text=Logging" - Log connection events +- @"events/gateway-events?text=Gateway Events" - Ready and Resumed events +- @"deployment/docker?text=Docker Deployment" - Container restart policies +- [Discord Docs: Gateway Lifecycle](https://discord.com/developers/docs/topics/gateway#connections) diff --git a/Documentation/guides/advanced-topics/rate-limiting.md b/Documentation/guides/advanced-topics/rate-limiting.md new file mode 100644 index 000000000..c87bea231 --- /dev/null +++ b/Documentation/guides/advanced-topics/rate-limiting.md @@ -0,0 +1,36 @@ +--- +title: Handling Discord API Rate Limits in NetCord Bots +description: Manage Discord API rate limits effectively. Learn rate limit handling, bucket strategies, and avoiding 429 errors with NetCord. +omitAppTitle: true +--- + +# Rate Limiting + +> [!NOTE] +> Content for this section is under development. + +## Rate Limit Manager {#rate-limit-manager} + +IRateLimitManager. + +## Handling Rate Limits {#handling-rate-limits} + +RestRateLimitHandling. + +## Gateway Rate Limits {#gateway-rate-limits} + +IRateLimiterProvider. + +--- + +## Navigation + +← **Previous:** @"advanced-topics/sharding?text=Sharding" | **Next:** @"advanced-topics/caching-strategies?text=Caching Strategies" → + +## See Also + +- @"advanced-topics/caching-strategies?text=Caching Strategies" - Reduce API calls +- @"webhooks/managing-webhooks?text=Managing Webhooks" - Webhook rate limits +- @"services-framework/preconditions?text=Preconditions" - Command cooldowns +- @"troubleshooting/common-issues?text=Common Issues" - Rate limit errors +- [Discord Docs: Rate Limits](https://discord.com/developers/docs/topics/rate-limits) diff --git a/Documentation/guides/advanced-topics/sharding.md b/Documentation/guides/advanced-topics/sharding.md new file mode 100644 index 000000000..5b18b5922 --- /dev/null +++ b/Documentation/guides/advanced-topics/sharding.md @@ -0,0 +1,40 @@ +--- +title: Scaling Discord Bots with Sharding in NetCord +description: Scale large Discord bots across multiple shards. Learn shard management, data synchronization, and multi-shard architecture with NetCord. +omitAppTitle: true +--- + +# Sharding + +> [!NOTE] +> Content for this section is under development. + +## Why Sharding {#why-sharding} + +When you need it (2500+ guilds). + +## Sharded Client {#sharded-client} + +ShardedGatewayClient. + +## Shard Configuration {#shard-configuration} + +Shard count and shard IDs. + +## Hosting Integration {#hosting-integration} + +UseShardedDiscordGateway. + +--- + +## Navigation + +← **Previous:** @"deployment/cloud-hosting?text=Cloud Hosting" | **Next:** @"advanced-topics/rate-limiting?text=Rate Limiting" → + +## See Also + +- @"advanced-topics/caching-strategies?text=Caching Strategies" - Cache across shards +- @"advanced-topics/connection-resilience?text=Connection Resilience" - Shard reconnection +- @"deployment/cloud-hosting?text=Cloud Hosting" - Deploy sharded bots +- @"dotnet-integration/generic-host?text=Generic Host" - Configure sharding +- [Discord Docs: Sharding](https://discord.com/developers/docs/topics/gateway#sharding) diff --git a/Documentation/guides/basic-concepts/HttpInteractions/HttpInteractionHandler.cs b/Documentation/guides/basic-concepts/HttpInteractions/HttpInteractionHandler.cs deleted file mode 100644 index ba50684b8..000000000 --- a/Documentation/guides/basic-concepts/HttpInteractions/HttpInteractionHandler.cs +++ /dev/null @@ -1,13 +0,0 @@ -using NetCord; -using NetCord.Hosting; - -namespace MyBot; - -public class HttpInteractionHandler(ILogger logger) : IHttpInteractionHandler -{ - public ValueTask HandleAsync(Interaction interaction) - { - logger.LogInformation("Received interaction: {}", interaction); - return default; - } -} diff --git a/Documentation/guides/basic-concepts/HttpInteractions/HttpInteractions.csproj b/Documentation/guides/basic-concepts/HttpInteractions/HttpInteractions.csproj deleted file mode 100644 index ae53d0f85..000000000 --- a/Documentation/guides/basic-concepts/HttpInteractions/HttpInteractions.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - Exe - - - - - - - - - diff --git a/Documentation/guides/basic-concepts/HttpInteractions/Program.cs b/Documentation/guides/basic-concepts/HttpInteractions/Program.cs deleted file mode 100644 index 7415a3d82..000000000 --- a/Documentation/guides/basic-concepts/HttpInteractions/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using NetCord.Hosting.AspNetCore; -using NetCord.Hosting.Rest; -using NetCord.Hosting.Services.ApplicationCommands; - -var builder = WebApplication.CreateBuilder(args); - -builder.Services - .AddDiscordRest() - .AddHttpApplicationCommands(); - -var app = builder.Build(); - -app.AddSlashCommand("ping", "Ping!", () => "Pong!"); - -// You can specify any pattern here, but remember to update it in the Discord Developer Portal -app.UseHttpInteractions("/interactions"); - -await app.RunAsync(); diff --git a/Documentation/guides/basic-concepts/HttpInteractions/Properties/launchSettings.json b/Documentation/guides/basic-concepts/HttpInteractions/Properties/launchSettings.json deleted file mode 100644 index e996b6a69..000000000 --- a/Documentation/guides/basic-concepts/HttpInteractions/Properties/launchSettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "profiles": { - "HttpInteractions": { - "commandName": "Project", - "launchBrowser": false, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "https://localhost:56793" - } - } -} diff --git a/Documentation/guides/basic-concepts/HttpInteractions/appsettings.json b/Documentation/guides/basic-concepts/HttpInteractions/appsettings.json deleted file mode 100644 index e88845212..000000000 --- a/Documentation/guides/basic-concepts/HttpInteractions/appsettings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "Discord": { - "Token": "Token from Discord Developer Portal", - "PublicKey": "Public Key from Discord Developer Portal" - } -} diff --git a/Documentation/guides/basic-concepts/RespondingToInteractions/Program.cs b/Documentation/guides/basic-concepts/RespondingToInteractions/Program.cs deleted file mode 100644 index d1653ea57..000000000 --- a/Documentation/guides/basic-concepts/RespondingToInteractions/Program.cs +++ /dev/null @@ -1,104 +0,0 @@ -using NetCord; -using NetCord.Rest; - -#pragma warning disable IDE0017, IDE0040, IDE0051, IDE0059, CS8321 - -static async Task RespondAsync() -{ - Interaction interaction = null!; - InteractionCallbackProperties callback = null!; - - await interaction.SendResponseAsync(callback); -} - -static void Callbacks() -{ - InteractionCallbackProperties callback; - - callback = InteractionCallback.Message("Here is a sample message interaction callback!"); - - callback = InteractionCallback.DeferredMessage(); - - callback = InteractionCallback.DeferredMessage(MessageFlags.Ephemeral); - - callback = InteractionCallback.DeferredModifyMessage; - - callback = InteractionCallback.ModifyMessage(message => message.Content = "New content!"); - - callback = InteractionCallback.ModifyMessage(message => message.WithContent("New content!")); - - callback = InteractionCallback.Modal(new("intro", "Introduce Yourself") - { - new LabelProperties("First Name", new TextInputProperties("name", TextInputStyle.Short)), - new LabelProperties("Your Bio", new TextInputProperties("bio", TextInputStyle.Paragraph)), - }); - - callback = InteractionCallback.Modal(new ModalProperties("intro", "Introduce Yourself") - .AddComponents( - new LabelProperties("First Name", new TextInputProperties("name", TextInputStyle.Short)), - new LabelProperties("Your Bio", new TextInputProperties("bio", TextInputStyle.Paragraph)))); - - callback = InteractionCallback.Modal(new("intro", "Introduce Yourself") - { - new LabelProperties("First Name", new TextInputProperties("name", TextInputStyle.Short) - { - MinLength = 2, - MaxLength = 32, - Placeholder = "Enter your name", - }), - new LabelProperties("Your Bio", new TextInputProperties("bio", TextInputStyle.Paragraph) - { - MinLength = 10, - Required = false, - Value = "I love programming!", - }), - }); - - callback = InteractionCallback.Modal(new ModalProperties("intro", "Introduce Yourself") - .AddComponents( - new LabelProperties("First Name", new TextInputProperties("name", TextInputStyle.Short) - .WithMinLength(2) - .WithMaxLength(32) - .WithPlaceholder("Enter your name")), - new LabelProperties("Your Bio", new TextInputProperties("bio", TextInputStyle.Paragraph) - .WithMinLength(10) - .WithRequired(false) - .WithValue("I love programming!")))); - - callback = InteractionCallback.Autocomplete([new("Dog", "dog"), new("Cat", "cat")]); - - callback = InteractionCallback.Autocomplete([new("Frog", 0), new("Duck", 1)]); - - callback = InteractionCallback.Autocomplete( - [ - new("Lion", "lion") - { - NameLocalizations = new Dictionary { ["pl"] = "Lew" }, - }, - new("Elephant", "elephant") - { - NameLocalizations = new Dictionary { ["pl"] = "Słoń" }, - }, - ]); - - callback = InteractionCallback.Autocomplete( - [ - new ApplicationCommandOptionChoiceProperties("Lion", "lion") - .WithNameLocalizations(new Dictionary { ["pl"] = "Lew" }), - new ApplicationCommandOptionChoiceProperties("Elephant", "elephant") - .WithNameLocalizations(new Dictionary { ["pl"] = "Słoń" }), - ]); - - callback = InteractionCallback.Pong; -} - -static async Task RespondDeferredAsync() -{ - Interaction interaction = null!; - - await interaction.ModifyResponseAsync(message => message.Content = "The response was modified!"); - - await interaction.ModifyResponseAsync(message => message.WithContent("The response was modified!")); - - await interaction.SendFollowupMessageAsync("The response was provided via follow-up!"); -} diff --git a/Documentation/guides/basic-concepts/RespondingToInteractions/RespondingToInteractions.csproj b/Documentation/guides/basic-concepts/RespondingToInteractions/RespondingToInteractions.csproj deleted file mode 100644 index 559b2b344..000000000 --- a/Documentation/guides/basic-concepts/RespondingToInteractions/RespondingToInteractions.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - - - - - - - diff --git a/Documentation/guides/basic-concepts/SendingMessages/Program.cs b/Documentation/guides/basic-concepts/SendingMessages/Program.cs deleted file mode 100644 index b00a331ce..000000000 --- a/Documentation/guides/basic-concepts/SendingMessages/Program.cs +++ /dev/null @@ -1,314 +0,0 @@ -using NetCord; -using NetCord.Rest; - -#pragma warning disable IDE0017, IDE0040, IDE0051, IDE0059, CS8321 - -async static Task PropertiesAsync() -{ - IMessageProperties message = null!; - - message.Content = "Hello, World!"; - - message.WithContent("Hello, World!"); - - EmbedProperties embed; - - embed = new() - { - Title = "Welcome to the Baking Club!", - Description = "Join us for delicious recipes and baking tips!", - Url = "https://example.com", - Timestamp = DateTimeOffset.UtcNow, - Color = new(0xFFA500), - Footer = new() - { - Text = "Happy Baking!", - IconUrl = "https://example.com/images/baking-icon.png", - }, - Image = "https://example.com/images/cake.jpg", - Thumbnail = "https://example.com/images/rolling-pin.png", - Author = new() - { - Name = "Baking Club", - Url = "https://example.com", - IconUrl = "https://example.com/images/club-logo.png", - }, - Fields = - [ - new() - { - Name = "Today's Special Recipe", - Value = "Chocolate Lava Cake", - }, - new() - { - Name = "Next Meetup", - Value = "Sunday, 4 PM", - Inline = true, - }, - new() - { - Name = "Location", - Value = "123 Baker's Street", - Inline = true, - }, - new() - { - Name = "Membership Fee", - Value = "Free for the first month!", - Inline = true, - }, - ], - }; - - embed = new EmbedProperties() - .WithTitle("Welcome to the Baking Club!") - .WithDescription("Join us for delicious recipes and baking tips!") - .WithUrl("https://example.com") - .WithTimestamp(DateTimeOffset.UtcNow) - .WithColor(new(0xFFA500)) - .WithFooter(new EmbedFooterProperties() - .WithText("Happy Baking!") - .WithIconUrl("https://example.com/images/baking-icon.png")) - .WithImage("https://example/com/images/cake.jpg") - .WithThumbnail("https://example.com/images/rolling-pin.png") - .WithAuthor(new EmbedAuthorProperties() - .WithName("Baking Club") - .WithUrl("https://example.com") - .WithIconUrl("https://example.com/images/club-logo.png")) - .AddFields( - new EmbedFieldProperties() - .WithName("Today's Special Recipe") - .WithValue("Chocolate Lava Cake"), - new EmbedFieldProperties() - .WithName("Next Meetup") - .WithValue("Sunday, 4 PM") - .WithInline(), - new EmbedFieldProperties() - .WithName("Location") - .WithValue("123 Baker's Street") - .WithInline(), - new EmbedFieldProperties() - .WithName("Membership Fee") - .WithValue("Free for the first month!") - .WithInline()); - - message.Embeds = [embed]; - - message.AddEmbeds(embed); - - message.AllowedMentions = AllowedMentionsProperties.All; - - message.WithAllowedMentions(AllowedMentionsProperties.All); - - message.AllowedMentions = AllowedMentionsProperties.None; - - message.WithAllowedMentions(AllowedMentionsProperties.None); - - message.AllowedMentions = new() - { - Everyone = true, // Allow @everyone and @here - ReplyMention = true, // Allow reply mention - AllowedRoles = [988888771187581010], // Allow specific roles - AllowedUsers = [265546281693347841], // Allow specific users - }; - - message.WithAllowedMentions(new AllowedMentionsProperties() - .WithEveryone() // Allow @everyone and @here - .WithReplyMention() // Allow reply mention - .AddAllowedRoles(988888771187581010) // Allow specific roles - .AddAllowedUsers(265546281693347841)); // Allow specific users - - AttachmentProperties attachment; - - attachment = new AttachmentProperties("hello.txt", new MemoryStream("Hello!"u8.ToArray())); - - attachment = new Base64AttachmentProperties("hello.txt", new MemoryStream("SGVsbG8sIGJhc2U2NCE="u8.ToArray())); - - attachment = new QuotedPrintableAttachmentProperties("polish.txt", - new MemoryStream("R=C3=B3=C5=BCowy means pink"u8.ToArray())); - - TextChannel textChannel = null!; - - HttpClient httpClient = null!; - - // Create a bucket with a file named "hello.txt" - var buckets = await textChannel.CreateGoogleCloudPlatformStorageBucketsAsync([new("hello.txt")]); - - var bucket = buckets[0]; - - // Upload the file content to the bucket - var response = await httpClient.PutAsync(bucket.UploadUrl, new StringContent("Hello, Google!")); - response.EnsureSuccessStatusCode(); - - attachment = new GoogleCloudPlatformAttachmentProperties("hello.txt", bucket.UploadFileName); - - attachment.Title = "Hello, World!"; - attachment.Description = "This is a file named hello.txt"; - - attachment - .WithTitle("Hello, World!") - .WithDescription("This is a file named hello.txt"); - - message.Attachments = [attachment]; - - message.AddAttachments(attachment); - - IMessageComponentProperties component; - - component = new ActionRowProperties - { - new ButtonProperties("welcome", "Welcome", EmojiProperties.Standard("👋"), ButtonStyle.Primary), - new ButtonProperties("hug", EmojiProperties.Custom(356377264209920002), ButtonStyle.Success), - new ButtonProperties("goodbye", "Goodbye", ButtonStyle.Secondary) - { - Disabled = true, - }, - new LinkButtonProperties("https://netcord.dev", "Learn More"), - new PremiumButtonProperties(1271914991536312372), - }; - - component = new ActionRowProperties() - .AddComponents( - new ButtonProperties("welcome", "Welcome", EmojiProperties.Standard("👋"), ButtonStyle.Primary), - new ButtonProperties("hug", EmojiProperties.Custom(356377264209920002), ButtonStyle.Success), - new ButtonProperties("goodbye", "Goodbye", ButtonStyle.Secondary) - .WithDisabled(), - new LinkButtonProperties("https://netcord.dev", "Learn More"), - new PremiumButtonProperties(1271914991536312372)); - - component = new StringMenuProperties("animal") - { - new("Dog", "dog") - { - Default = true, - Emoji = EmojiProperties.Standard("🐶"), - Description = "A loyal companion", - }, - new("Cat", "cat") - { - Emoji = EmojiProperties.Standard("🐱"), - Description = "A curious feline", - }, - new("Bird", "bird") - { - Emoji = EmojiProperties.Standard("🐦"), - Description = "A chirpy flyer", - }, - }; - - component = new StringMenuProperties("animal") - .AddOptions( - new StringMenuSelectOptionProperties("Dog", "dog") - .WithDefault() - .WithEmoji(EmojiProperties.Standard("🐶")) - .WithDescription("A loyal companion"), - new StringMenuSelectOptionProperties("Cat", "cat") - .WithEmoji(EmojiProperties.Standard("🐱")) - .WithDescription("A curious feline"), - new StringMenuSelectOptionProperties("Bird", "bird") - .WithEmoji(EmojiProperties.Standard("🐦")) - .WithDescription("A chirpy flyer")); - - component = new ChannelMenuProperties("channel") - { - DefaultValues = [1124777547687788626], - ChannelTypes = [ChannelType.ForumGuildChannel, ChannelType.PublicGuildThread], - }; - - component = new ChannelMenuProperties("channel") - .AddDefaultValues(1124777547687788626) - .AddChannelTypes(ChannelType.ForumGuildChannel, ChannelType.PublicGuildThread); - - component = new MentionableMenuProperties("mentionable") - { - DefaultValues = - [ - new(803324257194082314, MentionableValueType.User), - ], - }; - - component = new MentionableMenuProperties("mentionable") - .AddDefaultValues( - new MentionableValueProperties(803324257194082314, MentionableValueType.User)); - - component = new RoleMenuProperties("role") - { - DefaultValues = [803169206115237908], - }; - - component = new RoleMenuProperties("role") - .AddDefaultValues(803169206115237908); - - component = new UserMenuProperties("user") - { - DefaultValues = [233590074724319233], - }; - - component = new UserMenuProperties("user") - .AddDefaultValues(233590074724319233); - - message.Components = [component]; - - message.AddComponents(component); - - message.Flags = MessageFlags.SuppressEmbeds | MessageFlags.SuppressNotifications; - - message.WithFlags(MessageFlags.SuppressEmbeds | MessageFlags.SuppressNotifications); -} - -static void Menu() -{ - MenuProperties component = null!; - - component.Placeholder = "Select 2-5 animals"; - component.MinValues = 2; - component.MaxValues = 5; - component.Disabled = true; - - component - .WithPlaceholder("Select 2-5 animals") - .WithMinValues(2) - .WithMaxValues(5) - .WithDisabled(); -} - -static void ImplicitConversion() -{ - MessageProperties message = "Hello, World!"; -} - -static class Classic -{ - static T CreateMessage() where T : IMessageProperties, new() - { - return new() - { - Content = "Hello, World!", - Components = [], - }; - } -} - -static class Fluent -{ - static T CreateMessage() where T : IMessageProperties, new() - { - T message = new(); - - message - .WithContent("Hello, World!") - .WithComponents([]); - - return message; - } - - static void UseCreateMessage() - { - IMessageProperties message; - - message = CreateMessage(); - - message = CreateMessage(); - } -} diff --git a/Documentation/guides/basic-concepts/SendingMessages/SendingMessages.csproj b/Documentation/guides/basic-concepts/SendingMessages/SendingMessages.csproj deleted file mode 100644 index 559b2b344..000000000 --- a/Documentation/guides/basic-concepts/SendingMessages/SendingMessages.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - - - - - - - diff --git a/Documentation/guides/basic-concepts/Sharding/Program.cs b/Documentation/guides/basic-concepts/Sharding/Program.cs deleted file mode 100644 index 41fdb7e6f..000000000 --- a/Documentation/guides/basic-concepts/Sharding/Program.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; - -ShardedGatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new ShardedGatewayClientConfiguration -{ - LoggerFactory = ShardedConsoleLogger.GetFactory(), -}); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/basic-concepts/Sharding/RegisteringHandlers.cs b/Documentation/guides/basic-concepts/Sharding/RegisteringHandlers.cs deleted file mode 100644 index b6f0caaf3..000000000 --- a/Documentation/guides/basic-concepts/Sharding/RegisteringHandlers.cs +++ /dev/null @@ -1,24 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; - -namespace MyBot; - -internal class RegisteringHandlers -{ - public static async Task RegisterHandlersAsync() - { - ShardedGatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new ShardedGatewayClientConfiguration - { - LoggerFactory = ShardedConsoleLogger.GetFactory(), - }); - - client.MessageUpdate += async (client, message) => - { - await message.ReplyAsync("Message updated!"); - }; - - await client.StartAsync(); - await Task.Delay(-1); - } -} diff --git a/Documentation/guides/basic-concepts/Sharding/Sharding.csproj b/Documentation/guides/basic-concepts/Sharding/Sharding.csproj deleted file mode 100644 index 75d3fd4b9..000000000 --- a/Documentation/guides/basic-concepts/Sharding/Sharding.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - - - - - - - diff --git a/Documentation/guides/basic-concepts/ShardingHosting/MessageUpdateHandler.cs b/Documentation/guides/basic-concepts/ShardingHosting/MessageUpdateHandler.cs deleted file mode 100644 index 1872e7bef..000000000 --- a/Documentation/guides/basic-concepts/ShardingHosting/MessageUpdateHandler.cs +++ /dev/null @@ -1,12 +0,0 @@ -using NetCord.Gateway; -using NetCord.Hosting.Gateway; - -namespace MyBot; - -public class MessageUpdateHandler : IMessageUpdateShardedGatewayHandler -{ - public async ValueTask HandleAsync(GatewayClient client, Message message) - { - await message.ReplyAsync("Message updated!"); - } -} diff --git a/Documentation/guides/basic-concepts/ShardingHosting/RegisteringHandlers.cs b/Documentation/guides/basic-concepts/ShardingHosting/RegisteringHandlers.cs deleted file mode 100644 index e541c563e..000000000 --- a/Documentation/guides/basic-concepts/ShardingHosting/RegisteringHandlers.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using NetCord.Gateway; -using NetCord.Hosting.Gateway; - -namespace MyBot; - -internal class RegisteringHandlers -{ - public static async Task RegisterHandlersAsync(string[] args) - { - var builder = Host.CreateApplicationBuilder(args); - - builder.Services - .AddDiscordShardedGateway(options => - { - options.Intents = GatewayIntents.GuildMessages - | GatewayIntents.DirectMessages - | GatewayIntents.MessageContent; - }) - .AddShardedGatewayHandlers(typeof(Program).Assembly); - - var host = builder.Build(); - - await host.RunAsync(); - } -} diff --git a/Documentation/guides/basic-concepts/ShardingHosting/ShardingHosting.csproj b/Documentation/guides/basic-concepts/ShardingHosting/ShardingHosting.csproj deleted file mode 100644 index e3fb763cf..000000000 --- a/Documentation/guides/basic-concepts/ShardingHosting/ShardingHosting.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - - - - - - - - - - - - diff --git a/Documentation/guides/basic-concepts/Voice/Program.cs b/Documentation/guides/basic-concepts/Voice/Program.cs deleted file mode 100644 index 946bfc027..000000000 --- a/Documentation/guides/basic-concepts/Voice/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = GatewayIntents.Guilds | GatewayIntents.GuildVoiceStates, - Logger = new ConsoleLogger(), -}); - -ApplicationCommandService applicationCommandService = new(); -applicationCommandService.AddModules(typeof(Program).Assembly); - -client.InteractionCreate += async interaction => -{ - if (interaction is not ApplicationCommandInteraction applicationCommandInteraction) - return; - - var result = await applicationCommandService.ExecuteAsync(new ApplicationCommandContext(applicationCommandInteraction, client)); - - if (result is not IFailResult failResult) - return; - - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -await applicationCommandService.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/basic-concepts/Voice/Voice.csproj b/Documentation/guides/basic-concepts/Voice/Voice.csproj deleted file mode 100644 index c47a01465..000000000 --- a/Documentation/guides/basic-concepts/Voice/Voice.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/basic-concepts/Voice/VoiceModule.cs b/Documentation/guides/basic-concepts/Voice/VoiceModule.cs deleted file mode 100644 index 58139a000..000000000 --- a/Documentation/guides/basic-concepts/Voice/VoiceModule.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System.Diagnostics; - -using NetCord; -using NetCord.Gateway.Voice; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class VoiceModule : ApplicationCommandModule -{ - [SlashCommand("play", "Plays music", Contexts = [InteractionContextType.Guild])] - public async Task PlayAsync(string track) - { - // Check if the specified track is a well formed uri - if (!Uri.IsWellFormedUriString(track, UriKind.Absolute)) - { - await RespondAsync(InteractionCallback.Message("Invalid track!")); - return; - } - - var guild = Context.Guild!; - - // Get the user voice state - if (!guild.VoiceStates.TryGetValue(Context.User.Id, out var voiceState)) - { - await RespondAsync(InteractionCallback.Message("You are not connected to any voice channel!")); - return; - } - - var client = Context.Client; - - // You should check if the bot is already connected to the voice channel. - // If so, you should use an existing 'VoiceClient' instance instead of creating a new one. - // You also need to add a synchronization here. 'JoinVoiceChannelAsync' should not be used concurrently for the same guild - var voiceClient = await client.JoinVoiceChannelAsync( - guild.Id, - voiceState.ChannelId.GetValueOrDefault(), - new VoiceClientConfiguration - { - Logger = new ConsoleLogger(), - }); - - // Connect - await voiceClient.StartAsync(); - - // Enter speaking state, to be able to send voice - await voiceClient.EnterSpeakingStateAsync(new SpeakingProperties(SpeakingFlags.Microphone)); - - // Respond to the interaction - await RespondAsync(InteractionCallback.Message($"Playing {Path.GetFileName(track)}!")); - - // Create a stream that sends voice to Discord - var outStream = voiceClient.CreateOutputStream(); - - // We create this stream to automatically convert the PCM data returned by FFmpeg to Opus data. - // The Opus data is then written to 'outStream' that sends the data to Discord - OpusEncodeStream stream = new(outStream, PcmFormat.Short, VoiceChannels.Stereo, OpusApplication.Audio); - - ProcessStartInfo startInfo = new("ffmpeg") - { - RedirectStandardOutput = true, - }; - var arguments = startInfo.ArgumentList; - - // Set reconnect attempts in case of a lost connection to 1 - arguments.Add("-reconnect"); - arguments.Add("1"); - - // Set reconnect attempts in case of a lost connection for streamed media to 1 - arguments.Add("-reconnect_streamed"); - arguments.Add("1"); - - // Set the maximum delay between reconnection attempts to 5 seconds - arguments.Add("-reconnect_delay_max"); - arguments.Add("5"); - - // Specify the input - arguments.Add("-i"); - arguments.Add(track); - - // Set the logging level to quiet mode - arguments.Add("-loglevel"); - arguments.Add("-8"); - - // Set the number of audio channels to 2 (stereo) - arguments.Add("-ac"); - arguments.Add("2"); - - // Set the output format to 16-bit signed little-endian - arguments.Add("-f"); - arguments.Add("s16le"); - - // Set the audio sampling rate to 48 kHz - arguments.Add("-ar"); - arguments.Add("48000"); - - // Direct the output to stdout - arguments.Add("pipe:1"); - - // Start the FFmpeg process - var ffmpeg = Process.Start(startInfo)!; - - // Copy the FFmpeg stdout to 'stream', which encodes the voice using Opus and passes it to 'outStream' - await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream); - - // Flush 'stream' to make sure all the data has been sent and to indicate to Discord that we have finished sending - await stream.FlushAsync(); - } - - [SlashCommand("echo", "Creates echo", Contexts = [InteractionContextType.Guild])] - public async Task EchoAsync() - { - var guild = Context.Guild!; - var userId = Context.User.Id; - - // Get the user voice state - if (!guild.VoiceStates.TryGetValue(userId, out var voiceState)) - return "You are not connected to any voice channel!"; - - var client = Context.Client; - - // You should check if the bot is already connected to the voice channel. - // If so, you should use an existing 'VoiceClient' instance instead of creating a new one. - // You also need to add a synchronization here. 'JoinVoiceChannelAsync' should not be used concurrently for the same guild - var voiceClient = await client.JoinVoiceChannelAsync( - guild.Id, - voiceState.ChannelId.GetValueOrDefault(), - new VoiceClientConfiguration - { - ReceiveHandler = new VoiceReceiveHandler(), // Required to receive voice - Logger = new ConsoleLogger(), - }); - - // Connect - await voiceClient.StartAsync(); - - // Enter speaking state, to be able to send voice - await voiceClient.EnterSpeakingStateAsync(new SpeakingProperties(SpeakingFlags.Microphone)); - - // Create a stream that sends voice to Discord - var outStream = voiceClient.CreateOutputStream(normalizeSpeed: false); - - voiceClient.VoiceReceive += args => - { - // Pass current user voice directly to the output to create echo - if (voiceClient.Cache.Users.TryGetValue(args.Ssrc, out var voiceUserId) && voiceUserId == userId) - outStream.Write(args.Frame); - return default; - }; - - // Return the response - return "Echo!"; - } -} diff --git a/Documentation/guides/basic-concepts/http-interactions.md b/Documentation/guides/basic-concepts/http-interactions.md deleted file mode 100644 index f20752f68..000000000 --- a/Documentation/guides/basic-concepts/http-interactions.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -omitAppTitle: true -title: Handling Discord HTTP Interactions with C# and ASP.NET Core -description: Learn how to make your Discord bot receive interactions from Discord via HTTP requests using the NetCord.Hosting.AspNetCore package in C# and ASP.NET Core. ---- - -# Handling HTTP Interactions with ASP.NET Core - -This guide will show you how to receive and handle Discord interactions, like slash commands and button clicks, through HTTP requests using the [NetCord.Hosting.AspNetCore](https://www.nuget.org/packages/NetCord.Hosting.AspNetCore) package. This ASP.NET Core package can be effortlessly integrated with [NetCord.Hosting.Services](https://www.nuget.org/packages/NetCord.Hosting.Services) to handle these HTTP interactions in C# easily. Additionally, you can implement your own @NetCord.Hosting.IHttpInteractionHandler to manually handle HTTP interactions received from Discord, giving you full control over your bot's behavior. - -## Required Dependencies - -Before you get started, ensure that you've installed the necessary native dependencies. Follow the [installation guide](installing-native-dependencies.md) to set them up. - -## Setting Up HTTP Interactions in C# - -To handle HTTP interactions from Discord in your bot, you need to use @NetCord.Hosting.Rest.RestClientServiceCollectionExtensions.AddDiscordRest* to add the @NetCord.Rest.RestClient and then call @NetCord.Hosting.AspNetCore.EndpointRouteBuilderExtensions.UseHttpInteractions* to map the HTTP interactions route. You can also use @NetCord.Hosting.Services.ApplicationCommands.ApplicationCommandServiceServiceCollectionExtensions.AddHttpApplicationCommands* to add the application command service with preconfigured HTTP contexts to your host builder. -[!code-cs[Program.cs](HttpInteractions/Program.cs?highlight=8,16)] - -### Receiving HTTP Interactions via HTTP Interaction Handler - -You can also create your own @NetCord.Hosting.IHttpInteractionHandler to handle HTTP interactions manually. This allows you to have full control over the behavior of your bot when receiving HTTP interactions. You register them using @"NetCord.Hosting.HttpInteractionHandlerServiceCollectionExtensions.AddHttpInteractionHandler``1(Microsoft.Extensions.DependencyInjection.IServiceCollection)?text=AddHttpInteractionHandler". - -[!code-cs[HttpInteractionHandler.cs](HttpInteractions/HttpInteractionHandler.cs#L6-L14)] - -## Configuring Your Discord Bot for HTTP Interactions - -To make your bot receive HTTP interactions from Discord, you need to store the public key in the configuration and specify the endpoint URL in the [Discord Developer Portal](https://discord.com/developers/applications). - -![Shows 'Public Key' section in 'General Information' section](../../images/http-interactions_FindingPublicKeyAndSpecifyingInteractionEndpointUrl.webp){width=850px} - -### Specifying the Public Key in the Configuration - -You can for example use `appsettings.json` file for configuration. It should look like this: -[!code-json[appsettings.json](HttpInteractions/appsettings.json?highlight=4)] - -### Specifying the Interactions Endpoint URL - -If your bot is hosted at `https://example.com` and you have specified `/interactions` pattern in @NetCord.Hosting.AspNetCore.EndpointRouteBuilderExtensions.UseHttpInteractions*, the endpoint URL will be `https://example.com/interactions`. Also note that Discord sends validation requests to the endpoint URL, so your bot must be running while updating it. - -For local testing, you can use [ngrok](https://ngrok.com), a tool that exposes your local server to the internet, providing a public URL to receive interactions. Use the following command to start ngrok with a correct port specified: -```bash -ngrok http http://localhost:port -``` - -It will generate a URL that you can use to receive HTTP interactions from Discord. For example, if the URL is `https://random-subdomain.ngrok-free.app` and you have specified `/interactions` pattern in @NetCord.Hosting.AspNetCore.EndpointRouteBuilderExtensions.UseHttpInteractions*, the endpoint URL will be `https://random-subdomain.ngrok-free.app/interactions`. - -## Extending Your HTTP Interactions Bot - -Now, as you have your bot up and running, you can start adding more features to it. You can use the following guides to learn more about the features you can add to your HTTP interactions based bot: - -- **@"application-commands?text=Application Commands":** Learn how to make complex commands with parameters and subcommands with ease. -- **@"component-interactions?text=Component Interactions":** Make your HTTP interactions bot interactive with buttons, select menus, and other components easily. diff --git a/Documentation/guides/basic-concepts/installing-native-dependencies.md b/Documentation/guides/basic-concepts/installing-native-dependencies.md deleted file mode 100644 index 3baf8305a..000000000 --- a/Documentation/guides/basic-concepts/installing-native-dependencies.md +++ /dev/null @@ -1,81 +0,0 @@ -# Installing Native Dependencies - -This is a hidden guide that is not visible in the guides index! If you are reading this, you are probably looking for information on how to install native dependencies for HTTP interactions or voice. - -## HTTP Interactions - -For HTTP interactions, [Libsodium](https://doc.libsodium.org/installation) is required. - -## Voice - -For voice: -- [Libsodium](https://doc.libsodium.org/installation) **is not generally** required, but it **is highly recommended for production bots**. It is caused by the fact that generally @NetCord.Gateway.Voice.Encryption.Aes256GcmRtpSizeEncryption, which does not require Libsodium, is supported by Discord and is used by default. However, there is a small chance that Discord will not support this encryption mode for your connection. In this case, @NetCord.Gateway.Voice.Encryption.XChaCha20Poly1305RtpSizeEncryption, which does require Libsodium, is used by default. Libsodium is required when you use @NetCord.Gateway.Voice.Encryption.XChaCha20Poly1305RtpSizeEncryption, @NetCord.Gateway.Voice.Encryption.XSalsa20Poly1305Encryption, @NetCord.Gateway.Voice.Encryption.XSalsa20Poly1305LiteEncryption, @NetCord.Gateway.Voice.Encryption.XSalsa20Poly1305LiteRtpSizeEncryption, or @NetCord.Gateway.Voice.Encryption.XSalsa20Poly1305SuffixEncryption. -- [Opus](https://opus-codec.org/downloads) is only required when you are using `Opus` prefixed classes. - -## Installation - -### [Dynamic Linking](#tab/dynamic) - -For dynamic linking, you can install Libsodium for the most popular platforms by referencing the [official Libsodium NuGet package](https://www.nuget.org/packages/libsodium). - -### Manual or System-wide Installation - -#### Windows - -For dynamic linking on Windows, you need to use the dynamic link libraries (`libsodium` and/or `opus`). Here's how to set it up: -- Download or build the dynamic link libraries (`libsodium` and/or `opus`) compatible with your development environment. -- Place these files in the runtime directory of your application. This is the folder where your application's executable is located. - -#### Linux and MacOS - -Dynamic linking on Linux and MacOS involves using shared libraries (`libsodium` and/or `opus`). You can install them using your system's package manager if available or follow these steps to install them manually: -- Download or build the shared libraries (`libsodium` and/or `opus`) that are compatible with your development environment. -- Place these files in the runtime directory of your application, which is the folder where your application's executable is located. - -### [Static Linking](#tab/static) - -> [!NOTE] -> Static linking requires [Native AOT](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot) compilation. - -#### Windows - -When using static linking on Windows, you need to link to the static libraries (`libsodium` and/or `opus`). Here are the steps to set up static linking in your application: -- Download or build the static libraries (`libsodium` and/or `opus`) compatible with your development environment. -- Link these libraries in your project settings. Ensure that you specify the correct paths to these libraries: - ```xml - - - - - - - - ``` - -You don't need to place any of these files in the runtime directory, as static linking embeds the library code directly into your application, eliminating the need for separate files. - -#### Linux and MacOS - -Static linking on Linux and MacOS involves linking your application with the static libraries (`libsodium` and/or `opus`). You can install them using your system's package manager if available or download or build the static libraries (`libsodium` and/or `opus`) compatible with your development environment manually. - -Link these libraries in your project settings. Make sure you specify the correct paths to these libraries: -```xml - - - - - - - -``` - -Since you're statically linking, you won't need to place any of these files in the runtime directory. The necessary code from the libraries will be included directly in your application. - -*** - -#### Installation External Links - -| Library | Installation Link | -|-----------|----------------------------------------| -| Libsodium | https://doc.libsodium.org/installation | -| Opus | https://opus-codec.org/downloads | diff --git a/Documentation/guides/basic-concepts/responding-to-interactions.md b/Documentation/guides/basic-concepts/responding-to-interactions.md deleted file mode 100644 index 3409b5083..000000000 --- a/Documentation/guides/basic-concepts/responding-to-interactions.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -uid: responding-to-interactions -omitAppTitle: true -title: Responding to Interactions in C# Discord Bots with NetCord -description: Learn to handle interactions in your C# Discord bot with NetCord. Explore response types like messages, modals, and deferrals for building bots with .NET. ---- - -# Responding to Interactions - -This guide explains how to handle interactions and prepare appropriate responses. - -To create a response, use the @NetCord.Rest.InteractionCallback class. It supports various response types, such as messages, modals, and autocomplete suggestions. Once created, the callback must be passed to the @"NetCord.Interaction.SendResponseAsync*?text=Interaction.SendResponseAsync" method to send it to Discord. - -[!code-cs[Sample response](RespondingToInteractions/Program.cs#L11)] - -The [NetCord.Services](https://www.nuget.org/packages/NetCord.Services) package provides additional utilities to simplify this process. - -## Responding with a Message - -You can respond with a message by using @"NetCord.Rest.InteractionCallback.Message*?text=InteractionCallback.Message". - -[!code-cs[Responding with a message](RespondingToInteractions/Program.cs#L18)] - -For advanced message options, see @"sending-messages?text=Sending Messages". - -## Responding with Deferral - -Deferring is useful when performing long-running operations before sending a message. Deferrals give you up to 15 minutes to complete the operation. After deferring, you can either modify the initial response (the deferral) or send a follow-up message, both work the same way. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Responding after deferral](RespondingToInteractions/Program.cs#L99)] - -[!code-cs[Responding after deferral](RespondingToInteractions/Program.cs#L103)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Responding after deferral](RespondingToInteractions/Program.cs#L101)] - -[!code-cs[Responding after deferral](RespondingToInteractions/Program.cs#L103)] - -*** - -The [NetCord.Services](https://www.nuget.org/packages/NetCord.Services) package also provides shortcuts for deferral handling. - -For advanced message options, see @"sending-messages?text=Sending Messages". - -### Deferred Message - -For application commands, use @"NetCord.Rest.InteractionCallback.DeferredMessage*?text=InteractionCallback.DeferredMessage" to send a deferral response. This shows a loading state to the user while you prepare the message. - -[!code-cs[Responding with a deferred message](RespondingToInteractions/Program.cs#L20)] - -You can specify @"NetCord.MessageFlags.Ephemeral?text=MessageFlags.Ephemeral" to make the response visible only to the user who triggered the interaction. - -[!code-cs[Responding with a deferred message](RespondingToInteractions/Program.cs#L22)] - -### Deferred Modify Message - -For component interactions, use @"NetCord.Rest.InteractionCallback.DeferredModifyMessage?text=InteractionCallback.DeferredModifyMessage". This type of deferral doesn't display a loading state to the user. - -[!code-cs[Responding with a deferred modify message](RespondingToInteractions/Program.cs#L24)] - -## Responding with Message Modification - -For message component interactions, you can modify the message they are attached to using @"NetCord.Rest.InteractionCallback.ModifyMessage*?text=InteractionCallback.ModifyMessage". - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Responding with a modify message](RespondingToInteractions/Program.cs#L26)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Responding with a modify message](RespondingToInteractions/Program.cs#L28)] - -*** - -## Responding with a Modal - -Modals are interactive forms users can fill out. Use @"NetCord.Rest.InteractionCallback.Modal*?text=InteractionCallback.Modal" to create a modal callback. Each modal can include up to five components. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Responding with a modal](RespondingToInteractions/Program.cs#L30-L34)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Responding with a modal](RespondingToInteractions/Program.cs#L36-L39)] - -*** - -It is also supported to provide additional options for each input, such as placeholder text, default value, and whether the input is required. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Responding with a modal](RespondingToInteractions/Program.cs#L41-L55)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Responding with a modal](RespondingToInteractions/Program.cs#L57-L66)] - -*** - -## Responding with Autocomplete - -Autocomplete provides a list of options while the user types a slash command. Use @"NetCord.Rest.InteractionCallback.Autocomplete*?text=InteractionCallback.Autocomplete" to respond to autocomplete interactions. - -For string parameters: - -[!code-cs[Responding with autocomplete](RespondingToInteractions/Program.cs#L68)] - -For numeric parameters: - -[!code-cs[Responding with autocomplete](RespondingToInteractions/Program.cs#L70)] - -It is also supported to provide name localizations for each option. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Responding with autocomplete](RespondingToInteractions/Program.cs#L72-L82)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Responding with autocomplete](RespondingToInteractions/Program.cs#L84-L90)] - -*** - -## Responding with a Pong - -A "pong" callback is used to respond to ping HTTP interactions sent by Discord to verify the endpoint's availability. Use @"NetCord.Rest.InteractionCallback.Pong?text=InteractionCallback.Pong" to create this response. - -[!code-cs[Responding with a pong](RespondingToInteractions/Program.cs#L92)] - -If you're using the [NetCord.Hosting.AspNetCore](https://www.nuget.org/packages/NetCord.Hosting.AspNetCore) package, these ping interactions are handled automatically, and you don't need to provide the callback manually. diff --git a/Documentation/guides/basic-concepts/sending-messages.md b/Documentation/guides/basic-concepts/sending-messages.md deleted file mode 100644 index 87d09ea00..000000000 --- a/Documentation/guides/basic-concepts/sending-messages.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -uid: sending-messages -omitAppTitle: true -title: Sending Messages in a C# Discord Bot with NetCord Library -description: Learn how to send messages in a C# Discord bot using NetCord, covering text, embeds, attachments, allowed mentions, and interactive components like buttons. ---- - -# Sending Messages - -This guide demonstrates how to send messages to a channel. - -Different types of message properties are available because various endpoints support different options. However, all these types implement @NetCord.Rest.IMessageProperties, which defines the properties supported by all endpoints. This guide will cover the properties defined in @NetCord.Rest.IMessageProperties. - -## Types of Message Properties - -The following message properties types are available: -- @NetCord.Rest.MessageProperties - Can be used with @"NetCord.Rest.RestClient.SendMessageAsync*?text=RestClient.SendMessageAsync" to send messages to channels. -- @NetCord.Rest.InteractionMessageProperties - Used for sending messages in response to interactions. Refer to @"responding-to-interactions?text=Responding to Interactions#responding-with-a-message" for more information. -- @NetCord.Rest.ReplyMessageProperties - Can be used with @"NetCord.Rest.RestMessage.ReplyAsync*?text=RestMessage.ReplyAsync" to reply to messages. -- @NetCord.Rest.WebhookMessageProperties - Can be used with @"NetCord.Rest.RestClient.ExecuteWebhookAsync*?text=RestClient.ExecuteWebhookAsync" to send messages via webhooks. -- @NetCord.Rest.ForumGuildThreadMessageProperties - Can be used with @"NetCord.Rest.RestClient.CreateForumGuildThreadAsync*?text=RestClient.CreateForumGuildThreadAsync" to create forum posts. - -All the @NetCord.Rest.RestClient methods mentioned above have their equivalent methods in appropriate objects, such as @NetCord.TextChannel and @NetCord.Rest.WebhookClient. - -## Using @NetCord.Rest.IMessageProperties - -If you need to build an API that supports creating messages for multiple endpoints, you can utilize the @NetCord.Rest.IMessageProperties interface. This allows you to define the properties common to all message properties types in a straightforward manner. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Using 'IMessageProperties'](SendingMessages/Program.cs#L283-L290)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Using 'IMessageProperties'](SendingMessages/Program.cs#L295-L304)] - -*** - -You can view sample usages of this method below: - -[!code-cs[Using our API for 'MessageProperties'](SendingMessages/Program.cs#L310)] -[!code-cs[Using our API for 'InteractionMessageProperties'](SendingMessages/Program.cs#L312)] - -## Defining the Content - -The content refers to the main text of the message. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Defining the content](SendingMessages/Program.cs#L10)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Defining the content](SendingMessages/Program.cs#L12)] - -*** - -All message properties types support an implicit conversion from a string. However, note that this does not apply to @NetCord.Rest.IMessageProperties, as it is an interface. - -[!code-cs[Implicit conversion from string](SendingMessages/Program.cs#L278)] - -## Adding Embeds - -Embeds are rich content elements that can be attached to a message. They support titles, descriptions, images, and more. A message can include up to 10 embeds. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Adding embeds](SendingMessages/Program.cs#L96)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Adding embeds](SendingMessages/Program.cs#L98)] - -*** - -### Customizing Embeds - -You can customize embeds by specifying properties such as the title, description, color, and image. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Customizing embeds](SendingMessages/Program.cs#L16-L62)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Customizing embeds](SendingMessages/Program.cs#L64-L94)] - -*** - -## Managing Allowed Mentions - -Allowed mentions define which users and roles can be mentioned within the message. - -To allow all mentions, use @"NetCord.Rest.AllowedMentionsProperties.All?text=AllowedMentionsProperties.All". - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Setting allowed mentions](SendingMessages/Program.cs#L100)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Setting allowed mentions](SendingMessages/Program.cs#L102)] - -*** - -To disable all mentions, use @"NetCord.Rest.AllowedMentionsProperties.None?text=AllowedMentionsProperties.None". - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Setting allowed mentions](SendingMessages/Program.cs#L104)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Setting allowed mentions](SendingMessages/Program.cs#L106)] - -*** - -You can also define custom allowed mentions. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Customizing allowed mentions](SendingMessages/Program.cs#L108-L114)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Customizing allowed mentions](SendingMessages/Program.cs#L116-L120)] - -*** - -## Attaching Files - -Attachments are files that can be added to a message. A message can contain up to 10 attachments. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Adding attachments](SendingMessages/Program.cs#L153)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Adding attachments](SendingMessages/Program.cs#L155)] - -*** - -### Customizing Attachments - -Attachments are files that can be added to a message, with up to 10 attachments per message. All attachment types support any readable stream, such as file streams. Below are examples of how you can create and customize attachments. - -#### Standard Attachments - -This is an example of a standard attachment. The following code creates an attachment with the content "Hello!". - -[!code-cs[Creating attachments](SendingMessages/Program.cs#L124)] - -#### Base64-Encoded Attachments - -You can create an attachment with base64 encoding. The following example demonstrates an attachment that will display "Hello, base64!" in the chat. - -[!code-cs[Base64 attachment](SendingMessages/Program.cs#L126)] - -#### Quoted-Printable Attachments - -Quoted-printable encoding is another supported format. The following example creates an attachment that will display "Różowy means pink" in the chat. - -[!code-cs[Quoted-printable attachment](SendingMessages/Program.cs#L128-L129)] - -#### Google Cloud Attachments - -> [!WARNING] -> Discord does not offer any stability guarantees for this feature so it can break without notice. - -Discord supports uploading attachments directly to Google Cloud Platform. This example creates an attachment uploaded directly to Google Cloud Platform with the content "Hello, Google!". - -[!code-cs[Google Cloud attachment](SendingMessages/Program.cs#L135-L144)] - -#### Adding Titles and Descriptions - -You can enhance your attachments by adding titles and descriptions. Use the `AttachmentProperties.Title` and `AttachmentProperties.Description` properties to set these values. Here's an example: - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Attachment properties](SendingMessages/Program.cs#L146-L147)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Attachment properties](SendingMessages/Program.cs#L149-L151)] - -*** - -## Adding Components - -Components are interactive elements that can be attached to a message. These include buttons, select menus, and more. A message can contain up to 5 components, including action rows and select menus. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Adding components](SendingMessages/Program.cs#L251)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Adding components](SendingMessages/Program.cs#L253)] - -*** - -### Action Rows - -Action rows contain buttons, and each can have up to 5 buttons. Available button types include: -- @NetCord.Rest.ButtonProperties, which triggers an interaction when clicked. -- @NetCord.Rest.LinkButtonProperties, which opens a URL when clicked. -- @NetCord.Rest.PremiumButtonProperties, which prompts the user to pay when clicked. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Defining action rows](SendingMessages/Program.cs#L159-L169)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Defining action rows](SendingMessages/Program.cs#L171-L178)] - -*** - -### Select Menus - -Select menus are dropdown menus containing up to 25 options. They support various types, such as strings, channels, and users. - -#### String Menus - -String menus allow you to include any string options. Each option in the menu can be customized with additional properties, such as setting a default selection, adding an emoji, or providing a description for better context. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Creating string menus](SendingMessages/Program.cs#L180-L198)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Creating string menus](SendingMessages/Program.cs#L200-L211)] - -*** - -#### Channel Menus - -Channel menus include channels as options, and support filtering by channel type and the ability to specify default channels. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Creating channel menus](SendingMessages/Program.cs#L213-L217)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Creating channel menus](SendingMessages/Program.cs#L219-L221)] - -*** - -#### Mentionable Menus - -Mentionable menus include users and roles as options, and support specifying default users and roles. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Creating mentionable menus](SendingMessages/Program.cs#L223-L229)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Creating mentionable menus](SendingMessages/Program.cs#L231-L233)] - -*** - -#### Role Menus - -Role menus contain roles as options, and support specifying default roles. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Creating role menus](SendingMessages/Program.cs#L235-L238)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Creating role menus](SendingMessages/Program.cs#L240-L241)] - -*** - -#### User Menus - -User menus allow selecting users as options, and support specifying default users. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Creating user menus](SendingMessages/Program.cs#L243-L246)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Creating user menus](SendingMessages/Program.cs#L248-L249)] - -*** - -#### Specifying Additional Properties - -Additionally, all select menus allow you to specify a placeholder, set a minimum and maximum number of selectable options, and disable the select menu if necessary. - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Configuring select menus](SendingMessages/Program.cs#L264-L267)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Configuring select menus](SendingMessages/Program.cs#L269-L273)] - -*** - -## Configuring Flags - -Flags control how a message behaves. You can combine multiple flags using the bitwise OR operator. - -For example, this configuration specifies that no embeds from URLs should be displayed, and the message should be silent (not triggering push or desktop notifications). - -# [Classic Syntax](#tab/classic-syntax) - -[!code-cs[Setting flags](SendingMessages/Program.cs#L255)] - -# [Fluent Syntax](#tab/fluent-syntax) - -[!code-cs[Setting flags](SendingMessages/Program.cs#L257)] - -*** diff --git a/Documentation/guides/basic-concepts/sharding.md b/Documentation/guides/basic-concepts/sharding.md deleted file mode 100644 index 7491b0102..000000000 --- a/Documentation/guides/basic-concepts/sharding.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -uid: sharding -omitAppTitle: true -title: Scale Your C# Discord Bot with Sharding in NetCord -description: Implement sharding for your C# Discord bot with NetCord to improve scalability and performance by distributing tasks across multiple gateway connections. ---- - -# Sharding - -Sharding allows your bot to split its responsibilities across multiple gateway connections. In NetCord, this is managed by the @NetCord.Gateway.ShardedGatewayClient, which acts as a controller for multiple instances of @NetCord.Gateway.GatewayClient. Each shard, represented by a @NetCord.Gateway.GatewayClient, handles a specific subset of guilds. - -## When to Shard - -Sharding becomes necessary when your bot exceeds 2,500 guilds. However, it's recommended to implement sharding earlier, typically when targeting 1,000+ guilds, to ensure smoother scaling and performance. - -## How to Shard - -### [.NET Generic Host](#tab/generic-host) - -When using the .NET Generic Host, you can add the @NetCord.Gateway.ShardedGatewayClient by calling @NetCord.Hosting.Gateway.ShardedGatewayClientServiceCollectionExtensions.AddDiscordShardedGateway*. -[!code-cs[Program.cs](ShardingHosting/Program.cs)] - -### [Bare Bones](#tab/bare-bones) - -For a bare-bones setup, you need to manually create an instance of @NetCord.Gateway.ShardedGatewayClient. Its API is very similar to @NetCord.Gateway.GatewayClient. Here's an example: -[!code-cs[Program.cs](Sharding/Program.cs)] - -*** - -## How to Register Events - -### [.NET Generic Host](#tab/generic-host) - -To register event handlers with sharding in the .NET Generic Host, use @NetCord.Hosting.Gateway.GatewayHandlerServiceCollectionExtensions.AddShardedGatewayHandlers* to add all event handlers in an assembly and then call @NetCord.Hosting.Gateway.GatewayHandlerServiceCollectionExtensions.AddShardedGatewayHandlers* to bind these handlers to the sharded client. - -[!code-cs[Program.cs](ShardingHosting/RegisteringHandlers.cs?highlight=10#L12-L25)] - -When creating event handlers, implement @NetCord.Hosting.Gateway.IShardedGatewayHandler. Note the additional parameter representing the @NetCord.Gateway.GatewayClient that received the event. -[!code-cs[Program.cs](ShardingHosting/MessageUpdateHandler.cs)] - -### [Bare Bones](#tab/bare-bones) - -For bare-bones setups, adding event handlers is straightforward. Each handler has an additional parameter for the @NetCord.Gateway.GatewayClient that received the event. -[!code-cs[Program.cs](Sharding/RegisteringHandlers.cs#L16-L19)] diff --git a/Documentation/guides/basic-concepts/voice.md b/Documentation/guides/basic-concepts/voice.md deleted file mode 100644 index 20a17452d..000000000 --- a/Documentation/guides/basic-concepts/voice.md +++ /dev/null @@ -1,16 +0,0 @@ -# Voice - -## Native Dependencies - -Follow the [installation guide](installing-native-dependencies.md) to install the required native dependencies. - -## Example Usage - -> [!NOTE] -> In the following examples streams and @NetCord.Gateway.Voice.VoiceClient instances are not disposed because they should be stored somewhere and disposed later. - -### Sending Voice -[!code-cs[VoiceModule.cs](Voice/VoiceModule.cs#L13-L110)] - -### Receiving Voice -[!code-cs[VoiceModule.cs](Voice/VoiceModule.cs#L112-L155)] diff --git a/Documentation/guides/services/application-commands/IntroductionHosting/IntroductionHosting.csproj b/Documentation/guides/commands/Commands/Commands.csproj similarity index 53% rename from Documentation/guides/services/application-commands/IntroductionHosting/IntroductionHosting.csproj rename to Documentation/guides/commands/Commands/Commands.csproj index 3b76374f3..24d214337 100644 --- a/Documentation/guides/services/application-commands/IntroductionHosting/IntroductionHosting.csproj +++ b/Documentation/guides/commands/Commands/Commands.csproj @@ -1,7 +1,10 @@ - + Exe + net9.0 + enable + enable @@ -10,6 +13,8 @@ + + diff --git a/Documentation/guides/commands/Commands/MessageCommands.cs b/Documentation/guides/commands/Commands/MessageCommands.cs new file mode 100644 index 000000000..a0173c555 --- /dev/null +++ b/Documentation/guides/commands/Commands/MessageCommands.cs @@ -0,0 +1,21 @@ +using NetCord.Rest; +using NetCord.Services.ApplicationCommands; + +namespace Commands; + +/// +/// Examples for the Message Commands guide. +/// +public class MessageCommands : ApplicationCommandModule +{ + // TODO: Add message command examples (context menu on messages) + // - Basic message commands + // - Accessing message content + // - Responding to message commands + + [MessageCommand("Quote Message")] + public string QuoteMessage(Message target) + { + return $"> {target.Content}\n\n- {target.Author.Username}"; + } +} diff --git a/Documentation/guides/commands/Commands/Overview.cs b/Documentation/guides/commands/Commands/Overview.cs new file mode 100644 index 000000000..296550a61 --- /dev/null +++ b/Documentation/guides/commands/Commands/Overview.cs @@ -0,0 +1,14 @@ +using NetCord.Services.ApplicationCommands; + +namespace Commands; + +/// +/// Examples for the Commands Overview guide. +/// +public static class Overview +{ + // TODO: Add command system overview examples + // - Command types comparison + // - When to use each command type + // - Command registration overview +} diff --git a/Documentation/guides/commands/Commands/Program.cs b/Documentation/guides/commands/Commands/Program.cs new file mode 100644 index 000000000..0fe91ab41 --- /dev/null +++ b/Documentation/guides/commands/Commands/Program.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Hosting; +using NetCord.Hosting.Gateway; +using NetCord.Hosting.Services.ApplicationCommands; +using NetCord.Services.ApplicationCommands; + +var builder = Host.CreateApplicationBuilder(args); + +builder.Services + .AddDiscordGateway() + .AddApplicationCommands(); + +var host = builder.Build(); + +await host.RunAsync(); diff --git a/Documentation/guides/commands/Commands/SlashCommands.cs b/Documentation/guides/commands/Commands/SlashCommands.cs new file mode 100644 index 000000000..63d5d56b7 --- /dev/null +++ b/Documentation/guides/commands/Commands/SlashCommands.cs @@ -0,0 +1,28 @@ +using NetCord.Services.ApplicationCommands; + +namespace Commands; + +/// +/// Examples for the Slash Commands guide. +/// +public class SlashCommands : ApplicationCommandModule +{ + // TODO: Add comprehensive slash command examples + // - Basic slash commands + // - Commands with options + // - Subcommands and subcommand groups + // - Autocomplete + // - Choices and option types + + [SlashCommand("ping", "Check bot latency")] + public string Ping() + { + return "Pong!"; + } + + [SlashCommand("echo", "Echo a message")] + public string Echo([SlashCommandParameter(Description = "Message to echo")] string message) + { + return message; + } +} diff --git a/Documentation/guides/commands/Commands/TextCommands.cs b/Documentation/guides/commands/Commands/TextCommands.cs new file mode 100644 index 000000000..53ff66e74 --- /dev/null +++ b/Documentation/guides/commands/Commands/TextCommands.cs @@ -0,0 +1,29 @@ +using NetCord.Gateway; +using NetCord.Rest; +using NetCord.Services; + +namespace Commands; + +/// +/// Examples for the Text Commands guide. +/// +public class TextCommands : IModule +{ + // TODO: Add text command examples (prefix-based commands) + // - Basic text commands + // - Command parsing + // - Argument handling + // - Prefix configuration + + [Command("ping")] + public string Ping() + { + return "Pong!"; + } + + [Command("say")] + public string Say(string message) + { + return message; + } +} diff --git a/Documentation/guides/commands/Commands/UserCommands.cs b/Documentation/guides/commands/Commands/UserCommands.cs new file mode 100644 index 000000000..409bff673 --- /dev/null +++ b/Documentation/guides/commands/Commands/UserCommands.cs @@ -0,0 +1,21 @@ +using NetCord; +using NetCord.Services.ApplicationCommands; + +namespace Commands; + +/// +/// Examples for the User Commands guide. +/// +public class UserCommands : ApplicationCommandModule +{ + // TODO: Add user command examples (context menu on users) + // - Basic user commands + // - Accessing user information + // - Responding to user commands + + [UserCommand("Get User Info")] + public string GetUserInfo(User target) + { + return $"User: {target.Username} (ID: {target.Id})"; + } +} diff --git a/Documentation/guides/commands/message-commands.md b/Documentation/guides/commands/message-commands.md new file mode 100644 index 000000000..f43e38c11 --- /dev/null +++ b/Documentation/guides/commands/message-commands.md @@ -0,0 +1,34 @@ +--- +title: Creating Message Context Menu Commands in Discord Bots +description: Build message context menu commands that appear when right-clicking messages in Discord. Learn to process messages with NetCord. +omitAppTitle: true +--- + +# Message Commands + +> [!NOTE] +> Content for this section is under development. + +## Creating Command {#creating-command} + +MessageCommandAttribute. + +## Target Message {#target-message} + +Accessing the target message. + +## Context Menu {#context-menu} + +How it appears in Discord. + +--- + +## Navigation + +← **Previous:** @"commands/user-commands?text=User Commands" | **Next:** @"commands/text-commands?text=Text Commands" → + +## See Also + +- @"component-interactions/message-components?text=Message Components" - Interactive messages +- @"services-framework/overview?text=Services Framework" - Command handling +- [Discord Docs: Message Commands](https://discord.com/developers/docs/interactions/application-commands#message-commands) diff --git a/Documentation/guides/commands/overview.md b/Documentation/guides/commands/overview.md new file mode 100644 index 000000000..bfe7bfc9e --- /dev/null +++ b/Documentation/guides/commands/overview.md @@ -0,0 +1,34 @@ +--- +title: Discord Bot Commands Overview - Slash, User, Message, and Text Commands +description: Complete guide to Discord application commands and text commands in NetCord. Learn about slash commands, context menus, and prefix-based commands. +omitAppTitle: true +--- + +# Commands Overview + +> [!NOTE] +> Content for this section is under development. + +## Command Types {#command-types} + +Application vs Text commands. + +## When to Use {#when-to-use} + +Use cases for each type. + +## Services Framework {#services-framework} + +Link to Services Framework section. + +--- + +## Navigation + +**Next:** @"commands/slash-commands?text=Slash Commands" → + +## See Also + +- @"services-framework/overview?text=Services Framework" - Command handling framework +- @"component-interactions/message-components?text=Message Components" - Interactive UI elements +- @"events/gateway-events?text=Gateway Events" - Event-driven interactions diff --git a/Documentation/guides/commands/slash-commands.md b/Documentation/guides/commands/slash-commands.md new file mode 100644 index 000000000..74df31389 --- /dev/null +++ b/Documentation/guides/commands/slash-commands.md @@ -0,0 +1,39 @@ +--- +title: Building Slash Commands for Discord Bots with NetCord +description: Create Discord slash commands in C# with NetCord. Learn about command parameters, options, choices, autocomplete, and responding to interactions. +omitAppTitle: true +--- + +# Slash Commands + +> [!NOTE] +> Content for this section is under development. + +## Creating Command {#creating-command} + +SlashCommandAttribute. + +## Parameters {#parameters} + +Parameter types and options. + +## Options {#options} + +Required, choices, autocomplete. + +## Responding {#responding} + +InteractionCallback. + +--- + +## Navigation + +← **Previous:** @"commands/overview?text=Commands Overview" | **Next:** @"commands/user-commands?text=User Commands" → + +## See Also + +- @"services-framework/overview?text=Services Framework" - Advanced command handling +- @"services-framework/type-readers?text=Type Readers" - Parameter conversion +- @"services-framework/preconditions?text=Preconditions" - Command validation +- [Discord Docs: Application Commands](https://discord.com/developers/docs/interactions/application-commands) diff --git a/Documentation/guides/commands/text-commands.md b/Documentation/guides/commands/text-commands.md new file mode 100644 index 000000000..1fffd1112 --- /dev/null +++ b/Documentation/guides/commands/text-commands.md @@ -0,0 +1,38 @@ +--- +title: Building Traditional Prefix-Based Text Commands for Discord Bots +description: Create traditional prefix-based text commands in NetCord. Learn command parsing, argument handling, and responding to message-based commands. +omitAppTitle: true +--- + +# Text Commands + +> [!NOTE] +> Content for this section is under development. + +## Creating Command {#creating-command} + +CommandAttribute. + +## Prefixes {#prefixes} + +Command prefixes configuration. + +## Parameters {#parameters} + +Parameter parsing. + +## Aliases {#aliases} + +CommandAttribute aliases. + +--- + +## Navigation + +← **Previous:** @"commands/message-commands?text=Message Commands" + +## See Also + +- @"services-framework/overview?text=Services Framework" - Prefix command handling +- @"services-framework/type-readers?text=Type Readers" - Argument parsing +- @"events/gateway-events?text=Gateway Events" - Message events diff --git a/Documentation/guides/commands/user-commands.md b/Documentation/guides/commands/user-commands.md new file mode 100644 index 000000000..eaf647377 --- /dev/null +++ b/Documentation/guides/commands/user-commands.md @@ -0,0 +1,34 @@ +--- +title: Creating User Context Menu Commands in Discord Bots +description: Build user context menu commands that appear when right-clicking users in Discord. Learn to handle user interactions with NetCord. +omitAppTitle: true +--- + +# User Commands + +> [!NOTE] +> Content for this section is under development. + +## Creating Command {#creating-command} + +UserCommandAttribute. + +## Target User {#target-user} + +Accessing the target user. + +## Context Menu {#context-menu} + +How it appears in Discord. + +--- + +## Navigation + +← **Previous:** @"commands/slash-commands?text=Slash Commands" | **Next:** @"commands/message-commands?text=Message Commands" → + +## See Also + +- @"discord-entities/users?text=Working with Users" - User entity operations +- @"services-framework/custom-contexts?text=Custom Contexts" - Context customization +- [Discord Docs: User Commands](https://discord.com/developers/docs/interactions/application-commands#user-commands) diff --git a/Documentation/guides/component-interactions/message-components.md b/Documentation/guides/component-interactions/message-components.md new file mode 100644 index 000000000..ad7c48cc0 --- /dev/null +++ b/Documentation/guides/component-interactions/message-components.md @@ -0,0 +1,39 @@ +--- +title: Handling Button and Select Menu Interactions in Discord Bots +description: Build interactive Discord message components with NetCord. Learn to handle button clicks, select menus, and component interactions in C#. +omitAppTitle: true +--- + +# Message Component Interactions + +> [!NOTE] +> Content for this section is under development. + +## Handling Buttons {#handling-buttons} + +ButtonInteraction. + +## Handling Menus {#handling-menus} + +StringMenuInteraction, etc. + +## Custom ID Pattern {#custom-id-pattern} + +Parsing CustomId. + +## Parameters {#parameters} + +ComponentInteractionParameter. + +--- + +## Navigation + +**Next:** @"component-interactions/modals?text=Modal Interactions" → + +## See Also + +- @"components-v2/interactive-components?text=Interactive Components" - Components v2 buttons and menus +- @"commands/slash-commands?text=Slash Commands" - Commands with components +- @"services-framework/overview?text=Services Framework" - Handle component interactions +- [Discord Docs: Message Components](https://discord.com/developers/docs/interactions/message-components) diff --git a/Documentation/guides/component-interactions/modals.md b/Documentation/guides/component-interactions/modals.md new file mode 100644 index 000000000..b61c9d0eb --- /dev/null +++ b/Documentation/guides/component-interactions/modals.md @@ -0,0 +1,35 @@ +--- +title: Creating and Handling Discord Modal Forms in NetCord +description: Build modal forms for Discord bots. Learn to create text input modals, handle submissions, and validate user input with NetCord. +omitAppTitle: true +--- + +# Modal Interactions + +> [!NOTE] +> Content for this section is under development. + +## Showing Modal {#showing-modal} + +InteractionCallback.Modal(). + +## Handling Submission {#handling-submission} + +ModalInteraction. + +## Accessing Values {#accessing-values} + +TextInput.Value. + +--- + +## Navigation + +← **Previous:** @"component-interactions/message-components?text=Message Components" + +## See Also + +- @"components-v2/modal-components?text=Modal Components" - Components v2 modals +- @"services-framework/type-readers?text=Type Readers" - Validate modal input +- @"commands/slash-commands?text=Slash Commands" - Trigger modals from commands +- [Discord Docs: Modal Interactions](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-modal) diff --git a/Documentation/guides/services/Preconditions/ParameterPreconditions/ParameterPreconditions.csproj b/Documentation/guides/components-v2/Components/Components.csproj similarity index 66% rename from Documentation/guides/services/Preconditions/ParameterPreconditions/ParameterPreconditions.csproj rename to Documentation/guides/components-v2/Components/Components.csproj index 22013d152..e971ab53c 100644 --- a/Documentation/guides/services/Preconditions/ParameterPreconditions/ParameterPreconditions.csproj +++ b/Documentation/guides/components-v2/Components/Components.csproj @@ -2,6 +2,9 @@ Exe + net9.0 + enable + enable @@ -10,6 +13,7 @@ + diff --git a/Documentation/guides/components-v2/Components/ContentComponents.cs b/Documentation/guides/components-v2/Components/ContentComponents.cs new file mode 100644 index 000000000..a3456f0b2 --- /dev/null +++ b/Documentation/guides/components-v2/Components/ContentComponents.cs @@ -0,0 +1,45 @@ +using NetCord; +using NetCord.Rest; + +namespace Components; + +/// +/// Examples for the Content Components guide. +/// +public static class ContentComponents +{ + // TODO: Add content component examples + // - Text content + // - Embeds with components + // - Images with components + // - Combining content types + + public static MessageProperties CreateContentWithComponents() + { + return new MessageProperties + { + Content = "**Rich content example**", + Embeds = + [ + new EmbedProperties + { + Title = "Information", + Description = "This embed has components below it." + } + ], + Components = + [ + new ActionRowProperties + { + Components = + [ + new ButtonProperties("more_info", "More Info", ButtonStyle.Link) + { + Url = "https://example.com" + } + ] + } + ] + }; + } +} diff --git a/Documentation/guides/components-v2/Components/InteractiveComponents.cs b/Documentation/guides/components-v2/Components/InteractiveComponents.cs new file mode 100644 index 000000000..a6b94a7d8 --- /dev/null +++ b/Documentation/guides/components-v2/Components/InteractiveComponents.cs @@ -0,0 +1,63 @@ +using NetCord; +using NetCord.Rest; + +namespace Components; + +/// +/// Examples for the Interactive Components guide. +/// +public static class InteractiveComponents +{ + // TODO: Add interactive component examples + // - Buttons + // - Select menus (string, user, role, channel, mentionable) + // - Custom IDs and payloads + // - Component state management + + public static MessageProperties CreateButtonExample() + { + return new MessageProperties + { + Content = "Click a button:", + Components = + [ + new ActionRowProperties + { + Components = + [ + new ButtonProperties("btn_primary", "Primary", ButtonStyle.Primary), + new ButtonProperties("btn_secondary", "Secondary", ButtonStyle.Secondary), + new ButtonProperties("btn_success", "Success", ButtonStyle.Success), + new ButtonProperties("btn_danger", "Danger", ButtonStyle.Danger) + ] + } + ] + }; + } + + public static MessageProperties CreateSelectMenuExample() + { + return new MessageProperties + { + Content = "Choose an option:", + Components = + [ + new ActionRowProperties + { + Components = + [ + new StringMenuProperties("menu_select", + [ + new("Option 1", "opt1", "First option"), + new("Option 2", "opt2", "Second option"), + new("Option 3", "opt3", "Third option") + ]) + { + Placeholder = "Select an option..." + } + ] + } + ] + }; + } +} diff --git a/Documentation/guides/components-v2/Components/LayoutComponents.cs b/Documentation/guides/components-v2/Components/LayoutComponents.cs new file mode 100644 index 000000000..e212e7119 --- /dev/null +++ b/Documentation/guides/components-v2/Components/LayoutComponents.cs @@ -0,0 +1,42 @@ +using NetCord; +using NetCord.Rest; + +namespace Components; + +/// +/// Examples for the Layout Components guide. +/// +public static class LayoutComponents +{ + // TODO: Add layout component examples + // - ActionRow + // - Component spacing + // - Component limits + // - Layout patterns + + public static MessageProperties CreateMultiRowLayout() + { + return new MessageProperties + { + Content = "Layout example:", + Components = + [ + new ActionRowProperties + { + Components = + [ + new ButtonProperties("row1_btn1", "Button 1", ButtonStyle.Primary), + new ButtonProperties("row1_btn2", "Button 2", ButtonStyle.Primary) + ] + }, + new ActionRowProperties + { + Components = + [ + new ButtonProperties("row2_btn1", "Button 3", ButtonStyle.Secondary) + ] + } + ] + }; + } +} diff --git a/Documentation/guides/components-v2/Components/MigratingFromEmbeds.cs b/Documentation/guides/components-v2/Components/MigratingFromEmbeds.cs new file mode 100644 index 000000000..68895309a --- /dev/null +++ b/Documentation/guides/components-v2/Components/MigratingFromEmbeds.cs @@ -0,0 +1,13 @@ +namespace Components; + +/// +/// Examples for the Migrating from Embeds guide. +/// +public static class MigratingFromEmbeds +{ + // TODO: Add migration examples + // - Old embed-based patterns + // - New component-based patterns + // - Side-by-side comparisons + // - Common migration scenarios +} diff --git a/Documentation/guides/components-v2/Components/ModalComponents.cs b/Documentation/guides/components-v2/Components/ModalComponents.cs new file mode 100644 index 000000000..41f56b938 --- /dev/null +++ b/Documentation/guides/components-v2/Components/ModalComponents.cs @@ -0,0 +1,38 @@ +using NetCord; +using NetCord.Rest; + +namespace Components; + +/// +/// Examples for the Modal Components guide. +/// +public static class ModalComponents +{ + // TODO: Add modal component examples + // - Creating modals + // - Text inputs (short and paragraph) + // - Modal submission handling + // - Validation + + public static ModalProperties CreateBasicModal() + { + return new ModalProperties("modal_feedback", "Feedback Form") + { + Components = + [ + new TextInputProperties("input_name", TextInputStyle.Short, "Name") + { + MinLength = 2, + MaxLength = 50, + Placeholder = "Enter your name..." + }, + new TextInputProperties("input_feedback", TextInputStyle.Paragraph, "Feedback") + { + MinLength = 10, + MaxLength = 500, + Placeholder = "Tell us what you think..." + } + ] + }; + } +} diff --git a/Documentation/guides/components-v2/Components/Overview.cs b/Documentation/guides/components-v2/Components/Overview.cs new file mode 100644 index 000000000..699335a35 --- /dev/null +++ b/Documentation/guides/components-v2/Components/Overview.cs @@ -0,0 +1,35 @@ +using NetCord; +using NetCord.Rest; + +namespace Components; + +/// +/// Examples for the Components Overview guide. +/// +public static class Overview +{ + // TODO: Add component system overview + // - What are components + // - Component types + // - Component architecture + // - Best practices + + public static MessageProperties CreateBasicComponentMessage() + { + return new MessageProperties + { + Content = "Choose an action:", + Components = + [ + new ActionRowProperties + { + Components = + [ + new ButtonProperties("action_yes", "Yes", ButtonStyle.Success), + new ButtonProperties("action_no", "No", ButtonStyle.Danger) + ] + } + ] + }; + } +} diff --git a/Documentation/guides/getting-started/CodingHosting/Program.cs b/Documentation/guides/components-v2/Components/Program.cs similarity index 62% rename from Documentation/guides/getting-started/CodingHosting/Program.cs rename to Documentation/guides/components-v2/Components/Program.cs index d67b00b7a..0b64bd538 100644 --- a/Documentation/guides/getting-started/CodingHosting/Program.cs +++ b/Documentation/guides/components-v2/Components/Program.cs @@ -1,11 +1,9 @@ -using Microsoft.Extensions.Hosting; - +using Microsoft.Extensions.Hosting; using NetCord.Hosting.Gateway; var builder = Host.CreateApplicationBuilder(args); -builder.Services - .AddDiscordGateway(); +builder.Services.AddDiscordGateway(); var host = builder.Build(); diff --git a/Documentation/guides/components-v2/content-components.md b/Documentation/guides/components-v2/content-components.md new file mode 100644 index 000000000..208f93a2f --- /dev/null +++ b/Documentation/guides/components-v2/content-components.md @@ -0,0 +1,40 @@ +--- +title: Building Content Components - Text, Media, Files, and Thumbnails +description: Create content components in Discord Components v2. Learn text display, media galleries, file displays, and thumbnails with NetCord. +omitAppTitle: true +--- + +# Content Components + +> [!NOTE] +> Content for this section is under development. + +## Text Display {#text-display} + +TextDisplayProperties. + +## Media Gallery {#media-gallery} + +MediaGalleryProperties. + +## File Display {#file-display} + +FileDisplayProperties. + +## Thumbnail {#thumbnail} + +ComponentSectionThumbnailProperties. + +--- + +## Navigation + +← **Previous:** @"components-v2/overview?text=Components v2 Overview" | **Next:** @"components-v2/layout-components?text=Layout Components" → + +## See Also + +- @"components-v2/layout-components?text=Layout Components" - Organize content +- @"components-v2/interactive-components?text=Interactive Components" - Add buttons and menus +- @"discord-entities/channels?text=Channels" - Send component messages +- @"discord-entities/emojis-and-stickers?text=Emojis and Stickers" - Use in content +- @"webhooks/sending-messages?text=Sending Messages" - Components in webhooks diff --git a/Documentation/guides/components-v2/interactive-components.md b/Documentation/guides/components-v2/interactive-components.md new file mode 100644 index 000000000..f6c307965 --- /dev/null +++ b/Documentation/guides/components-v2/interactive-components.md @@ -0,0 +1,40 @@ +--- +title: Creating Interactive Buttons and Select Menus in Components v2 +description: Build interactive components in Discord Components v2. Learn buttons, select menus, and handling user interactions with NetCord. +omitAppTitle: true +--- + +# Interactive Components + +> [!NOTE] +> Content for this section is under development. + +## Buttons {#buttons} + +ButtonProperties, LinkButtonProperties, PremiumButtonProperties. + +## Button Styles {#button-styles} + +ButtonStyle enum. + +## Select Menus {#select-menus} + +String, User, Role, Mentionable, Channel. + +## Menu Options {#menu-options} + +MenuSelectOptionProperties. + +--- + +## Navigation + +← **Previous:** @"components-v2/layout-components?text=Layout Components" | **Next:** @"components-v2/modal-components?text=Modal Components" → + +## See Also + +- @"components-v2/modal-components?text=Modal Components" - Text input forms +- @"component-interactions/message-components?text=Message Components" - Handle interactions +- @"services-framework/overview?text=Services Framework" - Component command handling +- @"discord-entities/emojis-and-stickers?text=Emojis and Stickers" - Button emojis +- [Discord Docs: Button Styles](https://discord.com/developers/docs/interactions/message-components#button-object-button-styles) diff --git a/Documentation/guides/components-v2/layout-components.md b/Documentation/guides/components-v2/layout-components.md new file mode 100644 index 000000000..9ff9e06dc --- /dev/null +++ b/Documentation/guides/components-v2/layout-components.md @@ -0,0 +1,39 @@ +--- +title: Organizing Messages with Layout Components - Containers and Sections +description: Structure Discord messages with layout components. Learn containers, sections, separators, and action rows in Components v2. +omitAppTitle: true +--- + +# Layout Components + +> [!NOTE] +> Content for this section is under development. + +## Container {#container} + +ComponentContainerProperties. + +## Section {#section} + +ComponentSectionProperties. + +## Separator {#separator} + +ComponentSeparatorProperties. + +## Action Row {#action-row} + +ActionRowProperties (legacy bridge). + +--- + +## Navigation + +← **Previous:** @"components-v2/content-components?text=Content Components" | **Next:** @"components-v2/interactive-components?text=Interactive Components" → + +## See Also + +- @"components-v2/content-components?text=Content Components" - What goes in sections +- @"components-v2/interactive-components?text=Interactive Components" - Add buttons to action rows +- @"components-v2/overview?text=Components v2 Overview" - Component limits +- @"components-v2/migrating-from-embeds?text=Migrating from Embeds" - Layout patterns diff --git a/Documentation/guides/components-v2/migrating-from-embeds.md b/Documentation/guides/components-v2/migrating-from-embeds.md new file mode 100644 index 000000000..a14fbe7af --- /dev/null +++ b/Documentation/guides/components-v2/migrating-from-embeds.md @@ -0,0 +1,31 @@ +--- +title: Migrating from Discord Embeds to Components v2 +description: Convert embed-based message layouts to Components v2. Learn migration strategies and new component equivalents for NetCord bots. +omitAppTitle: true +--- + +# Migrating from Embeds + +> [!NOTE] +> Content for this section is under development. + +## Embeds vs Components {#embeds-vs-components} + +Key differences. + +## Migration Patterns {#migration-patterns} + +Converting embed layouts to components. + +--- + +## Navigation + +← **Previous:** @"components-v2/modal-components?text=Modal Components" | **Next:** @"deployment/docker?text=Docker Deployment" → + +## See Also + +- @"components-v2/content-components?text=Content Components" - Embed field equivalents +- @"components-v2/layout-components?text=Layout Components" - Structure your content +- @"components-v2/overview?text=Components v2 Overview" - When to use v2 +- @"discord-entities/channels?text=Channels" - Send components and embeds diff --git a/Documentation/guides/components-v2/modal-components.md b/Documentation/guides/components-v2/modal-components.md new file mode 100644 index 000000000..931ca099f --- /dev/null +++ b/Documentation/guides/components-v2/modal-components.md @@ -0,0 +1,40 @@ +--- +title: Building Modal Forms with Components v2 in Discord +description: Create modal components in Discord Components v2. Learn form inputs, modal interactions, and validation with NetCord. +omitAppTitle: true +--- + +# Modal Components + +> [!NOTE] +> Content for this section is under development. + +## Label {#label} + +LabelProperties. + +## Text Input {#text-input} + +TextInputProperties. + +## File Upload {#file-upload} + +FileUploadProperties. + +## Modal Structure {#modal-structure} + +ModalProperties. + +--- + +## Navigation + +← **Previous:** @"components-v2/interactive-components?text=Interactive Components" | **Next:** @"components-v2/migrating-from-embeds?text=Migrating from Embeds" → + +## See Also + +- @"component-interactions/modals?text=Modals" - Handle modal submissions +- @"components-v2/interactive-components?text=Interactive Components" - Trigger modals from buttons +- @"commands/slash-commands?text=Slash Commands" - Modal responses +- @"services-framework/type-readers?text=Type Readers" - Parse modal inputs +- [Discord Docs: Modal Interactions](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-modal) diff --git a/Documentation/guides/components-v2/overview.md b/Documentation/guides/components-v2/overview.md new file mode 100644 index 000000000..8fb29ee71 --- /dev/null +++ b/Documentation/guides/components-v2/overview.md @@ -0,0 +1,36 @@ +--- +title: Discord Components v2 - Modern Message Layout System +description: Complete guide to Discord's Components v2 system. Learn content, layout, and interactive components for rich message experiences in NetCord. +omitAppTitle: true +--- + +# Components v2 Overview + +> [!NOTE] +> Content for this section is under development. + +## Enabling v2 {#enabling-v2} + +MessageFlags.IsComponentsV2. + +## Component Limits {#component-limits} + +40 components maximum. + +## When to Use {#when-to-use} + +v2 vs legacy components. + +--- + +## Navigation + +← **Previous:** @"services-framework/preconditions?text=Preconditions" | **Next:** @"components-v2/content-components?text=Content Components" → + +## See Also + +- @"components-v2/content-components?text=Content Components" - Text, media, files +- @"components-v2/layout-components?text=Layout Components" - Containers, sections +- @"components-v2/interactive-components?text=Interactive Components" - Buttons, menus +- @"components-v2/migrating-from-embeds?text=Migrating from Embeds" - Convert embed layouts +- [Discord Docs: Message Components](https://discord.com/developers/docs/interactions/message-components) diff --git a/Documentation/guides/deployment/cloud-hosting.md b/Documentation/guides/deployment/cloud-hosting.md new file mode 100644 index 000000000..354fa00e5 --- /dev/null +++ b/Documentation/guides/deployment/cloud-hosting.md @@ -0,0 +1,36 @@ +--- +title: Hosting Discord Bots on Azure, AWS, and Cloud Platforms +description: Deploy NetCord bots to cloud providers. Learn Azure, AWS, and cloud hosting options with deployment strategies and best practices. +omitAppTitle: true +--- + +# Cloud Hosting + +> [!NOTE] +> Content for this section is under development. + +## Azure {#azure} + +Azure App Service deployment. + +## AWS {#aws} + +AWS deployment options. + +## VPS {#vps} + +Generic VPS setup. + +--- + +## Navigation + +← **Previous:** @"deployment/docker?text=Docker Deployment" | **Next:** @"advanced-topics/sharding?text=Sharding" → + +## See Also + +- @"deployment/docker?text=Docker Deployment" - Containerize for cloud +- @"dotnet-integration/configuration?text=Configuration" - Cloud configuration +- @"dotnet-integration/logging?text=Logging" - Cloud logging +- @"advanced-topics/sharding?text=Sharding" - Scale across instances +- [Azure Docs: App Service](https://learn.microsoft.com/en-us/azure/app-service/) diff --git a/Documentation/guides/deployment/docker.md b/Documentation/guides/deployment/docker.md new file mode 100644 index 000000000..916ad5576 --- /dev/null +++ b/Documentation/guides/deployment/docker.md @@ -0,0 +1,36 @@ +--- +title: Deploying Discord Bots with Docker and NetCord +description: Deploy NetCord bots using Docker containers. Learn Dockerfile creation, image optimization, and container orchestration for Discord bots. +omitAppTitle: true +--- + +# Docker Deployment + +> [!NOTE] +> Content for this section is under development. + +## Dockerfile {#dockerfile} + +Sample Dockerfile for NetCord bots. + +## Docker Compose {#docker-compose} + +Multi-service setup. + +## Secrets {#secrets} + +Managing tokens securely. + +--- + +## Navigation + +← **Previous:** @"components-v2/migrating-from-embeds?text=Migrating from Embeds" | **Next:** @"deployment/cloud-hosting?text=Cloud Hosting" → + +## See Also + +- @"deployment/cloud-hosting?text=Cloud Hosting" - Cloud provider options +- @"dotnet-integration/configuration?text=Configuration" - Environment variables +- @"dotnet-integration/logging?text=Logging" - Container logs +- @"advanced-topics/connection-resilience?text=Connection Resilience" - Restart policies +- [Docker Docs: Best Practices](https://docs.docker.com/develop/dev-best-practices/) diff --git a/Documentation/guides/discord-entities/channels.md b/Documentation/guides/discord-entities/channels.md new file mode 100644 index 000000000..8758a6e34 --- /dev/null +++ b/Documentation/guides/discord-entities/channels.md @@ -0,0 +1,36 @@ +--- +title: Working with Discord Channels, Threads, and Forums in NetCord +description: Manage Discord channels in C#. Learn text channels, voice channels, threads, forums, and channel operations with NetCord. +omitAppTitle: true +--- + +# Working with Channels + +> [!NOTE] +> Content for this section is under development. + +## Channel Types {#channel-types} + +Text, Voice, Category, Thread. + +## Channel Hierarchy {#channel-hierarchy} + +IGuildChannel, ITextChannel. + +## Sending Messages {#sending-messages} + +Using channels to send messages. + +--- + +## Navigation + +← **Previous:** @"discord-entities/guilds?text=Guilds" | **Next:** @"discord-entities/users?text=Users" → + +## See Also + +- @"discord-entities/users?text=Users" - User mentions and avatars +- @"discord-entities/roles-and-permissions?text=Roles and Permissions" - Channel permission overwrites +- @"voice/overview?text=Voice" - Voice channel connections +- @"components-v2/content-components?text=Content Components" - Message content builders +- [Discord Docs: Channel Resource](https://discord.com/developers/docs/resources/channel) diff --git a/Documentation/guides/discord-entities/emojis-and-stickers.md b/Documentation/guides/discord-entities/emojis-and-stickers.md new file mode 100644 index 000000000..2b69b435b --- /dev/null +++ b/Documentation/guides/discord-entities/emojis-and-stickers.md @@ -0,0 +1,36 @@ +--- +title: Working with Discord Custom Emojis and Stickers in NetCord +description: Use custom emojis and stickers in your Discord bot. Learn emoji management, animated emojis, and sticker operations with NetCord. +omitAppTitle: true +--- + +# Emojis and Stickers + +> [!NOTE] +> Content for this section is under development. + +## Emoji Types {#emoji-types} + +Emoji, GuildEmoji, ApplicationEmoji. + +## Using Emojis {#using-emojis} + +In messages and reactions. + +## Stickers {#stickers} + +Sticker types and usage. + +--- + +## Navigation + +← **Previous:** @"discord-entities/roles-and-permissions?text=Roles and Permissions" | **Next:** @"webhooks/overview?text=Webhooks" → + +## See Also + +- @"discord-entities/guilds?text=Guilds" - Guild custom emojis +- @"components-v2/content-components?text=Content Components" - Use emojis in messages +- @"component-interactions/message-components?text=Message Components" - Emojis in buttons +- [Discord Docs: Emoji Resource](https://discord.com/developers/docs/resources/emoji) +- [Discord Docs: Sticker Resource](https://discord.com/developers/docs/resources/sticker) diff --git a/Documentation/guides/discord-entities/guilds.md b/Documentation/guides/discord-entities/guilds.md new file mode 100644 index 000000000..feb71cfea --- /dev/null +++ b/Documentation/guides/discord-entities/guilds.md @@ -0,0 +1,36 @@ +--- +title: Working with Discord Guilds (Servers) in NetCord +description: Manage Discord guilds in your bot. Learn guild operations, member management, server settings, and guild events with NetCord. +omitAppTitle: true +--- + +# Working with Guilds + +> [!NOTE] +> Content for this section is under development. + +## Guild Types {#guild-types} + +Guild, RestGuild. + +## Guild Properties {#guild-properties} + +Name, icon, members. + +## Guild Operations {#guild-operations} + +Modifying guild settings. + +--- + +## Navigation + +← **Previous:** @"discord-entities/overview?text=Discord Entities Overview" | **Next:** @"discord-entities/channels?text=Channels" → + +## See Also + +- @"discord-entities/channels?text=Channels" - Guild channels and categories +- @"discord-entities/roles-and-permissions?text=Roles and Permissions" - Manage guild roles +- @"discord-entities/emojis-and-stickers?text=Emojis and Stickers" - Custom guild emojis +- @"events/gateway-events?text=Gateway Events" - Guild event handling +- [Discord Docs: Guild Resource](https://discord.com/developers/docs/resources/guild) diff --git a/Documentation/guides/discord-entities/overview.md b/Documentation/guides/discord-entities/overview.md new file mode 100644 index 000000000..7ca49d808 --- /dev/null +++ b/Documentation/guides/discord-entities/overview.md @@ -0,0 +1,36 @@ +--- +title: Understanding Discord Data Structures and Entities in NetCord +description: Complete guide to Discord entities in NetCord. Learn about guilds, channels, users, roles, messages, and how they map to C# types. +omitAppTitle: true +--- + +# Discord Entities Overview + +> [!NOTE] +> Content for this section is under development. + +## Entity Hierarchy {#entity-hierarchy} + +Base classes and inheritance. + +## REST vs Gateway {#rest-vs-gateway} + +RestGuild vs Guild differences. + +## Caching {#caching} + +How entities are cached. + +--- + +## Navigation + +← **Previous:** @"dotnet-integration/logging?text=Logging" | **Next:** @"discord-entities/guilds?text=Guilds" → + +## See Also + +- @"discord-entities/guilds?text=Guilds" - Guild properties and operations +- @"discord-entities/channels?text=Channels" - Channel types and management +- @"discord-entities/users?text=Users" - User and member objects +- @"advanced-topics/caching-strategies?text=Caching Strategies" - Optimize entity caching +- [Discord Docs: Resources](https://discord.com/developers/docs/resources/application) diff --git a/Documentation/guides/discord-entities/roles-and-permissions.md b/Documentation/guides/discord-entities/roles-and-permissions.md new file mode 100644 index 000000000..f0556e1ed --- /dev/null +++ b/Documentation/guides/discord-entities/roles-and-permissions.md @@ -0,0 +1,40 @@ +--- +title: Managing Discord Roles and Permissions in NetCord +description: Work with Discord roles and permission systems in C#. Learn role management, permission checks, and hierarchies with NetCord. +omitAppTitle: true +--- + +# Roles and Permissions + +> [!NOTE] +> Content for this section is under development. + +## Role Properties {#role-properties} + +Color, position, permissions. + +## Permission Flags {#permission-flags} + +Permissions enum usage. + +## Checking Permissions {#checking-permissions} + +HasPermission methods. + +## Permission Overwrites {#permission-overwrites} + +Channel-specific permissions. + +--- + +## Navigation + +← **Previous:** @"discord-entities/users?text=Users" | **Next:** @"discord-entities/emojis-and-stickers?text=Emojis and Stickers" → + +## See Also + +- @"discord-entities/guilds?text=Guilds" - Manage guild roles +- @"discord-entities/channels?text=Channels" - Channel permission overwrites +- @"services-framework/preconditions?text=Preconditions" - Permission-based command guards +- @"commands/overview?text=Commands Overview" - Command permissions +- [Discord Docs: Permissions](https://discord.com/developers/docs/topics/permissions) diff --git a/Documentation/guides/discord-entities/users.md b/Documentation/guides/discord-entities/users.md new file mode 100644 index 000000000..2d13aacfc --- /dev/null +++ b/Documentation/guides/discord-entities/users.md @@ -0,0 +1,36 @@ +--- +title: Working with Discord Users and Guild Members in NetCord +description: Access and manage Discord user data in C#. Learn about users, members, avatars, presence, and user operations with NetCord. +omitAppTitle: true +--- + +# Working with Users + +> [!NOTE] +> Content for this section is under development. + +## User Types {#user-types} + +User, CurrentUser, GuildUser. + +## Getting Users {#getting-users} + +Fetching user data. + +## User Properties {#user-properties} + +Username, avatar, and other properties. + +--- + +## Navigation + +← **Previous:** @"discord-entities/channels?text=Channels" | **Next:** @"discord-entities/roles-and-permissions?text=Roles and Permissions" → + +## See Also + +- @"discord-entities/guilds?text=Guilds" - Guild members vs users +- @"discord-entities/roles-and-permissions?text=Roles and Permissions" - User permissions in guilds +- @"commands/user-commands?text=User Commands" - Commands targeting users +- @"getting-started/creating-your-bot?text=Creating Your Bot" - Bot user setup +- [Discord Docs: User Resource](https://discord.com/developers/docs/resources/user) diff --git a/Documentation/guides/dotnet-integration/configuration.md b/Documentation/guides/dotnet-integration/configuration.md new file mode 100644 index 000000000..a1f2e8367 --- /dev/null +++ b/Documentation/guides/dotnet-integration/configuration.md @@ -0,0 +1,36 @@ +--- +title: Configuring Discord Bots with appsettings.json and Environment Variables +description: Manage bot configuration in NetCord using appsettings.json, user secrets, and environment variables. Learn best practices for secure config. +omitAppTitle: true +--- + +# Configuration + +> [!NOTE] +> Content for this section is under development. + +## appsettings {#appsettings} + +JSON configuration setup. + +## Environment Variables {#environment-variables} + +Secrets management. + +## Options Pattern {#options-pattern} + +GatewayClientOptions configuration. + +--- + +## Navigation + +← **Previous:** @"dotnet-integration/generic-host?text=Generic Host" | **Next:** @"dotnet-integration/logging?text=Logging" → + +## See Also + +- @"dotnet-integration/generic-host?text=Generic Host" - .NET Generic Host setup +- @"dotnet-integration/logging?text=Logging" - Configure structured logging +- @"events/intents?text=Intents" - Gateway intents configuration +- @"advanced-topics/connection-resilience?text=Connection Resilience" - Configure retry policies +- [Microsoft Docs: Options Pattern](https://learn.microsoft.com/en-us/dotnet/core/extensions/options) diff --git a/Documentation/guides/dotnet-integration/generic-host.md b/Documentation/guides/dotnet-integration/generic-host.md new file mode 100644 index 000000000..d9bf4b9dc --- /dev/null +++ b/Documentation/guides/dotnet-integration/generic-host.md @@ -0,0 +1,36 @@ +--- +title: Using .NET Generic Host for Discord Bot Development with NetCord +description: Integrate NetCord with .NET Generic Host for professional bot architecture. Learn dependency injection, configuration, logging, and lifecycle management. +omitAppTitle: true +--- + +# .NET Generic Host + +> [!NOTE] +> Content for this section is under development. + +## Why Generic Host {#why-generic-host} + +Benefits of using .NET Generic Host. + +## Adding Gateway {#adding-gateway} + +AddDiscordGateway/UseDiscordGateway setup. + +## Adding Services {#adding-services} + +UseApplicationCommands and other service extensions. + +--- + +## Navigation + +← **Previous:** @"getting-started/running-your-bot?text=Running Your Bot" | **Next:** @"dotnet-integration/configuration?text=Configuration" → + +## See Also + +- @"dotnet-integration/configuration?text=Configuration" - Configure services with options pattern +- @"dotnet-integration/logging?text=Logging" - Implement structured logging +- @"services-framework/dependency-injection?text=Dependency Injection" - Inject services into commands +- @"deployment?text=Deployment" - Production deployment strategies +- [Microsoft Docs: Generic Host](https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host) diff --git a/Documentation/guides/dotnet-integration/logging.md b/Documentation/guides/dotnet-integration/logging.md new file mode 100644 index 000000000..5d5b9df7c --- /dev/null +++ b/Documentation/guides/dotnet-integration/logging.md @@ -0,0 +1,36 @@ +--- +title: Discord Bot Logging with Microsoft.Extensions.Logging and NetCord +description: Implement structured logging for Discord bots using Microsoft.Extensions.Logging. Learn log levels, scopes, and integration with logging providers. +omitAppTitle: true +--- + +# Logging + +> [!NOTE] +> Content for this section is under development. + +## Microsoft Logging {#microsoft-logging} + +ILogger integration. + +## Log Levels {#log-levels} + +Configuring verbosity. + +## Custom Logging {#custom-logging} + +IRestLogger, IGatewayLogger. + +--- + +## Navigation + +← **Previous:** @"dotnet-integration/configuration?text=Configuration" | **Next:** @"discord-entities/overview?text=Discord Entities" → + +## See Also + +- @"dotnet-integration/generic-host?text=Generic Host" - Configure logging providers +- @"dotnet-integration/configuration?text=Configuration" - Logging configuration options +- @"advanced-topics/connection-resilience?text=Connection Resilience" - Log connection events +- @"troubleshooting/common-issues?text=Common Issues" - Debug with logs +- [Microsoft Docs: Logging](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging) diff --git a/Documentation/guides/events/FirstEvents/FirstEvents.csproj b/Documentation/guides/events/FirstEvents/FirstEvents.csproj deleted file mode 100644 index 75d3fd4b9..000000000 --- a/Documentation/guides/events/FirstEvents/FirstEvents.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - - - - - - - diff --git a/Documentation/guides/events/FirstEvents/Program.cs b/Documentation/guides/events/FirstEvents/Program.cs deleted file mode 100644 index 9e2378f23..000000000 --- a/Documentation/guides/events/FirstEvents/Program.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NetCord; -using NetCord.Gateway; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration() -{ - Intents = GatewayIntents.GuildMessages - | GatewayIntents.DirectMessages - | GatewayIntents.MessageContent - | GatewayIntents.DirectMessageReactions - | GatewayIntents.GuildMessageReactions, -}); - -client.MessageCreate += message => -{ - Console.WriteLine(message.Content); - return default; -}; - -client.MessageReactionAdd += async args => -{ - await client.Rest.SendMessageAsync(args.ChannelId, $"<@{args.UserId}> reacted with {args.Emoji.Name}!"); -}; diff --git a/Documentation/guides/events/FirstEventsHosting/FirstEventsHosting.csproj b/Documentation/guides/events/FirstEventsHosting/FirstEventsHosting.csproj deleted file mode 100644 index e3fb763cf..000000000 --- a/Documentation/guides/events/FirstEventsHosting/FirstEventsHosting.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - - - - - - - - - - - - diff --git a/Documentation/guides/events/FirstEventsHosting/MessageCreateHandler.cs b/Documentation/guides/events/FirstEventsHosting/MessageCreateHandler.cs deleted file mode 100644 index 5ae956b04..000000000 --- a/Documentation/guides/events/FirstEventsHosting/MessageCreateHandler.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.Extensions.Logging; - -using NetCord.Gateway; -using NetCord.Hosting.Gateway; - -namespace MyBot; - -public class MessageCreateHandler(ILogger logger) : IMessageCreateGatewayHandler -{ - public ValueTask HandleAsync(Message message) - { - logger.LogInformation("{}", message.Content); - return default; - } -} diff --git a/Documentation/guides/events/FirstEventsHosting/MessageReactionAddHandler.cs b/Documentation/guides/events/FirstEventsHosting/MessageReactionAddHandler.cs deleted file mode 100644 index 7e272c09c..000000000 --- a/Documentation/guides/events/FirstEventsHosting/MessageReactionAddHandler.cs +++ /dev/null @@ -1,13 +0,0 @@ -using NetCord.Gateway; -using NetCord.Hosting.Gateway; -using NetCord.Rest; - -namespace MyBot; - -public class MessageReactionAddHandler(RestClient client) : IMessageReactionAddGatewayHandler -{ - public async ValueTask HandleAsync(MessageReactionAddEventArgs args) - { - await client.SendMessageAsync(args.ChannelId, $"<@{args.UserId}> reacted with {args.Emoji.Name}!"); - } -} diff --git a/Documentation/guides/events/FirstEventsHosting/Program.cs b/Documentation/guides/events/FirstEventsHosting/Program.cs deleted file mode 100644 index 27a049b50..000000000 --- a/Documentation/guides/events/FirstEventsHosting/Program.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using NetCord.Gateway; -using NetCord.Hosting.Gateway; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddDiscordGateway(options => - { - options.Intents = GatewayIntents.GuildMessages - | GatewayIntents.DirectMessages - | GatewayIntents.MessageContent - | GatewayIntents.DirectMessageReactions - | GatewayIntents.GuildMessageReactions; - }) - .AddGatewayHandlers(typeof(Program).Assembly); - -var host = builder.Build(); - -await host.RunAsync(); diff --git a/Documentation/guides/events/Intents/Intents.csproj b/Documentation/guides/events/Intents/Intents.csproj deleted file mode 100644 index 75d3fd4b9..000000000 --- a/Documentation/guides/events/Intents/Intents.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - - - - - - - diff --git a/Documentation/guides/events/Intents/Program.cs b/Documentation/guides/events/Intents/Program.cs deleted file mode 100644 index 812005b20..000000000 --- a/Documentation/guides/events/Intents/Program.cs +++ /dev/null @@ -1,7 +0,0 @@ -using NetCord; -using NetCord.Gateway; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration() -{ - Intents = GatewayIntents.GuildMessages | GatewayIntents.DirectMessages | GatewayIntents.MessageContent, -}); diff --git a/Documentation/guides/events/IntentsHosting/IntentsHosting.csproj b/Documentation/guides/events/IntentsHosting/IntentsHosting.csproj deleted file mode 100644 index e3fb763cf..000000000 --- a/Documentation/guides/events/IntentsHosting/IntentsHosting.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - - - - - - - - - - - - diff --git a/Documentation/guides/events/IntentsHosting/Program.cs b/Documentation/guides/events/IntentsHosting/Program.cs deleted file mode 100644 index a918e9371..000000000 --- a/Documentation/guides/events/IntentsHosting/Program.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using NetCord.Gateway; -using NetCord.Hosting.Gateway; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddDiscordGateway(options => - { - options.Intents = GatewayIntents.GuildMessages | GatewayIntents.DirectMessages | GatewayIntents.MessageContent; - }); diff --git a/Documentation/guides/events/first-events.md b/Documentation/guides/events/first-events.md deleted file mode 100644 index df9b25a0a..000000000 --- a/Documentation/guides/events/first-events.md +++ /dev/null @@ -1,43 +0,0 @@ -# First Events - -## [.NET Generic Host](#tab/generic-host) - -The preferred way to receive events with the .NET Generic Host is by implementing appropriate @"NetCord.Hosting.Gateway.IGatewayHandler"s. An example of such an interface is @NetCord.Hosting.Gateway.IMessageCreateGatewayHandler. - -Use @NetCord.Hosting.Gateway.GatewayHandlerServiceCollectionExtensions.AddGatewayHandlers(Microsoft.Extensions.DependencyInjection.IServiceCollection,System.Reflection.Assembly) to add all event handlers in an assembly. -[!code-cs[Program.cs](FirstEventsHosting/Program.cs?highlight=17)] - -### MessageCreate Event -Now it's time to implement your MessageCreate event handler! -[!code-cs[Program.cs](FirstEventsHosting/MessageCreateHandler.cs)] - -When you run this code, when someone sends a message, the message will be printed on a console! - -### MessageReactionAdd Event -We will also implement a MessageReactionAdd event handler! -[!code-cs[Program.cs](FirstEventsHosting/MessageReactionAddHandler.cs)] - -When you run this code, when someone reacts to a message, the bot will notify everyone about it! - -### Other Events -Other events work similar to these. You can play with them if you want! - -> [!NOTE] -> When using @NetCord.Gateway.ShardedGatewayClient, you need to implement @NetCord.Hosting.Gateway.IShardedGatewayHandler instead. An example of such an interface is @NetCord.Hosting.Gateway.IMessageCreateShardedGatewayHandler. You also need to use @NetCord.Hosting.Gateway.GatewayHandlerServiceCollectionExtensions.AddShardedGatewayHandlers* to add event handlers. See @sharding?text=Sharding for more information. - -## [Bare Bones](#tab/bare-bones) - -### MessageCreate Event -To listen to the event, add the following lines before `client.StartAsync()`! -[!code-cs[Program.cs](FirstEvents/Program.cs#L13-L17)] - -When you run this code, when someone sends a message, the message will be printed on a console! - -### MessageReactionAdd Event -To listen to the event, add the following lines to your code. -[!code-cs[Program.cs](FirstEvents/Program.cs#L19-L22)] - -When you run this code, when someone reacts to a message, the bot will notify everyone about it! - -### Other Events -Other events work similar to these. You can play with them if you want! diff --git a/Documentation/guides/events/gateway-events.md b/Documentation/guides/events/gateway-events.md new file mode 100644 index 000000000..b7a5a1ad7 --- /dev/null +++ b/Documentation/guides/events/gateway-events.md @@ -0,0 +1,43 @@ +--- +title: Handling Discord Gateway Events in Real-Time with NetCord +description: Learn to handle Discord gateway events like message create, guild join, and voice state updates. Complete event handler reference for C# bots. +omitAppTitle: true +--- + +# Gateway Events + +> [!NOTE] +> Content for this section is under development. + +## Connection Events {#connection-events} + +Ready, Resumed, Disconnected. + +## Guild Events {#guild-events} + +GuildCreate, GuildUpdate, etc. + +## Message Events {#message-events} + +MessageCreate, MessageUpdate, etc. + +## Interaction Events {#interaction-events} + +InteractionCreate. + +## Voice Events {#voice-events} + +VoiceStateUpdate, VoiceServerUpdate. + +--- + +## Navigation + +← **Previous:** @"events/overview?text=Events Overview" | **Next:** @"events/intents?text=Gateway Intents" → + +## See Also + +- @"events/webhook-events?text=Webhook Events" - Alternative event handling +- @"commands/overview?text=Commands" - Handle command interactions +- @"advanced-topics/connection-resilience?text=Connection Resilience" - Maintain gateway connection +- [Discord Docs: Gateway Events Reference](https://discord.com/developers/docs/topics/gateway-events) diff --git a/Documentation/guides/events/intents.md b/Documentation/guides/events/intents.md index 0e228e834..b9d65d8b9 100644 --- a/Documentation/guides/events/intents.md +++ b/Documentation/guides/events/intents.md @@ -1,30 +1,37 @@ --- -uid: events +title: Configuring Discord Gateway Intents for Your Bot +description: Configure gateway intents to control which Discord events your bot receives. Learn about privileged intents, intent combinations, and bot permissions. +omitAppTitle: true --- -# Intents +# Gateway Intents -## What are intents? -Intents allow you to subscribe Discord events, such as @NetCord.Gateway.GatewayClient.MessageCreate and @NetCord.Gateway.GatewayClient.GuildUserAdd. If you don't specify certain intent, you will not subscribe certain events. +> [!NOTE] +> Content for this section is under development. -## Privileged intents -Privileged intents are intents that you need to enable in [Discord Developer Portal](https://discord.com/developers/applications). -![Shows 'Privileged Gateway Intents' section in 'Bot' section](../../images/intents_Privileged.webp){width=850px} +## What are Intents {#what-are-intents} -## How to specify intents in NetCord? +Gateway intents explained. -Intents in NetCord are handled by @NetCord.Gateway.GatewayIntents. -You specify them like this: +## Privileged Intents {#privileged-intents} -## [.NET Generic Host](#tab/generic-host) -[!code-cs[Program.cs](IntentsHosting/Program.cs?highlight=4#L8-L12)] +GuildMembers, Presences, MessageContent. -## [Bare Bones](#tab/bare-bones) -[!code-cs[Program.cs](Intents/Program.cs?highlight=3#L4-L7)] +> [!IMPORTANT] +> Privileged intents must be enabled in the Discord Developer Portal. -*** +## Configuring Intents {#configuring-intents} -If you have done this, you will receive guild and direct messages. +GatewayClientConfiguration setup. -> [!NOTE] -> `MessageContent` is a special, privileged intent that allows you to receive @NetCord.Rest.RestMessage.Content, @NetCord.Rest.RestMessage.Embeds, @NetCord.Rest.RestMessage.Attachments, @NetCord.Rest.RestMessage.Components and @NetCord.Rest.RestMessage.Poll of messages in events. Otherwise they are empty. +--- + +## Navigation + +← **Previous:** @"events/gateway-events?text=Gateway Events" | **Next:** @"events/webhook-events?text=Webhook Events" → + +## See Also + +- @"getting-started/creating-your-bot?text=Creating Your Bot" - Enable privileged intents +- @"advanced-topics/caching-strategies?text=Caching Strategies" - Intent-based caching +- [Discord Docs: Gateway Intents](https://discord.com/developers/docs/topics/gateway#gateway-intents) diff --git a/Documentation/guides/events/overview.md b/Documentation/guides/events/overview.md new file mode 100644 index 000000000..4dc8c7d1b --- /dev/null +++ b/Documentation/guides/events/overview.md @@ -0,0 +1,35 @@ +--- +title: Discord Bot Events Guide - Gateway and Webhook Event Handling +description: Complete guide to handling Discord events in NetCord. Learn about gateway events, intents, webhooks, and real-time bot interactions. +omitAppTitle: true +--- + +# Events Overview + +> [!NOTE] +> Content for this section is under development. + +## Event Model {#event-model} + +How events work in NetCord. + +## Subscribing {#subscribing} + ++= syntax and handlers. + +## Async Handlers {#async-handlers} + +ValueTask pattern. + +--- + +## Navigation + +**Next:** @"events/gateway-events?text=Gateway Events" → + +## See Also + +- @"events/intents?text=Gateway Intents" - Configure event subscriptions +- @"events/webhook-events?text=Webhook Events" - HTTP-based event handling +- @"commands/overview?text=Commands" - Command interactions +- [Discord Docs: Gateway Events](https://discord.com/developers/docs/topics/gateway-events) diff --git a/Documentation/guides/events/webhook-events.md b/Documentation/guides/events/webhook-events.md new file mode 100644 index 000000000..df8fdbf1f --- /dev/null +++ b/Documentation/guides/events/webhook-events.md @@ -0,0 +1,35 @@ +--- +title: Handling Discord Events via Webhooks with ASP.NET Core +description: Build Discord bots that handle interactions via HTTP webhooks in ASP.NET Core. Learn about webhook verification, endpoints, and stateless bots. +omitAppTitle: true +--- + +# Webhook Events + +> [!NOTE] +> Content for this section is under development. + +## Webhook Event Types {#webhook-event-types} + +WebhookEventType enum. + +## Handling Webhook Events {#handling-webhook-events} + +WebhookEventHandler. + +## ASP.NET Core Integration {#aspnetcore-integration} + +UseWebhookEvents(). + +--- + +## Navigation + +← **Previous:** @"events/intents?text=Gateway Intents" + +## See Also + +- @"webhooks/overview?text=Webhooks" - Webhook basics +- @"deployment/cloud-hosting?text=Cloud Hosting" - Deploy webhook bots +- @"commands/slash-commands?text=Slash Commands" - Handle slash command interactions +- [Discord Docs: Interactions Webhook](https://discord.com/developers/docs/interactions/receiving-and-responding#receiving-an-interaction) diff --git a/Documentation/guides/getting-started/Coding/Coding.csproj b/Documentation/guides/getting-started/Coding/Coding.csproj deleted file mode 100644 index 75d3fd4b9..000000000 --- a/Documentation/guides/getting-started/Coding/Coding.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - - - - - - - diff --git a/Documentation/guides/getting-started/Coding/Program.cs b/Documentation/guides/getting-started/Coding/Program.cs deleted file mode 100644 index c647a3601..000000000 --- a/Documentation/guides/getting-started/Coding/Program.cs +++ /dev/null @@ -1,11 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Logger = new ConsoleLogger(), -}); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/getting-started/CodingHosting/CodingHosting.csproj b/Documentation/guides/getting-started/CodingHosting/CodingHosting.csproj deleted file mode 100644 index e3fb763cf..000000000 --- a/Documentation/guides/getting-started/CodingHosting/CodingHosting.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - - - - - - - - - - - - diff --git a/Documentation/guides/getting-started/CodingHosting/appsettings.json b/Documentation/guides/getting-started/CodingHosting/appsettings.json deleted file mode 100644 index c6ef8532a..000000000 --- a/Documentation/guides/getting-started/CodingHosting/appsettings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "Discord": { - "Token": "Token from Discord Developer Portal" - } -} diff --git a/Documentation/guides/getting-started/GettingStarted/CreatingYourBot.cs b/Documentation/guides/getting-started/GettingStarted/CreatingYourBot.cs new file mode 100644 index 000000000..49187fe90 --- /dev/null +++ b/Documentation/guides/getting-started/GettingStarted/CreatingYourBot.cs @@ -0,0 +1,13 @@ +namespace GettingStarted; + +/// +/// Examples for the Creating Your Bot guide. +/// +public static class CreatingYourBot +{ + // TODO: Add Discord Developer Portal examples + // - Creating application + // - Bot token generation + // - Configuring bot permissions + // - Generating invite URL +} diff --git a/Documentation/guides/services/Preconditions/Preconditions/Preconditions.csproj b/Documentation/guides/getting-started/GettingStarted/GettingStarted.csproj similarity index 66% rename from Documentation/guides/services/Preconditions/Preconditions/Preconditions.csproj rename to Documentation/guides/getting-started/GettingStarted/GettingStarted.csproj index 22013d152..e971ab53c 100644 --- a/Documentation/guides/services/Preconditions/Preconditions/Preconditions.csproj +++ b/Documentation/guides/getting-started/GettingStarted/GettingStarted.csproj @@ -2,6 +2,9 @@ Exe + net9.0 + enable + enable @@ -10,6 +13,7 @@ + diff --git a/Documentation/guides/getting-started/GettingStarted/Installation.cs b/Documentation/guides/getting-started/GettingStarted/Installation.cs new file mode 100644 index 000000000..4ee7ffbb9 --- /dev/null +++ b/Documentation/guides/getting-started/GettingStarted/Installation.cs @@ -0,0 +1,12 @@ +namespace GettingStarted; + +/// +/// Examples for the Installation guide. +/// +public static class Installation +{ + // TODO: Add package installation examples + // - Installing NetCord via NuGet + // - Installing with .NET CLI + // - Package version selection +} diff --git a/Documentation/guides/basic-concepts/ShardingHosting/Program.cs b/Documentation/guides/getting-started/GettingStarted/Program.cs similarity index 60% rename from Documentation/guides/basic-concepts/ShardingHosting/Program.cs rename to Documentation/guides/getting-started/GettingStarted/Program.cs index b5d1a74cc..0b64bd538 100644 --- a/Documentation/guides/basic-concepts/ShardingHosting/Program.cs +++ b/Documentation/guides/getting-started/GettingStarted/Program.cs @@ -1,11 +1,9 @@ -using Microsoft.Extensions.Hosting; - +using Microsoft.Extensions.Hosting; using NetCord.Hosting.Gateway; var builder = Host.CreateApplicationBuilder(args); -builder.Services - .AddDiscordShardedGateway(); +builder.Services.AddDiscordGateway(); var host = builder.Build(); diff --git a/Documentation/guides/getting-started/GettingStarted/ProjectSetup.cs b/Documentation/guides/getting-started/GettingStarted/ProjectSetup.cs new file mode 100644 index 000000000..cc9b3a51e --- /dev/null +++ b/Documentation/guides/getting-started/GettingStarted/ProjectSetup.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.Hosting; +using NetCord.Hosting.Gateway; + +namespace GettingStarted; + +/// +/// Examples for the Project Setup guide. +/// +public static class ProjectSetup +{ + // TODO: Add project configuration examples + // - Generic Host configuration + // - appsettings.json structure + // - Environment variables + // - Secrets management + + public static void ConfigureServices() + { + var builder = Host.CreateApplicationBuilder(); + + // Example: Adding Discord Gateway + builder.Services.AddDiscordGateway(); + + // TODO: Add more configuration examples + } +} diff --git a/Documentation/guides/getting-started/GettingStarted/RunningYourBot.cs b/Documentation/guides/getting-started/GettingStarted/RunningYourBot.cs new file mode 100644 index 000000000..a93def6b4 --- /dev/null +++ b/Documentation/guides/getting-started/GettingStarted/RunningYourBot.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.Hosting; +using NetCord.Hosting.Gateway; + +namespace GettingStarted; + +/// +/// Examples for the Running Your Bot guide. +/// +public static class RunningYourBot +{ + // TODO: Add bot execution examples + // - Starting the host + // - Graceful shutdown + // - Handling cancellation + + public static async Task RunBasicBotAsync(CancellationToken cancellationToken = default) + { + var builder = Host.CreateApplicationBuilder(); + + builder.Services.AddDiscordGateway(); + + var host = builder.Build(); + + await host.RunAsync(cancellationToken); + } +} diff --git a/Documentation/guides/getting-started/GettingStarted/YourFirstResponse.cs b/Documentation/guides/getting-started/GettingStarted/YourFirstResponse.cs new file mode 100644 index 000000000..6bca50f65 --- /dev/null +++ b/Documentation/guides/getting-started/GettingStarted/YourFirstResponse.cs @@ -0,0 +1,30 @@ +using NetCord.Gateway; +using NetCord.Rest; + +namespace GettingStarted; + +/// +/// Examples for the Your First Response guide. +/// +public static class YourFirstResponse +{ + // TODO: Add message handling examples + // - Subscribing to message events + // - Sending basic text responses + // - Handling commands + // - Error handling + + public static void SetupMessageHandler(GatewayClient client) + { + client.MessageCreate += async message => + { + if (message.Content == "!ping") + { + await message.Channel!.SendMessageAsync(new MessageProperties + { + Content = "Pong!" + }); + } + }; + } +} diff --git a/Documentation/guides/getting-started/GettingStarted/appsettings.json b/Documentation/guides/getting-started/GettingStarted/appsettings.json new file mode 100644 index 000000000..cab155615 --- /dev/null +++ b/Documentation/guides/getting-started/GettingStarted/appsettings.json @@ -0,0 +1,9 @@ +{ + "Token": "YOUR_BOT_TOKEN_HERE", + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning" + } + } +} diff --git a/Documentation/guides/getting-started/creating-your-bot.md b/Documentation/guides/getting-started/creating-your-bot.md new file mode 100644 index 000000000..905a1007f --- /dev/null +++ b/Documentation/guides/getting-started/creating-your-bot.md @@ -0,0 +1,36 @@ +--- +title: Creating Your Discord Bot Application and Getting Your Token +description: Step-by-step guide to creating a Discord bot application in the Developer Portal, obtaining your bot token, and setting up OAuth2 permissions. +omitAppTitle: true +--- + +# Creating Your Bot + +> [!NOTE] +> Content for this section is under development. + +## Developer Portal {#developer-portal} + +Creating application in Discord Developer Portal. + +## Bot Token {#bot-token} + +Getting and securing your token. + +> [!IMPORTANT] +> Never share your bot token with anyone! It grants full control over your bot. + +## Inviting Bot {#inviting-bot} + +OAuth2 URL, scopes, and permissions. + +--- + +## Navigation + +← **Previous:** @"getting-started/installation?text=Installation" | **Next:** @"getting-started/project-setup?text=Project Setup" → + +## See Also + +- @"discord-entities/guilds?text=Working with Guilds" - Manage servers +- @"events/intents?text=Gateway Intents" - Configure bot permissions diff --git a/Documentation/guides/getting-started/installation.md b/Documentation/guides/getting-started/installation.md index 40c2b9009..4cb40a511 100644 --- a/Documentation/guides/getting-started/installation.md +++ b/Documentation/guides/getting-started/installation.md @@ -1,65 +1,28 @@ -# Installing NetCord +--- +title: Installing NetCord Packages for .NET Discord Bot Development +description: Learn how to install NetCord NuGet packages for your C# Discord bot using .NET CLI, Visual Studio, or JetBrains Rider. Includes package selection guide. +omitAppTitle: true +--- -This guide will walk you through the process of installing NetCord packages using various tools like the .NET CLI, Visual Studio and JetBrains Rider. +# Installing NetCord > [!NOTE] -> NetCord requires [.NET 9](https://dotnet.microsoft.com/download/dotnet/9.0) or higher. Older versions are not supported. - -## [.NET CLI](#tab/dotnet-cli) - -To install the NetCord package using the .NET CLI, run the following command: -```bash -dotnet add package NetCord --prerelease -``` - -## [Visual Studio](#tab/visual-studio) - -To install the NetCord package using the Visual Studio UI, follow these steps: - -1. Create a new project. - -2. Click `Manage NuGet Packages`. - - ![Click 'Manage NuGet Packages'](../../images/installation_VisualStudio_1.webp) - -3. Browse and install `NetCord` package. - - > [!NOTE] - > The `Include prerelease` checkbox must be checked to see the package. - - ![Browse and install 'NetCord' package](../../images/installation_VisualStudio_2.webp) - -## [JetBrains Rider](#tab/rider) - -To install the NetCord package using JetBrains Rider UI, follow these steps: - -1. Create a new project. - -2. Click `Manage NuGet Packages`. - - ![Click 'Manage NuGet Packages'](../../images/installation_JetBrainsRider_1.webp) - -3. Browse and install `NetCord` package. +> Content for this section is under development. - > [!NOTE] - > The `Prerelease` checkbox must be checked to see the package. +## NuGet {#nuget} - ![Browse and install 'NetCord' package](../../images/installation_JetBrainsRider_2.webp) +Package installation instructions. -## [Other](#tab/other) +## Packages Explained {#packages-explained} -To install the NetCord package using other tools, see the instructions on [NuGet](https://www.nuget.org/packages/NetCord). +Which packages for what purpose. -*** +--- -Other packages can be installed in the same way. +## Next Steps -### List of Packages +**Next:** @"getting-started/creating-your-bot?text=Creating Your Bot" → -| Package | Description | -|---------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| **[NetCord](https://www.nuget.org/packages/NetCord)** | Core package with fundamental functionality. | -| **[NetCord.Services](https://www.nuget.org/packages/NetCord.Services)** | Facilitates seamless handling of commands and interactions. | -| **[NetCord.Hosting](https://www.nuget.org/packages/NetCord.Hosting)** | Provides .NET Generic Host extensions for the NetCord package. | -| **[NetCord.Hosting.Services](https://www.nuget.org/packages/NetCord.Hosting.Services)** | Provides .NET Generic Host extensions for the NetCord.Services package. | -| **[NetCord.Hosting.AspNetCore](https://www.nuget.org/packages/NetCord.Hosting.AspNetCore)** | Provides ASP.NET Core extensions for seamless handling of HTTP events. | +**See Also:** +- @"quick-start?text=Quick Start" - Get running in 5 minutes +- @"dotnet-integration/generic-host?text=.NET Generic Host" - Professional bot architecture diff --git a/Documentation/guides/getting-started/making-a-bot.md b/Documentation/guides/getting-started/making-a-bot.md deleted file mode 100644 index 5e3cc46c0..000000000 --- a/Documentation/guides/getting-started/making-a-bot.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -omitAppTitle: true -title: Building Your First C# Discord Bot with .NET and NetCord -description: Build your first C# Discord bot with .NET and NetCord! This guide walks you through setting up a bot, writing C# code, and connecting to the Discord API. ---- - -# Building Your First C# Discord Bot - -Looking to build your first C# Discord bot? This step-by-step guide will show you how to create a bot on Discord and connect it to the Discord API using C# and NetCord, a powerful .NET library designed for building efficient and scalable Discord bots. - -## Step 1: Setting Up Your Discord Bot on the Discord Developer Portal - -Before diving into the code, you need to set up your bot on the Discord Developer Portal. This is the first essential step to making your bot available on Discord. - -### Creating a Discord Bot Application - -1. Head over to the [Discord Developer Portal](https://discord.com/developers/applications). Click **New Application** in the **Applications** section. - ![Click 'New Application' in the 'Applications' section](../../images/making-a-bot_CreateApplication_1.webp){width=600px} - -2. Enter a name for your bot, check the box, and click **Create**. - ![Enter a name for your bot, check the box, and click 'Create'](../../images/making-a-bot_CreateApplication_2.webp){width=350px} - -### Adding Your Bot to a Discord Server - -Once your bot application is created, you need to invite it to a server to interact with users: - -1. In the **OAuth2** section, select the **bot** scope to generate an invite link. - ![Generate a bot invite link in 'OAuth2 > URL Generator' by selecting 'bot' scope](../../images/making-a-bot_AddBotToServer_1.webp){width=850px} - -2. Use the generated invite link, paste it into your browser, select a server, and click **Authorise**. - ![Paste the invite link into your browser, select a server, and click 'Authorise'](../../images/making-a-bot_AddBotToServer_2.webp){width=400px} - -### Retrieving Your Discord Bot Token - -Before running the code, you'll need to retrieve your bot's token, which will allow your bot to communicate with Discord's API. - -> [!IMPORTANT] -> Never share your bot token with anyone! It grants full control over your bot. - -1. Go to the **Bot** section in the application settings and click **Reset Token**. - ![Go to 'Bot' section and click 'Reset Token'](../../images/making-a-bot_Token_1.webp){width=600px} - -2. Copy the token and save it. You'll need it later to connect your bot to Discord. - ![Click 'Copy' to copy the bot token to the clipboard](../../images/making-a-bot_Token_2.webp){width=350px} - -## Step 2: Coding Your C# Discord Bot - -Now that your bot is set up on Discord, it's time to write the C# code to bring your bot to life. In this section, you can select between two approaches for building your C# bot: using the **.NET Generic Host** or a **Bare Bones** setup. - -### Choosing Between the .NET Generic Host and Bare Bones Approach - -- **.NET Generic Host:** This approach allows you to set up your C# bot with ease, leveraging the power of dependency injection. It's straightforward and integrates well with the rest of the .NET ecosystem. You can read more about it [here](https://learn.microsoft.com/dotnet/core/extensions/generic-host). -- **Bare Bones:** For developers who prefer direct control, this approach lets you handle everything manually. It gives you more flexibility but requires a bit more setup. - -Pick one based on your preference and project requirements. - -### Writing the C# Code - -#### [.NET Generic Host](#tab/generic-host) - -> [!NOTE] -> The .NET Generic Host approach requires the following packages: -> - [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting) -> - [NetCord.Hosting](https://www.nuget.org/packages/NetCord.Hosting) - -To set up the bot with the .NET Generic Host, simply use @NetCord.Hosting.Gateway.GatewayClientServiceCollectionExtensions.AddDiscordGateway*. Here's an example showing how to add the bot to the host. -[!code-cs[Program.cs](CodingHosting/Program.cs)] - -For better configuration management, store the token in an `appsettings.json` file like this: -[!code-json[appsettings.json](CodingHosting/appsettings.json)] - -#### [Bare Bones](#tab/bare-bones) - -To create the @NetCord.Gateway.GatewayClient manually, add the following lines to your `Program.cs` file. -[!code-cs[Program.cs](Coding/Program.cs#L1-L8)] - -We have also added a console logger to log messages to the console. This is useful for debugging and monitoring your bot's activity. - -Finally, start your bot with the following lines. -[!code-cs[Program.cs](Coding/Program.cs#L10-L11)] - -#### The Final Product -[!code-cs[Program.cs](Coding/Program.cs)] - -*** - -Now, when you run the code, your C# bot should be online! -![Bot being online](../../images/making-a-bot_BotOnline.webp) - -## Extending Your C# Discord Bot - -Now, as you have your bot up and running, you can start adding more features to it. Here are some common functionalities you might want to implement: - -- **@"application-commands?text=Application Commands":** Allow users to interact with your bot easily by creating slash commands, user commands, and message commands. -- **@"events?text=Events Handling":** Listen for and respond to various events, such as message creation or user joining a server. diff --git a/Documentation/guides/getting-started/project-setup.md b/Documentation/guides/getting-started/project-setup.md new file mode 100644 index 000000000..109208a4c --- /dev/null +++ b/Documentation/guides/getting-started/project-setup.md @@ -0,0 +1,34 @@ +--- +title: Setting Up Your .NET Project for NetCord Bot Development +description: Configure your C# project for Discord bot development with NetCord using .NET Generic Host or bare-bones approach. Includes configuration setup. +omitAppTitle: true +--- + +# Project Setup + +> [!NOTE] +> Content for this section is under development. + +## Generic Host {#generic-host} + +.NET Generic Host approach. + +## Bare Bones {#bare-bones} + +Manual setup approach. + +## Configuration {#configuration} + +appsettings.json setup. + +--- + +## Navigation + +← **Previous:** @"getting-started/creating-your-bot?text=Creating Your Bot" | **Next:** @"getting-started/your-first-response?text=Your First Response" → + +## See Also + +- @"dotnet-integration/generic-host?text=.NET Generic Host Integration" - Advanced setup +- @"dotnet-integration/configuration?text=Configuration" - Managing settings +- @"dotnet-integration/logging?text=Logging" - Structured logging diff --git a/Documentation/guides/getting-started/running-your-bot.md b/Documentation/guides/getting-started/running-your-bot.md new file mode 100644 index 000000000..269b6eaea --- /dev/null +++ b/Documentation/guides/getting-started/running-your-bot.md @@ -0,0 +1,36 @@ +--- +title: Running and Testing Your Discord Bot Locally +description: Start your NetCord bot, test interactions, and debug common startup issues. Learn how to keep your bot running and monitor its status. +omitAppTitle: true +--- + +# Running Your Bot + +> [!NOTE] +> Content for this section is under development. + +## Starting Client {#starting-client} + +Starting GatewayClient. + +## Verifying Connection {#verifying-connection} + +Ready event confirmation. + +## Logging {#logging} + +Console output and diagnostics. + +--- + +## Navigation + +← **Previous:** @"getting-started/your-first-response?text=Your First Response" + +## Next Steps + +Now that your bot is running, explore these topics: + +- @"events/overview?text=Events Overview" - Handle Discord events +- @"commands/overview?text=Commands Overview" - Build slash and text commands +- @"troubleshooting/common-issues?text=Common Issues" - Debug problems diff --git a/Documentation/guides/getting-started/your-first-response.md b/Documentation/guides/getting-started/your-first-response.md new file mode 100644 index 000000000..e10fd4dcb --- /dev/null +++ b/Documentation/guides/getting-started/your-first-response.md @@ -0,0 +1,34 @@ +--- +title: Writing Your First Discord Bot Response in C# +description: Create your first interaction response handler in NetCord. Learn to respond to slash commands and handle user interactions with your bot. +omitAppTitle: true +--- + +# Your First Response + +> [!NOTE] +> Content for this section is under development. + +## Responding to Messages {#responding-to-messages} + +MessageCreate event handling. + +## Responding to Interactions {#responding-to-interactions} + +Slash command responses. + +## Using Components {#using-components} + +Adding buttons to responses. + +--- + +## Navigation + +← **Previous:** @"getting-started/project-setup?text=Project Setup" | **Next:** @"getting-started/running-your-bot?text=Running Your Bot" → + +## See Also + +- @"commands/slash-commands?text=Slash Commands" - Build application commands +- @"events/gateway-events?text=Gateway Events" - Handle Discord events +- @"component-interactions/message-components?text=Message Components" - Interactive buttons diff --git a/Documentation/guides/migration/discord-net.md b/Documentation/guides/migration/discord-net.md new file mode 100644 index 000000000..0f0b3f477 --- /dev/null +++ b/Documentation/guides/migration/discord-net.md @@ -0,0 +1,48 @@ +--- +title: Migrating from Discord.Net to NetCord - Complete Guide +description: Migrate Discord.Net bots to NetCord. Learn API equivalents, code patterns, and transition strategies for Discord.Net developers. +omitAppTitle: true +--- + +# Migrating from Discord.Net + +> [!NOTE] +> Content for this section is under development. + +## Overview {#overview} + +Key differences between Discord.Net and NetCord. + +## Client Setup {#client-setup} + +Comparison of client initialization. + +## Commands {#commands} + +Command framework differences. + +## Events {#events} + +Event handling comparison. + +## Entities {#entities} + +Entity structure differences. + +## Common Patterns {#common-patterns} + +Side-by-side code examples. + +--- + +## Navigation + +← **Previous:** @"migration/index?text=Migration Guide Overview" | **Next:** @"migration/dsharpplus?text=Migrating from DSharpPlus" → + +## See Also + +- @"migration/index?text=Migration Guide Overview" - Choose your migration path +- @"getting-started/installation?text=Installation" - Install NetCord +- @"dotnet-integration/generic-host?text=Generic Host" - Host setup differences +- @"commands/overview?text=Commands Overview" - NetCord command system +- @"events/gateway-events?text=Gateway Events" - NetCord event handling diff --git a/Documentation/guides/migration/dsharpplus.md b/Documentation/guides/migration/dsharpplus.md new file mode 100644 index 000000000..c5fdfd567 --- /dev/null +++ b/Documentation/guides/migration/dsharpplus.md @@ -0,0 +1,48 @@ +--- +title: Migrating from DSharpPlus to NetCord - Complete Guide +description: Migrate DSharpPlus bots to NetCord. Learn API equivalents, code patterns, and transition strategies for DSharpPlus developers. +omitAppTitle: true +--- + +# Migrating from DSharpPlus + +> [!NOTE] +> Content for this section is under development. + +## Overview {#overview} + +Key differences between DSharpPlus and NetCord. + +## Client Setup {#client-setup} + +Comparison of client initialization. + +## Commands {#commands} + +Command framework differences. + +## Events {#events} + +Event handling comparison. + +## Entities {#entities} + +Entity structure differences. + +## Common Patterns {#common-patterns} + +Side-by-side code examples. + +--- + +## Navigation + +← **Previous:** @"migration/discord-net?text=Migrating from Discord.Net" | **Next:** @"migration/other-csharp?text=Migrating from Other C# Libraries" → + +## See Also + +- @"migration/index?text=Migration Guide Overview" - Choose your migration path +- @"getting-started/installation?text=Installation" - Install NetCord +- @"dotnet-integration/generic-host?text=Generic Host" - Host setup +- @"commands/overview?text=Commands Overview" - NetCord command system +- @"events/gateway-events?text=Gateway Events" - NetCord event handling diff --git a/Documentation/guides/migration/other-csharp.md b/Documentation/guides/migration/other-csharp.md new file mode 100644 index 000000000..9c260e0ba --- /dev/null +++ b/Documentation/guides/migration/other-csharp.md @@ -0,0 +1,38 @@ +--- +title: Migrating from Other C# Discord Libraries to NetCord +description: Migrate from any C# Discord library to NetCord. Learn common patterns, API differences, and general migration strategies. +omitAppTitle: true +--- + +# Migrating from Other C# Libraries + +> [!NOTE] +> Content for this section is under development. + +This guide covers migration from less common C# Discord libraries. + +## Remora.Discord {#remora-discord} + +Key differences and migration notes. + +## DisCatSharp {#discatsharp} + +Key differences and migration notes. + +## Other Libraries {#other-libraries} + +General migration guidance. + +--- + +## Navigation + +← **Previous:** @"migration/dsharpplus?text=Migrating from DSharpPlus" | **Next:** @"migration/other-languages?text=Migrating from Other Languages" → + +## See Also + +- @"migration/index?text=Migration Guide Overview" - Choose your migration path +- @"migration/discord-net?text=Discord.Net Migration" - Popular C# library patterns +- @"getting-started/installation?text=Installation" - Install NetCord +- @"introduction/index?text=Introduction" - NetCord concepts +- @"commands/overview?text=Commands Overview" - NetCord command system diff --git a/Documentation/guides/migration/other-languages.md b/Documentation/guides/migration/other-languages.md new file mode 100644 index 000000000..cb27d75c4 --- /dev/null +++ b/Documentation/guides/migration/other-languages.md @@ -0,0 +1,111 @@ +--- +title: Migrating from JavaScript, Python, and Other Languages to NetCord +description: Transition to NetCord from discord.js, discord.py, and other language libraries. Learn C# equivalents and Discord API concepts. +omitAppTitle: true +--- + +# Migrating from Other Languages + +> [!NOTE] +> Content for this section is under development. + +This guide provides concept mapping between popular Discord libraries in other languages and NetCord. + +## JavaScript/TypeScript {#javascript-typescript} + +### discord.js {#discord-js} + +Mapping discord.js concepts to NetCord. + +- **Client Setup** - Compare initialization +- **Event Handling** - Event patterns +- **Commands** - Slash command comparison +- **Collectors** - Interaction patterns + +### Eris {#eris} + +Mapping Eris concepts to NetCord. + +## Python {#python} + +### discord.py {#discord-py} + +Mapping discord.py concepts to NetCord. + +- **Client Types** - Bot vs Client +- **Cogs** - Module system comparison +- **Commands** - Command decorators vs attributes +- **Events** - Event handling patterns + +### Pycord {#pycord} + +Mapping Pycord concepts to NetCord. + +### Nextcord {#nextcord} + +Mapping Nextcord concepts to NetCord. + +## Java {#java} + +### JDA {#jda} + +Mapping JDA concepts to NetCord. + +- **Client Setup** - JDABuilder vs GatewayClient +- **Events** - ListenerAdapter comparison +- **Commands** - Command system differences +- **Entities** - Entity structure comparison + +### Javacord {#javacord} + +Mapping Javacord concepts to NetCord. + +## Kotlin {#kotlin} + +### Kord {#kord} + +Mapping Kord concepts to NetCord. + +## Rust {#rust} + +### Serenity {#serenity} + +Mapping Serenity concepts to NetCord. + +### Twilight {#twilight} + +Mapping Twilight concepts to NetCord. + +## Go {#go} + +### DiscordGo {#discordgo} + +Mapping DiscordGo concepts to NetCord. + +## General Concepts {#general-concepts} + +### Async/Await Patterns {#async-await} + +How different languages handle async compared to C#. + +### Dependency Injection {#dependency-injection} + +DI patterns across languages vs .NET DI. + +### Type Systems {#type-systems} + +Strongly typed vs dynamically typed approaches. + +--- + +## Navigation + +← **Previous:** @"migration/other-csharp?text=Migrating from Other C# Libraries" | **Next:** @"troubleshooting/common-issues?text=Common Issues" → + +## See Also + +- @"migration/index?text=Migration Guide Overview" - Choose your migration path +- @"introduction/index?text=Introduction" - NetCord concepts +- @"getting-started/installation?text=Installation" - Install NetCord +- @"dotnet-integration/generic-host?text=Generic Host" - .NET patterns +- @"commands/overview?text=Commands Overview" - NetCord command system diff --git a/Documentation/guides/services-framework/custom-contexts.md b/Documentation/guides/services-framework/custom-contexts.md new file mode 100644 index 000000000..460088449 --- /dev/null +++ b/Documentation/guides/services-framework/custom-contexts.md @@ -0,0 +1,36 @@ +--- +title: Creating Custom Command Contexts in NetCord.Services +description: Extend context objects in NetCord.Services. Learn to create custom contexts with additional data and helper methods for your commands. +omitAppTitle: true +--- + +# Custom Contexts + +> [!NOTE] +> Content for this section is under development. + +## Context Interfaces {#context-interfaces} + +IContext hierarchy. + +## Creating Custom Context {#creating-custom-context} + +Extending contexts. + +## Accessing Context {#accessing-context} + +In module methods. + +--- + +## Navigation + +← **Previous:** @"services-framework/dependency-injection?text=Dependency Injection" | **Next:** @"services-framework/type-readers?text=Type Readers" → + +## See Also + +- @"services-framework/dependency-injection?text=Dependency Injection" - Inject data into contexts +- @"services-framework/type-readers?text=Type Readers" - Access context in readers +- @"services-framework/preconditions?text=Preconditions" - Access context in preconditions +- @"commands/overview?text=Commands Overview" - Context types for commands +- @"component-interactions/message-components?text=Message Components" - Component interaction contexts diff --git a/Documentation/guides/services-framework/dependency-injection.md b/Documentation/guides/services-framework/dependency-injection.md new file mode 100644 index 000000000..efb762714 --- /dev/null +++ b/Documentation/guides/services-framework/dependency-injection.md @@ -0,0 +1,36 @@ +--- +title: Using Dependency Injection in NetCord Command Modules +description: Implement dependency injection in NetCord.Services command modules. Learn constructor injection, service lifetimes, and DI best practices. +omitAppTitle: true +--- + +# Dependency Injection + +> [!NOTE] +> Content for this section is under development. + +## Constructor Injection {#constructor-injection} + +Injecting services into modules. + +## Service Lifetime {#service-lifetime} + +Scoped vs Singleton. + +## Service Provider {#service-provider} + +IServiceProvider usage. + +--- + +## Navigation + +← **Previous:** @"services-framework/overview?text=Services Framework Overview" | **Next:** @"services-framework/custom-contexts?text=Custom Contexts" → + +## See Also + +- @"services-framework/custom-contexts?text=Custom Contexts" - Inject data into contexts +- @"services-framework/type-readers?text=Type Readers" - DI in type readers +- @"dotnet-integration/generic-host?text=Generic Host" - Configure DI container +- @"commands/overview?text=Commands Overview" - DI in command handlers +- [Microsoft Docs: Dependency Injection](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection) diff --git a/Documentation/guides/services-framework/overview.md b/Documentation/guides/services-framework/overview.md new file mode 100644 index 000000000..779f77432 --- /dev/null +++ b/Documentation/guides/services-framework/overview.md @@ -0,0 +1,36 @@ +--- +title: NetCord Services Framework - Command Handling and Middleware +description: Build robust command systems with NetCord.Services. Learn command modules, execution pipeline, type readers, and preconditions. +omitAppTitle: true +--- + +# Services Framework Overview + +> [!NOTE] +> Content for this section is under development. + +## Architecture {#architecture} + +Service pattern explained. + +## Shared Features {#shared-features} + +What's shared across services. + +## Modules {#modules} + +Module base classes. + +--- + +## Navigation + +← **Previous:** @"webhooks/sending-messages?text=Sending Messages" | **Next:** @"services-framework/dependency-injection?text=Dependency Injection" → + +## See Also + +- @"services-framework/dependency-injection?text=Dependency Injection" - Inject services into modules +- @"services-framework/type-readers?text=Type Readers" - Parse command parameters +- @"services-framework/preconditions?text=Preconditions" - Command authorization +- @"services-framework/custom-contexts?text=Custom Contexts" - Extend context objects +- @"commands/overview?text=Commands Overview" - Application commands integration diff --git a/Documentation/guides/services-framework/preconditions.md b/Documentation/guides/services-framework/preconditions.md new file mode 100644 index 000000000..ef5cd3762 --- /dev/null +++ b/Documentation/guides/services-framework/preconditions.md @@ -0,0 +1,36 @@ +--- +title: Implementing Command Preconditions and Authorization in NetCord +description: Create preconditions to validate command requirements. Learn permission checks, cooldowns, and custom validation in NetCord.Services. +omitAppTitle: true +--- + +# Preconditions + +> [!NOTE] +> Content for this section is under development. + +## Built-in Preconditions {#built-in-preconditions} + +RequireUserPermissions, etc. + +## Custom Preconditions {#custom-preconditions} + +PreconditionAttribute. + +## Parameter Preconditions {#parameter-preconditions} + +ParameterPreconditionAttribute. + +--- + +## Navigation + +← **Previous:** @"services-framework/type-readers?text=Type Readers" | **Next:** @"components-v2/overview?text=Components v2 Overview" → + +## See Also + +- @"services-framework/type-readers?text=Type Readers" - Parse parameters first +- @"services-framework/custom-contexts?text=Custom Contexts" - Access context in preconditions +- @"discord-entities/roles-and-permissions?text=Roles and Permissions" - Permission checks +- @"commands/overview?text=Commands Overview" - Command permissions +- @"advanced-topics/rate-limiting?text=Rate Limiting" - Implement cooldowns diff --git a/Documentation/guides/services-framework/type-readers.md b/Documentation/guides/services-framework/type-readers.md new file mode 100644 index 000000000..78c591d74 --- /dev/null +++ b/Documentation/guides/services-framework/type-readers.md @@ -0,0 +1,36 @@ +--- +title: Building Type Readers for Discord Command Parameters +description: Create custom type readers in NetCord.Services. Learn parameter parsing, type conversion, and validation for command arguments. +omitAppTitle: true +--- + +# Type Readers + +> [!NOTE] +> Content for this section is under development. + +## Built-in Readers {#built-in-readers} + +User, Role, Channel, etc. + +## Custom Readers {#custom-readers} + +Creating custom type readers. + +## Registering Readers {#registering-readers} + +Configuration. + +--- + +## Navigation + +← **Previous:** @"services-framework/custom-contexts?text=Custom Contexts" | **Next:** @"services-framework/preconditions?text=Preconditions" → + +## See Also + +- @"services-framework/preconditions?text=Preconditions" - Validate after parsing +- @"services-framework/custom-contexts?text=Custom Contexts" - Access context in readers +- @"commands/slash-commands?text=Slash Commands" - Command option types +- @"discord-entities/overview?text=Discord Entities" - Parse entities +- @"commands/text-commands?text=Text Commands" - Text command parsing diff --git a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/CustomCommandContext.cs b/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/CustomCommandContext.cs deleted file mode 100644 index 255fb1bf1..000000000 --- a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/CustomCommandContext.cs +++ /dev/null @@ -1,10 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Services.Commands; - -namespace MyBot; - -public class CustomCommandContext(Message message, GatewayClient client) : CommandContext(message, client) -{ - public GuildUser BotGuildUser => Guild!.Users[Client.Id]; -} diff --git a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/CustomContexts.csproj b/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/CustomContexts.csproj deleted file mode 100644 index f4393da38..000000000 --- a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/CustomContexts.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/ExampleModule.cs b/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/ExampleModule.cs deleted file mode 100644 index db85038e3..000000000 --- a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomContexts/ExampleModule.cs +++ /dev/null @@ -1,15 +0,0 @@ -using NetCord.Services; -using NetCord.Services.Commands; - -namespace MyBot; - -public class ExampleModule : CommandModule -{ - [RequireContext(RequiredContext.Guild)] - [Command("botname")] - public string BotName() - { - var user = Context.BotGuildUser; - return user.Nickname ?? user.Username; - } -} diff --git a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/CustomCommandModule.cs b/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/CustomCommandModule.cs deleted file mode 100644 index b32bb7e2c..000000000 --- a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/CustomCommandModule.cs +++ /dev/null @@ -1,14 +0,0 @@ -using NetCord; -using NetCord.Services.Commands; - -namespace MyBot; - -public abstract class CustomCommandModule : CommandModule -{ - public Color GetUserColor(GuildUser user) - { - return (user.GetRoles(Context.Guild!) - .OrderByDescending(r => r.Position) - .FirstOrDefault(r => r.Color != default)?.Color).GetValueOrDefault(); - } -} diff --git a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/CustomModuleBases.csproj b/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/CustomModuleBases.csproj deleted file mode 100644 index f4393da38..000000000 --- a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/CustomModuleBases.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/ExampleModule.cs b/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/ExampleModule.cs deleted file mode 100644 index b6beab683..000000000 --- a/Documentation/guides/services/CustomModuleBasesAndContexts/CustomModuleBases/ExampleModule.cs +++ /dev/null @@ -1,17 +0,0 @@ -using NetCord; -using NetCord.Services; -using NetCord.Services.Commands; - -namespace MyBot; - -public class ExampleModule : CustomCommandModule -{ - [RequireContext(RequiredContext.Guild)] - [Command("color")] - public string Color(GuildUser? user = null) - { - user ??= (GuildUser)Context.User; - var color = GetUserColor(user); - return $"#{color.RawValue:X6}"; - } -} diff --git a/Documentation/guides/services/DependencyInjection/DataAutocompleteProvider.cs b/Documentation/guides/services/DependencyInjection/DataAutocompleteProvider.cs deleted file mode 100644 index d7c966a48..000000000 --- a/Documentation/guides/services/DependencyInjection/DataAutocompleteProvider.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NetCord; -using NetCord.Rest; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class DataAutocompleteProvider(ISomeService someService) : IAutocompleteProvider -{ - public ValueTask?> GetChoicesAsync( - ApplicationCommandInteractionDataOption option, - AutocompleteInteractionContext context) - { - var input = option.Value!; - var data = someService.GetSomeData(); - - var result = data.Where(d => d.Contains(input)) - .Take(25) - .Select(d => new ApplicationCommandOptionChoiceProperties(d, d)); - - return new(result); - } -} diff --git a/Documentation/guides/services/DependencyInjection/DataModule.cs b/Documentation/guides/services/DependencyInjection/DataModule.cs deleted file mode 100644 index 77a27674d..000000000 --- a/Documentation/guides/services/DependencyInjection/DataModule.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NetCord.Services.Commands; - -namespace MyBot; - -public class DataModule(ISomeService someService) : CommandModule -{ - [Command("data")] - public string Data(int count) => string.Join(' ', someService.GetSomeData().Take(count)); -} diff --git a/Documentation/guides/services/DependencyInjection/DependencyInjection.csproj b/Documentation/guides/services/DependencyInjection/DependencyInjection.csproj deleted file mode 100644 index 8f7975131..000000000 --- a/Documentation/guides/services/DependencyInjection/DependencyInjection.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - - - - - - - - - - - - diff --git a/Documentation/guides/services/DependencyInjection/ISomeService.cs b/Documentation/guides/services/DependencyInjection/ISomeService.cs deleted file mode 100644 index c4f158814..000000000 --- a/Documentation/guides/services/DependencyInjection/ISomeService.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace MyBot; - -public interface ISomeService -{ - public IReadOnlyList GetSomeData(); -} - -public class SomeService : ISomeService -{ - public IReadOnlyList GetSomeData() => ["hello", "world"]; -} diff --git a/Documentation/guides/services/DependencyInjection/Program.cs b/Documentation/guides/services/DependencyInjection/Program.cs deleted file mode 100644 index 2a33d7522..000000000 --- a/Documentation/guides/services/DependencyInjection/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -using MyBot; - -using NetCord; -using NetCord.Gateway; -using NetCord.Hosting.Gateway; -using NetCord.Hosting.Services; -using NetCord.Hosting.Services.ApplicationCommands; -using NetCord.Hosting.Services.Commands; -using NetCord.Services.ApplicationCommands; -using NetCord.Services.Commands; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddSingleton() - .AddDiscordGateway(o => o.Intents = GatewayIntents.GuildMessages | GatewayIntents.DirectMessages | GatewayIntents.MessageContent) - .AddCommands() - .AddApplicationCommands(); - -var host = builder.Build(); - -host.AddModules(typeof(Program).Assembly); - -host.AddSlashCommand( - name: "data", - description: "Shows the data!", - (ISomeService someService, ApplicationCommandContext context, int count) => string.Join(' ', - someService.GetSomeData() - .Take(count))); - -await host.RunAsync(); diff --git a/Documentation/guides/services/Preconditions/ParameterPreconditions/HelloModule.cs b/Documentation/guides/services/Preconditions/ParameterPreconditions/HelloModule.cs deleted file mode 100644 index 5c1bd5fd5..000000000 --- a/Documentation/guides/services/Preconditions/ParameterPreconditions/HelloModule.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class HelloModule : ApplicationCommandModule -{ - [SlashCommand("hello", "Say hello!")] - public static string Hello([MustContain("hello")] string text) => text; -} diff --git a/Documentation/guides/services/Preconditions/ParameterPreconditions/MustContainAttribute.cs b/Documentation/guides/services/Preconditions/ParameterPreconditions/MustContainAttribute.cs deleted file mode 100644 index 2554463fa..000000000 --- a/Documentation/guides/services/Preconditions/ParameterPreconditions/MustContainAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -using NetCord.Services; - -namespace MyBot; - -// We use generics to make our attribute usable for all types of commands and interactions at the same time -public class MustContainAttribute(string required) : ParameterPreconditionAttribute -{ - public override ValueTask EnsureCanExecuteAsync(object? value, TContext context, IServiceProvider? serviceProvider) - { - var text = (string)value!; - - // Return a fail result when the parameter value does not contain the required text - if (!text.Contains(required, StringComparison.InvariantCultureIgnoreCase)) - return new(PreconditionResult.Fail($"The parameter must contain '{required}'.")); - - return new(PreconditionResult.Success); - } -} diff --git a/Documentation/guides/services/Preconditions/ParameterPreconditions/Program.cs b/Documentation/guides/services/Preconditions/ParameterPreconditions/Program.cs deleted file mode 100644 index 1a01cac5a..000000000 --- a/Documentation/guides/services/Preconditions/ParameterPreconditions/Program.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using MyBot; - -using NetCord; -using NetCord.Hosting.Gateway; -using NetCord.Hosting.Services; -using NetCord.Hosting.Services.ApplicationCommands; -using NetCord.Hosting.Services.Commands; -using NetCord.Services.ApplicationCommands; -using NetCord.Services.Commands; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddDiscordGateway() - .AddApplicationCommands() - .AddCommands(); - -var host = builder.Build(); - -host.AddCommand( - aliases: ["bye"], - ([MustContain("bye")] string text) => text); - -host.AddModules(typeof(Program).Assembly); - -await host.RunAsync(); diff --git a/Documentation/guides/services/Preconditions/Preconditions/AvatarModule.cs b/Documentation/guides/services/Preconditions/Preconditions/AvatarModule.cs deleted file mode 100644 index 3bcc7555b..000000000 --- a/Documentation/guides/services/Preconditions/Preconditions/AvatarModule.cs +++ /dev/null @@ -1,10 +0,0 @@ -using NetCord.Services.Commands; - -namespace MyBot; - -public class AvatarModule : CommandModule -{ - [RequireAnimatedAvatar] - [Command("avatar")] - public string Avatar() => Context.User.GetAvatarUrl()!.ToString(); -} diff --git a/Documentation/guides/services/Preconditions/Preconditions/ButtonModule.cs b/Documentation/guides/services/Preconditions/Preconditions/ButtonModule.cs deleted file mode 100644 index 5727199d7..000000000 --- a/Documentation/guides/services/Preconditions/Preconditions/ButtonModule.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NetCord.Services.ComponentInteractions; - -namespace MyBot; - -[RequireAnimatedAvatar] -public class ButtonModule : ComponentInteractionModule -{ - // All interactions here will require animated avatars -} diff --git a/Documentation/guides/services/Preconditions/Preconditions/Program.cs b/Documentation/guides/services/Preconditions/Preconditions/Program.cs deleted file mode 100644 index f12bbd13f..000000000 --- a/Documentation/guides/services/Preconditions/Preconditions/Program.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using MyBot; - -using NetCord; -using NetCord.Hosting.Gateway; -using NetCord.Hosting.Services; -using NetCord.Hosting.Services.ApplicationCommands; -using NetCord.Hosting.Services.Commands; -using NetCord.Hosting.Services.ComponentInteractions; -using NetCord.Services.ApplicationCommands; -using NetCord.Services.Commands; -using NetCord.Services.ComponentInteractions; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddDiscordGateway() - .AddApplicationCommands() - .AddComponentInteractions() - .AddCommands(); - -var host = builder.Build(); - -host.AddSlashCommand( - name: "hi", - description: "Hi!", - [RequireAnimatedAvatar] () => "Hi! You can use this command because your avatar is animated!"); - -host.AddModules(typeof(Program).Assembly); - -await host.RunAsync(); diff --git a/Documentation/guides/services/Preconditions/Preconditions/RequireAnimatedAvatarAttribute.cs b/Documentation/guides/services/Preconditions/Preconditions/RequireAnimatedAvatarAttribute.cs deleted file mode 100644 index 842019ba9..000000000 --- a/Documentation/guides/services/Preconditions/Preconditions/RequireAnimatedAvatarAttribute.cs +++ /dev/null @@ -1,16 +0,0 @@ -using NetCord.Services; - -namespace MyBot; - -// We use generics to make our attribute usable for all types of commands and interactions at the same time -public class RequireAnimatedAvatarAttribute : PreconditionAttribute where TContext : IUserContext -{ - public override ValueTask EnsureCanExecuteAsync(TContext context, IServiceProvider? serviceProvider) - { - // Return a fail result when the user has no avatar or it's not animated - if (context.User.AvatarHash is not string hash || !hash.StartsWith("a_")) - return new(PreconditionResult.Fail("You need an animated avatar to use this.")); - - return new(PreconditionResult.Success); - } -} diff --git a/Documentation/guides/services/application-commands/Introduction/ExampleModule.cs b/Documentation/guides/services/application-commands/Introduction/ExampleModule.cs deleted file mode 100644 index afad139a1..000000000 --- a/Documentation/guides/services/application-commands/Introduction/ExampleModule.cs +++ /dev/null @@ -1,17 +0,0 @@ -using NetCord; -using NetCord.Rest; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class ExampleModule : ApplicationCommandModule -{ - [SlashCommand("pong", "Pong!")] - public static string Pong() => "Ping!"; - - [UserCommand("ID")] - public static string Id(User user) => user.Id.ToString(); - - [MessageCommand("Timestamp")] - public static string Timestamp(RestMessage message) => message.CreatedAt.ToString(); -} diff --git a/Documentation/guides/services/application-commands/Introduction/Introduction.csproj b/Documentation/guides/services/application-commands/Introduction/Introduction.csproj deleted file mode 100644 index 7379c7dd7..000000000 --- a/Documentation/guides/services/application-commands/Introduction/Introduction.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/services/application-commands/Introduction/Program.cs b/Documentation/guides/services/application-commands/Introduction/Program.cs deleted file mode 100644 index 0502b049d..000000000 --- a/Documentation/guides/services/application-commands/Introduction/Program.cs +++ /dev/null @@ -1,53 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = default, - Logger = new ConsoleLogger(), -}); - -// Create the application command service -ApplicationCommandService applicationCommandService = new(); - -// Add commands using minimal APIs -applicationCommandService.AddSlashCommand(new SlashCommandBuilder("ping", "Ping!", () => "Pong!")); -applicationCommandService.AddUserCommand(new UserCommandBuilder("Username", (User user) => user.Username)); -applicationCommandService.AddMessageCommand(new MessageCommandBuilder("Length", (RestMessage message) => message.Content.Length.ToString())); - -// Add commands from modules -applicationCommandService.AddModules(typeof(Program).Assembly); - -// Add the handler to handle interactions -client.InteractionCreate += async interaction => -{ - // Check if the interaction is an application command interaction - if (interaction is not ApplicationCommandInteraction applicationCommandInteraction) - return; - - // Execute the command - var result = await applicationCommandService.ExecuteAsync(new ApplicationCommandContext(applicationCommandInteraction, client)); - - // Check if the execution failed - if (result is not IFailResult failResult) - return; - - // Return the error message to the user if the execution failed - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -// Register the commands so that you can use them in the Discord client -await applicationCommandService.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/services/application-commands/IntroductionHosting/Program.cs b/Documentation/guides/services/application-commands/IntroductionHosting/Program.cs deleted file mode 100644 index 0d818414a..000000000 --- a/Documentation/guides/services/application-commands/IntroductionHosting/Program.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using NetCord; -using NetCord.Hosting.Gateway; -using NetCord.Hosting.Services; -using NetCord.Hosting.Services.ApplicationCommands; -using NetCord.Rest; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddDiscordGateway() - .AddApplicationCommands(); - -var host = builder.Build(); - -// Add commands using minimal APIs -host.AddSlashCommand("ping", "Ping!", () => "Pong!"); -host.AddUserCommand("Username", (User user) => user.Username); -host.AddMessageCommand("Length", (RestMessage message) => message.Content.Length.ToString()); - -// Add commands from modules -host.AddModules(typeof(Program).Assembly); - -await host.RunAsync(); diff --git a/Documentation/guides/services/application-commands/Localizations/AnimalModule.cs b/Documentation/guides/services/application-commands/Localizations/AnimalModule.cs deleted file mode 100644 index 97b50c398..000000000 --- a/Documentation/guides/services/application-commands/Localizations/AnimalModule.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class AnimalModule : ApplicationCommandModule -{ - [SlashCommand("animal", "Sends the animal you selected")] - public static string Animal( - [SlashCommandParameter(Description = "Animal to send")] Animal animal) - { - return animal.ToString(); - } -} - -public enum Animal -{ - Dog, - Cat, - Fish, - [SlashCommandChoice(Name = "Guinea Pig")] - GuineaPig, -} diff --git a/Documentation/guides/services/application-commands/Localizations/Localizations.csproj b/Documentation/guides/services/application-commands/Localizations/Localizations.csproj deleted file mode 100644 index 590515c2d..000000000 --- a/Documentation/guides/services/application-commands/Localizations/Localizations.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - Exe - - - - - - - - - - PreserveNewest - - - - diff --git a/Documentation/guides/services/application-commands/Localizations/Localizations/pl.json b/Documentation/guides/services/application-commands/Localizations/Localizations/pl.json deleted file mode 100644 index f8aa1052a..000000000 --- a/Documentation/guides/services/application-commands/Localizations/Localizations/pl.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "commands": { - "animal": { - "name": "zwierzę", - "description": "Wysyła zwierzę, które wybrałeś", - "parameters": { - "animal": { - "name": "zwierzę", - "description": "Zwierzę do wysłania" - } - } - }, - "permissions": { - "name": "uprawnienia", - "description": "Zarządza uprawnieniami", - "subcommands": { - "user": { - "name": "użytkownik", - "description": "Zarządza uprawnienia użytkownika", - "subcommands": { - "show": { - "name": "pokaż", - "description": "Pokazuje uprawnienia użytkownika", - "parameters": { - "user": { - "name": "użytkownik", - "description": "Użytkownik, którego uprawnienia chcesz zobaczyć" - } - } - } - } - }, - "channel": { - "name": "kanał", - "description": "Zarządza uprawnieniami kanału", - "subcommands": { - "show": { - "name": "pokaż", - "description": "Pokazuje uprawnienia kanału", - "parameters": { - "role": { - "name": "kanał", - "description": "Kanał, którego uprawnienia chcesz zobaczyć" - } - } - } - } - } - } - } - }, - "enums": { - "MyBot.Animal": { - "Dog": "Pies", - "Cat": "Kot", - "Fish": "Ryba", - "GuineaPig": "Świnka morska" - } - } -} diff --git a/Documentation/guides/services/application-commands/Localizations/PermissionsModule.cs b/Documentation/guides/services/application-commands/Localizations/PermissionsModule.cs deleted file mode 100644 index 98bd8e73b..000000000 --- a/Documentation/guides/services/application-commands/Localizations/PermissionsModule.cs +++ /dev/null @@ -1,30 +0,0 @@ -using NetCord; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -[SlashCommand("permissions", "Manages permissions")] -public class PermissionsModule : ApplicationCommandModule -{ - [SubSlashCommand("user", "Manages user permissions")] - public class UserPermissionsModule : ApplicationCommandModule - { - [SubSlashCommand("show", "Shows user permissions")] - public static string Show( - [SlashCommandParameter(Description = "The user whose permissions you want to see")] GuildUser user) - { - return ((GuildInteractionUser)user).Permissions.ToString(); - } - } - - [SubSlashCommand("channel", "Manages channel permissions")] - public class ChannelPermissionsModule : ApplicationCommandModule - { - [SubSlashCommand("show", "Shows channel permissions")] - public static string Show( - [SlashCommandParameter(Description = "The channel whose permissions you want to see")] IGuildChannel channel) - { - return ((IInteractionChannel)channel).Permissions.ToString(); - } - } -} diff --git a/Documentation/guides/services/application-commands/Localizations/Program.cs b/Documentation/guides/services/application-commands/Localizations/Program.cs deleted file mode 100644 index 66267a881..000000000 --- a/Documentation/guides/services/application-commands/Localizations/Program.cs +++ /dev/null @@ -1,43 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = default, - Logger = new ConsoleLogger(), -}); - -ApplicationCommandService applicationCommandService = new(ApplicationCommandServiceConfiguration.Default with -{ - LocalizationsProvider = new JsonLocalizationsProvider(), -}); - -applicationCommandService.AddModules(typeof(Program).Assembly); - -client.InteractionCreate += async interaction => -{ - if (interaction is not ApplicationCommandInteraction applicationCommandInteraction) - return; - - var result = await applicationCommandService.ExecuteAsync(new ApplicationCommandContext(applicationCommandInteraction, client)); - - if (result is not IFailResult failResult) - return; - - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -await applicationCommandService.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/services/application-commands/LocalizationsHosting/LocalizationsHosting.csproj b/Documentation/guides/services/application-commands/LocalizationsHosting/LocalizationsHosting.csproj deleted file mode 100644 index 3b76374f3..000000000 --- a/Documentation/guides/services/application-commands/LocalizationsHosting/LocalizationsHosting.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - - - - - - - - - - - - diff --git a/Documentation/guides/services/application-commands/LocalizationsHosting/Program.cs b/Documentation/guides/services/application-commands/LocalizationsHosting/Program.cs deleted file mode 100644 index b6c839389..000000000 --- a/Documentation/guides/services/application-commands/LocalizationsHosting/Program.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.Extensions.Hosting; - -using NetCord.Hosting.Gateway; -using NetCord.Hosting.Services; -using NetCord.Hosting.Services.ApplicationCommands; -using NetCord.Services.ApplicationCommands; - -var builder = Host.CreateApplicationBuilder(args); - -builder.Services - .AddApplicationCommands(options => - { - options.LocalizationsProvider = new JsonLocalizationsProvider(); - }) - .AddDiscordGateway(); - -var host = builder.Build() - .AddModules(typeof(Program).Assembly); - -await host.RunAsync(); diff --git a/Documentation/guides/services/application-commands/MultipleServices/MultipleServices.csproj b/Documentation/guides/services/application-commands/MultipleServices/MultipleServices.csproj deleted file mode 100644 index 696a9094a..000000000 --- a/Documentation/guides/services/application-commands/MultipleServices/MultipleServices.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/services/application-commands/MultipleServices/Program.cs b/Documentation/guides/services/application-commands/MultipleServices/Program.cs deleted file mode 100644 index bfcd95641..000000000 --- a/Documentation/guides/services/application-commands/MultipleServices/Program.cs +++ /dev/null @@ -1,49 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = default, - Logger = new ConsoleLogger(), -}); - -ApplicationCommandService slashCommandService = new(); -ApplicationCommandService messageCommandService = new(); - -ApplicationCommandServiceManager manager = new(); -manager.AddService(slashCommandService); -manager.AddService(messageCommandService); - -var assembly = typeof(Program).Assembly; -slashCommandService.AddModules(assembly); -messageCommandService.AddModules(assembly); - -client.InteractionCreate += async interaction => -{ - var result = await (interaction switch - { - SlashCommandInteraction slashCommandInteraction => slashCommandService.ExecuteAsync(new SlashCommandContext(slashCommandInteraction, client)), - MessageCommandInteraction messageCommandInteraction => messageCommandService.ExecuteAsync(new MessageCommandContext(messageCommandInteraction, client)), - _ => throw new("Invalid interaction."), - }); - - if (result is not IFailResult failResult) - return; - - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -await manager.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/services/application-commands/Parameters/Animal.cs b/Documentation/guides/services/application-commands/Parameters/Animal.cs deleted file mode 100644 index 0076a7765..000000000 --- a/Documentation/guides/services/application-commands/Parameters/Animal.cs +++ /dev/null @@ -1,12 +0,0 @@ -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public enum Animal -{ - Dog, - Cat, - Fish, - [SlashCommandChoice(Name = "Guinea Pig")] - GuineaPig, -} diff --git a/Documentation/guides/services/application-commands/Parameters/ExampleModule.cs b/Documentation/guides/services/application-commands/Parameters/ExampleModule.cs deleted file mode 100644 index 9a00b7fde..000000000 --- a/Documentation/guides/services/application-commands/Parameters/ExampleModule.cs +++ /dev/null @@ -1,25 +0,0 @@ -using NetCord; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class ExampleModule : ApplicationCommandModule -{ - [SlashCommand("username", "Returns user's username")] - public string Username(User? user = null) - { - user ??= Context.User; - return user.Username; - } - - [SlashCommand("power", "Raises a number to a power")] - public static string Power( - [SlashCommandParameter(Name = "base", Description = "The base")] double @base, - [SlashCommandParameter(Description = "The power")] double power = 2) - { - return $"Result: {Math.Pow(@base, power)}"; - } - - [SlashCommand("animal", "Sends animal you selected")] - public static string Animal(Animal animal) => animal.ToString(); -} diff --git a/Documentation/guides/services/application-commands/Parameters/Parameters.csproj b/Documentation/guides/services/application-commands/Parameters/Parameters.csproj deleted file mode 100644 index 696a9094a..000000000 --- a/Documentation/guides/services/application-commands/Parameters/Parameters.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/services/application-commands/Parameters/Program.cs b/Documentation/guides/services/application-commands/Parameters/Program.cs deleted file mode 100644 index c23207606..000000000 --- a/Documentation/guides/services/application-commands/Parameters/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = default, - Logger = new ConsoleLogger(), -}); - -ApplicationCommandService applicationCommandService = new(); -applicationCommandService.AddModules(typeof(Program).Assembly); - -client.InteractionCreate += async interaction => -{ - if (interaction is not ApplicationCommandInteraction applicationCommandInteraction) - return; - - var result = await applicationCommandService.ExecuteAsync(new ApplicationCommandContext(applicationCommandInteraction, client)); - - if (result is not IFailResult failResult) - return; - - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -await applicationCommandService.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/services/application-commands/Permissions/ExampleModule.cs b/Documentation/guides/services/application-commands/Permissions/ExampleModule.cs deleted file mode 100644 index 120150a77..000000000 --- a/Documentation/guides/services/application-commands/Permissions/ExampleModule.cs +++ /dev/null @@ -1,20 +0,0 @@ -using NetCord; -using NetCord.Rest; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -public class ExampleModule : ApplicationCommandModule -{ - [SlashCommand("mention-everyone", "Mentions @everyone", - DefaultGuildPermissions = Permissions.MentionEveryone, - Contexts = [InteractionContextType.Guild])] - public static InteractionMessageProperties MentionEveryone() - { - return new() - { - AllowedMentions = AllowedMentionsProperties.All, - Content = "@everyone", - }; - } -} diff --git a/Documentation/guides/services/application-commands/Permissions/Permissions.csproj b/Documentation/guides/services/application-commands/Permissions/Permissions.csproj deleted file mode 100644 index 696a9094a..000000000 --- a/Documentation/guides/services/application-commands/Permissions/Permissions.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/services/application-commands/Permissions/Program.cs b/Documentation/guides/services/application-commands/Permissions/Program.cs deleted file mode 100644 index c23207606..000000000 --- a/Documentation/guides/services/application-commands/Permissions/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = default, - Logger = new ConsoleLogger(), -}); - -ApplicationCommandService applicationCommandService = new(); -applicationCommandService.AddModules(typeof(Program).Assembly); - -client.InteractionCreate += async interaction => -{ - if (interaction is not ApplicationCommandInteraction applicationCommandInteraction) - return; - - var result = await applicationCommandService.ExecuteAsync(new ApplicationCommandContext(applicationCommandInteraction, client)); - - if (result is not IFailResult failResult) - return; - - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -await applicationCommandService.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/services/application-commands/Subcommands/GuildCommandsModule.cs b/Documentation/guides/services/application-commands/Subcommands/GuildCommandsModule.cs deleted file mode 100644 index 513eb70dd..000000000 --- a/Documentation/guides/services/application-commands/Subcommands/GuildCommandsModule.cs +++ /dev/null @@ -1,29 +0,0 @@ -using NetCord; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -namespace MyBot; - -[SlashCommand("guild", "Guild command")] -public class GuildCommandsModule : ApplicationCommandModule -{ - [SubSlashCommand("channels", "Get guild channel count")] - public string Channels() => $"Channels: {Context.Guild!.Channels.Count}"; - - [SubSlashCommand("name", "Guild name")] - public class GuildNameModule : ApplicationCommandModule - { - [SubSlashCommand("get", "Get guild name")] - public string GetName() => $"Name: {Context.Guild!.Name}"; - - [RequireUserPermissions(Permissions.ManageGuild)] - [RequireBotPermissions(Permissions.ManageGuild)] - [SubSlashCommand("set", "Set guild name")] - public async Task SetNameAsync(string name) - { - var guild = Context.Guild!; - await guild.ModifyAsync(g => g.Name = name); - return $"Name: {guild.Name} -> {name}"; - } - } -} diff --git a/Documentation/guides/services/application-commands/Subcommands/Program.cs b/Documentation/guides/services/application-commands/Subcommands/Program.cs deleted file mode 100644 index 9b7dfcab4..000000000 --- a/Documentation/guides/services/application-commands/Subcommands/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -using NetCord; -using NetCord.Gateway; -using NetCord.Logging; -using NetCord.Rest; -using NetCord.Services; -using NetCord.Services.ApplicationCommands; - -GatewayClient client = new(new BotToken("Token from Discord Developer Portal"), new GatewayClientConfiguration -{ - Intents = GatewayIntents.Guilds, - Logger = new ConsoleLogger(), -}); - -ApplicationCommandService applicationCommandService = new(); -applicationCommandService.AddModules(typeof(Program).Assembly); - -client.InteractionCreate += async interaction => -{ - if (interaction is not ApplicationCommandInteraction applicationCommandInteraction) - return; - - var result = await applicationCommandService.ExecuteAsync(new ApplicationCommandContext(applicationCommandInteraction, client)); - - if (result is not IFailResult failResult) - return; - - try - { - await interaction.SendResponseAsync(InteractionCallback.Message(failResult.Message)); - } - catch - { - } -}; - -await applicationCommandService.RegisterCommandsAsync(client.Rest, client.Id); - -await client.StartAsync(); -await Task.Delay(-1); diff --git a/Documentation/guides/services/application-commands/Subcommands/Subcommands.csproj b/Documentation/guides/services/application-commands/Subcommands/Subcommands.csproj deleted file mode 100644 index 696a9094a..000000000 --- a/Documentation/guides/services/application-commands/Subcommands/Subcommands.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/services/application-commands/introduction.md b/Documentation/guides/services/application-commands/introduction.md deleted file mode 100644 index 831154d6a..000000000 --- a/Documentation/guides/services/application-commands/introduction.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -uid: application-commands ---- - -# Introduction - -## [.NET Generic Host](#tab/generic-host) - -Adding application commands with the .NET Generic Host is very easy. Use @NetCord.Hosting.Services.ApplicationCommands.ApplicationCommandServiceServiceCollectionExtensions.AddApplicationCommands(Microsoft.Extensions.DependencyInjection.IServiceCollection) to add the application command service to your host builder. Then, use @NetCord.Hosting.Services.ApplicationCommands.ApplicationCommandServiceHostExtensions.AddSlashCommand*, @NetCord.Hosting.Services.ApplicationCommands.ApplicationCommandServiceHostExtensions.AddUserCommand* or @NetCord.Hosting.Services.ApplicationCommands.ApplicationCommandServiceHostExtensions.AddMessageCommand* to add an application command using the minimal APIs way and/or use @NetCord.Hosting.Services.ServicesHostExtensions.AddModules(Microsoft.Extensions.Hosting.IHost,System.Reflection.Assembly) to add application command modules from an assembly. -[!code-cs[Program.cs](IntroductionHosting/Program.cs?highlight=13,18-20,23)] - -## [Bare Bones](#tab/bare-bones) - -First, add the following lines to the using section. -[!code-cs[Program.cs](Introduction/Program.cs#L4-L6)] - -Now, it's time to create @NetCord.Services.ApplicationCommands.ApplicationCommandService`1 instance and add application commands to it. You can do it by using @NetCord.Services.ApplicationCommands.ApplicationCommandService`1.AddSlashCommand*, @NetCord.Services.ApplicationCommands.ApplicationCommandService`1.AddUserCommand* or @NetCord.Services.ApplicationCommands.ApplicationCommandService`1.AddMessageCommand* to add an application command using the minimal APIs way and/or by using @NetCord.Services.ApplicationCommands.ApplicationCommandService`1.AddModules(System.Reflection.Assembly) to add application command modules from an assembly. -[!code-cs[Program.cs](Introduction/Program.cs#L14-L23)] - -We can add a command handler now. If you used a context other than @NetCord.Services.ApplicationCommands.ApplicationCommandContext, you may need to change the interaction type of the handler to the appropriate one. -[!code-cs[Program.cs](Introduction/Program.cs#L25-L47)] - -Now, we should send the commands to Discord, to make them usable. Add the following line under the handler: -[!code-cs[Program.cs](Introduction/Program.cs#L49-L50)] - -### The Final Product - -#### Program.cs -[!code-cs[Program.cs](Introduction/Program.cs)] - -*** - -> [!NOTE] -> If you don't see the commands in Discord, try refreshing the Discord client using `Ctrl + R` on PC or `⌘ + R` on Mac. - -> [!IMPORTANT] -> Please note that names of slash commands must be lowercase. - -### Example Module - -Here you can see an example module showing how to use modules with application commands. -[!code-cs[ExampleModule.cs](Introduction/ExampleModule.cs)] diff --git a/Documentation/guides/services/application-commands/localizations.md b/Documentation/guides/services/application-commands/localizations.md deleted file mode 100644 index 7c9725a05..000000000 --- a/Documentation/guides/services/application-commands/localizations.md +++ /dev/null @@ -1,31 +0,0 @@ -# Localizations - -To localize application commands, you need to use @NetCord.Services.ApplicationCommands.ILocalizationsProvider. You specify it in the configuration. - -## Specifying the localizations provider - -The samples below show how to specify the @NetCord.Services.ApplicationCommands.JsonLocalizationsProvider. - -## [.NET Generic Host](#tab/generic-host) -[!code-cs[Program.cs](LocalizationsHosting/Program.cs?highlight=4#L10-L14)] - -## [Bare Bones](#tab/bare-bones) -[!code-cs[Program.cs](Localizations/Program.cs?highlight=3#L14-L17)] - -*** - -## Localizing commands with the @NetCord.Services.ApplicationCommands.JsonLocalizationsProvider - -The @NetCord.Services.ApplicationCommands.JsonLocalizationsProvider employs JSON files to localize commands. By default, these JSON files are expected to reside in the `Localizations` directory, with each file named after its respective locale in the format `{locale}.json`. For instance, a Polish localization file might be named `pl.json`. A list of supported locales can be found [here](https://discord.com/developers/docs/reference#locales). - -### Example - -The file below shows Polish localization of `permissions` and `animal` commands. - -[!code-json[pl.json](Localizations/Localizations/pl.json)] - -Here are the commands. - -[!code-cs[AnimalModule.cs](Localizations/AnimalModule.cs)] - -[!code-cs[PermissionsModule.cs](Localizations/PermissionsModule.cs)] diff --git a/Documentation/guides/services/application-commands/multiple-services.md b/Documentation/guides/services/application-commands/multiple-services.md deleted file mode 100644 index 9b85eae57..000000000 --- a/Documentation/guides/services/application-commands/multiple-services.md +++ /dev/null @@ -1,8 +0,0 @@ -# Multiple Services - -> [!NOTE] -> When using hosting, multiple instances of @NetCord.Services.ApplicationCommands.ApplicationCommandService`1 are handled automatically, so no additional configuration is needed. - -In some scenarios, you might want to use multiple instances of @NetCord.Services.ApplicationCommands.ApplicationCommandService`1. For instance, you may want to use different contexts for different application commands. In such cases, you can utilize the @NetCord.Services.ApplicationCommands.ApplicationCommandServiceManager, which allows you to register commands to Discord from different instances of @NetCord.Services.ApplicationCommands.ApplicationCommandService`1 simultaneously. - -[!code-cs[Program.cs](MultipleServices/Program.cs)] diff --git a/Documentation/guides/services/application-commands/parameters.md b/Documentation/guides/services/application-commands/parameters.md deleted file mode 100644 index 83e7effb9..000000000 --- a/Documentation/guides/services/application-commands/parameters.md +++ /dev/null @@ -1,47 +0,0 @@ -# Parameters - -## Slash Commands - -Slash commands support up to 25 parameters. - -### Optional parameters - -To mark parameters as optional, give them a default value, example: -[!code-cs[ExampleModule.cs](Parameters/ExampleModule.cs#L8-L13)] - -### Parameter name and description - -You can change parameter name and parameter description using @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute, example: -[!code-cs[ExampleModule.cs](Parameters/ExampleModule.cs#L15-L21)] - -### Min and Max Values - -You can specify min and max parameter values by setting @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute.MinValue and @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute.MaxValue properties in @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute. It's only possible for numeric types. - -### Min and Max Length - -You can specify min and max parameter length by setting @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute.MinLength and @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute.MaxLength properties in @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute. It's only possible for text types. - -### Choices and Autocomplete - -Choices are constants for a given parameter, autocomplete may depend on a text entered by a user. - -#### Choices - -Choices are automatically generated when you set `enum` as a parameter type, you can override choices' names using @NetCord.Services.ApplicationCommands.SlashCommandChoiceAttribute on enum fields, example: -[!code-cs[ExampleModule.cs](Parameters/ExampleModule.cs#L23-L24)] -[!code-cs[Animal.cs](Parameters/Animal.cs#l5-L12)] - -You can also define own choices in the Type Reader by overriding @NetCord.Services.ApplicationCommands.SlashCommandTypeReader`1.ChoicesProvider property or in @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute by setting @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute.ChoicesProviderType property. - -#### Autocomplete - -You can turn on autocomplete in Type Reader by overriding @NetCord.Services.ApplicationCommands.SlashCommandTypeReader`1.AutocompleteProviderType property or in @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute by setting @NetCord.Services.ApplicationCommands.SlashCommandParameterAttribute.AutocompleteProviderType property. You run it using @NetCord.Services.ApplicationCommands.ApplicationCommandService`2.ExecuteAutocompleteAsync(`1,System.IServiceProvider). - -## User Commands - -User commands only support a single parameter of type @NetCord.User. It's is not required, but allows you to access the target user of the user command easily. - -## Message Commands - -Message commands only support a single parameter of type @NetCord.Rest.RestMessage. It's is not required, but allows you to access the target message of the message command easily. diff --git a/Documentation/guides/services/application-commands/permissions.md b/Documentation/guides/services/application-commands/permissions.md deleted file mode 100644 index bcd16420c..000000000 --- a/Documentation/guides/services/application-commands/permissions.md +++ /dev/null @@ -1,4 +0,0 @@ -# Permissions - -Instead of using Precondition Attributes, you can specify command required permissions to Discord. The commands will not show up to users without the permissions then. You can also specify if commands can be used in DM. Example: -[!code-cs[ExampleModule.cs](Permissions/ExampleModule.cs#L9-L19)] diff --git a/Documentation/guides/services/application-commands/subcommands.md b/Documentation/guides/services/application-commands/subcommands.md deleted file mode 100644 index f7886cbfe..000000000 --- a/Documentation/guides/services/application-commands/subcommands.md +++ /dev/null @@ -1,7 +0,0 @@ -# Subcommands - -> [!NOTE] -> Subcommands are only supported by slash commands. - -## Example -[!code-cs[GuildCommandsModule.cs](Subcommands/GuildCommandsModule.cs)] diff --git a/Documentation/guides/services/component-interactions/Introduction/ButtonModule.cs b/Documentation/guides/services/component-interactions/Introduction/ButtonModule.cs deleted file mode 100644 index e5df821af..000000000 --- a/Documentation/guides/services/component-interactions/Introduction/ButtonModule.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NetCord.Services.ComponentInteractions; - -namespace MyBot; - -public class ButtonModule : ComponentInteractionModule -{ - [ComponentInteraction("button")] - public static string Button() => "You clicked a button!"; -} diff --git a/Documentation/guides/services/component-interactions/Introduction/ChannelMenuModule.cs b/Documentation/guides/services/component-interactions/Introduction/ChannelMenuModule.cs deleted file mode 100644 index cd4f62b76..000000000 --- a/Documentation/guides/services/component-interactions/Introduction/ChannelMenuModule.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NetCord.Services.ComponentInteractions; - -namespace MyBot; - -public class ChannelMenuModule : ComponentInteractionModule -{ - [ComponentInteraction("menu")] - public string Menu() => $"You selected: {string.Join(", ", Context.SelectedValues)}"; -} diff --git a/Documentation/guides/services/component-interactions/Introduction/Introduction.csproj b/Documentation/guides/services/component-interactions/Introduction/Introduction.csproj deleted file mode 100644 index 59b282e2d..000000000 --- a/Documentation/guides/services/component-interactions/Introduction/Introduction.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - - - - - - - - diff --git a/Documentation/guides/services/component-interactions/Introduction/MentionableMenuModule.cs b/Documentation/guides/services/component-interactions/Introduction/MentionableMenuModule.cs deleted file mode 100644 index 1bd486daf..000000000 --- a/Documentation/guides/services/component-interactions/Introduction/MentionableMenuModule.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NetCord.Services.ComponentInteractions; - -namespace MyBot; - -public class MentionableMenuModule : ComponentInteractionModule -{ - [ComponentInteraction("menu")] - public string Menu() => $"You selected: {string.Join(", ", Context.SelectedValues)}"; -} diff --git a/Documentation/guides/services/component-interactions/Introduction/ModalModule.cs b/Documentation/guides/services/component-interactions/Introduction/ModalModule.cs deleted file mode 100644 index 71800bd90..000000000 --- a/Documentation/guides/services/component-interactions/Introduction/ModalModule.cs +++ /dev/null @@ -1,13 +0,0 @@ -using NetCord; -using NetCord.Services.ComponentInteractions; - -namespace MyBot; - -public class ModalModule : ComponentInteractionModule -{ - [ComponentInteraction("modal")] - public string Modal() => string.Join('\n', Context.Components.OfType