Browse Source

Merge upstream/dev & resolve conflicts

pull/988/head
Still Hsu 7 years ago
parent
commit
f38e72bbb4
No known key found for this signature in database GPG Key ID: 8601A145FDA95209
38 changed files with 449 additions and 83 deletions
  1. +34
    -2
      Discord.Net.sln
  2. +12
    -0
      samples/01_basic_ping_bot/01_basic_ping_bot.csproj
  3. +69
    -0
      samples/01_basic_ping_bot/Program.cs
  4. +17
    -0
      samples/02_commands_framework/02_commands_framework.csproj
  5. +63
    -0
      samples/02_commands_framework/Modules/PublicModule.cs
  6. +60
    -0
      samples/02_commands_framework/Program.cs
  7. +49
    -0
      samples/02_commands_framework/Services/CommandHandlingService.cs
  8. +20
    -0
      samples/02_commands_framework/Services/PictureService.cs
  9. +1
    -0
      src/Discord.Net.Commands/Attributes/CommandAttribute.cs
  10. +1
    -0
      src/Discord.Net.Commands/Builders/CommandBuilder.cs
  11. +1
    -0
      src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs
  12. +2
    -2
      src/Discord.Net.Commands/CommandParser.cs
  13. +0
    -6
      src/Discord.Net.Commands/CommandServiceConfig.cs
  14. +6
    -1
      src/Discord.Net.Commands/Info/CommandInfo.cs
  15. +0
    -4
      src/Discord.Net.Commands/Info/ModuleInfo.cs
  16. +2
    -2
      src/Discord.Net.Commands/Readers/ChannelTypeReader.cs
  17. +2
    -2
      src/Discord.Net.Commands/Readers/MessageTypeReader.cs
  18. +1
    -1
      src/Discord.Net.Commands/Readers/RoleTypeReader.cs
  19. +1
    -1
      src/Discord.Net.Commands/Readers/UserTypeReader.cs
  20. +4
    -0
      src/Discord.Net.Commands/Results/TypeReaderResult.cs
  21. +2
    -0
      src/Discord.Net.Core/CDN.cs
  22. +19
    -11
      src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs
  23. +6
    -3
      src/Discord.Net.Core/Entities/Invites/IInvite.cs
  24. +12
    -1
      src/Discord.Net.Core/Entities/Messages/Embed.cs
  25. +1
    -1
      src/Discord.Net.Core/IDiscordClient.cs
  26. +5
    -1
      src/Discord.Net.Rest/API/Common/Invite.cs
  27. +7
    -0
      src/Discord.Net.Rest/API/Rest/GetInviteParams.cs
  28. +1
    -1
      src/Discord.Net.Rest/BaseDiscordClient.cs
  29. +8
    -4
      src/Discord.Net.Rest/ClientHelper.cs
  30. +5
    -10
      src/Discord.Net.Rest/DiscordRestApiClient.cs
  31. +6
    -7
      src/Discord.Net.Rest/DiscordRestClient.cs
  32. +1
    -6
      src/Discord.Net.Rest/Entities/Invites/InviteHelper.cs
  33. +11
    -4
      src/Discord.Net.Rest/Entities/Invites/RestInvite.cs
  34. +4
    -4
      src/Discord.Net.WebSocket/BaseSocketClient.cs
  35. +2
    -2
      src/Discord.Net.WebSocket/DiscordShardedClient.cs
  36. +6
    -4
      src/Discord.Net.WebSocket/DiscordSocketClient.cs
  37. +1
    -0
      src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs
  38. +7
    -3
      src/Discord.Net.WebSocket/Extensions/EntityExtensions.cs

+ 34
- 2
Discord.Net.sln View File

