From a3ce80c1dcaecc255d1650b9e227d2f30e440d0c Mon Sep 17 00:00:00 2001 From: Still Hsu <341464@gmail.com> Date: Sun, 29 Apr 2018 23:08:43 +0800 Subject: [PATCH 1/9] Fix Embed.Length behavior (#1012) - This commit splits up the get statement lines for better analysis. --- src/Discord.Net.Core/Entities/Messages/Embed.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Discord.Net.Core/Entities/Messages/Embed.cs b/src/Discord.Net.Core/Entities/Messages/Embed.cs index 5fae7acde..dc62066eb 100644 --- a/src/Discord.Net.Core/Entities/Messages/Embed.cs +++ b/src/Discord.Net.Core/Entities/Messages/Embed.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; @@ -57,7 +57,18 @@ namespace Discord Fields = fields; } - public int Length => Title?.Length + Author?.Name?.Length + Description?.Length + Footer?.Text?.Length + Fields.Sum(f => f.Name.Length + f.Value.ToString().Length) ?? 0; + public int Length + { + get + { + int titleLength = Title?.Length ?? 0; + int authorLength = Author?.Name?.Length ?? 0; + int descriptionLength = Description?.Length ?? 0; + int footerLength = Footer?.Text?.Length ?? 0; + int fieldSum = Fields.Sum(f => f.Name?.Length + f.Value?.ToString().Length) ?? 0; + return titleLength + authorLength + descriptionLength + footerLength + fieldSum; + } + } public override string ToString() => Title; private string DebuggerDisplay => $"{Title} ({Type})"; From 6d3010065fdeddaf58701c6a59d0eb0d0749a7fd Mon Sep 17 00:00:00 2001 From: Joe4evr Date: Sun, 29 Apr 2018 17:10:00 +0200 Subject: [PATCH 2/9] Allow setting IgnoreExtraArgs on an individual basis (#998) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Allow setting IgnoreExtraArgs on an individual basis * Remove passing in the flag as a separate parameter * VS plz * Push the RunMode setting out to its own attribute, because fox wants consistency. Bonus: Removes the need for that godawful 'RunMode.Default'. * Revert previous commit * Fox doesn't like module-wide switches 😒 --- src/Discord.Net.Commands/Attributes/CommandAttribute.cs | 1 + src/Discord.Net.Commands/Builders/CommandBuilder.cs | 6 +++--- src/Discord.Net.Commands/Builders/ModuleBuilder.cs | 1 - src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs | 1 + src/Discord.Net.Commands/CommandParser.cs | 6 +++--- src/Discord.Net.Commands/CommandService.cs | 1 - src/Discord.Net.Commands/CommandServiceConfig.cs | 6 ------ src/Discord.Net.Commands/Info/CommandInfo.cs | 4 +++- src/Discord.Net.Commands/Info/ModuleInfo.cs | 5 ----- 9 files changed, 11 insertions(+), 20 deletions(-) diff --git a/src/Discord.Net.Commands/Attributes/CommandAttribute.cs b/src/Discord.Net.Commands/Attributes/CommandAttribute.cs index 5f8e9ceaf..a0fcf3e4a 100644 --- a/src/Discord.Net.Commands/Attributes/CommandAttribute.cs +++ b/src/Discord.Net.Commands/Attributes/CommandAttribute.cs @@ -7,6 +7,7 @@ namespace Discord.Commands { public string Text { get; } public RunMode RunMode { get; set; } = RunMode.Default; + public bool? IgnoreExtraArgs { get; set; } public CommandAttribute() { diff --git a/src/Discord.Net.Commands/Builders/CommandBuilder.cs b/src/Discord.Net.Commands/Builders/CommandBuilder.cs index b6d002c70..17a170775 100644 --- a/src/Discord.Net.Commands/Builders/CommandBuilder.cs +++ b/src/Discord.Net.Commands/Builders/CommandBuilder.cs @@ -1,8 +1,7 @@ -using System; +using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; -using Microsoft.Extensions.DependencyInjection; namespace Discord.Commands.Builders { @@ -22,6 +21,7 @@ namespace Discord.Commands.Builders public string PrimaryAlias { get; set; } public RunMode RunMode { get; set; } public int Priority { get; set; } + public bool IgnoreExtraArgs { get; set; } public IReadOnlyList Preconditions => _preconditions; public IReadOnlyList Parameters => _parameters; @@ -140,4 +140,4 @@ namespace Discord.Commands.Builders return new CommandInfo(this, info, service); } } -} \ No newline at end of file +} diff --git a/src/Discord.Net.Commands/Builders/ModuleBuilder.cs b/src/Discord.Net.Commands/Builders/ModuleBuilder.cs index 1809c2c63..0ada5a9c2 100644 --- a/src/Discord.Net.Commands/Builders/ModuleBuilder.cs +++ b/src/Discord.Net.Commands/Builders/ModuleBuilder.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; namespace Discord.Commands.Builders { diff --git a/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs b/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs index 1dd66cc77..cbe02aafb 100644 --- a/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs +++ b/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs @@ -158,6 +158,7 @@ namespace Discord.Commands builder.AddAliases(command.Text); builder.RunMode = command.RunMode; builder.Name = builder.Name ?? command.Text; + builder.IgnoreExtraArgs = command.IgnoreExtraArgs ?? service._ignoreExtraArgs; break; case NameAttribute name: builder.Name = name.Text; diff --git a/src/Discord.Net.Commands/CommandParser.cs b/src/Discord.Net.Commands/CommandParser.cs index d65d99349..64daf841e 100644 --- a/src/Discord.Net.Commands/CommandParser.cs +++ b/src/Discord.Net.Commands/CommandParser.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Immutable; using System.Text; using System.Threading.Tasks; @@ -14,7 +14,7 @@ namespace Discord.Commands QuotedParameter } - public static async Task ParseArgsAsync(CommandInfo command, ICommandContext context, bool ignoreExtraArgs, IServiceProvider services, string input, int startPos) + public static async Task ParseArgsAsync(CommandInfo command, ICommandContext context, IServiceProvider services, string input, int startPos) { ParameterInfo curParam = null; StringBuilder argBuilder = new StringBuilder(input.Length); @@ -110,7 +110,7 @@ namespace Discord.Commands { if (curParam == null) { - if (ignoreExtraArgs) + if (command.IgnoreExtraArgs) break; else return ParseResult.FromError(CommandError.BadArgCount, "The input text has too many parameters."); diff --git a/src/Discord.Net.Commands/CommandService.cs b/src/Discord.Net.Commands/CommandService.cs index c880dd454..c996f7334 100644 --- a/src/Discord.Net.Commands/CommandService.cs +++ b/src/Discord.Net.Commands/CommandService.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Discord.Commands.Builders; using Discord.Logging; diff --git a/src/Discord.Net.Commands/CommandServiceConfig.cs b/src/Discord.Net.Commands/CommandServiceConfig.cs index 77c5b2262..f5cd14fef 100644 --- a/src/Discord.Net.Commands/CommandServiceConfig.cs +++ b/src/Discord.Net.Commands/CommandServiceConfig.cs @@ -20,11 +20,5 @@ namespace Discord.Commands /// Determines whether extra parameters should be ignored. public bool IgnoreExtraArgs { get; set; } = false; - - ///// Gets or sets the to use. - //public IServiceProvider ServiceProvider { get; set; } = null; - - ///// Gets or sets a factory function for the to use. - //public Func ServiceProviderFactory { get; set; } = null; } } diff --git a/src/Discord.Net.Commands/Info/CommandInfo.cs b/src/Discord.Net.Commands/Info/CommandInfo.cs index 6e74c8abc..1a9cf69c5 100644 --- a/src/Discord.Net.Commands/Info/CommandInfo.cs +++ b/src/Discord.Net.Commands/Info/CommandInfo.cs @@ -27,6 +27,7 @@ namespace Discord.Commands public string Remarks { get; } public int Priority { get; } public bool HasVarArgs { get; } + public bool IgnoreExtraArgs { get; } public RunMode RunMode { get; } public IReadOnlyList Aliases { get; } @@ -63,6 +64,7 @@ namespace Discord.Commands Parameters = builder.Parameters.Select(x => x.Build(this)).ToImmutableArray(); HasVarArgs = builder.Parameters.Count > 0 ? builder.Parameters[builder.Parameters.Count - 1].IsMultiple : false; + IgnoreExtraArgs = builder.IgnoreExtraArgs; _action = builder.Callback; _commandService = service; @@ -119,7 +121,7 @@ namespace Discord.Commands return ParseResult.FromError(preconditionResult); string input = searchResult.Text.Substring(startIndex); - return await CommandParser.ParseArgsAsync(this, context, _commandService._ignoreExtraArgs, services, input, 0).ConfigureAwait(false); + return await CommandParser.ParseArgsAsync(this, context, services, input, 0).ConfigureAwait(false); } public Task ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) diff --git a/src/Discord.Net.Commands/Info/ModuleInfo.cs b/src/Discord.Net.Commands/Info/ModuleInfo.cs index 5a7f9208e..7c144599b 100644 --- a/src/Discord.Net.Commands/Info/ModuleInfo.cs +++ b/src/Discord.Net.Commands/Info/ModuleInfo.cs @@ -2,7 +2,6 @@ using System; using System.Linq; using System.Collections.Generic; using System.Collections.Immutable; -using System.Reflection; using Discord.Commands.Builders; namespace Discord.Commands @@ -23,8 +22,6 @@ namespace Discord.Commands public ModuleInfo Parent { get; } public bool IsSubmodule => Parent != null; - //public TypeInfo TypeInfo { get; } - internal ModuleInfo(ModuleBuilder builder, CommandService service, IServiceProvider services, ModuleInfo parent = null) { Service = service; @@ -35,8 +32,6 @@ namespace Discord.Commands Group = builder.Group; Parent = parent; - //TypeInfo = builder.TypeInfo; - Aliases = BuildAliases(builder, service).ToImmutableArray(); Commands = builder.Commands.Select(x => x.Build(this, service)).ToImmutableArray(); Preconditions = BuildPreconditions(builder).ToImmutableArray(); From 7022149536ea1c9a92d6dce846cdf7d1df76772e Mon Sep 17 00:00:00 2001 From: Still Hsu <341464@gmail.com> Date: Sun, 29 Apr 2018 23:11:06 +0800 Subject: [PATCH 3/9] Fix/Implement various invite-related behaviors (#1023) * Initial support for invite member count arg * Fix IDiscordClient#GetInviteAsync behavior - Previously, the GetInviteAsync method would return null since it couldn't be parsed as a simple RestInvite object. The object should be a RestInviteMetadata instead. * Fix methods that didn't comply with the interface * Change with_counts REST behaviour * Remove unnecessary JSON prop * Remove AcceptAsync --- src/Discord.Net.Core/Entities/Invites/IInvite.cs | 9 +++++---- src/Discord.Net.Core/IDiscordClient.cs | 2 +- src/Discord.Net.Rest/API/Common/Invite.cs | 6 +++++- src/Discord.Net.Rest/API/Rest/GetInviteParams.cs | 7 +++++++ src/Discord.Net.Rest/BaseDiscordClient.cs | 2 +- src/Discord.Net.Rest/ClientHelper.cs | 12 ++++++++---- src/Discord.Net.Rest/DiscordRestApiClient.cs | 13 ++++--------- src/Discord.Net.Rest/DiscordRestClient.cs | 8 ++++---- .../Entities/Invites/InviteHelper.cs | 7 +------ .../Entities/Invites/RestInvite.cs | 15 ++++++++++----- src/Discord.Net.WebSocket/BaseSocketClient.cs | 8 ++++---- src/Discord.Net.WebSocket/DiscordShardedClient.cs | 4 ++-- src/Discord.Net.WebSocket/DiscordSocketClient.cs | 4 ++-- 13 files changed, 54 insertions(+), 43 deletions(-) create mode 100644 src/Discord.Net.Rest/API/Rest/GetInviteParams.cs diff --git a/src/Discord.Net.Core/Entities/Invites/IInvite.cs b/src/Discord.Net.Core/Entities/Invites/IInvite.cs index 73555e453..0ebb65679 100644 --- a/src/Discord.Net.Core/Entities/Invites/IInvite.cs +++ b/src/Discord.Net.Core/Entities/Invites/IInvite.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; namespace Discord { @@ -22,8 +22,9 @@ namespace Discord ulong GuildId { get; } /// Gets the name of the guild this invite is linked to. string GuildName { get; } - - /// Accepts this invite and joins the target guild. This will fail on bot accounts. - Task AcceptAsync(RequestOptions options = null); + /// Gets the approximated count of online members in the guild. + int? PresenceCount { get; } + /// Gets the approximated count of total members in the guild. + int? MemberCount { get; } } } diff --git a/src/Discord.Net.Core/IDiscordClient.cs b/src/Discord.Net.Core/IDiscordClient.cs index a383c37da..083c0b512 100644 --- a/src/Discord.Net.Core/IDiscordClient.cs +++ b/src/Discord.Net.Core/IDiscordClient.cs @@ -27,7 +27,7 @@ namespace Discord Task> GetGuildsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); Task CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null); - Task GetInviteAsync(string inviteId, RequestOptions options = null); + Task GetInviteAsync(string inviteId, bool withCount = false, RequestOptions options = null); Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); Task GetUserAsync(string username, string discriminator, RequestOptions options = null); diff --git a/src/Discord.Net.Rest/API/Common/Invite.cs b/src/Discord.Net.Rest/API/Common/Invite.cs index 67a318c5a..1b35da870 100644 --- a/src/Discord.Net.Rest/API/Common/Invite.cs +++ b/src/Discord.Net.Rest/API/Common/Invite.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API @@ -11,5 +11,9 @@ namespace Discord.API public InviteGuild Guild { get; set; } [JsonProperty("channel")] public InviteChannel Channel { get; set; } + [JsonProperty("approximate_presence_count")] + public Optional PresenceCount { get; set; } + [JsonProperty("approximate_member_count")] + public Optional MemberCount { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Rest/GetInviteParams.cs b/src/Discord.Net.Rest/API/Rest/GetInviteParams.cs new file mode 100644 index 000000000..cb8d8f7fe --- /dev/null +++ b/src/Discord.Net.Rest/API/Rest/GetInviteParams.cs @@ -0,0 +1,7 @@ +namespace Discord.API.Rest +{ + internal class GetInviteParams + { + public Optional WithCounts { get; set; } + } +} diff --git a/src/Discord.Net.Rest/BaseDiscordClient.cs b/src/Discord.Net.Rest/BaseDiscordClient.cs index f8642b96c..db8e2e691 100644 --- a/src/Discord.Net.Rest/BaseDiscordClient.cs +++ b/src/Discord.Net.Rest/BaseDiscordClient.cs @@ -148,7 +148,7 @@ namespace Discord.Rest Task> IDiscordClient.GetConnectionsAsync(RequestOptions options) => Task.FromResult>(ImmutableArray.Create()); - Task IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options) + Task IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options) => Task.FromResult(null); Task IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) diff --git a/src/Discord.Net.Rest/ClientHelper.cs b/src/Discord.Net.Rest/ClientHelper.cs index 08305f857..a1f8ece69 100644 --- a/src/Discord.Net.Rest/ClientHelper.cs +++ b/src/Discord.Net.Rest/ClientHelper.cs @@ -50,12 +50,16 @@ namespace Discord.Rest return models.Select(x => RestConnection.Create(x)).ToImmutableArray(); } - public static async Task GetInviteAsync(BaseDiscordClient client, - string inviteId, RequestOptions options) + public static async Task GetInviteAsync(BaseDiscordClient client, + string inviteId, bool withCount, RequestOptions options) { - var model = await client.ApiClient.GetInviteAsync(inviteId, options).ConfigureAwait(false); + var args = new GetInviteParams + { + WithCounts = withCount + }; + var model = await client.ApiClient.GetInviteAsync(inviteId, args, options).ConfigureAwait(false); if (model != null) - return RestInvite.Create(client, null, null, model); + return RestInviteMetadata.Create(client, null, null, model); return null; } diff --git a/src/Discord.Net.Rest/DiscordRestApiClient.cs b/src/Discord.Net.Rest/DiscordRestApiClient.cs index f0c4358ad..7ec30c3aa 100644 --- a/src/Discord.Net.Rest/DiscordRestApiClient.cs +++ b/src/Discord.Net.Rest/DiscordRestApiClient.cs @@ -897,7 +897,7 @@ namespace Discord.API } //Guild Invites - public async Task GetInviteAsync(string inviteId, RequestOptions options = null) + public async Task GetInviteAsync(string inviteId, GetInviteParams args, RequestOptions options = null) { Preconditions.NotNullOrEmpty(inviteId, nameof(inviteId)); options = RequestOptions.CreateOrClone(options); @@ -910,9 +910,11 @@ namespace Discord.API if (index >= 0) inviteId = inviteId.Substring(index + 1); + var withCounts = args.WithCounts.GetValueOrDefault(false); + try { - return await SendAsync("GET", () => $"invites/{inviteId}", new BucketIds(), options: options).ConfigureAwait(false); + return await SendAsync("GET", () => $"invites/{inviteId}?with_counts={withCounts}", new BucketIds(), options: options).ConfigureAwait(false); } catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.NotFound) { return null; } } @@ -950,13 +952,6 @@ namespace Discord.API return await SendAsync("DELETE", () => $"invites/{inviteId}", new BucketIds(), options: options).ConfigureAwait(false); } - public async Task AcceptInviteAsync(string inviteId, RequestOptions options = null) - { - Preconditions.NotNullOrEmpty(inviteId, nameof(inviteId)); - options = RequestOptions.CreateOrClone(options); - - await SendAsync("POST", () => $"invites/{inviteId}", new BucketIds(), options: options).ConfigureAwait(false); - } //Guild Members public async Task GetGuildMemberAsync(ulong guildId, ulong userId, RequestOptions options = null) diff --git a/src/Discord.Net.Rest/DiscordRestClient.cs b/src/Discord.Net.Rest/DiscordRestClient.cs index 8850da3a5..3a596624d 100644 --- a/src/Discord.Net.Rest/DiscordRestClient.cs +++ b/src/Discord.Net.Rest/DiscordRestClient.cs @@ -56,8 +56,8 @@ namespace Discord.Rest => ClientHelper.GetConnectionsAsync(this, options); /// - public Task GetInviteAsync(string inviteId, RequestOptions options = null) - => ClientHelper.GetInviteAsync(this, inviteId, options); + public Task GetInviteAsync(string inviteId, bool withCount = false, RequestOptions options = null) + => ClientHelper.GetInviteAsync(this, inviteId, withCount, options); /// public Task GetGuildAsync(ulong id, RequestOptions options = null) @@ -131,8 +131,8 @@ namespace Discord.Rest async Task> IDiscordClient.GetConnectionsAsync(RequestOptions options) => await GetConnectionsAsync(options).ConfigureAwait(false); - async Task IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options) - => await GetInviteAsync(inviteId, options).ConfigureAwait(false); + async Task IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options) + => await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false); async Task IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) { diff --git a/src/Discord.Net.Rest/Entities/Invites/InviteHelper.cs b/src/Discord.Net.Rest/Entities/Invites/InviteHelper.cs index 80a49e34e..ebcd93777 100644 --- a/src/Discord.Net.Rest/Entities/Invites/InviteHelper.cs +++ b/src/Discord.Net.Rest/Entities/Invites/InviteHelper.cs @@ -1,14 +1,9 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; namespace Discord.Rest { internal static class InviteHelper { - public static async Task AcceptAsync(IInvite invite, BaseDiscordClient client, - RequestOptions options) - { - await client.ApiClient.AcceptInviteAsync(invite.Code, options).ConfigureAwait(false); - } public static async Task DeleteAsync(IInvite invite, BaseDiscordClient client, RequestOptions options) { diff --git a/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs b/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs index 900d1f0ac..18698c626 100644 --- a/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs +++ b/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs @@ -1,6 +1,7 @@ -using System; +using System; using System.Diagnostics; using System.Threading.Tasks; +using Discord.API.Rest; using Model = Discord.API.Invite; namespace Discord.Rest @@ -10,6 +11,8 @@ namespace Discord.Rest { public string ChannelName { get; private set; } public string GuildName { get; private set; } + public int? PresenceCount { get; private set; } + public int? MemberCount { get; private set; } public ulong ChannelId { get; private set; } public ulong GuildId { get; private set; } internal IChannel Channel { get; private set; } @@ -36,19 +39,21 @@ namespace Discord.Rest ChannelId = model.Channel.Id; GuildName = model.Guild.Name; ChannelName = model.Channel.Name; + MemberCount = model.MemberCount.IsSpecified ? model.MemberCount.Value : null; + PresenceCount = model.PresenceCount.IsSpecified ? model.PresenceCount.Value : null; } public async Task UpdateAsync(RequestOptions options = null) { - var model = await Discord.ApiClient.GetInviteAsync(Code, options).ConfigureAwait(false); + var args = new GetInviteParams(); + if (MemberCount != null || PresenceCount != null) + args.WithCounts = true; + var model = await Discord.ApiClient.GetInviteAsync(Code, args, options).ConfigureAwait(false); Update(model); } public Task DeleteAsync(RequestOptions options = null) => InviteHelper.DeleteAsync(this, Discord, options); - public Task AcceptAsync(RequestOptions options = null) - => InviteHelper.AcceptAsync(this, Discord, options); - public override string ToString() => Url; private string DebuggerDisplay => $"{Url} ({GuildName} / {ChannelName})"; diff --git a/src/Discord.Net.WebSocket/BaseSocketClient.cs b/src/Discord.Net.WebSocket/BaseSocketClient.cs index 923b2c23b..fb82fe14a 100644 --- a/src/Discord.Net.WebSocket/BaseSocketClient.cs +++ b/src/Discord.Net.WebSocket/BaseSocketClient.cs @@ -55,8 +55,8 @@ namespace Discord.WebSocket public Task> GetConnectionsAsync(RequestOptions options = null) => ClientHelper.GetConnectionsAsync(this, options ?? RequestOptions.Default); /// - public Task GetInviteAsync(string inviteId, RequestOptions options = null) - => ClientHelper.GetInviteAsync(this, inviteId, options ?? RequestOptions.Default); + public Task GetInviteAsync(string inviteId, bool withCount = false, RequestOptions options = null) + => ClientHelper.GetInviteAsync(this, inviteId, withCount, options ?? RequestOptions.Default); // IDiscordClient async Task IDiscordClient.GetApplicationInfoAsync(RequestOptions options) @@ -70,8 +70,8 @@ namespace Discord.WebSocket async Task> IDiscordClient.GetConnectionsAsync(RequestOptions options) => await GetConnectionsAsync(options).ConfigureAwait(false); - async Task IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options) - => await GetInviteAsync(inviteId, options).ConfigureAwait(false); + async Task IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options) + => await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false); Task IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetGuild(id)); diff --git a/src/Discord.Net.WebSocket/DiscordShardedClient.cs b/src/Discord.Net.WebSocket/DiscordShardedClient.cs index ad89067df..45d76e61a 100644 --- a/src/Discord.Net.WebSocket/DiscordShardedClient.cs +++ b/src/Discord.Net.WebSocket/DiscordShardedClient.cs @@ -327,8 +327,8 @@ namespace Discord.WebSocket async Task> IDiscordClient.GetConnectionsAsync(RequestOptions options) => await GetConnectionsAsync().ConfigureAwait(false); - async Task IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options) - => await GetInviteAsync(inviteId).ConfigureAwait(false); + async Task IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options) + => await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false); Task IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetGuild(id)); diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index 593f796c2..0188f7e9f 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -1796,8 +1796,8 @@ namespace Discord.WebSocket async Task> IDiscordClient.GetConnectionsAsync(RequestOptions options) => await GetConnectionsAsync().ConfigureAwait(false); - async Task IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options) - => await GetInviteAsync(inviteId).ConfigureAwait(false); + async Task IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options) + => await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false); Task IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetGuild(id)); From 9b29c004fa8216cff1bd593f6eb90936656886a8 Mon Sep 17 00:00:00 2001 From: Allan Date: Sun, 29 Apr 2018 17:11:44 +0200 Subject: [PATCH 4/9] Fixed GetReactionUsersAsync that was not using limit and afterUserId arguments. (#1017) --- src/Discord.Net.Rest/DiscordRestApiClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Discord.Net.Rest/DiscordRestApiClient.cs b/src/Discord.Net.Rest/DiscordRestApiClient.cs index 7ec30c3aa..042ae9970 100644 --- a/src/Discord.Net.Rest/DiscordRestApiClient.cs +++ b/src/Discord.Net.Rest/DiscordRestApiClient.cs @@ -626,7 +626,7 @@ namespace Discord.API ulong afterUserId = args.AfterUserId.GetValueOrDefault(0); var ids = new BucketIds(channelId: channelId); - Expression> endpoint = () => $"channels/{channelId}/messages/{messageId}/reactions/{emoji}"; + Expression> endpoint = () => $"channels/{channelId}/messages/{messageId}/reactions/{emoji}?limit={limit}&after={afterUserId}"; return await SendAsync>("GET", endpoint, ids, options: options).ConfigureAwait(false); } public async Task AckMessageAsync(ulong channelId, ulong messageId, RequestOptions options = null) From 3631886d2bf63b2a2e6175c185f51598612becf3 Mon Sep 17 00:00:00 2001 From: Still Hsu <341464@gmail.com> Date: Sun, 29 Apr 2018 23:14:34 +0800 Subject: [PATCH 5/9] Resolves #1024 (#1031) - Replace 'var _' with simple '_' discard as well. --- src/Discord.Net.WebSocket/DiscordSocketClient.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index 0188f7e9f..18413e840 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -479,14 +479,14 @@ namespace Discord.WebSocket await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false); await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false); }); - var _ = _connection.CompleteAsync(); + _ = _connection.CompleteAsync(); } break; case "RESUMED": { await _gatewayLogger.DebugAsync("Received Dispatch (RESUMED)").ConfigureAwait(false); - var _ = _connection.CompleteAsync(); + _ = _connection.CompleteAsync(); //Notify the client that these guilds are available again foreach (var guild in State.Guilds) @@ -1095,8 +1095,10 @@ namespace Discord.WebSocket else if (channel is SocketGroupChannel) author = (channel as SocketGroupChannel).GetOrAddUser(data.Author.Value); else + { await UnknownChannelUserAsync(type, data.Author.Value.Id, channel.Id).ConfigureAwait(false); - return; + return; + } } var msg = SocketMessage.Create(this, State, author, channel, data); From 73dc884d47bbff897de234351b39b97979cc9f14 Mon Sep 17 00:00:00 2001 From: Still Hsu <341464@gmail.com> Date: Sun, 29 Apr 2018 23:15:24 +0800 Subject: [PATCH 6/9] Improve SpotifyGame (#1039) * Initial commit * Add TrackUrl * Rename AlbumArt to AlbumArtUrl for consistency --- src/Discord.Net.Core/CDN.cs | 2 ++ .../Entities/Activities/SpotifyGame.cs | 13 ++++++++----- .../Extensions/EntityExtensions.cs | 10 +++++++--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/Discord.Net.Core/CDN.cs b/src/Discord.Net.Core/CDN.cs index 52b9a2878..6bac241aa 100644 --- a/src/Discord.Net.Core/CDN.cs +++ b/src/Discord.Net.Core/CDN.cs @@ -34,6 +34,8 @@ namespace Discord public static string GetSpotifyAlbumArtUrl(string albumArtId) => $"https://i.scdn.co/image/{albumArtId}"; + public static string GetSpotifyDirectUrl(string trackId) + => $"https://open.spotify.com/track/{trackId}"; private static string FormatToExtension(ImageFormat format, string imageId) { diff --git a/src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs b/src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs index a20384242..8b966d68b 100644 --- a/src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs +++ b/src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs @@ -7,17 +7,20 @@ namespace Discord [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class SpotifyGame : Game { - public IEnumerable Artists { get; internal set; } - public string AlbumArt { get; internal set; } + public IReadOnlyCollection Artists { get; internal set; } public string AlbumTitle { get; internal set; } public string TrackTitle { get; internal set; } - public string SyncId { get; internal set; } - public string SessionId { get; internal set; } public TimeSpan? Duration { get; internal set; } + public string TrackId { get; internal set; } + public string SessionId { get; internal set; } + + public string AlbumArtUrl { get; internal set; } + public string TrackUrl { get; internal set; } + internal SpotifyGame() { } - public override string ToString() => Name; + public override string ToString() => $"{string.Join(", ", Artists)} - {TrackTitle} ({Duration})"; private string DebuggerDisplay => $"{Name} (Spotify)"; } } diff --git a/src/Discord.Net.WebSocket/Extensions/EntityExtensions.cs b/src/Discord.Net.WebSocket/Extensions/EntityExtensions.cs index ff395a932..e8dc4b5f0 100644 --- a/src/Discord.Net.WebSocket/Extensions/EntityExtensions.cs +++ b/src/Discord.Net.WebSocket/Extensions/EntityExtensions.cs @@ -1,3 +1,6 @@ +using System.Collections.Immutable; +using System.Linq; + namespace Discord.WebSocket { internal static class EntityExtensions @@ -15,12 +18,13 @@ namespace Discord.WebSocket { Name = model.Name, SessionId = model.SessionId.GetValueOrDefault(), - SyncId = model.SyncId.Value, + TrackId = model.SyncId.Value, + TrackUrl = CDN.GetSpotifyDirectUrl(model.SyncId.Value), AlbumTitle = albumText, TrackTitle = model.Details.GetValueOrDefault(), - Artists = model.State.GetValueOrDefault()?.Split(';'), + Artists = model.State.GetValueOrDefault()?.Split(';').Select(x=>x?.Trim()).ToImmutableArray(), Duration = timestamps?.End - timestamps?.Start, - AlbumArt = albumArtId != null ? CDN.GetSpotifyAlbumArtUrl(albumArtId) : null, + AlbumArtUrl = albumArtId != null ? CDN.GetSpotifyAlbumArtUrl(albumArtId) : null, Type = ActivityType.Listening }; } From 217ec34ef05ef3f022e20394a62801546b2ce5d2 Mon Sep 17 00:00:00 2001 From: Christopher F Date: Sun, 29 Apr 2018 11:16:27 -0400 Subject: [PATCH 7/9] Add sample bots to the solution (#972) * Add sample bots to the solution * Fix missing attributes, show use of preconditions --- Discord.Net.sln | 36 +++++++++- .../01_basic_ping_bot.csproj | 12 ++++ samples/01_basic_ping_bot/Program.cs | 69 +++++++++++++++++++ .../02_commands_framework.csproj | 17 +++++ .../Modules/PublicModule.cs | 63 +++++++++++++++++ samples/02_commands_framework/Program.cs | 60 ++++++++++++++++ .../Services/CommandHandlingService.cs | 49 +++++++++++++ .../Services/PictureService.cs | 20 ++++++ 8 files changed, 324 insertions(+), 2 deletions(-) create mode 100644 samples/01_basic_ping_bot/01_basic_ping_bot.csproj create mode 100644 samples/01_basic_ping_bot/Program.cs create mode 100644 samples/02_commands_framework/02_commands_framework.csproj create mode 100644 samples/02_commands_framework/Modules/PublicModule.cs create mode 100644 samples/02_commands_framework/Program.cs create mode 100644 samples/02_commands_framework/Services/CommandHandlingService.cs create mode 100644 samples/02_commands_framework/Services/PictureService.cs diff --git a/Discord.Net.sln b/Discord.Net.sln index daf902b96..9bb940d8c 100644 --- a/Discord.Net.sln +++ b/Discord.Net.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.27130.0 +VisualStudioVersion = 15.0.27004.2009 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Core", "src\Discord.Net.Core\Discord.Net.Core.csproj", "{91E9E7BD-75C9-4E98-84AA-2C271922E5C2}" EndProject @@ -22,7 +22,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Tests", "test\D EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Webhook", "src\Discord.Net.Webhook\Discord.Net.Webhook.csproj", "{9AFAB80E-D2D3-4EDB-B58C-BACA78D1EA30}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Discord.Net.Analyzers", "src\Discord.Net.Analyzers\Discord.Net.Analyzers.csproj", "{BBA8E7FB-C834-40DC-822F-B112CB7F0140}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Analyzers", "src\Discord.Net.Analyzers\Discord.Net.Analyzers.csproj", "{BBA8E7FB-C834-40DC-822F-B112CB7F0140}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{BB59D5B5-E7B0-4BF4-8F82-D14431B2799B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_basic_ping_bot", "samples\01_basic_ping_bot\01_basic_ping_bot.csproj", "{F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02_commands_framework", "samples\02_commands_framework\02_commands_framework.csproj", "{4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -130,6 +136,30 @@ Global {BBA8E7FB-C834-40DC-822F-B112CB7F0140}.Release|x64.Build.0 = Release|Any CPU {BBA8E7FB-C834-40DC-822F-B112CB7F0140}.Release|x86.ActiveCfg = Release|Any CPU {BBA8E7FB-C834-40DC-822F-B112CB7F0140}.Release|x86.Build.0 = Release|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Debug|x64.ActiveCfg = Debug|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Debug|x64.Build.0 = Debug|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Debug|x86.ActiveCfg = Debug|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Debug|x86.Build.0 = Debug|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Release|Any CPU.Build.0 = Release|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Release|x64.ActiveCfg = Release|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Release|x64.Build.0 = Release|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Release|x86.ActiveCfg = Release|Any CPU + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E}.Release|x86.Build.0 = Release|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Debug|x64.ActiveCfg = Debug|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Debug|x64.Build.0 = Debug|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Debug|x86.ActiveCfg = Debug|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Debug|x86.Build.0 = Debug|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Release|Any CPU.Build.0 = Release|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Release|x64.ActiveCfg = Release|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Release|x64.Build.0 = Release|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Release|x86.ActiveCfg = Release|Any CPU + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -141,6 +171,8 @@ Global {6BDEEC08-417B-459F-9CA3-FF8BAB18CAC7} = {B0657AAE-DCC5-4FBF-8E5D-1FB578CF3012} {9AFAB80E-D2D3-4EDB-B58C-BACA78D1EA30} = {CC3D4B1C-9DE0-448B-8AE7-F3F1F3EC5C3A} {BBA8E7FB-C834-40DC-822F-B112CB7F0140} = {CC3D4B1C-9DE0-448B-8AE7-F3F1F3EC5C3A} + {F2FF84FB-F6AD-47E5-9EE5-18206CAE136E} = {BB59D5B5-E7B0-4BF4-8F82-D14431B2799B} + {4E1F1F40-B1DD-40C9-A4B1-A2046A4C9C76} = {BB59D5B5-E7B0-4BF4-8F82-D14431B2799B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {D2404771-EEC8-45F2-9D71-F3373F6C1495} diff --git a/samples/01_basic_ping_bot/01_basic_ping_bot.csproj b/samples/01_basic_ping_bot/01_basic_ping_bot.csproj new file mode 100644 index 000000000..5484e3d55 --- /dev/null +++ b/samples/01_basic_ping_bot/01_basic_ping_bot.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp2.0 + + + + + + + diff --git a/samples/01_basic_ping_bot/Program.cs b/samples/01_basic_ping_bot/Program.cs new file mode 100644 index 000000000..0fcc52b85 --- /dev/null +++ b/samples/01_basic_ping_bot/Program.cs @@ -0,0 +1,69 @@ +using System; +using System.Threading.Tasks; +using Discord; +using Discord.WebSocket; + +namespace _01_basic_ping_bot +{ + // This is a minimal, barebones example of using Discord.Net + // + // If writing a bot with commands, we recommend using the Discord.Net.Commands + // framework, rather than handling commands yourself, like we do in this sample. + // + // You can find samples of using the command framework: + // - Here, under the 02_commands_framework sample + // - https://github.com/foxbot/DiscordBotBase - a barebones bot template + // - https://github.com/foxbot/patek - a more feature-filled bot, utilizing more aspects of the library + class Program + { + private DiscordSocketClient _client; + + // Discord.Net heavily utilizes TAP for async, so we create + // an asynchronous context from the beginning. + static void Main(string[] args) + => new Program().MainAsync().GetAwaiter().GetResult(); + + public async Task MainAsync() + { + _client = new DiscordSocketClient(); + + _client.Log += LogAsync; + _client.Ready += ReadyAsync; + _client.MessageReceived += MessageReceivedAsync; + + // Tokens should be considered secret data, and never hard-coded. + await _client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token")); + await _client.StartAsync(); + + // Block the program until it is closed. + await Task.Delay(-1); + } + + private Task LogAsync(LogMessage log) + { + Console.WriteLine(log.ToString()); + return Task.CompletedTask; + } + + // The Ready event indicates that the client has opened a + // connection and it is now safe to access the cache. + private Task ReadyAsync() + { + Console.WriteLine($"{_client.CurrentUser} is connected!"); + + return Task.CompletedTask; + } + + // This is not the recommmended way to write a bot - consider + // reading over the Commands Framework sample. + private async Task MessageReceivedAsync(SocketMessage message) + { + // The bot should never respond to itself. + if (message.Author.Id == _client.CurrentUser.Id) + return; + + if (message.Content == "!ping") + await message.Channel.SendMessageAsync("pong!"); + } + } +} diff --git a/samples/02_commands_framework/02_commands_framework.csproj b/samples/02_commands_framework/02_commands_framework.csproj new file mode 100644 index 000000000..77fdc65e1 --- /dev/null +++ b/samples/02_commands_framework/02_commands_framework.csproj @@ -0,0 +1,17 @@ + + + + Exe + netcoreapp2.0 + + + + + + + + + + + + diff --git a/samples/02_commands_framework/Modules/PublicModule.cs b/samples/02_commands_framework/Modules/PublicModule.cs new file mode 100644 index 000000000..f30dfd73f --- /dev/null +++ b/samples/02_commands_framework/Modules/PublicModule.cs @@ -0,0 +1,63 @@ +using System.IO; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using _02_commands_framework.Services; + +namespace _02_commands_framework.Modules +{ + // Modules must be public and inherit from an IModuleBase + public class PublicModule : ModuleBase + { + // Dependency Injection will fill this value in for us + public PictureService PictureService { get; set; } + + [Command("ping")] + [Alias("pong", "hello")] + public Task PingAsync() + => ReplyAsync("pong!"); + + [Command("cat")] + public async Task CatAsync() + { + // Get a stream containing an image of a cat + var stream = await PictureService.GetCatPictureAsync(); + // Streams must be seeked to their beginning before being uploaded! + stream.Seek(0, SeekOrigin.Begin); + await Context.Channel.SendFileAsync(stream, "cat.png"); + } + + // Get info on a user, or the user who invoked the command if one is not specified + [Command("userinfo")] + public async Task UserInfoAsync(IUser user = null) + { + user = user ?? Context.User; + + await ReplyAsync(user.ToString()); + } + + // Ban a user + [Command("ban")] + [RequireContext(ContextType.Guild)] + // make sure the user invoking the command can ban + [RequireUserPermission(GuildPermission.BanMembers)] + // make sure the bot itself can ban + [RequireBotPermission(GuildPermission.BanMembers)] + public async Task BanUserAsync(IGuildUser user, [Remainder] string reason = null) + { + await user.Guild.AddBanAsync(user, reason: reason); + await ReplyAsync("ok!"); + } + + // [Remainder] takes the rest of the command's arguments as one argument, rather than splitting every space + [Command("echo")] + public Task EchoAsync([Remainder] string text) + // Insert a ZWSP before the text to prevent triggering other bots! + => ReplyAsync('\u200B' + text); + + // 'params' will parse space-separated elements into a list + [Command("list")] + public Task ListAsync(params string[] objects) + => ReplyAsync("You listed: " + string.Join("; ", objects)); + } +} diff --git a/samples/02_commands_framework/Program.cs b/samples/02_commands_framework/Program.cs new file mode 100644 index 000000000..3fed652d3 --- /dev/null +++ b/samples/02_commands_framework/Program.cs @@ -0,0 +1,60 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Discord; +using Discord.WebSocket; +using Discord.Commands; +using _02_commands_framework.Services; + +namespace _02_commands_framework +{ + // This is a minimal example of using Discord.Net's command + // framework - by no means does it show everything the framework + // is capable of. + // + // You can find samples of using the command framework: + // - Here, under the 02_commands_framework sample + // - https://github.com/foxbot/DiscordBotBase - a barebones bot template + // - https://github.com/foxbot/patek - a more feature-filled bot, utilizing more aspects of the library + class Program + { + static void Main(string[] args) + => new Program().MainAsync().GetAwaiter().GetResult(); + + public async Task MainAsync() + { + var services = ConfigureServices(); + + var client = services.GetRequiredService(); + + client.Log += LogAsync; + services.GetRequiredService().Log += LogAsync; + + await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token")); + await client.StartAsync(); + + await services.GetRequiredService().InitializeAsync(); + + await Task.Delay(-1); + } + + private Task LogAsync(LogMessage log) + { + Console.WriteLine(log.ToString()); + + return Task.CompletedTask; + } + + private IServiceProvider ConfigureServices() + { + return new ServiceCollection() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .BuildServiceProvider(); + } + } +} diff --git a/samples/02_commands_framework/Services/CommandHandlingService.cs b/samples/02_commands_framework/Services/CommandHandlingService.cs new file mode 100644 index 000000000..fc253eed3 --- /dev/null +++ b/samples/02_commands_framework/Services/CommandHandlingService.cs @@ -0,0 +1,49 @@ +using System; +using System.Reflection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Discord; +using Discord.Commands; +using Discord.WebSocket; + +namespace _02_commands_framework.Services +{ + public class CommandHandlingService + { + private readonly CommandService _commands; + private readonly DiscordSocketClient _discord; + private readonly IServiceProvider _services; + + public CommandHandlingService(IServiceProvider services) + { + _commands = services.GetRequiredService(); + _discord = services.GetRequiredService(); + _services = services; + + _discord.MessageReceived += MessageReceivedAsync; + } + + 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 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; + + var context = new SocketCommandContext(_discord, message); + var result = await _commands.ExecuteAsync(context, argPos, _services); + + if (result.Error.HasValue && + result.Error.Value != CommandError.UnknownCommand) // it's bad practice to send 'unknown command' errors + await context.Channel.SendMessageAsync(result.ToString()); + } + } +} diff --git a/samples/02_commands_framework/Services/PictureService.cs b/samples/02_commands_framework/Services/PictureService.cs new file mode 100644 index 000000000..dda818cc3 --- /dev/null +++ b/samples/02_commands_framework/Services/PictureService.cs @@ -0,0 +1,20 @@ +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; + +namespace _02_commands_framework.Services +{ + public class PictureService + { + private readonly HttpClient _http; + + public PictureService(HttpClient http) + => _http = http; + + public async Task GetCatPictureAsync() + { + var resp = await _http.GetAsync("https://cataas.com/cat"); + return await resp.Content.ReadAsStreamAsync(); + } + } +} From 6a7810b3a4d1050149681864d02d55ce722ed58f Mon Sep 17 00:00:00 2001 From: Alex Gravely Date: Sun, 29 Apr 2018 11:18:57 -0400 Subject: [PATCH 8/9] Fix Guild not being populated in SocketWebhookUser (#1044) --- src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs b/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs index 78a29639b..dd80648d2 100644 --- a/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs +++ b/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs @@ -26,6 +26,7 @@ namespace Discord.WebSocket internal SocketWebhookUser(SocketGuild guild, ulong id, ulong webhookId) : base(guild.Discord, id) { + Guild = guild; WebhookId = webhookId; } internal static SocketWebhookUser Create(SocketGuild guild, ClientState state, Model model, ulong webhookId) From 660fec0cbc705b996838ba7a574fb36c02f35ce2 Mon Sep 17 00:00:00 2001 From: Joe4evr Date: Sun, 29 Apr 2018 17:24:24 +0200 Subject: [PATCH 9/9] Expose the internal entity type readers (#986) * Expose the internal entity type readers * Add BestMatch property to TypeReaderResult for easily accessing the parsed object --- src/Discord.Net.Commands/Readers/ChannelTypeReader.cs | 4 ++-- src/Discord.Net.Commands/Readers/MessageTypeReader.cs | 4 ++-- src/Discord.Net.Commands/Readers/RoleTypeReader.cs | 4 ++-- src/Discord.Net.Commands/Readers/UserTypeReader.cs | 4 ++-- src/Discord.Net.Commands/Results/TypeReaderResult.cs | 6 +++++- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/Discord.Net.Commands/Readers/ChannelTypeReader.cs b/src/Discord.Net.Commands/Readers/ChannelTypeReader.cs index 3136eb2cb..cd7a9d744 100644 --- a/src/Discord.Net.Commands/Readers/ChannelTypeReader.cs +++ b/src/Discord.Net.Commands/Readers/ChannelTypeReader.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Discord.Commands { - internal class ChannelTypeReader : TypeReader + public class ChannelTypeReader : TypeReader where T : class, IChannel { public override async Task ReadAsync(ICommandContext context, string input, IServiceProvider services) diff --git a/src/Discord.Net.Commands/Readers/MessageTypeReader.cs b/src/Discord.Net.Commands/Readers/MessageTypeReader.cs index fe576c3c6..a87cfbe43 100644 --- a/src/Discord.Net.Commands/Readers/MessageTypeReader.cs +++ b/src/Discord.Net.Commands/Readers/MessageTypeReader.cs @@ -1,10 +1,10 @@ -using System; +using System; using System.Globalization; using System.Threading.Tasks; namespace Discord.Commands { - internal class MessageTypeReader : TypeReader + public class MessageTypeReader : TypeReader where T : class, IMessage { public override async Task ReadAsync(ICommandContext context, string input, IServiceProvider services) diff --git a/src/Discord.Net.Commands/Readers/RoleTypeReader.cs b/src/Discord.Net.Commands/Readers/RoleTypeReader.cs index 703374c05..508624103 100644 --- a/src/Discord.Net.Commands/Readers/RoleTypeReader.cs +++ b/src/Discord.Net.Commands/Readers/RoleTypeReader.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Discord.Commands { - internal class RoleTypeReader : TypeReader + public class RoleTypeReader : TypeReader where T : class, IRole { public override Task ReadAsync(ICommandContext context, string input, IServiceProvider services) diff --git a/src/Discord.Net.Commands/Readers/UserTypeReader.cs b/src/Discord.Net.Commands/Readers/UserTypeReader.cs index 8fc330d4c..425c2ccb7 100644 --- a/src/Discord.Net.Commands/Readers/UserTypeReader.cs +++ b/src/Discord.Net.Commands/Readers/UserTypeReader.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace Discord.Commands { - internal class UserTypeReader : TypeReader + public class UserTypeReader : TypeReader where T : class, IUser { public override async Task ReadAsync(ICommandContext context, string input, IServiceProvider services) diff --git a/src/Discord.Net.Commands/Results/TypeReaderResult.cs b/src/Discord.Net.Commands/Results/TypeReaderResult.cs index 68bc359c6..639ca3ac1 100644 --- a/src/Discord.Net.Commands/Results/TypeReaderResult.cs +++ b/src/Discord.Net.Commands/Results/TypeReaderResult.cs @@ -1,7 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Linq; namespace Discord.Commands { @@ -30,6 +31,9 @@ namespace Discord.Commands public string ErrorReason { get; } public bool IsSuccess => !Error.HasValue; + public object BestMatch => IsSuccess + ? (Values.Count == 1 ? Values.Single().Value : Values.OrderByDescending(v => v.Score).First().Value) + : throw new InvalidOperationException("TypeReaderResult was not successful."); private TypeReaderResult(IReadOnlyCollection values, CommandError? error, string errorReason) {