Update sample projects & samples in docs (#2823)
* update them all * more docs * moar docs
This commit is contained in:
@@ -1,18 +1,16 @@
|
||||
using Discord.Interactions;
|
||||
using Discord.WebSocket;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ShardedClient.Modules
|
||||
namespace ShardedClient.Modules;
|
||||
|
||||
// A display of portability, which shows how minimal the difference between the 2 frameworks is.
|
||||
public class InteractionModule : InteractionModuleBase<ShardedInteractionContext>
|
||||
{
|
||||
// A display of portability, which shows how minimal the difference between the 2 frameworks is.
|
||||
public class InteractionModule : InteractionModuleBase<ShardedInteractionContext>
|
||||
[SlashCommand("info", "Information about this shard.")]
|
||||
public async Task InfoAsync()
|
||||
{
|
||||
[SlashCommand("info", "Information about this shard.")]
|
||||
public async Task InfoAsync()
|
||||
{
|
||||
var msg = $@"Hi {Context.User}! There are currently {Context.Client.Shards.Count} shards!
|
||||
var msg = $@"Hi {Context.User}! There are currently {Context.Client.Shards.Count} shards!
|
||||
This guild is being served by shard number {Context.Client.GetShardFor(Context.Guild).ShardId}";
|
||||
await RespondAsync(msg);
|
||||
}
|
||||
await RespondAsync(msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
using Discord.Commands;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ShardedClient.Modules
|
||||
namespace ShardedClient.Modules;
|
||||
|
||||
// Remember to make your module reference the ShardedCommandContext
|
||||
public class PublicModule : ModuleBase<ShardedCommandContext>
|
||||
{
|
||||
// Remember to make your module reference the ShardedCommandContext
|
||||
public class PublicModule : ModuleBase<ShardedCommandContext>
|
||||
[Command("info")]
|
||||
public async Task InfoAsync()
|
||||
{
|
||||
[Command("info")]
|
||||
public async Task InfoAsync()
|
||||
{
|
||||
var msg = $@"Hi {Context.User}! There are currently {Context.Client.Shards.Count} shards!
|
||||
var msg = $@"Hi {Context.User}! There are currently {Context.Client.Shards.Count} shards!
|
||||
This guild is being served by shard number {Context.Client.GetShardFor(Context.Guild).ShardId}";
|
||||
await ReplyAsync(msg);
|
||||
}
|
||||
await ReplyAsync(msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,78 +8,70 @@ using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ShardedClient
|
||||
namespace ShardedClient;
|
||||
|
||||
// This is a minimal example of using Discord.Net's Sharded Client
|
||||
// The provided DiscordShardedClient class simplifies having multiple
|
||||
// DiscordSocketClient instances (or shards) to serve a large number of guilds.
|
||||
class Program
|
||||
{
|
||||
// This is a minimal example of using Discord.Net's Sharded Client
|
||||
// The provided DiscordShardedClient class simplifies having multiple
|
||||
// DiscordSocketClient instances (or shards) to serve a large number of guilds.
|
||||
class Program
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
static void Main(string[] args)
|
||||
=> new Program()
|
||||
.MainAsync()
|
||||
.GetAwaiter()
|
||||
.GetResult();
|
||||
|
||||
public async Task MainAsync()
|
||||
// You specify the amount of shards you'd like to have with the
|
||||
// DiscordSocketConfig. Generally, it's recommended to
|
||||
// have 1 shard per 1500-2000 guilds your bot is in.
|
||||
var config = new DiscordSocketConfig
|
||||
{
|
||||
// You specify the amount of shards you'd like to have with the
|
||||
// DiscordSocketConfig. Generally, it's recommended to
|
||||
// have 1 shard per 1500-2000 guilds your bot is in.
|
||||
var config = new DiscordSocketConfig
|
||||
{
|
||||
TotalShards = 2,
|
||||
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
|
||||
};
|
||||
TotalShards = 2,
|
||||
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
|
||||
};
|
||||
|
||||
// You should dispose a service provider created using ASP.NET
|
||||
// when you are finished using it, at the end of your app's lifetime.
|
||||
// If you use another dependency injection framework, you should inspect
|
||||
// its documentation for the best way to do this.
|
||||
using (var services = ConfigureServices(config))
|
||||
{
|
||||
var client = services.GetRequiredService<DiscordShardedClient>();
|
||||
// You should dispose a service provider created using ASP.NET
|
||||
// when you are finished using it, at the end of your app's lifetime.
|
||||
// If you use another dependency injection framework, you should inspect
|
||||
// its documentation for the best way to do this.
|
||||
await using var services = ConfigureServices(config);
|
||||
|
||||
// The Sharded Client does not have a Ready event.
|
||||
// The ShardReady event is used instead, allowing for individual
|
||||
// control per shard.
|
||||
client.ShardReady += ReadyAsync;
|
||||
client.Log += LogAsync;
|
||||
var client = services.GetRequiredService<DiscordShardedClient>();
|
||||
|
||||
await services.GetRequiredService<InteractionHandlingService>()
|
||||
.InitializeAsync();
|
||||
// The Sharded Client does not have a Ready event.
|
||||
// The ShardReady event is used instead, allowing for individual
|
||||
// control per shard.
|
||||
client.ShardReady += ReadyAsync;
|
||||
client.Log += LogAsync;
|
||||
|
||||
await services.GetRequiredService<CommandHandlingService>()
|
||||
.InitializeAsync();
|
||||
await services.GetRequiredService<InteractionHandlingService>()
|
||||
.InitializeAsync();
|
||||
|
||||
// Tokens should be considered secret data, and never hard-coded.
|
||||
await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token"));
|
||||
await client.StartAsync();
|
||||
await services.GetRequiredService<CommandHandlingService>()
|
||||
.InitializeAsync();
|
||||
|
||||
await Task.Delay(Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
// Tokens should be considered secret data, and never hard-coded.
|
||||
await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token"));
|
||||
await client.StartAsync();
|
||||
|
||||
private ServiceProvider ConfigureServices(DiscordSocketConfig config)
|
||||
=> new ServiceCollection()
|
||||
.AddSingleton(new DiscordShardedClient(config))
|
||||
.AddSingleton<CommandService>()
|
||||
.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordShardedClient>()))
|
||||
.AddSingleton<CommandHandlingService>()
|
||||
.AddSingleton<InteractionHandlingService>()
|
||||
.BuildServiceProvider();
|
||||
await Task.Delay(Timeout.Infinite);
|
||||
}
|
||||
|
||||
private static ServiceProvider ConfigureServices(DiscordSocketConfig config)
|
||||
=> new ServiceCollection()
|
||||
.AddSingleton(new DiscordShardedClient(config))
|
||||
.AddSingleton<CommandService>()
|
||||
.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordShardedClient>()))
|
||||
.AddSingleton<CommandHandlingService>()
|
||||
.AddSingleton<InteractionHandlingService>()
|
||||
.BuildServiceProvider();
|
||||
|
||||
|
||||
private Task ReadyAsync(DiscordSocketClient shard)
|
||||
{
|
||||
Console.WriteLine($"Shard Number {shard.ShardId} is connected and ready!");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
private static Task ReadyAsync(DiscordSocketClient shard)
|
||||
{
|
||||
Console.WriteLine($"Shard Number {shard.ShardId} is connected and ready!");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task LogAsync(LogMessage log)
|
||||
{
|
||||
Console.WriteLine(log.ToString());
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
private static Task LogAsync(LogMessage log)
|
||||
{
|
||||
Console.WriteLine(log.ToString());
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,67 +6,66 @@ using System;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ShardedClient.Services
|
||||
namespace ShardedClient.Services;
|
||||
|
||||
public class CommandHandlingService
|
||||
{
|
||||
public class CommandHandlingService
|
||||
private readonly CommandService _commands;
|
||||
private readonly DiscordShardedClient _discord;
|
||||
private readonly IServiceProvider _services;
|
||||
|
||||
public CommandHandlingService(IServiceProvider services)
|
||||
{
|
||||
private readonly CommandService _commands;
|
||||
private readonly DiscordShardedClient _discord;
|
||||
private readonly IServiceProvider _services;
|
||||
_commands = services.GetRequiredService<CommandService>();
|
||||
_discord = services.GetRequiredService<DiscordShardedClient>();
|
||||
_services = services;
|
||||
|
||||
public CommandHandlingService(IServiceProvider services)
|
||||
{
|
||||
_commands = services.GetRequiredService<CommandService>();
|
||||
_discord = services.GetRequiredService<DiscordShardedClient>();
|
||||
_services = services;
|
||||
_commands.CommandExecuted += CommandExecutedAsync;
|
||||
_commands.Log += LogAsync;
|
||||
_discord.MessageReceived += MessageReceivedAsync;
|
||||
}
|
||||
|
||||
_commands.CommandExecuted += CommandExecutedAsync;
|
||||
_commands.Log += LogAsync;
|
||||
_discord.MessageReceived += MessageReceivedAsync;
|
||||
}
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
|
||||
}
|
||||
public async Task MessageReceivedAsync(SocketMessage rawMessage)
|
||||
{
|
||||
// Ignore system messages, or messages from other bots
|
||||
if (rawMessage is not SocketUserMessage message)
|
||||
return;
|
||||
if (message.Source != MessageSource.User)
|
||||
return;
|
||||
|
||||
public async Task MessageReceivedAsync(SocketMessage rawMessage)
|
||||
{
|
||||
// Ignore system messages, or messages from other bots
|
||||
if (rawMessage is not SocketUserMessage message)
|
||||
return;
|
||||
if (message.Source != MessageSource.User)
|
||||
return;
|
||||
// This value holds the offset where the prefix ends
|
||||
var argPos = 0;
|
||||
if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos))
|
||||
return;
|
||||
|
||||
// This value holds the offset where the prefix ends
|
||||
var argPos = 0;
|
||||
if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos))
|
||||
return;
|
||||
// A new kind of command context, ShardedCommandContext can be utilized with the commands framework
|
||||
var context = new ShardedCommandContext(_discord, message);
|
||||
await _commands.ExecuteAsync(context, argPos, _services);
|
||||
}
|
||||
|
||||
// A new kind of command context, ShardedCommandContext can be utilized with the commands framework
|
||||
var context = new ShardedCommandContext(_discord, message);
|
||||
await _commands.ExecuteAsync(context, argPos, _services);
|
||||
}
|
||||
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
|
||||
{
|
||||
// command is unspecified when there was a search failure (command not found); we don't care about these errors
|
||||
if (!command.IsSpecified)
|
||||
return;
|
||||
|
||||
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
|
||||
{
|
||||
// command is unspecified when there was a search failure (command not found); we don't care about these errors
|
||||
if (!command.IsSpecified)
|
||||
return;
|
||||
// the command was successful, we don't care about this result, unless we want to log that a command succeeded.
|
||||
if (result.IsSuccess)
|
||||
return;
|
||||
|
||||
// the command was successful, we don't care about this result, unless we want to log that a command succeeded.
|
||||
if (result.IsSuccess)
|
||||
return;
|
||||
// the command failed, let's notify the user that something happened.
|
||||
await context.Channel.SendMessageAsync($"error: {result}");
|
||||
}
|
||||
|
||||
// the command failed, let's notify the user that something happened.
|
||||
await context.Channel.SendMessageAsync($"error: {result}");
|
||||
}
|
||||
private Task LogAsync(LogMessage log)
|
||||
{
|
||||
Console.WriteLine(log.ToString());
|
||||
|
||||
private Task LogAsync(LogMessage log)
|
||||
{
|
||||
Console.WriteLine(log.ToString());
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +1,65 @@
|
||||
using Discord;
|
||||
using Discord.Interactions;
|
||||
using Discord.WebSocket;
|
||||
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ShardedClient.Services
|
||||
namespace ShardedClient.Services;
|
||||
|
||||
public class InteractionHandlingService
|
||||
{
|
||||
public class InteractionHandlingService
|
||||
private readonly InteractionService _service;
|
||||
private readonly DiscordShardedClient _client;
|
||||
private readonly IServiceProvider _provider;
|
||||
|
||||
public InteractionHandlingService(IServiceProvider services)
|
||||
{
|
||||
private readonly InteractionService _service;
|
||||
private readonly DiscordShardedClient _client;
|
||||
private readonly IServiceProvider _provider;
|
||||
_service = services.GetRequiredService<InteractionService>();
|
||||
_client = services.GetRequiredService<DiscordShardedClient>();
|
||||
_provider = services;
|
||||
|
||||
public InteractionHandlingService(IServiceProvider services)
|
||||
_service.Log += LogAsync;
|
||||
_client.InteractionCreated += OnInteractionAsync;
|
||||
_client.ShardReady += ReadyAsync;
|
||||
// For examples on how to handle post execution,
|
||||
// see the InteractionFramework samples.
|
||||
}
|
||||
|
||||
// Register all modules, and add the commands from these modules to either guild or globally depending on the build state.
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await _service.AddModulesAsync(typeof(InteractionHandlingService).Assembly, _provider);
|
||||
}
|
||||
|
||||
private async Task OnInteractionAsync(SocketInteraction interaction)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
_service = services.GetRequiredService<InteractionService>();
|
||||
_client = services.GetRequiredService<DiscordShardedClient>();
|
||||
_provider = services;
|
||||
var context = new ShardedInteractionContext(_client, interaction);
|
||||
await _service.ExecuteCommandAsync(context, _provider);
|
||||
});
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
_service.Log += LogAsync;
|
||||
_client.InteractionCreated += OnInteractionAsync;
|
||||
_client.ShardReady += ReadyAsync;
|
||||
// For examples on how to handle post execution,
|
||||
// see the InteractionFramework samples.
|
||||
}
|
||||
private Task LogAsync(LogMessage log)
|
||||
{
|
||||
Console.WriteLine(log.ToString());
|
||||
|
||||
// Register all modules, and add the commands from these modules to either guild or globally depending on the build state.
|
||||
public async Task InitializeAsync()
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private bool _hasRegistered = false;
|
||||
|
||||
private async Task ReadyAsync(DiscordSocketClient _)
|
||||
{
|
||||
// ShardReady is called for each shard; to avoid getting ratelimited we only want to register commands once.
|
||||
if (!_hasRegistered)
|
||||
{
|
||||
await _service.AddModulesAsync(typeof(InteractionHandlingService).Assembly, _provider);
|
||||
}
|
||||
|
||||
private async Task OnInteractionAsync(SocketInteraction interaction)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
var context = new ShardedInteractionContext(_client, interaction);
|
||||
await _service.ExecuteCommandAsync(context, _provider);
|
||||
});
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task LogAsync(LogMessage log)
|
||||
{
|
||||
Console.WriteLine(log.ToString());
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task ReadyAsync(DiscordSocketClient _)
|
||||
{
|
||||
#if DEBUG
|
||||
await _service.RegisterCommandsToGuildAsync(1 /* implement */);
|
||||
#else
|
||||
await _service.RegisterCommandsGloballyAsync();
|
||||
#endif
|
||||
_hasRegistered = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.2" />
|
||||
<PackageReference Include="Discord.Net" Version="3.10.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
|
||||
<PackageReference Include="Discord.Net" Version="3.13.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user