@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15 # Visual Studio 15
VisualStudioVersion = 15.0.27130.0
VisualStudioVersion = 15.0.27004.2009
MinimumVisualStudioVersion = 10.0.40219.1 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}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Core", "src\Discord.Net.Core\Discord.Net.Core.csproj", "{91E9E7BD-75C9-4E98-84AA-2C271922E5C2}"
EndProject EndProject
@@ -22,7 +22,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Tests", "test\D
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Webhook", "src\Discord.Net.Webhook\Discord.Net.Webhook.csproj", "{9AFAB80E-D2D3-4EDB-B58C-BACA78D1EA30}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Discord.Net.Webhook", "src\Discord.Net.Webhook\Discord.Net.Webhook.csproj", "{9AFAB80E-D2D3-4EDB-B58C-BACA78D1EA30}"
EndProject 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 EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution 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|x64.Build.0 = Release|Any CPU
{BBA8E7FB-C834-40DC-822F-B112CB7F0140}.Release|x86.ActiveCfg = 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 {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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@@ -141,6 +171,8 @@ Global
{6BDEEC08-417B-459F-9CA3-FF8BAB18CAC7} = {B0657AAE-DCC5-4FBF-8E5D-1FB578CF3012} {6BDEEC08-417B-459F-9CA3-FF8BAB18CAC7} = {B0657AAE-DCC5-4FBF-8E5D-1FB578CF3012}
{9AFAB80E-D2D3-4EDB-B58C-BACA78D1EA30} = {CC3D4B1C-9DE0-448B-8AE7-F3F1F3EC5C3A} {9AFAB80E-D2D3-4EDB-B58C-BACA78D1EA30} = {CC3D4B1C-9DE0-448B-8AE7-F3F1F3EC5C3A}
{BBA8E7FB-C834-40DC-822F-B112CB7F0140} = {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 EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D2404771-EEC8-45F2-9D71-F3373F6C1495} SolutionGuid = {D2404771-EEC8-45F2-9D71-F3373F6C1495}


+ 12
- 0
samples/01_basic_ping_bot/01_basic_ping_bot.csproj View File

@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Discord.Net.WebSocket\Discord.Net.WebSocket.csproj" />
</ItemGroup>

</Project>

+ 69
- 0
samples/01_basic_ping_bot/Program.cs View File

@@ -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!");
}
}
}

+ 17
- 0
samples/02_commands_framework/02_commands_framework.csproj View File

@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0-preview1-final" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Discord.Net.Commands\Discord.Net.Commands.csproj" />
<ProjectReference Include="..\..\src\Discord.Net.WebSocket\Discord.Net.WebSocket.csproj" />
</ItemGroup>

</Project>

+ 63
- 0
samples/02_commands_framework/Modules/PublicModule.cs View File

@@ -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<SocketCommandContext>
{
// 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));
}
}

+ 60
- 0
samples/02_commands_framework/Program.cs View File

@@ -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<DiscordSocketClient>();

client.Log += LogAsync;
services.GetRequiredService<CommandService>().Log += LogAsync;

await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token"));
await client.StartAsync();

await services.GetRequiredService<CommandHandlingService>().InitializeAsync();

await Task.Delay(-1);
}

private Task LogAsync(LogMessage log)
{
Console.WriteLine(log.ToString());

return Task.CompletedTask;
}

private IServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddSingleton<DiscordSocketClient>()
.AddSingleton<CommandService>()
.AddSingleton<CommandHandlingService>()
.AddSingleton<HttpClient>()
.AddSingleton<PictureService>()
.BuildServiceProvider();
}
}
}

+ 49
- 0
samples/02_commands_framework/Services/CommandHandlingService.cs View File

@@ -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<CommandService>();
_discord = services.GetRequiredService<DiscordSocketClient>();
_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());
}
}
}

+ 20
- 0
samples/02_commands_framework/Services/PictureService.cs View File

@@ -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<Stream> GetCatPictureAsync()
{
var resp = await _http.GetAsync("https://cataas.com/cat");
return await resp.Content.ReadAsStreamAsync();
}
}
}

+ 1
- 0
src/Discord.Net.Commands/Attributes/CommandAttribute.cs View File

@@ -14,6 +14,7 @@ namespace Discord.Commands
/// Specifies the <see cref="RunMode" /> of the command. This affects how the command is executed. /// Specifies the <see cref="RunMode" /> of the command. This affects how the command is executed.
/// </summary> /// </summary>
public RunMode RunMode { get; set; } = RunMode.Default; public RunMode RunMode { get; set; } = RunMode.Default;
public bool? IgnoreExtraArgs { get; set; }


/// <inheritdoc /> /// <inheritdoc />
public CommandAttribute() public CommandAttribute()


+ 1
- 0
src/Discord.Net.Commands/Builders/CommandBuilder.cs View File

@@ -21,6 +21,7 @@ namespace Discord.Commands.Builders
public string PrimaryAlias { get; set; } public string PrimaryAlias { get; set; }
public RunMode RunMode { get; set; } public RunMode RunMode { get; set; }
public int Priority { get; set; } public int Priority { get; set; }
public bool IgnoreExtraArgs { get; set; }


public IReadOnlyList<PreconditionAttribute> Preconditions => _preconditions; public IReadOnlyList<PreconditionAttribute> Preconditions => _preconditions;
public IReadOnlyList<ParameterBuilder> Parameters => _parameters; public IReadOnlyList<ParameterBuilder> Parameters => _parameters;


+ 1
- 0
src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs View File

@@ -158,6 +158,7 @@ namespace Discord.Commands
builder.AddAliases(command.Text); builder.AddAliases(command.Text);
builder.RunMode = command.RunMode; builder.RunMode = command.RunMode;
builder.Name = builder.Name ?? command.Text; builder.Name = builder.Name ?? command.Text;
builder.IgnoreExtraArgs = command.IgnoreExtraArgs ?? service._ignoreExtraArgs;
break; break;
case NameAttribute name: case NameAttribute name:
builder.Name = name.Text; builder.Name = name.Text;


+ 2
- 2
src/Discord.Net.Commands/CommandParser.cs View File

@@ -14,7 +14,7 @@ namespace Discord.Commands
QuotedParameter QuotedParameter
} }
public static async Task<ParseResult> ParseArgsAsync(CommandInfo command, ICommandContext context, bool ignoreExtraArgs, IServiceProvider services, string input, int startPos)
public static async Task<ParseResult> ParseArgsAsync(CommandInfo command, ICommandContext context, IServiceProvider services, string input, int startPos)
{ {
ParameterInfo curParam = null; ParameterInfo curParam = null;
StringBuilder argBuilder = new StringBuilder(input.Length); StringBuilder argBuilder = new StringBuilder(input.Length);
@@ -110,7 +110,7 @@ namespace Discord.Commands
{ {
if (curParam == null) if (curParam == null)
{ {
if (ignoreExtraArgs)
if (command.IgnoreExtraArgs)
break; break;
else else
return ParseResult.FromError(CommandError.BadArgCount, "The input text has too many parameters."); return ParseResult.FromError(CommandError.BadArgCount, "The input text has too many parameters.");


+ 0
- 6
src/Discord.Net.Commands/CommandServiceConfig.cs View File

@@ -37,11 +37,5 @@ namespace Discord.Commands
/// Gets or sets whether extra parameters should be ignored. /// Gets or sets whether extra parameters should be ignored.
/// </summary> /// </summary>
public bool IgnoreExtraArgs { get; set; } = false; public bool IgnoreExtraArgs { get; set; } = false;

///// <summary> Gets or sets the <see cref="IServiceProvider"/> to use. </summary>
//public IServiceProvider ServiceProvider { get; set; } = null;

///// <summary> Gets or sets a factory function for the <see cref="IServiceProvider"/> to use. </summary>
//public Func<CommandService, IServiceProvider> ServiceProviderFactory { get; set; } = null;
} }
} }

+ 6
- 1
src/Discord.Net.Commands/Info/CommandInfo.cs View File

@@ -61,6 +61,10 @@ namespace Discord.Commands
/// </summary> /// </summary>
public bool HasVarArgs { get; } public bool HasVarArgs { get; }
/// <summary> /// <summary>
/// Indicates whether extra arguments should be ignored for this command.
/// </summary>
public bool IgnoreExtraArgs { get; }
/// <summary>
/// Gets the <see cref="RunMode" /> that is being used for the command. /// Gets the <see cref="RunMode" /> that is being used for the command.
/// </summary> /// </summary>
public RunMode RunMode { get; } public RunMode RunMode { get; }
@@ -111,6 +115,7 @@ namespace Discord.Commands


Parameters = builder.Parameters.Select(x => x.Build(this)).ToImmutableArray(); Parameters = builder.Parameters.Select(x => x.Build(this)).ToImmutableArray();
HasVarArgs = builder.Parameters.Count > 0 ? builder.Parameters[builder.Parameters.Count - 1].IsMultiple : false; HasVarArgs = builder.Parameters.Count > 0 ? builder.Parameters[builder.Parameters.Count - 1].IsMultiple : false;
IgnoreExtraArgs = builder.IgnoreExtraArgs;


_action = builder.Callback; _action = builder.Callback;
_commandService = service; _commandService = service;
@@ -167,7 +172,7 @@ namespace Discord.Commands
return ParseResult.FromError(preconditionResult); return ParseResult.FromError(preconditionResult);


string input = searchResult.Text.Substring(startIndex); 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<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)


+ 0
- 4
src/Discord.Net.Commands/Info/ModuleInfo.cs View File

@@ -22,8 +22,6 @@ namespace Discord.Commands
public ModuleInfo Parent { get; } public ModuleInfo Parent { get; }
public bool IsSubmodule => Parent != null; public bool IsSubmodule => Parent != null;


//public TypeInfo TypeInfo { get; }

internal ModuleInfo(ModuleBuilder builder, CommandService service, IServiceProvider services, ModuleInfo parent = null) internal ModuleInfo(ModuleBuilder builder, CommandService service, IServiceProvider services, ModuleInfo parent = null)
{ {
Service = service; Service = service;
@@ -34,8 +32,6 @@ namespace Discord.Commands
Group = builder.Group; Group = builder.Group;
Parent = parent; Parent = parent;


//TypeInfo = builder.TypeInfo;

Aliases = BuildAliases(builder, service).ToImmutableArray(); Aliases = BuildAliases(builder, service).ToImmutableArray();
Commands = builder.Commands.Select(x => x.Build(this, service)).ToImmutableArray(); Commands = builder.Commands.Select(x => x.Build(this, service)).ToImmutableArray();
Preconditions = BuildPreconditions(builder).ToImmutableArray(); Preconditions = BuildPreconditions(builder).ToImmutableArray();


+ 2
- 2
src/Discord.Net.Commands/Readers/ChannelTypeReader.cs View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
@@ -6,7 +6,7 @@ using System.Threading.Tasks;


namespace Discord.Commands namespace Discord.Commands
{ {
internal class ChannelTypeReader<T> : TypeReader
public class ChannelTypeReader<T> : TypeReader
where T : class, IChannel where T : class, IChannel
{ {
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)


+ 2
- 2
src/Discord.Net.Commands/Readers/MessageTypeReader.cs View File

@@ -1,10 +1,10 @@
using System;
using System;
using System.Globalization; using System.Globalization;
using System.Threading.Tasks; using System.Threading.Tasks;


namespace Discord.Commands namespace Discord.Commands
{ {
internal class MessageTypeReader<T> : TypeReader
public class MessageTypeReader<T> : TypeReader
where T : class, IMessage where T : class, IMessage
{ {
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)


+ 1
- 1
src/Discord.Net.Commands/Readers/RoleTypeReader.cs View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;


namespace Discord.Commands namespace Discord.Commands
{ {
internal class RoleTypeReader<T> : TypeReader
public class RoleTypeReader<T> : TypeReader
where T : class, IRole where T : class, IRole
{ {
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)


+ 1
- 1
src/Discord.Net.Commands/Readers/UserTypeReader.cs View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;


namespace Discord.Commands namespace Discord.Commands
{ {
internal class UserTypeReader<T> : TypeReader
public class UserTypeReader<T> : TypeReader
where T : class, IUser where T : class, IUser
{ {
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)


+ 4
- 0
src/Discord.Net.Commands/Results/TypeReaderResult.cs View File

@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;


namespace Discord.Commands namespace Discord.Commands
{ {
@@ -33,6 +34,9 @@ namespace Discord.Commands


/// <inheritdoc/> /// <inheritdoc/>
public bool IsSuccess => !Error.HasValue; 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<TypeReaderValue> values, CommandError? error, string errorReason) private TypeReaderResult(IReadOnlyCollection<TypeReaderValue> values, CommandError? error, string errorReason)
{ {


+ 2
- 0
src/Discord.Net.Core/CDN.cs View File

@@ -65,6 +65,8 @@ namespace Discord
/// </summary> /// </summary>
public static string GetSpotifyAlbumArtUrl(string albumArtId) public static string GetSpotifyAlbumArtUrl(string albumArtId)
=> $"https://i.scdn.co/image/{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) private static string FormatToExtension(ImageFormat format, string imageId)
{ {


+ 19
- 11
src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs View File

@@ -13,11 +13,7 @@ namespace Discord
/// <summary> /// <summary>
/// Gets the song's artist(s). /// Gets the song's artist(s).
/// </summary> /// </summary>
public IEnumerable<string> Artists { get; internal set; }
/// <summary>
/// Gets the Spotify album art of the song.
/// </summary>
public string AlbumArt { get; internal set; }
public IReadOnlyCollection<string> Artists { get; internal set; }
/// <summary> /// <summary>
/// Gets the Spotify album title of the song. /// Gets the Spotify album title of the song.
/// </summary> /// </summary>
@@ -27,22 +23,34 @@ namespace Discord
/// </summary> /// </summary>
public string TrackTitle { get; internal set; } public string TrackTitle { get; internal set; }
/// <summary> /// <summary>
/// Gets the synchronization ID of the song.
/// Gets the duration of the song.
/// </summary>
public TimeSpan? Duration { get; internal set; }

/// <summary>
/// Gets the track ID of the song.
/// </summary> /// </summary>
public string SyncId { get; internal set; }
public string TrackId { get; internal set; }
/// <summary> /// <summary>
/// Gets the session ID of the song. /// Gets the session ID of the song.
/// </summary> /// </summary>
public string SessionId { get; internal set; } public string SessionId { get; internal set; }

/// <summary> /// <summary>
/// Gets the duration of the song.
/// Gets the URL of the album art.
/// </summary> /// </summary>
public TimeSpan? Duration { get; internal set; }
public string AlbumArtUrl { get; internal set; }
/// <summary>
/// Gets the direct Spotify URL of the track.
/// </summary>
public string TrackUrl { get; internal set; }


internal SpotifyGame() { } internal SpotifyGame() { }


/// <summary> Gets the name of the song. </summary>
public override string ToString() => Name;
/// <summary>
/// Gets the full information of the song.
/// </summary>
public override string ToString() => $"{string.Join(", ", Artists)} - {TrackTitle} ({Duration})";
private string DebuggerDisplay => $"{Name} (Spotify)"; private string DebuggerDisplay => $"{Name} (Spotify)";
} }
} }

+ 6
- 3
src/Discord.Net.Core/Entities/Invites/IInvite.cs View File

@@ -41,10 +41,13 @@ namespace Discord
/// Gets the name of the guild this invite is linked to. /// Gets the name of the guild this invite is linked to.
/// </summary> /// </summary>
string GuildName { get; } string GuildName { get; }

/// <summary> /// <summary>
/// Accepts this invite and joins the target guild. This will fail on bot accounts.
/// Gets the approximated count of online members in the guild.
/// </summary>
int? PresenceCount { get; }
/// <summary>
/// Gets the approximated count of total members in the guild.
/// </summary> /// </summary>
Task AcceptAsync(RequestOptions options = null);
int? MemberCount { get; }
} }
} }

+ 12
- 1
src/Discord.Net.Core/Entities/Messages/Embed.cs View File

@@ -76,7 +76,18 @@ namespace Discord
/// <summary> /// <summary>
/// Gets the total length of all embed properties. /// Gets the total length of all embed properties.
/// </summary> /// </summary>
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;
}
}


/// <summary> /// <summary>
/// Gets the title of the embed. /// Gets the title of the embed.


+ 1
- 1
src/Discord.Net.Core/IDiscordClient.cs View File

@@ -56,7 +56,7 @@ namespace Discord
Task<IReadOnlyCollection<IGuild>> GetGuildsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); Task<IReadOnlyCollection<IGuild>> GetGuildsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null);
Task<IGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null); Task<IGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null);
Task<IInvite> GetInviteAsync(string inviteId, RequestOptions options = null);
Task<IInvite> GetInviteAsync(string inviteId, bool withCount = false, RequestOptions options = null);


Task<IUser> GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); Task<IUser> GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null);
Task<IUser> GetUserAsync(string username, string discriminator, RequestOptions options = null); Task<IUser> GetUserAsync(string username, string discriminator, RequestOptions options = null);


+ 5
- 1
src/Discord.Net.Rest/API/Common/Invite.cs View File

@@ -1,4 +1,4 @@
#pragma warning disable CS1591
#pragma warning disable CS1591
using Newtonsoft.Json; using Newtonsoft.Json;


namespace Discord.API namespace Discord.API
@@ -11,5 +11,9 @@ namespace Discord.API
public InviteGuild Guild { get; set; } public InviteGuild Guild { get; set; }
[JsonProperty("channel")] [JsonProperty("channel")]
public InviteChannel Channel { get; set; } public InviteChannel Channel { get; set; }
[JsonProperty("approximate_presence_count")]
public Optional<int?> PresenceCount { get; set; }
[JsonProperty("approximate_member_count")]
public Optional<int?> MemberCount { get; set; }
} }
} }

+ 7
- 0
src/Discord.Net.Rest/API/Rest/GetInviteParams.cs View File

@@ -0,0 +1,7 @@
namespace Discord.API.Rest
{
internal class GetInviteParams
{
public Optional<bool?> WithCounts { get; set; }
}
}

+ 1
- 1
src/Discord.Net.Rest/BaseDiscordClient.cs View File

@@ -164,7 +164,7 @@ namespace Discord.Rest
=> Task.FromResult<IReadOnlyCollection<IConnection>>(ImmutableArray.Create<IConnection>()); => Task.FromResult<IReadOnlyCollection<IConnection>>(ImmutableArray.Create<IConnection>());


/// <inheritdoc /> /// <inheritdoc />
Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options)
=> Task.FromResult<IInvite>(null); => Task.FromResult<IInvite>(null);


/// <inheritdoc /> /// <inheritdoc />


+ 8
- 4
src/Discord.Net.Rest/ClientHelper.cs View File

@@ -52,12 +52,16 @@ namespace Discord.Rest
return models.Select(x => RestConnection.Create(x)).ToImmutableArray(); return models.Select(x => RestConnection.Create(x)).ToImmutableArray();
} }
public static async Task<RestInvite> GetInviteAsync(BaseDiscordClient client,
string inviteId, RequestOptions options)
public static async Task<RestInviteMetadata> 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) if (model != null)
return RestInvite.Create(client, null, null, model);
return RestInviteMetadata.Create(client, null, null, model);
return null; return null;
} }


+ 5
- 10
src/Discord.Net.Rest/DiscordRestApiClient.cs View File

@@ -638,7 +638,7 @@ namespace Discord.API
ulong afterUserId = args.AfterUserId.GetValueOrDefault(0); ulong afterUserId = args.AfterUserId.GetValueOrDefault(0);


var ids = new BucketIds(channelId: channelId); var ids = new BucketIds(channelId: channelId);
Expression<Func<string>> endpoint = () => $"channels/{channelId}/messages/{messageId}/reactions/{emoji}";
Expression<Func<string>> endpoint = () => $"channels/{channelId}/messages/{messageId}/reactions/{emoji}?limit={limit}&after={afterUserId}";
return await SendAsync<IReadOnlyCollection<User>>("GET", endpoint, ids, options: options).ConfigureAwait(false); return await SendAsync<IReadOnlyCollection<User>>("GET", endpoint, ids, options: options).ConfigureAwait(false);
} }
public async Task AckMessageAsync(ulong channelId, ulong messageId, RequestOptions options = null) public async Task AckMessageAsync(ulong channelId, ulong messageId, RequestOptions options = null)
@@ -909,7 +909,7 @@ namespace Discord.API
} }


//Guild Invites //Guild Invites
public async Task<Invite> GetInviteAsync(string inviteId, RequestOptions options = null)
public async Task<InviteMetadata> GetInviteAsync(string inviteId, GetInviteParams args, RequestOptions options = null)
{ {
Preconditions.NotNullOrEmpty(inviteId, nameof(inviteId)); Preconditions.NotNullOrEmpty(inviteId, nameof(inviteId));
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
@@ -922,9 +922,11 @@ namespace Discord.API
if (index >= 0) if (index >= 0)
inviteId = inviteId.Substring(index + 1); inviteId = inviteId.Substring(index + 1);


var withCounts = args.WithCounts.GetValueOrDefault(false);

try try
{ {
return await SendAsync<Invite>("GET", () => $"invites/{inviteId}", new BucketIds(), options: options).ConfigureAwait(false);
return await SendAsync<InviteMetadata>("GET", () => $"invites/{inviteId}?with_counts={withCounts}", new BucketIds(), options: options).ConfigureAwait(false);
} }
catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.NotFound) { return null; } catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.NotFound) { return null; }
} }
@@ -962,13 +964,6 @@ namespace Discord.API
return await SendAsync<Invite>("DELETE", () => $"invites/{inviteId}", new BucketIds(), options: options).ConfigureAwait(false); return await SendAsync<Invite>("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 //Guild Members
public async Task<GuildMember> GetGuildMemberAsync(ulong guildId, ulong userId, RequestOptions options = null) public async Task<GuildMember> GetGuildMemberAsync(ulong guildId, ulong userId, RequestOptions options = null)


+ 6
- 7
src/Discord.Net.Rest/DiscordRestClient.cs View File

@@ -52,10 +52,10 @@ namespace Discord.Rest
public Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync(RequestOptions options = null) public Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync(RequestOptions options = null)
=> ClientHelper.GetConnectionsAsync(this, options); => ClientHelper.GetConnectionsAsync(this, options);
public Task<RestInvite> GetInviteAsync(string inviteId, RequestOptions options = null)
=> ClientHelper.GetInviteAsync(this, inviteId, options);
public Task<RestInviteMetadata> GetInviteAsync(string inviteId, bool withCount = false, RequestOptions options = null)
=> ClientHelper.GetInviteAsync(this, inviteId, withCount, options);
public Task<RestGuild> GetGuildAsync(ulong id, RequestOptions options = null) public Task<RestGuild> GetGuildAsync(ulong id, RequestOptions options = null)
=> ClientHelper.GetGuildAsync(this, id, options); => ClientHelper.GetGuildAsync(this, id, options);
public Task<RestGuildEmbed?> GetGuildEmbedAsync(ulong id, RequestOptions options = null) public Task<RestGuildEmbed?> GetGuildEmbedAsync(ulong id, RequestOptions options = null)
@@ -123,9 +123,8 @@ namespace Discord.Rest
async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options) async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
=> await GetConnectionsAsync(options).ConfigureAwait(false); => await GetConnectionsAsync(options).ConfigureAwait(false);


/// <inheritdoc />
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options)
=> await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
async Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) async Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)


+ 1
- 6
src/Discord.Net.Rest/Entities/Invites/InviteHelper.cs View File

@@ -1,14 +1,9 @@
using System.Threading.Tasks;
using System.Threading.Tasks;


namespace Discord.Rest namespace Discord.Rest
{ {
internal static class InviteHelper 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, public static async Task DeleteAsync(IInvite invite, BaseDiscordClient client,
RequestOptions options) RequestOptions options)
{ {


+ 11
- 4
src/Discord.Net.Rest/Entities/Invites/RestInvite.cs View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.API.Rest;
using Model = Discord.API.Invite; using Model = Discord.API.Invite;


namespace Discord.Rest namespace Discord.Rest
@@ -13,6 +14,10 @@ namespace Discord.Rest
/// <inheritdoc /> /// <inheritdoc />
public string GuildName { get; private set; } public string GuildName { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
public int? PresenceCount { get; private set; }
/// <inheritdoc />
public int? MemberCount { get; private set; }
/// <inheritdoc />
public ulong ChannelId { get; private set; } public ulong ChannelId { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
public ulong GuildId { get; private set; } public ulong GuildId { get; private set; }
@@ -42,20 +47,22 @@ namespace Discord.Rest
ChannelId = model.Channel.Id; ChannelId = model.Channel.Id;
GuildName = model.Guild.Name; GuildName = model.Guild.Name;
ChannelName = model.Channel.Name; ChannelName = model.Channel.Name;
MemberCount = model.MemberCount.IsSpecified ? model.MemberCount.Value : null;
PresenceCount = model.PresenceCount.IsSpecified ? model.PresenceCount.Value : null;
} }


/// <inheritdoc /> /// <inheritdoc />
public async Task UpdateAsync(RequestOptions options = 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); Update(model);
} }
/// <inheritdoc /> /// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null) public Task DeleteAsync(RequestOptions options = null)
=> InviteHelper.DeleteAsync(this, Discord, options); => InviteHelper.DeleteAsync(this, Discord, options);
/// <inheritdoc />
public Task AcceptAsync(RequestOptions options = null)
=> InviteHelper.AcceptAsync(this, Discord, options);


public override string ToString() => Url; public override string ToString() => Url;
private string DebuggerDisplay => $"{Url} ({GuildName} / {ChannelName})"; private string DebuggerDisplay => $"{Url} ({GuildName} / {ChannelName})";


+ 4
- 4
src/Discord.Net.WebSocket/BaseSocketClient.cs View File

@@ -178,8 +178,8 @@ namespace Discord.WebSocket
/// <returns> /// <returns>
/// An awaitable <see cref="Task"/> containing the invite information. /// An awaitable <see cref="Task"/> containing the invite information.
/// </returns> /// </returns>
public Task<RestInvite> GetInviteAsync(string inviteId, RequestOptions options = null)
=> ClientHelper.GetInviteAsync(this, inviteId, options ?? RequestOptions.Default);
public Task<RestInviteMetadata> GetInviteAsync(string inviteId, bool withCount = false, RequestOptions options = null)
=> ClientHelper.GetInviteAsync(this, inviteId, withCount, options ?? RequestOptions.Default);
// IDiscordClient // IDiscordClient
/// <inheritdoc /> /// <inheritdoc />
@@ -198,8 +198,8 @@ namespace Discord.WebSocket
=> await GetConnectionsAsync(options).ConfigureAwait(false); => await GetConnectionsAsync(options).ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
=> await GetInviteAsync(inviteId, options).ConfigureAwait(false);
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options)
=> await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)


+ 2
- 2
src/Discord.Net.WebSocket/DiscordShardedClient.cs View File

@@ -342,8 +342,8 @@ namespace Discord.WebSocket
=> await GetConnectionsAsync().ConfigureAwait(false); => await GetConnectionsAsync().ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
=> await GetInviteAsync(inviteId).ConfigureAwait(false);
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options)
=> await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)


+ 6
- 4
src/Discord.Net.WebSocket/DiscordSocketClient.cs View File

@@ -499,7 +499,7 @@ namespace Discord.WebSocket
{ {
await _gatewayLogger.DebugAsync("Received Dispatch (RESUMED)").ConfigureAwait(false); await _gatewayLogger.DebugAsync("Received Dispatch (RESUMED)").ConfigureAwait(false);


var _ = _connection.CompleteAsync();
_ = _connection.CompleteAsync();


//Notify the client that these guilds are available again //Notify the client that these guilds are available again
foreach (var guild in State.Guilds) foreach (var guild in State.Guilds)
@@ -1108,8 +1108,10 @@ namespace Discord.WebSocket
else if (channel is SocketGroupChannel) else if (channel is SocketGroupChannel)
author = (channel as SocketGroupChannel).GetOrAddUser(data.Author.Value); author = (channel as SocketGroupChannel).GetOrAddUser(data.Author.Value);
else else
{
await UnknownChannelUserAsync(type, data.Author.Value.Id, channel.Id).ConfigureAwait(false); await UnknownChannelUserAsync(type, data.Author.Value.Id, channel.Id).ConfigureAwait(false);
return;
return;
}
} }


var msg = SocketMessage.Create(this, State, author, channel, data); var msg = SocketMessage.Create(this, State, author, channel, data);
@@ -1817,8 +1819,8 @@ namespace Discord.WebSocket
=> await GetConnectionsAsync().ConfigureAwait(false); => await GetConnectionsAsync().ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options)
=> await GetInviteAsync(inviteId).ConfigureAwait(false);
async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options)
=> await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false);


/// <inheritdoc /> /// <inheritdoc />
Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)


+ 1
- 0
src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs View File

@@ -34,6 +34,7 @@ namespace Discord.WebSocket
internal SocketWebhookUser(SocketGuild guild, ulong id, ulong webhookId) internal SocketWebhookUser(SocketGuild guild, ulong id, ulong webhookId)
: base(guild.Discord, id) : base(guild.Discord, id)
{ {
Guild = guild;
WebhookId = webhookId; WebhookId = webhookId;
} }
internal static SocketWebhookUser Create(SocketGuild guild, ClientState state, Model model, ulong webhookId) internal static SocketWebhookUser Create(SocketGuild guild, ClientState state, Model model, ulong webhookId)


+ 7
- 3
src/Discord.Net.WebSocket/Extensions/EntityExtensions.cs View File

@@ -1,3 +1,6 @@
using System.Collections.Immutable;
using System.Linq;

namespace Discord.WebSocket namespace Discord.WebSocket
{ {
internal static class EntityExtensions internal static class EntityExtensions
@@ -15,12 +18,13 @@ namespace Discord.WebSocket
{ {
Name = model.Name, Name = model.Name,
SessionId = model.SessionId.GetValueOrDefault(), SessionId = model.SessionId.GetValueOrDefault(),
SyncId = model.SyncId.Value,
TrackId = model.SyncId.Value,
TrackUrl = CDN.GetSpotifyDirectUrl(model.SyncId.Value),
AlbumTitle = albumText, AlbumTitle = albumText,
TrackTitle = model.Details.GetValueOrDefault(), TrackTitle = model.Details.GetValueOrDefault(),
Artists = model.State.GetValueOrDefault()?.Split(';'),
Artists = model.State.GetValueOrDefault()?.Split(';').Select(x=>x?.Trim()).ToImmutableArray(),
Duration = timestamps?.End - timestamps?.Start, Duration = timestamps?.End - timestamps?.Start,
AlbumArt = albumArtId != null ? CDN.GetSpotifyAlbumArtUrl(albumArtId) : null,
AlbumArtUrl = albumArtId != null ? CDN.GetSpotifyAlbumArtUrl(albumArtId) : null,
Type = ActivityType.Listening Type = ActivityType.Listening
}; };
} }


Loading…
Cancel
Save