diff --git a/.gitignore b/.gitignore index d72e0b5ea..654370842 100644 --- a/.gitignore +++ b/.gitignore @@ -127,7 +127,7 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings +# TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj @@ -151,7 +151,6 @@ AppPackages/ # Others *.[Cc]ache ClientBin/ -[Ss]tyle[Cc]op.* ~$* *~ *.dbmdl @@ -206,4 +205,4 @@ docs/api/\.manifest \.idea/ # Codealike UID -codealike.json \ No newline at end of file +codealike.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 886754052..7f4041a7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,96 @@ # Changelog +## [2.3.0] - 2021-01-28 +### Added +- #1491 Add INVITE_CREATE and INVITE_DELETE events (1ab670b) +- #1520 Support reading multiple activities (421a0c1) +- #1521 Allow for inherited commands in modules (a51cdf6) +- #1526 Add Direction.Around to GetMessagesAsync (f2130f8) +- #1537 Implement gateway ratelimit (ec673e1) +- #1544 Add MESSAGE_REACTION_REMOVE_EMOJI and RemoveAllReactionsForEmoteAsync (a89f076) +- #1549 Add GetUsersAsync to SocketGuild (30b5a83) +- #1566 Support Gateway Intents (d5d10d3) +- #1573 Add missing properties to Guild and deprecate GuildEmbed (ec212b1) +- #1581 Add includeRoleIds to PruneUsersAsync (a80e5ff) +- #1588 Add GetStreams to AudioClient (1e012ac) +- #1596 Add missing channel properties (2d80037) +- #1604 Add missing application properties (including Teams) (10fcde0) +- #1619 Add "View Guild Insights" to GuildPermission (2592264) +- #1637 Added CultureInvariant RegexOption to WebhookUrlRegex (e3925a7) +- #1659 Add inline replies (e3850e1) +- #1688 Send presence on Identify payload (25d5d36) +- #1721 Add role tags (6a62c47) +- #1722 Add user public flags (c683b29) +- #1724 Add MessageFlags and AllowedMentions to message modify (225550d) +- #1731 Add GuildUser IsPending property (8b25c9b) +- #1690 Add max bitrate value to SocketGuild (aacfea0) + +### Fixed +- #1244 Missing AddReactions permission for DM channels. (e40ca4a) +- #1469 unsupported property causes an exception (468f826) +- #1525 AllowedMentions and AllowedMentionTypes (3325031) +- #1531 Add AllowedMentions to SendFileAsync (ab32607) +- #1532 GuildEmbed.ChannelId as nullable per API documentation (971d519) +- #1546 Different ratelimits for the same route (implement discord buckets) (2f6c017) +- #1548 Incomplete Ready, DownloadUsersAsync, and optimize AlwaysDownloadUsers (dc8c959) +- #1555 InvalidOperationException at MESSAGE_CREATE (bd4672a) +- #1557 Sending 2 requests instead of 1 to create a Guild role. (5430cc8) +- #1571 Not using the new domain name. (df8a0f7) +- #1578 Trim token before passing it to the authorization header (42ba372) +- #1580 Stop TaskCanceledException from bubbling up (b8fa464) +- #1599 Invite audit log without inviter (b95b95b) +- #1602 Add AllowedMentions to webhooks (bd4516b) +- #1603 Cancel reconnection when 4014 (f396cd9) +- #1608 Voice overwrites and CategoryId remarks (43c8fc0) +- #1614 Check error 404 and return null for GetBanAsync (ae9fff6) +- #1621 Parse mentions from message payload (366ca9a) +- #1622 Do not update overwrite cache locally (3860da0) +- #1623 Invoke UserUpdated from GuildMemberUpdated if needed (3085e88) +- #1624 Handle null PreferredLocale in rare cases (c1d04b4) +- #1639 Invite and InviteMetadata properties (dd2e524) +- #1642 Add missing permissions (4b389f3) +- #1647 handicap member downloading for verified bots (fa5ef5e) +- #1652 Update README.MD to reflect new discord domain (03b831e) +- #1667 Audio stream dispose (a2af985) +- #1671 Crosspost throwing InvalidOperationException (9134443) +- #1672 Team is nullable, not optional (be60d81) +- #1681 Emoji url encode (04389a4) +- #1683 SocketGuild.HasAllMembers is false if a user left a guild (47f571e) +- #1686 Revert PremiumSubscriptionCount type (97e71cd) +- #1695 Possible NullReferenceException when receiving InvalidSession (5213916) +- #1702 Rollback Activities to Game (9d7cb39) +- #1727 Move and fix internal AllowedMentions object (4a7f8fe) +- limit request members batch size (084db25) +- UserMentions throwing NullRef (5ed01a3) +- Wrong author for SocketUserMessage.ReferencedMessage (1e9b252) +- Discord sends null when there's no team (05a1f0a) +- IMessage.Embeds docs remarks (a4d32d3) +- Missing MessageReference when sending files (2095701) + +### Misc +- #1545 MutualGuilds optimization (323a677) +- #1551 Update webhook regex to support discord.com (7585789) +- #1556 Add SearchUsersAsync (57880de) +- #1561 Minor refactor to switch expression (42826df) +- #1576 Updating comments for privileged intents (c42bfa6) +- #1678 Change ratelimit messages (47ed806) +- #1714 Update summary of SocketVoiceChannel.Users (e385c40) +- #1720 VoiceRegions and related changes (5934c79) +- Add updated libraries for LastModified (d761846) +- Add alternative documentation link (accd351) +- Temporarily disable StyleCops until all the fixes are impl'd (36de7b2) +- Remove redundant CreateGuildRoleParams (3df0539) +- Add minor tweaks to DiscordSocketConfig docs strings (2cd1880) +- Fix MaxWaitBetweenGuildAvailablesBeforeReady docs string (e31cdc7) +- Missing summary tag for GatewayIntents (3a10018) +- Add new method of role ID copy (857ef77) +- Resolve inheritdocs for IAttachment (9ea3291) +- Mark null as a specific langword in summary (13a41f8) +- Cleanup GatewayReconnectException docs (833ee42) +- Update Docfx.Plugins.LastModified to v1.2.4 (28a6f97) +- Update framework version for tests to Core 3.1 to comply with LTS (4988a07) +- Move bulk deletes remarks from to (62539f0) + ## [2.2.0] - 2020-04-16 ### Added - #1247 Implement Client Status Support (9da11b4) diff --git a/Discord.Net.targets b/Discord.Net.targets index adb42f7a9..a7e2c8a51 100644 --- a/Discord.Net.targets +++ b/Discord.Net.targets @@ -1,15 +1,15 @@ - 2.3.0 + 2.3.1 dev latest Discord.Net Contributors discord;discordapp - https://github.com/RogueException/Discord.Net + https://github.com/Discord-Net/Discord.Net http://opensource.org/licenses/MIT - https://github.com/RogueException/Discord.Net/raw/dev/docs/marketing/logo/PackageLogo.png + https://github.com/Discord-Net/Discord.Net/raw/dev/docs/marketing/logo/PackageLogo.png git - git://github.com/RogueException/Discord.Net + git://github.com/Discord-Net/Discord.Net $(VersionSuffix)-dev diff --git a/README.md b/README.md index f4bc5811e..34a633f72 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,16 @@ [![NuGet](https://img.shields.io/nuget/vpre/Discord.Net.svg?maxAge=2592000?style=plastic)](https://www.nuget.org/packages/Discord.Net) [![MyGet](https://img.shields.io/myget/discord-net/vpre/Discord.Net.svg)](https://www.myget.org/feed/Packages/discord-net) [![Build Status](https://dev.azure.com/discord-net/Discord.Net/_apis/build/status/discord-net.Discord.Net?branchName=dev)](https://dev.azure.com/discord-net/Discord.Net/_build/latest?definitionId=1&branchName=dev) -[![Discord](https://discordapp.com/api/guilds/81384788765712384/widget.png)](https://discord.gg/jkrBmQR) +[![Discord](https://discord.com/api/guilds/81384788765712384/widget.png)](https://discord.gg/jkrBmQR) -An unofficial .NET API Wrapper for the Discord client (http://discordapp.com). +An unofficial .NET API Wrapper for the Discord client (https://discord.com). -Check out the [documentation](https://discord.foxbot.me/) or join the [Discord API Chat](https://discord.gg/jkrBmQR). +## Documentation + +- [Stable](https://discord.foxbot.me/) + - Hosted by @foxbot +- [Nightly](https://docs.stillu.cc/) + - [Latest CI repo](https://github.com/discord-net/docs-static) ## Installation ### Stable (NuGet) diff --git a/StyleAnalyzer.targets b/StyleAnalyzer.targets new file mode 100644 index 000000000..0794cfacb --- /dev/null +++ b/StyleAnalyzer.targets @@ -0,0 +1,9 @@ + + + + diff --git a/docs/_overwrites/Common/EmbedObjectBuilder.Inclusion.md b/docs/_overwrites/Common/EmbedObjectBuilder.Inclusion.md index eac0d9ca5..a9d3539ed 100644 --- a/docs/_overwrites/Common/EmbedObjectBuilder.Inclusion.md +++ b/docs/_overwrites/Common/EmbedObjectBuilder.Inclusion.md @@ -4,10 +4,10 @@ field, and 2 normal fields using an @Discord.EmbedBuilder: ```cs var exampleAuthor = new EmbedAuthorBuilder() .WithName("I am a bot") - .WithIconUrl("https://discordapp.com/assets/e05ead6e6ebc08df9291738d0aa6986d.png"); + .WithIconUrl("https://discord.com/assets/e05ead6e6ebc08df9291738d0aa6986d.png"); var exampleFooter = new EmbedFooterBuilder() .WithText("I am a nice footer") - .WithIconUrl("https://discordapp.com/assets/28174a34e77bb5e5310ced9f95cb480b.png"); + .WithIconUrl("https://discord.com/assets/28174a34e77bb5e5310ced9f95cb480b.png"); var exampleField = new EmbedFieldBuilder() .WithName("Title of Another Field") .WithValue("I am an [example](https://example.com).") @@ -22,4 +22,4 @@ var embed = new EmbedBuilder() .WithAuthor(exampleAuthor) .WithFooter(exampleFooter) .Build(); -``` \ No newline at end of file +``` diff --git a/docs/_template/last-modified/plugins/LastModifiedPostProcessor.dll b/docs/_template/last-modified/plugins/LastModifiedPostProcessor.dll index dd790e55e..ccb2b0e37 100644 Binary files a/docs/_template/last-modified/plugins/LastModifiedPostProcessor.dll and b/docs/_template/last-modified/plugins/LastModifiedPostProcessor.dll differ diff --git a/docs/_template/last-modified/plugins/LibGit2Sharp.dll b/docs/_template/last-modified/plugins/LibGit2Sharp.dll index 82f214846..316515072 100644 Binary files a/docs/_template/last-modified/plugins/LibGit2Sharp.dll and b/docs/_template/last-modified/plugins/LibGit2Sharp.dll differ diff --git a/docs/_template/last-modified/plugins/LibGit2Sharp.dll.config b/docs/_template/last-modified/plugins/LibGit2Sharp.dll.config index ddc821b29..21a2b5601 100644 --- a/docs/_template/last-modified/plugins/LibGit2Sharp.dll.config +++ b/docs/_template/last-modified/plugins/LibGit2Sharp.dll.config @@ -1,4 +1,4 @@ - - - + + + diff --git a/docs/_template/last-modified/plugins/lib/alpine-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/alpine-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..793f4483a Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/alpine-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/alpine.3.9-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/alpine.3.9-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..49186df25 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/alpine.3.9-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/debian-arm64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/debian-arm64/libgit2-ef5a385.so new file mode 100644 index 000000000..11ef799ab Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/debian-arm64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/debian.9-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/debian.9-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..5cd5e46b0 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/debian.9-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/fedora-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/fedora-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..be1be9322 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/fedora-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/linux-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/linux-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..1ec4b01f5 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/linux-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/osx/libgit2-ef5a385.dylib b/docs/_template/last-modified/plugins/lib/osx/libgit2-ef5a385.dylib new file mode 100644 index 000000000..81f71d6ea Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/osx/libgit2-ef5a385.dylib differ diff --git a/docs/_template/last-modified/plugins/lib/rhel-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/rhel-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..3d194a97f Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/rhel-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/ubuntu.16.04-arm64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/ubuntu.16.04-arm64/libgit2-ef5a385.so new file mode 100644 index 000000000..a3282b0d2 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/ubuntu.16.04-arm64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/ubuntu.18.04-x64/libgit2-ef5a385.so b/docs/_template/last-modified/plugins/lib/ubuntu.18.04-x64/libgit2-ef5a385.so new file mode 100644 index 000000000..0360ce3e0 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/ubuntu.18.04-x64/libgit2-ef5a385.so differ diff --git a/docs/_template/last-modified/plugins/lib/win32/x64/git2-ef5a385.dll b/docs/_template/last-modified/plugins/lib/win32/x64/git2-ef5a385.dll new file mode 100644 index 000000000..7ffcdf97f Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/win32/x64/git2-ef5a385.dll differ diff --git a/docs/_template/last-modified/plugins/lib/win32/x86/git2-ef5a385.dll b/docs/_template/last-modified/plugins/lib/win32/x86/git2-ef5a385.dll new file mode 100644 index 000000000..9fe2e3e01 Binary files /dev/null and b/docs/_template/last-modified/plugins/lib/win32/x86/git2-ef5a385.dll differ diff --git a/docs/_template/light-dark-theme/partials/affix.tmpl.partial b/docs/_template/light-dark-theme/partials/affix.tmpl.partial index aafcdf05b..b3ce60b5c 100644 --- a/docs/_template/light-dark-theme/partials/affix.tmpl.partial +++ b/docs/_template/light-dark-theme/partials/affix.tmpl.partial @@ -27,7 +27,8 @@ {{/_disableContribution}} diff --git a/docs/faq/basics/client-basics.md b/docs/faq/basics/client-basics.md index 9377ac2e9..1176ee3fd 100644 --- a/docs/faq/basics/client-basics.md +++ b/docs/faq/basics/client-basics.md @@ -30,7 +30,7 @@ There are few possible reasons why this may occur. [TokenType]: xref:Discord.TokenType [827]: https://github.com/RogueException/Discord.Net/issues/827 [958]: https://github.com/RogueException/Discord.Net/issues/958 -[Discord API Terms of Service]: https://discordapp.com/developers/docs/legal +[Discord API Terms of Service]: https://discord.com/developers/docs/legal ## How do I do X, Y, Z when my bot connects/logs on? Why do I get a `NullReferenceException` upon calling any client methods after connect? diff --git a/docs/faq/basics/getting-started.md b/docs/faq/basics/getting-started.md index f38d2cea7..e254226d0 100644 --- a/docs/faq/basics/getting-started.md +++ b/docs/faq/basics/getting-started.md @@ -74,6 +74,9 @@ it will return the user ID of the aforementioned user. Several common ways to do this: -1. Make the role mentionable and mention the role, and escape it +1. (Easiest) Right click on the role either in the Server Settings + or in the user's role list. + ![Roles](images/role-copy.png) +2. Make the role mentionable and mention the role, and escape it using the `\` character in front. -2. Inspect the roles collection within the guild via your debugger. \ No newline at end of file +3. Inspect the roles collection within the guild via your debugger. \ No newline at end of file diff --git a/docs/faq/basics/images/role-copy.png b/docs/faq/basics/images/role-copy.png new file mode 100644 index 000000000..1dbc2982f Binary files /dev/null and b/docs/faq/basics/images/role-copy.png differ diff --git a/docs/faq/misc/glossary.md b/docs/faq/misc/glossary.md index 95bdbaa03..4b661f65c 100644 --- a/docs/faq/misc/glossary.md +++ b/docs/faq/misc/glossary.md @@ -19,7 +19,7 @@ channels, and are often referred to as "servers". * A **Channel** ([IChannel]) represents a generic channel. - Example: #dotnet_discord-net - See [Channel Types](#channel-types) - + [IGuild]: xref:Discord.IGuild [IChannel]: xref:Discord.IChannel @@ -79,4 +79,4 @@ activity for listening to a song on Spotify. [RichGame]: xref:Discord.RichGame [StreamingGame]: xref:Discord.StreamingGame [SpotifyGame]: xref:Discord.SpotifyGame -[Rich Presence Intro]: https://discordapp.com/developers/docs/rich-presence/best-practices \ No newline at end of file +[Rich Presence Intro]: https://discord.com/developers/docs/rich-presence/best-practices diff --git a/docs/guides/getting_started/first-bot.md b/docs/guides/getting_started/first-bot.md index bdae80c7f..150466be1 100644 --- a/docs/guides/getting_started/first-bot.md +++ b/docs/guides/getting_started/first-bot.md @@ -31,7 +31,7 @@ the Discord Applications Portal first. ![Step 7](images/intro-public-bot.png) -[Discord Applications Portal]: https://discordapp.com/developers/applications/ +[Discord Applications Portal]: https://discord.com/developers/applications/ ## Adding your bot to a server @@ -165,11 +165,11 @@ or any other blocking method, such as reading from the console. > the source code for your bot. > > In the following example, we retrieve the token from a pre-defined -> variable, which is **NOT** secure, especially if you plan on +> variable, which is **NOT** secure, especially if you plan on > distributing the application in any shape or form. > -> We recommend alternative storage such as -> [Environment Variables], an external configuration file, or a +> We recommend alternative storage such as +> [Environment Variables], an external configuration file, or a > secrets manager for safe-handling of secrets. > > [Environment Variables]: https://en.wikipedia.org/wiki/Environment_variable @@ -221,4 +221,4 @@ should be to separate... 2. the modules (handle commands) 3. the services (persistent storage, pure functions, data manipulation) -[CommandService]: xref:Discord.Commands.CommandService \ No newline at end of file +[CommandService]: xref:Discord.Commands.CommandService diff --git a/docs/index.md b/docs/index.md index 34350df70..1d0f5aaf7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -11,12 +11,12 @@ title: Home [![NuGet](https://img.shields.io/nuget/vpre/Discord.Net.svg?maxAge=2592000?style=plastic)](https://www.nuget.org/packages/Discord.Net) [![MyGet](https://img.shields.io/myget/discord-net/vpre/Discord.Net.svg)](https://www.myget.org/feed/Packages/discord-net) [![Build Status](https://dev.azure.com/discord-net/Discord.Net/_apis/build/status/discord-net.Discord.Net?branchName=dev)](https://dev.azure.com/discord-net/Discord.Net/_build/latest?definitionId=1&branchName=dev) -[![Discord](https://discordapp.com/api/guilds/81384788765712384/widget.png)](https://discord.gg/jkrBmQR) +[![Discord](https://discord.com/api/guilds/81384788765712384/widget.png)](https://discord.gg/jkrBmQR) ## What is Discord.Net? Discord.Net is an asynchronous, multi-platform .NET Library used to -interface with the [Discord API](https://discordapp.com/). +interface with the [Discord API](https://discord.com/). ## Where to begin? diff --git a/samples/04_webhook_client/Program.cs b/samples/04_webhook_client/Program.cs index c2e5faa03..f3a50036c 100644 --- a/samples/04_webhook_client/Program.cs +++ b/samples/04_webhook_client/Program.cs @@ -14,10 +14,10 @@ namespace _04_webhook_client public async Task MainAsync() { - // The webhook url follows the format https://discordapp.com/api/webhooks/{id}/{token} + // The webhook url follows the format https://discord.com/api/webhooks/{id}/{token} // Because anyone with the webhook URL can use your webhook - // you should NOT hard code the URL or ID + token into your application. - using (var client = new DiscordWebhookClient("https://discordapp.com/api/webhooks/123/abc123")) + // you should NOT hard code the URL or ID + token into your application. + using (var client = new DiscordWebhookClient("https://discord.com/api/webhooks/123/abc123")) { var embed = new EmbedBuilder { @@ -26,7 +26,7 @@ namespace _04_webhook_client }; // Webhooks are able to send multiple embeds per message - // As such, your embeds must be passed as a collection. + // As such, your embeds must be passed as a collection. await client.SendMessageAsync(text: "Send a message to this webhook!", embeds: new[] { embed.Build() }); } } diff --git a/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs b/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs index 28037b0fa..7a752090e 100644 --- a/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs +++ b/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs @@ -136,7 +136,7 @@ namespace Discord.Commands builder.Name = typeInfo.Name; // Get all methods (including from inherited members), that are valid commands - var validCommands = typeInfo.GetMethods().Where(IsValidCommandDefinition); + var validCommands = typeInfo.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(IsValidCommandDefinition); foreach (var method in validCommands) { diff --git a/src/Discord.Net.Commands/Discord.Net.Commands.csproj b/src/Discord.Net.Commands/Discord.Net.Commands.csproj index 95e7db491..21869d91c 100644 --- a/src/Discord.Net.Commands/Discord.Net.Commands.csproj +++ b/src/Discord.Net.Commands/Discord.Net.Commands.csproj @@ -1,5 +1,6 @@ + Discord.Net.Commands Discord.Commands diff --git a/src/Discord.Net.Commands/ModuleBase.cs b/src/Discord.Net.Commands/ModuleBase.cs index ec1722c70..6ec2db54d 100644 --- a/src/Discord.Net.Commands/ModuleBase.cs +++ b/src/Discord.Net.Commands/ModuleBase.cs @@ -35,9 +35,10 @@ namespace Discord.Commands /// Specifies if notifications are sent for mentioned users and roles in the . /// If null, all mentioned roles and users will be notified. /// - protected virtual async Task ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) + /// The message references to be included. Used to reply to specific messages. + protected virtual async Task ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { - return await Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + return await Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); } /// /// The method to execute before executing the command. diff --git a/src/Discord.Net.Core/Audio/IAudioClient.cs b/src/Discord.Net.Core/Audio/IAudioClient.cs index 018c8bc05..2fc52a529 100644 --- a/src/Discord.Net.Core/Audio/IAudioClient.cs +++ b/src/Discord.Net.Core/Audio/IAudioClient.cs @@ -1,4 +1,5 @@ -using System; +using System; +using System.Collections.Generic; using System.Threading.Tasks; namespace Discord.Audio @@ -20,6 +21,9 @@ namespace Discord.Audio /// Gets the estimated round-trip latency, in milliseconds, to the voice UDP server. int UdpLatency { get; } + /// Gets the current audio streams. + IReadOnlyDictionary GetStreams(); + Task StopAsync(); Task SetSpeakingAsync(bool value); diff --git a/src/Discord.Net.Core/CDN.cs b/src/Discord.Net.Core/CDN.cs index 32ffbba90..e1e8e5e1a 100644 --- a/src/Discord.Net.Core/CDN.cs +++ b/src/Discord.Net.Core/CDN.cs @@ -7,6 +7,17 @@ namespace Discord /// public static class CDN { + /// + /// Returns a team icon URL. + /// + /// The team identifier. + /// The icon identifier. + /// + /// A URL pointing to the team's icon. + /// + public static string GetTeamIconUrl(ulong teamId, string iconId) + => iconId != null ? $"{DiscordConfig.CDNUrl}team-icons/{teamId}/{iconId}.jpg" : null; + /// /// Returns an application icon URL. /// @@ -62,11 +73,21 @@ namespace Discord /// The guild snowflake identifier. /// The splash icon identifier. /// - /// A URL pointing to the guild's icon. + /// A URL pointing to the guild's splash. /// public static string GetGuildSplashUrl(ulong guildId, string splashId) => splashId != null ? $"{DiscordConfig.CDNUrl}splashes/{guildId}/{splashId}.jpg" : null; /// + /// Returns a guild discovery splash URL. + /// + /// The guild snowflake identifier. + /// The discovery splash icon identifier. + /// + /// A URL pointing to the guild's discovery splash. + /// + public static string GetGuildDiscoverySplashUrl(ulong guildId, string discoverySplashId) + => discoverySplashId != null ? $"{DiscordConfig.CDNUrl}discovery-splashes/{guildId}/{discoverySplashId}.jpg" : null; + /// /// Returns a channel icon URL. /// /// The channel snowflake identifier. diff --git a/src/Discord.Net.Core/Discord.Net.Core.csproj b/src/Discord.Net.Core/Discord.Net.Core.csproj index dd2f2afe3..bc513390c 100644 --- a/src/Discord.Net.Core/Discord.Net.Core.csproj +++ b/src/Discord.Net.Core/Discord.Net.Core.csproj @@ -1,5 +1,6 @@ + Discord.Net.Core Discord diff --git a/src/Discord.Net.Core/DiscordConfig.cs b/src/Discord.Net.Core/DiscordConfig.cs index 51970a781..429ad7b0c 100644 --- a/src/Discord.Net.Core/DiscordConfig.cs +++ b/src/Discord.Net.Core/DiscordConfig.cs @@ -13,7 +13,7 @@ namespace Discord /// /// An representing the API version that Discord.Net uses to communicate with Discord. /// A list of available API version can be seen on the official - /// Discord API documentation + /// Discord API documentation /// . /// public const int APIVersion = 6; @@ -50,7 +50,7 @@ namespace Discord /// /// The Discord API URL using . /// - public static readonly string APIUrl = $"https://discordapp.com/api/v{APIVersion}/"; + public static readonly string APIUrl = $"https://discord.com/api/v{APIVersion}/"; /// /// Returns the base Discord CDN URL. /// diff --git a/src/Discord.Net.Core/Entities/Channels/GuildChannelProperties.cs b/src/Discord.Net.Core/Entities/Channels/GuildChannelProperties.cs index 9552b0a60..339d6fffd 100644 --- a/src/Discord.Net.Core/Entities/Channels/GuildChannelProperties.cs +++ b/src/Discord.Net.Core/Entities/Channels/GuildChannelProperties.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; + namespace Discord { /// @@ -26,9 +28,13 @@ namespace Discord /// /// /// Setting this value to a category's snowflake identifier will change or set this channel's parent to the - /// specified channel; setting this value to 0 will detach this channel from its parent if one + /// specified channel; setting this value to will detach this channel from its parent if one /// is set. /// public Optional CategoryId { get; set; } + /// + /// Gets or sets the permission overwrites for this channel. + /// + public Optional> PermissionOverwrites { get; set; } } } diff --git a/src/Discord.Net.Core/Entities/Channels/IMessageChannel.cs b/src/Discord.Net.Core/Entities/Channels/IMessageChannel.cs index 030a278bc..abd20e4f0 100644 --- a/src/Discord.Net.Core/Entities/Channels/IMessageChannel.cs +++ b/src/Discord.Net.Core/Entities/Channels/IMessageChannel.cs @@ -27,11 +27,12 @@ namespace Discord /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null); + Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Sends a file to this message channel with an optional caption. /// @@ -63,11 +64,12 @@ namespace Discord /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null); + Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Sends a file to this message channel with an optional caption. /// @@ -96,11 +98,12 @@ namespace Discord /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null); + Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Gets a message from this message channel. diff --git a/src/Discord.Net.Core/Entities/Channels/INewsChannel.cs b/src/Discord.Net.Core/Entities/Channels/INewsChannel.cs new file mode 100644 index 000000000..a1223b48b --- /dev/null +++ b/src/Discord.Net.Core/Entities/Channels/INewsChannel.cs @@ -0,0 +1,9 @@ +namespace Discord +{ + /// + /// Represents a generic news channel in a guild that can send and receive messages. + /// + public interface INewsChannel : ITextChannel + { + } +} diff --git a/src/Discord.Net.Core/Entities/Gateway/BotGateway.cs b/src/Discord.Net.Core/Entities/Gateway/BotGateway.cs new file mode 100644 index 000000000..c9be0ac1f --- /dev/null +++ b/src/Discord.Net.Core/Entities/Gateway/BotGateway.cs @@ -0,0 +1,22 @@ +namespace Discord +{ + /// + /// Stores the gateway information related to the current bot. + /// + public class BotGateway + { + /// + /// Gets the WSS URL that can be used for connecting to the gateway. + /// + public string Url { get; internal set; } + /// + /// Gets the recommended number of shards to use when connecting. + /// + public int Shards { get; internal set; } + /// + /// Gets the that contains the information + /// about the current session start limit. + /// + public SessionStartLimit SessionStartLimit { get; internal set; } + } +} diff --git a/src/Discord.Net.Core/Entities/Gateway/SessionStartLimit.cs b/src/Discord.Net.Core/Entities/Gateway/SessionStartLimit.cs new file mode 100644 index 000000000..74ae96af1 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Gateway/SessionStartLimit.cs @@ -0,0 +1,38 @@ +namespace Discord +{ + /// + /// Stores the information related to the gateway identify request. + /// + public class SessionStartLimit + { + /// + /// Gets the total number of session starts the current user is allowed. + /// + /// + /// The maximum amount of session starts the current user is allowed. + /// + public int Total { get; internal set; } + /// + /// Gets the remaining number of session starts the current user is allowed. + /// + /// + /// The remaining amount of session starts the current user is allowed. + /// + public int Remaining { get; internal set; } + /// + /// Gets the number of milliseconds after which the limit resets. + /// + /// + /// The milliseconds until the limit resets back to the . + /// + public int ResetAfter { get; internal set; } + /// + /// Gets the maximum concurrent identify requests in a time window. + /// + /// + /// The maximum concurrent identify requests in a time window, + /// limited to the same rate limit key. + /// + public int MaxConcurrency { get; internal set; } + } +} diff --git a/src/Discord.Net.Core/Entities/Guilds/GuildWidgetProperties.cs b/src/Discord.Net.Core/Entities/Guilds/GuildWidgetProperties.cs new file mode 100644 index 000000000..842bb7f3e --- /dev/null +++ b/src/Discord.Net.Core/Entities/Guilds/GuildWidgetProperties.cs @@ -0,0 +1,21 @@ +namespace Discord +{ + /// + /// Provides properties that are used to modify the widget of an with the specified changes. + /// + public class GuildWidgetProperties + { + /// + /// Sets whether the widget should be enabled. + /// + public Optional Enabled { get; set; } + /// + /// Sets the channel that the invite should place its users in, if not . + /// + public Optional Channel { get; set; } + /// + /// Sets the channel that the invite should place its users in, if not . + /// + public Optional ChannelId { get; set; } + } +} diff --git a/src/Discord.Net.Core/Entities/Guilds/IGuild.cs b/src/Discord.Net.Core/Entities/Guilds/IGuild.cs index 81b5e8dd9..6283508e5 100644 --- a/src/Discord.Net.Core/Entities/Guilds/IGuild.cs +++ b/src/Discord.Net.Core/Entities/Guilds/IGuild.cs @@ -23,7 +23,7 @@ namespace Discord /// automatically moved to the AFK voice channel. /// /// - /// An representing the amount of time in seconds for a user to be marked as inactive + /// An representing the amount of time in seconds for a user to be marked as inactive /// and moved into the AFK voice channel. /// int AFKTimeout { get; } @@ -31,10 +31,17 @@ namespace Discord /// Gets a value that indicates whether this guild is embeddable (i.e. can use widget). /// /// - /// true if this guild can be embedded via widgets; otherwise false. + /// if this guild has a widget enabled; otherwise . /// bool IsEmbeddable { get; } /// + /// Gets a value that indicates whether this guild has the widget enabled. + /// + /// + /// if this guild has a widget enabled; otherwise . + /// + bool IsWidgetEnabled { get; } + /// /// Gets the default message notifications for users who haven't explicitly set their notification settings. /// DefaultMessageNotifications DefaultMessageNotifications { get; } @@ -64,31 +71,45 @@ namespace Discord /// Gets the ID of this guild's icon. /// /// - /// An identifier for the splash image; null if none is set. + /// An identifier for the splash image; if none is set. /// string IconId { get; } /// /// Gets the URL of this guild's icon. /// /// - /// A URL pointing to the guild's icon; null if none is set. + /// A URL pointing to the guild's icon; if none is set. /// string IconUrl { get; } /// /// Gets the ID of this guild's splash image. /// /// - /// An identifier for the splash image; null if none is set. + /// An identifier for the splash image; if none is set. /// string SplashId { get; } /// /// Gets the URL of this guild's splash image. /// /// - /// A URL pointing to the guild's splash image; null if none is set. + /// A URL pointing to the guild's splash image; if none is set. /// string SplashUrl { get; } /// + /// Gets the ID of this guild's discovery splash image. + /// + /// + /// An identifier for the discovery splash image; if none is set. + /// + string DiscoverySplashId { get; } + /// + /// Gets the URL of this guild's discovery splash image. + /// + /// + /// A URL pointing to the guild's discovery splash image; if none is set. + /// + string DiscoverySplashUrl { get; } + /// /// Determines if this guild is currently connected and ready to be used. /// /// @@ -98,7 +119,7 @@ namespace Discord /// This boolean is used to determine if the guild is currently connected to the WebSocket and is ready to be used/accessed. /// /// - /// true if this guild is currently connected and ready to be used; otherwise false. + /// true if this guild is currently connected and ready to be used; otherwise . /// bool Available { get; } @@ -106,7 +127,7 @@ namespace Discord /// Gets the ID of the AFK voice channel for this guild. /// /// - /// A representing the snowflake identifier of the AFK voice channel; null if + /// A representing the snowflake identifier of the AFK voice channel; if /// none is set. /// ulong? AFKChannelId { get; } @@ -121,7 +142,7 @@ namespace Discord /// /// /// - /// A representing the snowflake identifier of the default text channel; 0 if + /// A representing the snowflake identifier of the default text channel; 0 if /// none can be found. /// ulong DefaultChannelId { get; } @@ -129,30 +150,54 @@ namespace Discord /// Gets the ID of the widget embed channel of this guild. /// /// - /// A representing the snowflake identifier of the embedded channel found within the - /// widget settings of this guild; null if none is set. + /// A representing the snowflake identifier of the embedded channel found within the + /// widget settings of this guild; if none is set. /// ulong? EmbedChannelId { get; } /// + /// Gets the ID of the channel assigned to the widget of this guild. + /// + /// + /// A representing the snowflake identifier of the channel assigned to the widget found + /// within the widget settings of this guild; if none is set. + /// + ulong? WidgetChannelId { get; } + /// /// Gets the ID of the channel where randomized welcome messages are sent. /// /// - /// A representing the snowflake identifier of the system channel where randomized - /// welcome messages are sent; null if none is set. + /// A representing the snowflake identifier of the system channel where randomized + /// welcome messages are sent; if none is set. /// ulong? SystemChannelId { get; } /// + /// Gets the ID of the channel with the rules. + /// + /// + /// A representing the snowflake identifier of the channel that contains the rules; + /// if none is set. + /// + ulong? RulesChannelId { get; } + /// + /// Gets the ID of the channel where admins and moderators of Community guilds receive notices from Discord. + /// + /// + /// A representing the snowflake identifier of the channel where admins and moderators + /// of Community guilds receive notices from Discord; if none is set. + /// + ulong? PublicUpdatesChannelId { get; } + /// /// Gets the ID of the user that owns this guild. /// /// - /// A representing the snowflake identifier of the user that owns this guild. + /// A representing the snowflake identifier of the user that owns this guild. /// ulong OwnerId { get; } /// /// Gets the application ID of the guild creator if it is bot-created. /// /// - /// A representing the snowflake identifier of the application ID that created this guild, or null if it was not bot-created. + /// A representing the snowflake identifier of the application ID that created this guild, or if it was not bot-created. /// ulong? ApplicationId { get; } /// @@ -208,21 +253,21 @@ namespace Discord /// Gets the identifier for this guilds banner image. /// /// - /// An identifier for the banner image; null if none is set. + /// An identifier for the banner image; if none is set. /// string BannerId { get; } /// /// Gets the URL of this guild's banner image. /// /// - /// A URL pointing to the guild's banner image; null if none is set. + /// A URL pointing to the guild's banner image; if none is set. /// string BannerUrl { get; } /// /// Gets the code for this guild's vanity invite URL. /// /// - /// A string containing the vanity invite code for this guild; null if none is set. + /// A string containing the vanity invite code for this guild; if none is set. /// string VanityURLCode { get; } /// @@ -236,7 +281,7 @@ namespace Discord /// Gets the description for the guild. /// /// - /// The description for the guild; null if none is set. + /// The description for the guild; if none is set. /// string Description { get; } /// @@ -246,9 +291,50 @@ namespace Discord /// This is the number of users who have boosted this guild. /// /// - /// The number of premium subscribers of this guild. + /// The number of premium subscribers of this guild; if not available. /// int PremiumSubscriptionCount { get; } + /// + /// Gets the maximum number of presences for the guild. + /// + /// + /// The maximum number of presences for the guild. + /// + int? MaxPresences { get; } + /// + /// Gets the maximum number of members for the guild. + /// + /// + /// The maximum number of members for the guild. + /// + int? MaxMembers { get; } + /// + /// Gets the maximum amount of users in a video channel. + /// + /// + /// The maximum amount of users in a video channel. + /// + int? MaxVideoChannelUsers { get; } + /// + /// Gets the approximate number of members in this guild. + /// + /// + /// Only available when getting a guild via REST when `with_counts` is true. + /// + /// + /// The approximate number of members in this guild. + /// + int? ApproximateMemberCount { get; } + /// + /// Gets the approximate number of non-offline members in this guild. + /// + /// + /// Only available when getting a guild via REST when `with_counts` is true. + /// + /// + /// The approximate number of non-offline members in this guild. + /// + int? ApproximatePresenceCount { get; } /// /// Gets the preferred locale of this guild in IETF BCP 47 @@ -285,8 +371,18 @@ namespace Discord /// /// A task that represents the asynchronous modification operation. /// + [Obsolete("This endpoint is deprecated, use ModifyWidgetAsync instead.")] Task ModifyEmbedAsync(Action func, RequestOptions options = null); /// + /// Modifies this guild's widget. + /// + /// The delegate containing the properties to modify the guild widget with. + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous modification operation. + /// + Task ModifyWidgetAsync(Action func, RequestOptions options = null); + /// /// Bulk-modifies the order of channels in this guild. /// /// The properties used to modify the channel positions with. @@ -336,7 +432,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains a ban object, which - /// contains the user information and the reason for the ban; null if the ban entry cannot be found. + /// contains the user information and the reason for the ban; if the ban entry cannot be found. /// Task GetBanAsync(IUser user, RequestOptions options = null); /// @@ -346,7 +442,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains a ban object, which - /// contains the user information and the reason for the ban; null if the ban entry cannot be found. + /// contains the user information and the reason for the ban; if the ban entry cannot be found. /// Task GetBanAsync(ulong userId, RequestOptions options = null); /// @@ -410,7 +506,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the generic channel - /// associated with the specified ; null if none is found. + /// associated with the specified ; if none is found. /// Task GetChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -431,7 +527,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the text channel - /// associated with the specified ; null if none is found. + /// associated with the specified ; if none is found. /// Task GetTextChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -462,7 +558,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the voice channel associated - /// with the specified ; null if none is found. + /// with the specified ; if none is found. /// Task GetVoiceChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -472,7 +568,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the voice channel that the - /// AFK users will be moved to after they have idled for too long; null if none is set. + /// AFK users will be moved to after they have idled for too long; if none is set. /// Task GetAFKChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -482,7 +578,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the text channel where - /// randomized welcome messages will be sent to; null if none is set. + /// randomized welcome messages will be sent to; if none is set. /// Task GetSystemChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -492,7 +588,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the first viewable text - /// channel in this guild; null if none is found. + /// channel in this guild; if none is found. /// Task GetDefaultChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -502,9 +598,40 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the embed channel set - /// within the server's widget settings; null if none is set. + /// within the server's widget settings; if none is set. /// + [Obsolete("This endpoint is deprecated, use GetWidgetChannelAsync instead.")] Task GetEmbedChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); + /// + /// Gets the widget channel (i.e. the channel set in the guild's widget settings) in this guild. + /// + /// The that determines whether the object should be fetched from cache. + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains the widget channel set + /// within the server's widget settings; if none is set. + /// + Task GetWidgetChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); + /// + /// Gets the text channel where Community guilds can display rules and/or guidelines. + /// + /// The that determines whether the object should be fetched from cache. + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains the text channel + /// where Community guilds can display rules and/or guidelines; if none is set. + /// + Task GetRulesChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); + /// + /// Gets the text channel channel where admins and moderators of Community guilds receive notices from Discord. + /// + /// The that determines whether the object should be fetched from cache. + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains the text channel channel where + /// admins and moderators of Community guilds receive notices from Discord; if none is set. + /// + Task GetPublicUpdatesChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// /// Creates a new text channel in this guild. @@ -573,7 +700,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the partial metadata of - /// the vanity invite found within this guild; null if none is found. + /// the vanity invite found within this guild; if none is found. /// Task GetVanityInviteAsync(RequestOptions options = null); @@ -582,7 +709,7 @@ namespace Discord /// /// The snowflake identifier for the role. /// - /// A role that is associated with the specified ; null if none is found. + /// A role that is associated with the specified ; if none is found. /// IRole GetRole(ulong id); /// @@ -624,7 +751,7 @@ namespace Discord /// The OAuth2 access token for the user, requested with the guilds.join scope. /// The delegate containing the properties to be applied to the user upon being added to the guild. /// The options to be used when sending the request. - /// A guild user associated with the specified ; null if the user is already in the guild. + /// A guild user associated with the specified ; if the user is already in the guild. Task AddGuildUserAsync(ulong userId, string accessToken, Action func = null, RequestOptions options = null); /// /// Gets a collection of all users in this guild. @@ -649,7 +776,7 @@ namespace Discord /// /// This method retrieves a user found within this guild. /// - /// This may return null in the WebSocket implementation due to incomplete user collection in + /// This may return in the WebSocket implementation due to incomplete user collection in /// large guilds. /// /// @@ -658,7 +785,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the guild user - /// associated with the specified ; null if none is found. + /// associated with the specified ; if none is found. /// Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// @@ -705,11 +832,12 @@ namespace Discord /// The number of days required for the users to be kicked. /// Whether this prune action is a simulation. /// The options to be used when sending the request. + /// An array of role IDs to be included in the prune of users who do not have any additional roles. /// /// A task that represents the asynchronous prune operation. The task result contains the number of users to /// be or has been removed from this guild. /// - Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null); + Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null, IEnumerable includeRoleIds = null); /// /// Gets a collection of users in this guild that the name or nickname starts with the /// provided at . @@ -751,7 +879,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the webhook with the - /// specified ; null if none is found. + /// specified ; if none is found. /// Task GetWebhookAsync(ulong id, RequestOptions options = null); /// @@ -771,7 +899,7 @@ namespace Discord /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the emote found with the - /// specified ; null if none is found. + /// specified ; if none is found. /// Task GetEmoteAsync(ulong id, RequestOptions options = null); /// diff --git a/src/Discord.Net.Core/Entities/IApplication.cs b/src/Discord.Net.Core/Entities/IApplication.cs index 78a87dc19..2174baff9 100644 --- a/src/Discord.Net.Core/Entities/IApplication.cs +++ b/src/Discord.Net.Core/Entities/IApplication.cs @@ -22,6 +22,18 @@ namespace Discord /// Gets the icon URL of the application. /// string IconUrl { get; } + /// + /// Gets if the bot is public. + /// + bool IsBotPublic { get; } + /// + /// Gets if the bot requires code grant. + /// + bool BotRequiresCodeGrant { get; } + /// + /// Gets the team associated with this application if there is one. + /// + ITeam Team { get; } /// /// Gets the partial user object containing info on the owner of the application. diff --git a/src/Discord.Net.Core/Entities/IUpdateable.cs b/src/Discord.Net.Core/Entities/IUpdateable.cs index 3ae4613f5..d561e57a6 100644 --- a/src/Discord.Net.Core/Entities/IUpdateable.cs +++ b/src/Discord.Net.Core/Entities/IUpdateable.cs @@ -10,6 +10,7 @@ namespace Discord /// /// Updates this object's properties with its current state. /// + /// The options to be used when sending the request. Task UpdateAsync(RequestOptions options = null); } } diff --git a/src/Discord.Net.Core/Entities/Invites/IInvite.cs b/src/Discord.Net.Core/Entities/Invites/IInvite.cs index 993f1f047..47ffffacb 100644 --- a/src/Discord.Net.Core/Entities/Invites/IInvite.cs +++ b/src/Discord.Net.Core/Entities/Invites/IInvite.cs @@ -20,6 +20,13 @@ namespace Discord /// string Url { get; } + /// + /// Gets the user that created this invite. + /// + /// + /// A user that created this invite. + /// + IUser Inviter { get; } /// /// Gets the channel this invite is linked to. /// @@ -83,5 +90,19 @@ namespace Discord /// invite points to; null if one cannot be obtained. /// int? MemberCount { get; } + /// + /// Gets the user this invite is linked to via . + /// + /// + /// A user that is linked to this invite. + /// + IUser TargetUser { get; } + /// + /// Gets the type of the linked for this invite. + /// + /// + /// The type of the linked user that is linked to this invite. + /// + TargetUserType TargetUserType { get; } } } diff --git a/src/Discord.Net.Core/Entities/Invites/IInviteMetadata.cs b/src/Discord.Net.Core/Entities/Invites/IInviteMetadata.cs index 471dc377f..c64b3205b 100644 --- a/src/Discord.Net.Core/Entities/Invites/IInviteMetadata.cs +++ b/src/Discord.Net.Core/Entities/Invites/IInviteMetadata.cs @@ -8,28 +8,22 @@ namespace Discord public interface IInviteMetadata : IInvite { /// - /// Gets the user that created this invite. + /// Gets a value that indicates whether the invite is a temporary one. /// /// - /// A user that created this invite. + /// true if users accepting this invite will be removed from the guild when they log off; otherwise + /// false. /// - IUser Inviter { get; } + bool IsTemporary { get; } /// /// Gets a value that indicates whether the invite has been revoked. /// /// /// true if this invite was revoked; otherwise false. /// + [Obsolete("This property doesn't exist anymore and shouldn't be used.")] bool IsRevoked { get; } /// - /// Gets a value that indicates whether the invite is a temporary one. - /// - /// - /// true if users accepting this invite will be removed from the guild when they log off; otherwise - /// false. - /// - bool IsTemporary { get; } - /// /// Gets the time (in seconds) until the invite expires. /// /// diff --git a/src/Discord.Net.Core/Entities/Invites/TargetUserType.cs b/src/Discord.Net.Core/Entities/Invites/TargetUserType.cs new file mode 100644 index 000000000..74263b888 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Invites/TargetUserType.cs @@ -0,0 +1,14 @@ +namespace Discord +{ + public enum TargetUserType + { + /// + /// The invite whose target user type is not defined. + /// + Undefined = 0, + /// + /// The invite is for a Go Live stream. + /// + Stream = 1 + } +} diff --git a/src/Discord.Net.Core/Entities/Messages/AllowedMentions.cs b/src/Discord.Net.Core/Entities/Messages/AllowedMentions.cs index d52feaa7d..0206ad7b1 100644 --- a/src/Discord.Net.Core/Entities/Messages/AllowedMentions.cs +++ b/src/Discord.Net.Core/Entities/Messages/AllowedMentions.cs @@ -49,6 +49,14 @@ namespace Discord /// public List UserIds { get; set; } = new List(); + /// + /// Gets or sets whether to mention the author of the message you are replying to or not. + /// + /// + /// Specifically for inline replies. + /// + public bool? MentionRepliedUser { get; set; } = null; + /// /// Initializes a new instance of the class. /// diff --git a/src/Discord.Net.Core/Entities/Messages/IMessage.cs b/src/Discord.Net.Core/Entities/Messages/IMessage.cs index 530c1cd82..80b1ffa68 100644 --- a/src/Discord.Net.Core/Entities/Messages/IMessage.cs +++ b/src/Discord.Net.Core/Entities/Messages/IMessage.cs @@ -39,6 +39,13 @@ namespace Discord /// bool IsSuppressed { get; } /// + /// Gets the value that indicates whether this message mentioned everyone. + /// + /// + /// true if this message mentioned everyone; otherwise false. + /// + bool MentionedEveryone { get; } + /// /// Gets the content for this message. /// /// @@ -85,10 +92,10 @@ namespace Discord /// Gets all embeds included in this message. /// /// - /// /// This property gets a read-only collection of embeds associated with this message. Depending on the /// message, a sent message may contain one or more embeds. This is usually true when multiple link previews /// are generated; however, only one can be featured. + /// /// /// A read-only collection of embed objects. /// @@ -141,11 +148,11 @@ namespace Discord MessageApplication Application { get; } /// - /// Gets the reference to the original message if it was crossposted. + /// Gets the reference to the original message if it is a crosspost, channel follow add, pin, or reply message. /// /// - /// Sent with Cross-posted messages, meaning they were published from news channels - /// and received by subscriber channels. + /// Sent with cross-posted messages, meaning they were published from news channels + /// and received by subscriber channels, channel follow adds, pins, and message replies. /// /// /// A message's reference, if any is associated. @@ -157,6 +164,17 @@ namespace Discord /// IReadOnlyDictionary Reactions { get; } + /// + /// Gets the flags related to this message. + /// + /// + /// This value is determined by bitwise OR-ing values together. + /// + /// + /// A message's flags, if any is associated. + /// + MessageFlags? Flags { get; } + /// /// Adds a reaction to this message. /// diff --git a/src/Discord.Net.Core/Entities/Messages/IUserMessage.cs b/src/Discord.Net.Core/Entities/Messages/IUserMessage.cs index e2fb25aae..1589e2ae5 100644 --- a/src/Discord.Net.Core/Entities/Messages/IUserMessage.cs +++ b/src/Discord.Net.Core/Entities/Messages/IUserMessage.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; namespace Discord @@ -9,6 +8,14 @@ namespace Discord /// public interface IUserMessage : IMessage { + /// + /// Gets the referenced message if it is a crosspost, channel follow add, pin, or reply message. + /// + /// + /// The referenced message, if any is associated and still exists. + /// + IUserMessage ReferencedMessage { get; } + /// /// Modifies this message. /// diff --git a/src/Discord.Net.Core/Entities/Messages/MessageFlags.cs b/src/Discord.Net.Core/Entities/Messages/MessageFlags.cs new file mode 100644 index 000000000..52d0f0e9e --- /dev/null +++ b/src/Discord.Net.Core/Entities/Messages/MessageFlags.cs @@ -0,0 +1,36 @@ +using System; + +namespace Discord +{ + [Flags] + public enum MessageFlags + { + /// + /// Default value for flags, when none are given to a message. + /// + None = 0, + /// + /// Flag given to messages that have been published to subscribed + /// channels (via Channel Following). + /// + Crossposted = 1 << 0, + /// + /// Flag given to messages that originated from a message in another + /// channel (via Channel Following). + /// + IsCrosspost = 1 << 1, + /// + /// Flag given to messages that do not display any embeds. + /// + SuppressEmbeds = 1 << 2, + /// + /// Flag given to messages that the source message for this crosspost + /// has been deleted (via Channel Following). + /// + SourceMessageDeleted = 1 << 3, + /// + /// Flag given to messages that came from the urgent message system. + /// + Urgent = 1 << 4, + } +} diff --git a/src/Discord.Net.Core/Entities/Messages/MessageProperties.cs b/src/Discord.Net.Core/Entities/Messages/MessageProperties.cs index b632d6a18..9504e04cb 100644 --- a/src/Discord.Net.Core/Entities/Messages/MessageProperties.cs +++ b/src/Discord.Net.Core/Entities/Messages/MessageProperties.cs @@ -21,5 +21,17 @@ namespace Discord /// Gets or sets the embed the message should display. /// public Optional Embed { get; set; } + /// + /// Gets or sets the flags of the message. + /// + /// + /// Only can be set/unset and you need to be + /// the author of the message. + /// + public Optional Flags { get; set; } + /// + /// Gets or sets the allowed mentions of the message. + /// + public Optional AllowedMentions { get; set; } } } diff --git a/src/Discord.Net.Core/Entities/Messages/MessageReference.cs b/src/Discord.Net.Core/Entities/Messages/MessageReference.cs index 57a508a7c..029910e56 100644 --- a/src/Discord.Net.Core/Entities/Messages/MessageReference.cs +++ b/src/Discord.Net.Core/Entities/Messages/MessageReference.cs @@ -3,7 +3,7 @@ using System.Diagnostics; namespace Discord { /// - /// Contains the IDs sent from a crossposted message. + /// Contains the IDs sent from a crossposted message or inline reply. /// [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class MessageReference @@ -16,13 +16,36 @@ namespace Discord /// /// Gets the Channel ID of the original message. /// - public ulong ChannelId { get; internal set; } + /// + /// It only will be the default value (zero) if it was instantiated with a in the constructor. + /// + public ulong ChannelId { get => InternalChannelId.GetValueOrDefault(); } + internal Optional InternalChannelId; /// /// Gets the Guild ID of the original message. /// public Optional GuildId { get; internal set; } + /// + /// Initializes a new instance of the class. + /// + /// + /// The ID of the message that will be referenced. Used to reply to specific messages and the only parameter required for it. + /// + /// + /// The ID of the channel that will be referenced. It will be validated if sent. + /// + /// + /// The ID of the guild that will be referenced. It will be validated if sent. + /// + public MessageReference(ulong? messageId = null, ulong? channelId = null, ulong? guildId = null) + { + MessageId = messageId ?? Optional.Create(); + InternalChannelId = channelId ?? Optional.Create(); + GuildId = guildId ?? Optional.Create(); + } + private string DebuggerDisplay => $"Channel ID: ({ChannelId}){(GuildId.IsSpecified ? $", Guild ID: ({GuildId.Value})" : "")}" + $"{(MessageId.IsSpecified ? $", Message ID: ({MessageId.Value})" : "")}"; diff --git a/src/Discord.Net.Core/Entities/Messages/MessageType.cs b/src/Discord.Net.Core/Entities/Messages/MessageType.cs index ee5f4fb4d..ad1f3a3cd 100644 --- a/src/Discord.Net.Core/Entities/Messages/MessageType.cs +++ b/src/Discord.Net.Core/Entities/Messages/MessageType.cs @@ -57,5 +57,12 @@ namespace Discord /// The message for when a news channel subscription is added to a text channel. /// ChannelFollowAdd = 12, + /// + /// The message is an inline reply. + /// + /// + /// Only available in API v8. + /// + Reply = 19, } } diff --git a/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs b/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs index 99885b070..ed675b5f3 100644 --- a/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs +++ b/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs @@ -17,7 +17,7 @@ namespace Discord /// Gets a that grants all permissions for category channels. public static readonly ChannelPermissions Category = new ChannelPermissions(0b01100_1111110_1111111110001_010001); /// Gets a that grants all permissions for direct message channels. - public static readonly ChannelPermissions DM = new ChannelPermissions(0b00000_1000110_1011100110000_000000); + public static readonly ChannelPermissions DM = new ChannelPermissions(0b00000_1000110_1011100110001_000000); /// Gets a that grants all permissions for group channels. public static readonly ChannelPermissions Group = new ChannelPermissions(0b00000_1000110_0001101100000_000000); /// Gets a that grants all permissions for a given channel type. diff --git a/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs b/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs index 3c8a5e810..645b67489 100644 --- a/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs +++ b/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs @@ -51,6 +51,10 @@ namespace Discord /// authentication when used on a guild that has server-wide 2FA enabled. /// ManageGuild = 0x00_00_00_20, + /// + /// Allows for viewing of guild insights + /// + ViewGuildInsights = 0x00_08_00_00, // Text /// diff --git a/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs b/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs index a5adad47c..ba6757fc6 100644 --- a/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs +++ b/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs @@ -12,7 +12,7 @@ namespace Discord /// Gets a that grants all guild permissions for webhook users. public static readonly GuildPermissions Webhook = new GuildPermissions(0b00000_0000000_0001101100000_000000); /// Gets a that grants all guild permissions. - public static readonly GuildPermissions All = new GuildPermissions(0b11111_1111110_1111111111111_111111); + public static readonly GuildPermissions All = new GuildPermissions(0b11111_1111111_1111111111111_111111); /// Gets a packed value representing all the permissions in this . public ulong RawValue { get; } @@ -34,6 +34,8 @@ namespace Discord public bool AddReactions => Permissions.GetValue(RawValue, GuildPermission.AddReactions); /// If true, a user may view the audit log. public bool ViewAuditLog => Permissions.GetValue(RawValue, GuildPermission.ViewAuditLog); + /// If true, a user may view the guild insights. + public bool ViewGuildInsights => Permissions.GetValue(RawValue, GuildPermission.ViewGuildInsights); /// If True, a user may join channels. [Obsolete("Use ViewChannel instead.")] @@ -97,6 +99,7 @@ namespace Discord bool? manageGuild = null, bool? addReactions = null, bool? viewAuditLog = null, + bool? viewGuildInsights = null, bool? viewChannel = null, bool? sendMessages = null, bool? sendTTSMessages = null, @@ -130,6 +133,7 @@ namespace Discord Permissions.SetValue(ref value, manageGuild, GuildPermission.ManageGuild); Permissions.SetValue(ref value, addReactions, GuildPermission.AddReactions); Permissions.SetValue(ref value, viewAuditLog, GuildPermission.ViewAuditLog); + Permissions.SetValue(ref value, viewGuildInsights, GuildPermission.ViewGuildInsights); Permissions.SetValue(ref value, viewChannel, GuildPermission.ViewChannel); Permissions.SetValue(ref value, sendMessages, GuildPermission.SendMessages); Permissions.SetValue(ref value, sendTTSMessages, GuildPermission.SendTTSMessages); @@ -166,6 +170,7 @@ namespace Discord bool manageGuild = false, bool addReactions = false, bool viewAuditLog = false, + bool viewGuildInsights = false, bool viewChannel = false, bool sendMessages = false, bool sendTTSMessages = false, @@ -198,6 +203,7 @@ namespace Discord manageGuild: manageGuild, addReactions: addReactions, viewAuditLog: viewAuditLog, + viewGuildInsights: viewGuildInsights, viewChannel: viewChannel, sendMessages: sendMessages, sendTTSMessages: sendTTSMessages, @@ -231,6 +237,7 @@ namespace Discord bool? manageGuild = null, bool? addReactions = null, bool? viewAuditLog = null, + bool? viewGuildInsights = null, bool? viewChannel = null, bool? sendMessages = null, bool? sendTTSMessages = null, @@ -254,7 +261,7 @@ namespace Discord bool? manageWebhooks = null, bool? manageEmojis = null) => new GuildPermissions(RawValue, createInstantInvite, kickMembers, banMembers, administrator, manageChannels, manageGuild, addReactions, - viewAuditLog, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, + viewAuditLog, viewGuildInsights, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers, moveMembers, useVoiceActivation, prioritySpeaker, stream, changeNickname, manageNicknames, manageRoles, manageWebhooks, manageEmojis); diff --git a/src/Discord.Net.Core/Entities/Permissions/OverwritePermissions.cs b/src/Discord.Net.Core/Entities/Permissions/OverwritePermissions.cs index 04bb2f668..7876d49ff 100644 --- a/src/Discord.Net.Core/Entities/Permissions/OverwritePermissions.cs +++ b/src/Discord.Net.Core/Entities/Permissions/OverwritePermissions.cs @@ -76,6 +76,10 @@ namespace Discord public PermValue MoveMembers => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.MoveMembers); /// If Allowed, a user may use voice-activity-detection rather than push-to-talk. public PermValue UseVAD => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.UseVAD); + /// If Allowed, a user may use priority speaker in a voice channel. + public PermValue PrioritySpeaker => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.PrioritySpeaker); + /// If Allowed, a user may go live in a voice channel. + public PermValue Stream => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.Stream); /// If Allowed, a user may adjust role permissions. This also implicitly grants all other permissions. public PermValue ManageRoles => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageRoles); @@ -109,7 +113,9 @@ namespace Discord PermValue? moveMembers = null, PermValue? useVoiceActivation = null, PermValue? manageRoles = null, - PermValue? manageWebhooks = null) + PermValue? manageWebhooks = null, + PermValue? prioritySpeaker = null, + PermValue? stream = null) { Permissions.SetValue(ref allowValue, ref denyValue, createInstantInvite, ChannelPermission.CreateInstantInvite); Permissions.SetValue(ref allowValue, ref denyValue, manageChannel, ChannelPermission.ManageChannels); @@ -129,6 +135,8 @@ namespace Discord Permissions.SetValue(ref allowValue, ref denyValue, deafenMembers, ChannelPermission.DeafenMembers); Permissions.SetValue(ref allowValue, ref denyValue, moveMembers, ChannelPermission.MoveMembers); Permissions.SetValue(ref allowValue, ref denyValue, useVoiceActivation, ChannelPermission.UseVAD); + Permissions.SetValue(ref allowValue, ref denyValue, prioritySpeaker, ChannelPermission.PrioritySpeaker); + Permissions.SetValue(ref allowValue, ref denyValue, stream, ChannelPermission.Stream); Permissions.SetValue(ref allowValue, ref denyValue, manageRoles, ChannelPermission.ManageRoles); Permissions.SetValue(ref allowValue, ref denyValue, manageWebhooks, ChannelPermission.ManageWebhooks); @@ -159,10 +167,12 @@ namespace Discord PermValue moveMembers = PermValue.Inherit, PermValue useVoiceActivation = PermValue.Inherit, PermValue manageRoles = PermValue.Inherit, - PermValue manageWebhooks = PermValue.Inherit) + PermValue manageWebhooks = PermValue.Inherit, + PermValue prioritySpeaker = PermValue.Inherit, + PermValue stream = PermValue.Inherit) : this(0, 0, createInstantInvite, manageChannel, addReactions, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers, - moveMembers, useVoiceActivation, manageRoles, manageWebhooks) { } + moveMembers, useVoiceActivation, manageRoles, manageWebhooks, prioritySpeaker, stream) { } /// /// Initializes a new from the current one, changing the provided @@ -188,10 +198,12 @@ namespace Discord PermValue? moveMembers = null, PermValue? useVoiceActivation = null, PermValue? manageRoles = null, - PermValue? manageWebhooks = null) + PermValue? manageWebhooks = null, + PermValue? prioritySpeaker = null, + PermValue? stream = null) => new OverwritePermissions(AllowValue, DenyValue, createInstantInvite, manageChannel, addReactions, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers, - moveMembers, useVoiceActivation, manageRoles, manageWebhooks); + moveMembers, useVoiceActivation, manageRoles, manageWebhooks, prioritySpeaker, stream); /// /// Creates a of all the values that are allowed. diff --git a/src/Discord.Net.Core/Entities/Roles/IRole.cs b/src/Discord.Net.Core/Entities/Roles/IRole.cs index 66556fc2c..c02322be9 100644 --- a/src/Discord.Net.Core/Entities/Roles/IRole.cs +++ b/src/Discord.Net.Core/Entities/Roles/IRole.cs @@ -65,6 +65,13 @@ namespace Discord /// An representing the position of the role in the role list of the guild. /// int Position { get; } + /// + /// Gets the tags related to this role. + /// + /// + /// A object containing all tags related to this role. + /// + RoleTags Tags { get; } /// /// Modifies this role. diff --git a/src/Discord.Net.Core/Entities/Roles/RoleTags.cs b/src/Discord.Net.Core/Entities/Roles/RoleTags.cs new file mode 100644 index 000000000..d0cbd3580 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Roles/RoleTags.cs @@ -0,0 +1,40 @@ +namespace Discord +{ + /// + /// Provides tags related to a discord role. + /// + public class RoleTags + { + /// + /// Gets the identifier of the bot that this role belongs to, if it does. + /// + /// + /// A if this role belongs to a bot; otherwise + /// . + /// + public ulong? BotId { get; } + /// + /// Gets the identifier of the integration that this role belongs to, if it does. + /// + /// + /// A if this role belongs to an integration; otherwise + /// . + /// + public ulong? IntegrationId { get; } + /// + /// Gets if this role is the guild's premium subscriber (booster) role. + /// + /// + /// if this role is the guild's premium subscriber role; + /// otherwise . + /// + public bool IsPremiumSubscriberRole { get; } + + internal RoleTags(ulong? botId, ulong? integrationId, bool isPremiumSubscriber) + { + BotId = botId; + IntegrationId = integrationId; + IsPremiumSubscriberRole = isPremiumSubscriber; + } + } +} diff --git a/src/Discord.Net.Core/Entities/Teams/ITeam.cs b/src/Discord.Net.Core/Entities/Teams/ITeam.cs new file mode 100644 index 000000000..5ef3e4253 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Teams/ITeam.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace Discord +{ + /// + /// Represents a Discord Team. + /// + public interface ITeam + { + /// + /// Gets the team icon url. + /// + string IconUrl { get; } + /// + /// Gets the team unique identifier. + /// + ulong Id { get; } + /// + /// Gets the members of this team. + /// + IReadOnlyList TeamMembers { get; } + /// + /// Gets the user identifier that owns this team. + /// + ulong OwnerUserId { get; } + } +} diff --git a/src/Discord.Net.Core/Entities/Teams/ITeamMember.cs b/src/Discord.Net.Core/Entities/Teams/ITeamMember.cs new file mode 100644 index 000000000..fe0e499e5 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Teams/ITeamMember.cs @@ -0,0 +1,25 @@ +namespace Discord +{ + /// + /// Represents a Discord Team member. + /// + public interface ITeamMember + { + /// + /// Gets the membership state of this team member. + /// + MembershipState MembershipState { get; } + /// + /// Gets the permissions of this team member. + /// + string[] Permissions { get; } + /// + /// Gets the team unique identifier for this team member. + /// + ulong TeamId { get; } + /// + /// Gets the Discord user of this team member. + /// + IUser User { get; } + } +} diff --git a/src/Discord.Net.Core/Entities/Teams/MembershipState.cs b/src/Discord.Net.Core/Entities/Teams/MembershipState.cs new file mode 100644 index 000000000..45b1693b0 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Teams/MembershipState.cs @@ -0,0 +1,11 @@ +namespace Discord +{ + /// + /// Represents the membership state of a team member. + /// + public enum MembershipState + { + Invited, + Accepted, + } +} diff --git a/src/Discord.Net.Core/Entities/Users/IGuildUser.cs b/src/Discord.Net.Core/Entities/Users/IGuildUser.cs index 92b146e05..582e9e7a7 100644 --- a/src/Discord.Net.Core/Entities/Users/IGuildUser.cs +++ b/src/Discord.Net.Core/Entities/Users/IGuildUser.cs @@ -68,12 +68,17 @@ namespace Discord /// IReadOnlyCollection RoleIds { get; } + /// + /// Whether the user has passed the guild's Membership Screening requirements. + /// + bool? IsPending { get; } + /// /// Gets the level permissions granted to this user to a given channel. /// /// /// The following example checks if the current user has the ability to send a message with attachment in - /// this channel; if so, uploads a file via . + /// this channel; if so, uploads a file via . /// /// if (currentUser?.GetPermissions(targetChannel)?.AttachFiles) /// await targetChannel.SendFileAsync("fortnite.png"); diff --git a/src/Discord.Net.Core/Entities/Users/IPresence.cs b/src/Discord.Net.Core/Entities/Users/IPresence.cs index 620eb907c..a17ac0df2 100644 --- a/src/Discord.Net.Core/Entities/Users/IPresence.cs +++ b/src/Discord.Net.Core/Entities/Users/IPresence.cs @@ -19,5 +19,9 @@ namespace Discord /// Gets the set of clients where this user is currently active. /// IImmutableSet ActiveClients { get; } + /// + /// Gets the list of activities that this user currently has available. + /// + IImmutableList Activities { get; } } } diff --git a/src/Discord.Net.Core/Entities/Users/IUser.cs b/src/Discord.Net.Core/Entities/Users/IUser.cs index c36fb2326..e6008aab6 100644 --- a/src/Discord.Net.Core/Entities/Users/IUser.cs +++ b/src/Discord.Net.Core/Entities/Users/IUser.cs @@ -75,6 +75,16 @@ namespace Discord /// Gets the username for this user. /// string Username { get; } + /// + /// Gets the public flags that are applied to this user's account. + /// + /// + /// This value is determined by bitwise OR-ing values together. + /// + /// + /// The value of public flags for this user. + /// + UserProperties? PublicFlags { get; } /// /// Gets the direct message channel of this user, or create one if it does not already exist. diff --git a/src/Discord.Net.Core/Entities/Users/UserProperties.cs b/src/Discord.Net.Core/Entities/Users/UserProperties.cs index 4f7272daa..b6deb744b 100644 --- a/src/Discord.Net.Core/Entities/Users/UserProperties.cs +++ b/src/Discord.Net.Core/Entities/Users/UserProperties.cs @@ -10,32 +10,62 @@ namespace Discord /// None = 0, /// - /// Flag given to Discord staff. + /// Flag given to users who are a Discord employee. /// - Staff = 0b1, + Staff = 1 << 0, /// - /// Flag given to Discord partners. + /// Flag given to users who are owners of a partnered Discord server. /// - Partner = 0b10, + Partner = 1 << 1, + /// + /// Flag given to users in HypeSquad events. + /// + HypeSquadEvents = 1 << 2, /// /// Flag given to users who have participated in the bug report program. + /// This flag is obsolete, use instead. + /// + [Obsolete("Use BugHunterLevel1 instead.")] + BugHunter = 1 << 3, + /// + /// Flag given to users who have participated in the bug report program and are level 1. /// - BugHunter = 0b1000, + BugHunterLevel1 = 1 << 3, /// /// Flag given to users who are in the HypeSquad House of Bravery. /// - HypeSquadBravery = 0b100_0000, + HypeSquadBravery = 1 << 6, /// /// Flag given to users who are in the HypeSquad House of Brilliance. /// - HypeSquadBrilliance = 0b1000_0000, + HypeSquadBrilliance = 1 << 7, /// /// Flag given to users who are in the HypeSquad House of Balance. /// - HypeSquadBalance = 0b1_0000_0000, + HypeSquadBalance = 1 << 8, /// /// Flag given to users who subscribed to Nitro before games were added. /// - EarlySupporter = 0b10_0000_0000, + EarlySupporter = 1 << 9, + /// + /// Flag given to users who are part of a team. + /// + TeamUser = 1 << 10, + /// + /// Flag given to users who represent Discord (System). + /// + System = 1 << 12, + /// + /// Flag given to users who have participated in the bug report program and are level 2. + /// + BugHunterLevel2 = 1 << 14, + /// + /// Flag given to users who are verified bots. + /// + VerifiedBot = 1 << 16, + /// + /// Flag given to users that developed bots and early verified their accounts. + /// + EarlyVerifiedBotDeveloper = 1 << 17, } } diff --git a/src/Discord.Net.Core/Extensions/MessageExtensions.cs b/src/Discord.Net.Core/Extensions/MessageExtensions.cs index 64a1d89ab..b043d7b77 100644 --- a/src/Discord.Net.Core/Extensions/MessageExtensions.cs +++ b/src/Discord.Net.Core/Extensions/MessageExtensions.cs @@ -17,7 +17,7 @@ namespace Discord public static string GetJumpUrl(this IMessage msg) { var channel = msg.Channel; - return $"https://discordapp.com/channels/{(channel is IDMChannel ? "@me" : $"{(channel as ITextChannel).GuildId}")}/{channel.Id}/{msg.Id}"; + return $"https://discord.com/channels/{(channel is IDMChannel ? "@me" : $"{(channel as ITextChannel).GuildId}")}/{channel.Id}/{msg.Id}"; } /// @@ -71,5 +71,25 @@ namespace Discord foreach (var rxn in reactions) await msg.RemoveReactionAsync(rxn, user, options).ConfigureAwait(false); } + + /// + /// Sends an inline reply that references a message. + /// + /// The message to be sent. + /// Determines whether the message should be read aloud by Discord or not. + /// The to be sent. + /// + /// Specifies if notifications are sent for mentioned users and roles in the message . + /// If null, all mentioned roles and users will be notified. + /// + /// The options to be used when sending the request. + /// + /// A task that represents an asynchronous send operation for delivering the message. The task result + /// contains the sent message. + /// + public static async Task ReplyAsync(this IUserMessage msg, string text = null, bool isTTS = false, Embed embed = null, AllowedMentions allowedMentions = null, RequestOptions options = null) + { + return await msg.Channel.SendMessageAsync(text, isTTS, embed, options, allowedMentions, new MessageReference(messageId: msg.Id)).ConfigureAwait(false); + } } } diff --git a/src/Discord.Net.Core/IDiscordClient.cs b/src/Discord.Net.Core/IDiscordClient.cs index f972cd71d..d7d6d2856 100644 --- a/src/Discord.Net.Core/IDiscordClient.cs +++ b/src/Discord.Net.Core/IDiscordClient.cs @@ -274,5 +274,15 @@ namespace Discord /// that represents the number of shards that should be used with this account. /// Task GetRecommendedShardCountAsync(RequestOptions options = null); + + /// + /// Gets the gateway information related to the bot. + /// + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains a + /// that represents the gateway information related to the bot. + /// + Task GetBotGatewayAsync(RequestOptions options = null); } } diff --git a/src/Discord.Net.Core/Net/BucketId.cs b/src/Discord.Net.Core/Net/BucketId.cs new file mode 100644 index 000000000..96281a0ed --- /dev/null +++ b/src/Discord.Net.Core/Net/BucketId.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace Discord.Net +{ + /// + /// Represents a ratelimit bucket. + /// + public class BucketId : IEquatable + { + /// + /// Gets the http method used to make the request if available. + /// + public string HttpMethod { get; } + /// + /// Gets the endpoint that is going to be requested if available. + /// + public string Endpoint { get; } + /// + /// Gets the major parameters of the route. + /// + public IOrderedEnumerable> MajorParameters { get; } + /// + /// Gets the hash of this bucket. + /// + /// + /// The hash is provided by Discord to group ratelimits. + /// + public string BucketHash { get; } + /// + /// Gets if this bucket is a hash type. + /// + public bool IsHashBucket { get => BucketHash != null; } + + private BucketId(string httpMethod, string endpoint, IEnumerable> majorParameters, string bucketHash) + { + HttpMethod = httpMethod; + Endpoint = endpoint; + MajorParameters = majorParameters.OrderBy(x => x.Key); + BucketHash = bucketHash; + } + + /// + /// Creates a new based on the + /// and . + /// + /// Http method used to make the request. + /// Endpoint that is going to receive requests. + /// Major parameters of the route of this endpoint. + /// + /// A based on the + /// and the with the provided data. + /// + public static BucketId Create(string httpMethod, string endpoint, Dictionary majorParams) + { + Preconditions.NotNullOrWhitespace(endpoint, nameof(endpoint)); + majorParams ??= new Dictionary(); + return new BucketId(httpMethod, endpoint, majorParams, null); + } + + /// + /// Creates a new based on a + /// and a previous . + /// + /// Bucket hash provided by Discord. + /// that is going to be upgraded to a hash type. + /// + /// A based on the + /// and . + /// + public static BucketId Create(string hash, BucketId oldBucket) + { + Preconditions.NotNullOrWhitespace(hash, nameof(hash)); + Preconditions.NotNull(oldBucket, nameof(oldBucket)); + return new BucketId(null, null, oldBucket.MajorParameters, hash); + } + + /// + /// Gets the string that will define this bucket as a hash based one. + /// + /// + /// A that defines this bucket as a hash based one. + /// + public string GetBucketHash() + => IsHashBucket ? $"{BucketHash}:{string.Join("/", MajorParameters.Select(x => x.Value))}" : null; + + /// + /// Gets the string that will define this bucket as an endpoint based one. + /// + /// + /// A that defines this bucket as an endpoint based one. + /// + public string GetUniqueEndpoint() + => HttpMethod != null ? $"{HttpMethod} {Endpoint}" : Endpoint; + + public override bool Equals(object obj) + => Equals(obj as BucketId); + + public override int GetHashCode() + => IsHashBucket ? (BucketHash, string.Join("/", MajorParameters.Select(x => x.Value))).GetHashCode() : (HttpMethod, Endpoint).GetHashCode(); + + public override string ToString() + => GetBucketHash() ?? GetUniqueEndpoint(); + + public bool Equals(BucketId other) + { + if (other is null) + return false; + if (ReferenceEquals(this, other)) + return true; + if (GetType() != other.GetType()) + return false; + return ToString() == other.ToString(); + } + } +} diff --git a/src/Discord.Net.Core/Net/HttpException.cs b/src/Discord.Net.Core/Net/HttpException.cs index d36bd66f9..ff9cf91f2 100644 --- a/src/Discord.Net.Core/Net/HttpException.cs +++ b/src/Discord.Net.Core/Net/HttpException.cs @@ -13,7 +13,7 @@ namespace Discord.Net /// /// /// An - /// HTTP status code + /// HTTP status code /// from Discord. /// public HttpStatusCode HttpCode { get; } @@ -22,7 +22,7 @@ namespace Discord.Net /// /// /// A - /// JSON error code + /// JSON error code /// from Discord, or null if none. /// public int? DiscordCode { get; } diff --git a/src/Discord.Net.Core/Net/WebSocketClosedException.cs b/src/Discord.Net.Core/Net/WebSocketClosedException.cs index 6e2564f6e..c743cd696 100644 --- a/src/Discord.Net.Core/Net/WebSocketClosedException.cs +++ b/src/Discord.Net.Core/Net/WebSocketClosedException.cs @@ -11,7 +11,7 @@ namespace Discord.Net /// /// /// A - /// close code + /// close code /// from Discord. /// public int CloseCode { get; } diff --git a/src/Discord.Net.Core/RequestOptions.cs b/src/Discord.Net.Core/RequestOptions.cs index 1b05df2a3..dbb240273 100644 --- a/src/Discord.Net.Core/RequestOptions.cs +++ b/src/Discord.Net.Core/RequestOptions.cs @@ -1,3 +1,4 @@ +using Discord.Net; using System.Threading; namespace Discord @@ -57,9 +58,10 @@ namespace Discord public bool? UseSystemClock { get; set; } internal bool IgnoreState { get; set; } - internal string BucketId { get; set; } + internal BucketId BucketId { get; set; } internal bool IsClientBucket { get; set; } internal bool IsReactionBucket { get; set; } + internal bool IsGatewayBucket { get; set; } internal static RequestOptions CreateOrClone(RequestOptions options) { diff --git a/src/Discord.Net.Rest/Entities/Messages/AllowedMentions.cs b/src/Discord.Net.Rest/API/Common/AllowedMentions.cs similarity index 73% rename from src/Discord.Net.Rest/Entities/Messages/AllowedMentions.cs rename to src/Discord.Net.Rest/API/Common/AllowedMentions.cs index 5ab96032f..7737a464f 100644 --- a/src/Discord.Net.Rest/Entities/Messages/AllowedMentions.cs +++ b/src/Discord.Net.Rest/API/Common/AllowedMentions.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; namespace Discord.API { - public class AllowedMentions + internal class AllowedMentions { [JsonProperty("parse")] public Optional Parse { get; set; } @@ -11,5 +11,7 @@ namespace Discord.API public Optional Roles { get; set; } [JsonProperty("users")] public Optional Users { get; set; } + [JsonProperty("replied_user")] + public Optional RepliedUser { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/Application.cs b/src/Discord.Net.Rest/API/Common/Application.cs index ca4c443f1..aba3e524b 100644 --- a/src/Discord.Net.Rest/API/Common/Application.cs +++ b/src/Discord.Net.Rest/API/Common/Application.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API @@ -15,6 +15,12 @@ namespace Discord.API public ulong Id { get; set; } [JsonProperty("icon")] public string Icon { get; set; } + [JsonProperty("bot_public")] + public bool IsBotPublic { get; set; } + [JsonProperty("bot_require_code_grant")] + public bool BotRequiresCodeGrant { get; set; } + [JsonProperty("team")] + public Team Team { get; set; } [JsonProperty("flags"), Int53] public Optional Flags { get; set; } diff --git a/src/Discord.Net.Rest/API/Common/Guild.cs b/src/Discord.Net.Rest/API/Common/Guild.cs index 56bd841ea..46075ce4d 100644 --- a/src/Discord.Net.Rest/API/Common/Guild.cs +++ b/src/Discord.Net.Rest/API/Common/Guild.cs @@ -13,6 +13,8 @@ namespace Discord.API public string Icon { get; set; } [JsonProperty("splash")] public string Splash { get; set; } + [JsonProperty("discovery_splash")] + public string DiscoverySplash { get; set; } [JsonProperty("owner_id")] public ulong OwnerId { get; set; } [JsonProperty("region")] @@ -22,9 +24,9 @@ namespace Discord.API [JsonProperty("afk_timeout")] public int AFKTimeout { get; set; } [JsonProperty("embed_enabled")] - public bool EmbedEnabled { get; set; } + public Optional EmbedEnabled { get; set; } [JsonProperty("embed_channel_id")] - public ulong? EmbedChannelId { get; set; } + public Optional EmbedChannelId { get; set; } [JsonProperty("verification_level")] public VerificationLevel VerificationLevel { get; set; } [JsonProperty("default_message_notifications")] @@ -43,6 +45,10 @@ namespace Discord.API public MfaLevel MfaLevel { get; set; } [JsonProperty("application_id")] public ulong? ApplicationId { get; set; } + [JsonProperty("widget_enabled")] + public Optional WidgetEnabled { get; set; } + [JsonProperty("widget_channel_id")] + public Optional WidgetChannelId { get; set; } [JsonProperty("system_channel_id")] public ulong? SystemChannelId { get; set; } [JsonProperty("premium_tier")] @@ -56,9 +62,23 @@ namespace Discord.API // this value is inverted, flags set will turn OFF features [JsonProperty("system_channel_flags")] public SystemChannelMessageDeny SystemChannelFlags { get; set; } + [JsonProperty("rules_channel_id")] + public ulong? RulesChannelId { get; set; } + [JsonProperty("max_presences")] + public Optional MaxPresences { get; set; } + [JsonProperty("max_members")] + public Optional MaxMembers { get; set; } [JsonProperty("premium_subscription_count")] public int? PremiumSubscriptionCount { get; set; } [JsonProperty("preferred_locale")] public string PreferredLocale { get; set; } + [JsonProperty("public_updates_channel_id")] + public ulong? PublicUpdatesChannelId { get; set; } + [JsonProperty("max_video_channel_users")] + public Optional MaxVideoChannelUsers { get; set; } + [JsonProperty("approximate_member_count")] + public Optional ApproximateMemberCount { get; set; } + [JsonProperty("approximate_presence_count")] + public Optional ApproximatePresenceCount { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/GuildEmbed.cs b/src/Discord.Net.Rest/API/Common/GuildEmbed.cs index ff8b8e180..d81632181 100644 --- a/src/Discord.Net.Rest/API/Common/GuildEmbed.cs +++ b/src/Discord.Net.Rest/API/Common/GuildEmbed.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API @@ -8,6 +8,6 @@ namespace Discord.API [JsonProperty("enabled")] public bool Enabled { get; set; } [JsonProperty("channel_id")] - public ulong ChannelId { get; set; } + public ulong? ChannelId { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/GuildMember.cs b/src/Discord.Net.Rest/API/Common/GuildMember.cs index 940eb925a..fc2092d6c 100644 --- a/src/Discord.Net.Rest/API/Common/GuildMember.cs +++ b/src/Discord.Net.Rest/API/Common/GuildMember.cs @@ -18,6 +18,8 @@ namespace Discord.API public Optional Deaf { get; set; } [JsonProperty("mute")] public Optional Mute { get; set; } + [JsonProperty("pending")] + public Optional Pending { get; set; } [JsonProperty("premium_since")] public Optional PremiumSince { get; set; } } diff --git a/src/Discord.Net.Rest/API/Common/GuildWidget.cs b/src/Discord.Net.Rest/API/Common/GuildWidget.cs new file mode 100644 index 000000000..c15ad8aac --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/GuildWidget.cs @@ -0,0 +1,13 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API +{ + internal class GuildWidget + { + [JsonProperty("enabled")] + public bool Enabled { get; set; } + [JsonProperty("channel_id")] + public ulong? ChannelId { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Common/Invite.cs b/src/Discord.Net.Rest/API/Common/Invite.cs index 649bc37ec..aba267f34 100644 --- a/src/Discord.Net.Rest/API/Common/Invite.cs +++ b/src/Discord.Net.Rest/API/Common/Invite.cs @@ -11,9 +11,15 @@ namespace Discord.API public Optional Guild { get; set; } [JsonProperty("channel")] public InviteChannel Channel { get; set; } + [JsonProperty("inviter")] + public Optional Inviter { get; set; } [JsonProperty("approximate_presence_count")] public Optional PresenceCount { get; set; } [JsonProperty("approximate_member_count")] public Optional MemberCount { get; set; } + [JsonProperty("target_user")] + public Optional TargetUser { get; set; } + [JsonProperty("target_user_type")] + public Optional TargetUserType { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/InviteMetadata.cs b/src/Discord.Net.Rest/API/Common/InviteMetadata.cs index ca019b79b..f818de699 100644 --- a/src/Discord.Net.Rest/API/Common/InviteMetadata.cs +++ b/src/Discord.Net.Rest/API/Common/InviteMetadata.cs @@ -6,19 +6,15 @@ namespace Discord.API { internal class InviteMetadata : Invite { - [JsonProperty("inviter")] - public User Inviter { get; set; } [JsonProperty("uses")] - public Optional Uses { get; set; } + public int Uses { get; set; } [JsonProperty("max_uses")] - public Optional MaxUses { get; set; } + public int MaxUses { get; set; } [JsonProperty("max_age")] - public Optional MaxAge { get; set; } + public int MaxAge { get; set; } [JsonProperty("temporary")] public bool Temporary { get; set; } [JsonProperty("created_at")] - public Optional CreatedAt { get; set; } - [JsonProperty("revoked")] - public bool Revoked { get; set; } + public DateTimeOffset CreatedAt { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/MembershipState.cs b/src/Discord.Net.Rest/API/Common/MembershipState.cs new file mode 100644 index 000000000..67fcc8908 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/MembershipState.cs @@ -0,0 +1,9 @@ +namespace Discord.API +{ + internal enum MembershipState + { + None = 0, + Invited = 1, + Accepted = 2, + } +} diff --git a/src/Discord.Net.Rest/API/Common/Message.cs b/src/Discord.Net.Rest/API/Common/Message.cs index b4529d457..b781de346 100644 --- a/src/Discord.Net.Rest/API/Common/Message.cs +++ b/src/Discord.Net.Rest/API/Common/Message.cs @@ -56,5 +56,7 @@ namespace Discord.API public Optional Flags { get; set; } [JsonProperty("allowed_mentions")] public Optional AllowedMentions { get; set; } + [JsonProperty("referenced_message")] + public Optional ReferencedMessage { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/MessageFlags.cs b/src/Discord.Net.Rest/API/Common/MessageFlags.cs deleted file mode 100644 index ebe4e80ca..000000000 --- a/src/Discord.Net.Rest/API/Common/MessageFlags.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace Discord.API -{ - [Flags] - internal enum MessageFlags : byte // probably safe to constrain this to 8 values, if not, it's internal so who cares - { - Suppressed = 0x04, - } -} diff --git a/src/Discord.Net.Rest/API/Common/MessageReference.cs b/src/Discord.Net.Rest/API/Common/MessageReference.cs index 8c0f8fe14..6cc7603e0 100644 --- a/src/Discord.Net.Rest/API/Common/MessageReference.cs +++ b/src/Discord.Net.Rest/API/Common/MessageReference.cs @@ -8,7 +8,7 @@ namespace Discord.API public Optional MessageId { get; set; } [JsonProperty("channel_id")] - public ulong ChannelId { get; set; } + public Optional ChannelId { get; set; } // Optional when sending, always present when receiving [JsonProperty("guild_id")] public Optional GuildId { get; set; } diff --git a/src/Discord.Net.Rest/API/Common/Presence.cs b/src/Discord.Net.Rest/API/Common/Presence.cs index 22526e8ac..b37ad4229 100644 --- a/src/Discord.Net.Rest/API/Common/Presence.cs +++ b/src/Discord.Net.Rest/API/Common/Presence.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 using Newtonsoft.Json; +using System; using System.Collections.Generic; namespace Discord.API @@ -26,5 +27,9 @@ namespace Discord.API // "client_status": { "desktop": "dnd", "mobile": "dnd" } [JsonProperty("client_status")] public Optional> ClientStatus { get; set; } + [JsonProperty("activities")] + public List Activities { get; set; } + [JsonProperty("premium_since")] + public Optional PremiumSince { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/Role.cs b/src/Discord.Net.Rest/API/Common/Role.cs index 856a8695f..190ae25c0 100644 --- a/src/Discord.Net.Rest/API/Common/Role.cs +++ b/src/Discord.Net.Rest/API/Common/Role.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API @@ -21,5 +21,7 @@ namespace Discord.API public ulong Permissions { get; set; } [JsonProperty("managed")] public bool Managed { get; set; } + [JsonProperty("tags")] + public Optional Tags { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Common/RoleTags.cs b/src/Discord.Net.Rest/API/Common/RoleTags.cs new file mode 100644 index 000000000..6446f2037 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/RoleTags.cs @@ -0,0 +1,15 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API +{ + internal class RoleTags + { + [JsonProperty("bot_id")] + public Optional BotId { get; set; } + [JsonProperty("integration_id")] + public Optional IntegrationId { get; set; } + [JsonProperty("premium_subscriber")] + public Optional IsPremiumSubscriber { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Common/SessionStartLimit.cs b/src/Discord.Net.Rest/API/Common/SessionStartLimit.cs new file mode 100644 index 000000000..29d5ddf85 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/SessionStartLimit.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json; + +namespace Discord.API.Rest +{ + internal class SessionStartLimit + { + [JsonProperty("total")] + public int Total { get; set; } + [JsonProperty("remaining")] + public int Remaining { get; set; } + [JsonProperty("reset_after")] + public int ResetAfter { get; set; } + [JsonProperty("max_concurrency")] + public int MaxConcurrency { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Common/Team.cs b/src/Discord.Net.Rest/API/Common/Team.cs new file mode 100644 index 000000000..4910f43f7 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/Team.cs @@ -0,0 +1,17 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API +{ + internal class Team + { + [JsonProperty("icon")] + public Optional Icon { get; set; } + [JsonProperty("id")] + public ulong Id { get; set; } + [JsonProperty("members")] + public TeamMember[] TeamMembers { get; set; } + [JsonProperty("owner_user_id")] + public ulong OwnerUserId { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Common/TeamMember.cs b/src/Discord.Net.Rest/API/Common/TeamMember.cs new file mode 100644 index 000000000..788f73b61 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/TeamMember.cs @@ -0,0 +1,17 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API +{ + internal class TeamMember + { + [JsonProperty("membership_state")] + public MembershipState MembershipState { get; set; } + [JsonProperty("permissions")] + public string[] Permissions { get; set; } + [JsonProperty("team_id")] + public ulong TeamId { get; set; } + [JsonProperty("user")] + public User User { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Common/User.cs b/src/Discord.Net.Rest/API/Common/User.cs index 2eff3753d..d1f436afb 100644 --- a/src/Discord.Net.Rest/API/Common/User.cs +++ b/src/Discord.Net.Rest/API/Common/User.cs @@ -29,5 +29,7 @@ namespace Discord.API public Optional PremiumType { get; set; } [JsonProperty("locale")] public Optional Locale { get; set; } + [JsonProperty("public_flags")] + public Optional PublicFlags { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Rest/CreateGuildChannelParams.cs b/src/Discord.Net.Rest/API/Rest/CreateGuildChannelParams.cs index a102bd38d..aec43dbef 100644 --- a/src/Discord.Net.Rest/API/Rest/CreateGuildChannelParams.cs +++ b/src/Discord.Net.Rest/API/Rest/CreateGuildChannelParams.cs @@ -14,12 +14,16 @@ namespace Discord.API.Rest public Optional CategoryId { get; set; } [JsonProperty("position")] public Optional Position { get; set; } + [JsonProperty("permission_overwrites")] + public Optional Overwrites { get; set; } //Text channels [JsonProperty("topic")] public Optional Topic { get; set; } [JsonProperty("nsfw")] public Optional IsNsfw { get; set; } + [JsonProperty("rate_limit_per_user")] + public Optional SlowModeInterval { get; set; } //Voice channels [JsonProperty("bitrate")] diff --git a/src/Discord.Net.Rest/API/Rest/CreateMessageParams.cs b/src/Discord.Net.Rest/API/Rest/CreateMessageParams.cs index 4b56658d6..e64532864 100644 --- a/src/Discord.Net.Rest/API/Rest/CreateMessageParams.cs +++ b/src/Discord.Net.Rest/API/Rest/CreateMessageParams.cs @@ -17,6 +17,8 @@ namespace Discord.API.Rest public Optional Embed { get; set; } [JsonProperty("allowed_mentions")] public Optional AllowedMentions { get; set; } + [JsonProperty("message_reference")] + public Optional MessageReference { get; set; } public CreateMessageParams(string content) { diff --git a/src/Discord.Net.Rest/API/Rest/CreateWebhookMessageParams.cs b/src/Discord.Net.Rest/API/Rest/CreateWebhookMessageParams.cs index 970a30201..0a4f80a3c 100644 --- a/src/Discord.Net.Rest/API/Rest/CreateWebhookMessageParams.cs +++ b/src/Discord.Net.Rest/API/Rest/CreateWebhookMessageParams.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API.Rest @@ -19,6 +19,8 @@ namespace Discord.API.Rest public Optional Username { get; set; } [JsonProperty("avatar_url")] public Optional AvatarUrl { get; set; } + [JsonProperty("allowed_mentions")] + public Optional AllowedMentions { get; set; } public CreateWebhookMessageParams(string content) { diff --git a/src/Discord.Net.Rest/API/Rest/GetBotGatewayResponse.cs b/src/Discord.Net.Rest/API/Rest/GetBotGatewayResponse.cs index 111fcf3db..d3285051b 100644 --- a/src/Discord.Net.Rest/API/Rest/GetBotGatewayResponse.cs +++ b/src/Discord.Net.Rest/API/Rest/GetBotGatewayResponse.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API.Rest @@ -9,5 +9,7 @@ namespace Discord.API.Rest public string Url { get; set; } [JsonProperty("shards")] public int Shards { get; set; } + [JsonProperty("session_start_limit")] + public SessionStartLimit SessionStartLimit { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs b/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs index 6a98d3758..e4c9192ad 100644 --- a/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs +++ b/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs @@ -9,9 +9,13 @@ namespace Discord.API.Rest [JsonProperty("days")] public int Days { get; } - public GuildPruneParams(int days) + [JsonProperty("include_roles")] + public ulong[] IncludeRoleIds { get; } + + public GuildPruneParams(int days, ulong[] includeRoleIds) { Days = days; + IncludeRoleIds = includeRoleIds; } } } diff --git a/src/Discord.Net.Rest/API/Rest/ModifyGuildWidgetParams.cs b/src/Discord.Net.Rest/API/Rest/ModifyGuildWidgetParams.cs new file mode 100644 index 000000000..506f1dfbb --- /dev/null +++ b/src/Discord.Net.Rest/API/Rest/ModifyGuildWidgetParams.cs @@ -0,0 +1,14 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API.Rest +{ + [JsonObject(MemberSerialization = MemberSerialization.OptIn)] + internal class ModifyGuildWidgetParams + { + [JsonProperty("enabled")] + public Optional Enabled { get; set; } + [JsonProperty("channel")] + public Optional ChannelId { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Rest/ModifyMessageParams.cs b/src/Discord.Net.Rest/API/Rest/ModifyMessageParams.cs index fdff4de15..3752df3a2 100644 --- a/src/Discord.Net.Rest/API/Rest/ModifyMessageParams.cs +++ b/src/Discord.Net.Rest/API/Rest/ModifyMessageParams.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API.Rest @@ -10,5 +10,9 @@ namespace Discord.API.Rest public Optional Content { get; set; } [JsonProperty("embed")] public Optional Embed { get; set; } + [JsonProperty("flags")] + public Optional Flags { get; set; } + [JsonProperty("allowed_mentions")] + public Optional AllowedMentions { get; set; } } } diff --git a/src/Discord.Net.Rest/API/Rest/UploadFileParams.cs b/src/Discord.Net.Rest/API/Rest/UploadFileParams.cs index 64535e6d7..dd442a6de 100644 --- a/src/Discord.Net.Rest/API/Rest/UploadFileParams.cs +++ b/src/Discord.Net.Rest/API/Rest/UploadFileParams.cs @@ -20,6 +20,7 @@ namespace Discord.API.Rest public Optional IsTTS { get; set; } public Optional Embed { get; set; } public Optional AllowedMentions { get; set; } + public Optional MessageReference { get; set; } public bool IsSpoiler { get; set; } = false; public UploadFileParams(Stream file) @@ -48,6 +49,8 @@ namespace Discord.API.Rest payload["allowed_mentions"] = AllowedMentions.Value; if (IsSpoiler) payload["hasSpoiler"] = IsSpoiler.ToString(); + if (MessageReference.IsSpecified) + payload["message_reference"] = MessageReference.Value; var json = new StringBuilder(); using (var text = new StringWriter(json)) diff --git a/src/Discord.Net.Rest/API/Rest/UploadWebhookFileParams.cs b/src/Discord.Net.Rest/API/Rest/UploadWebhookFileParams.cs index 26153c21b..8da7681ae 100644 --- a/src/Discord.Net.Rest/API/Rest/UploadWebhookFileParams.cs +++ b/src/Discord.Net.Rest/API/Rest/UploadWebhookFileParams.cs @@ -21,6 +21,7 @@ namespace Discord.API.Rest public Optional Username { get; set; } public Optional AvatarUrl { get; set; } public Optional Embeds { get; set; } + public Optional AllowedMentions { get; set; } public bool IsSpoiler { get; set; } = false; @@ -51,6 +52,8 @@ namespace Discord.API.Rest payload["avatar_url"] = AvatarUrl.Value; if (Embeds.IsSpecified) payload["embeds"] = Embeds.Value; + if (AllowedMentions.IsSpecified) + payload["allowed_mentions"] = AllowedMentions.Value; var json = new StringBuilder(); using (var text = new StringWriter(json)) diff --git a/src/Discord.Net.Rest/BaseDiscordClient.cs b/src/Discord.Net.Rest/BaseDiscordClient.cs index 1837e38c0..68589a4f1 100644 --- a/src/Discord.Net.Rest/BaseDiscordClient.cs +++ b/src/Discord.Net.Rest/BaseDiscordClient.cs @@ -46,12 +46,12 @@ namespace Discord.Rest _restLogger = LogManager.CreateLogger("Rest"); _isFirstLogin = config.DisplayInitialLog; - ApiClient.RequestQueue.RateLimitTriggered += async (id, info) => + ApiClient.RequestQueue.RateLimitTriggered += async (id, info, endpoint) => { if (info == null) - await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {id ?? "null"}").ConfigureAwait(false); + await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); else - await _restLogger.WarningAsync($"Rate limit triggered: {id ?? "null"}").ConfigureAwait(false); + await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); }; ApiClient.SentRequest += async (method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false); } @@ -152,6 +152,10 @@ namespace Discord.Rest public Task GetRecommendedShardCountAsync(RequestOptions options = null) => ClientHelper.GetRecommendShardCountAsync(this, options); + /// + public Task GetBotGatewayAsync(RequestOptions options = null) + => ClientHelper.GetBotGatewayAsync(this, options); + //IDiscordClient /// ConnectionState IDiscordClient.ConnectionState => ConnectionState.Disconnected; diff --git a/src/Discord.Net.Rest/ClientHelper.cs b/src/Discord.Net.Rest/ClientHelper.cs index a8f6b58ef..8910e999a 100644 --- a/src/Discord.Net.Rest/ClientHelper.cs +++ b/src/Discord.Net.Rest/ClientHelper.cs @@ -62,9 +62,9 @@ namespace Discord.Rest } public static async Task GetGuildAsync(BaseDiscordClient client, - ulong id, RequestOptions options) + ulong id, bool withCounts, RequestOptions options) { - var model = await client.ApiClient.GetGuildAsync(id, options).ConfigureAwait(false); + var model = await client.ApiClient.GetGuildAsync(id, withCounts, options).ConfigureAwait(false); if (model != null) return RestGuild.Create(client, model); return null; @@ -77,6 +77,14 @@ namespace Discord.Rest return RestGuildEmbed.Create(model); return null; } + public static async Task GetGuildWidgetAsync(BaseDiscordClient client, + ulong id, RequestOptions options) + { + var model = await client.ApiClient.GetGuildWidgetAsync(id, options).ConfigureAwait(false); + if (model != null) + return RestGuildWidget.Create(model); + return null; + } public static IAsyncEnumerable> GetGuildSummariesAsync(BaseDiscordClient client, ulong? fromGuildId, int? limit, RequestOptions options) { @@ -106,13 +114,13 @@ namespace Discord.Rest count: limit ); } - public static async Task> GetGuildsAsync(BaseDiscordClient client, RequestOptions options) + public static async Task> GetGuildsAsync(BaseDiscordClient client, bool withCounts, RequestOptions options) { var summaryModels = await GetGuildSummariesAsync(client, null, null, options).FlattenAsync().ConfigureAwait(false); var guilds = ImmutableArray.CreateBuilder(); foreach (var summaryModel in summaryModels) { - var guildModel = await client.ApiClient.GetGuildAsync(summaryModel.Id).ConfigureAwait(false); + var guildModel = await client.ApiClient.GetGuildAsync(summaryModel.Id, withCounts).ConfigureAwait(false); if (guildModel != null) guilds.Add(RestGuild.Create(client, guildModel)); } @@ -140,7 +148,7 @@ namespace Discord.Rest public static async Task GetGuildUserAsync(BaseDiscordClient client, ulong guildId, ulong id, RequestOptions options) { - var guild = await GetGuildAsync(client, guildId, options).ConfigureAwait(false); + var guild = await GetGuildAsync(client, guildId, false, options).ConfigureAwait(false); if (guild == null) return null; @@ -176,5 +184,22 @@ namespace Discord.Rest var response = await client.ApiClient.GetBotGatewayAsync(options).ConfigureAwait(false); return response.Shards; } + + public static async Task GetBotGatewayAsync(BaseDiscordClient client, RequestOptions options) + { + var response = await client.ApiClient.GetBotGatewayAsync(options).ConfigureAwait(false); + return new BotGateway + { + Url = response.Url, + Shards = response.Shards, + SessionStartLimit = new SessionStartLimit + { + Total = response.SessionStartLimit.Total, + Remaining = response.SessionStartLimit.Remaining, + ResetAfter = response.SessionStartLimit.ResetAfter, + MaxConcurrency = response.SessionStartLimit.MaxConcurrency + } + }; + } } } diff --git a/src/Discord.Net.Rest/Discord.Net.Rest.csproj b/src/Discord.Net.Rest/Discord.Net.Rest.csproj index b9592f18d..8407abfd6 100644 --- a/src/Discord.Net.Rest/Discord.Net.Rest.csproj +++ b/src/Discord.Net.Rest/Discord.Net.Rest.csproj @@ -1,5 +1,6 @@ + Discord.Net.Rest Discord.Rest diff --git a/src/Discord.Net.Rest/DiscordRestApiClient.cs b/src/Discord.Net.Rest/DiscordRestApiClient.cs index 30984c0e9..592ad7e92 100644 --- a/src/Discord.Net.Rest/DiscordRestApiClient.cs +++ b/src/Discord.Net.Rest/DiscordRestApiClient.cs @@ -24,7 +24,7 @@ namespace Discord.API { internal class DiscordRestApiClient : IDisposable { - private static readonly ConcurrentDictionary> _bucketIdGenerators = new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary> _bucketIdGenerators = new ConcurrentDictionary>(); public event Func SentRequest { add { _sentRequestEvent.Add(value); } remove { _sentRequestEvent.Remove(value); } } private readonly AsyncEvent> _sentRequestEvent = new AsyncEvent>(); @@ -80,17 +80,13 @@ namespace Discord.API /// Unknown OAuth token type. internal static string GetPrefixedToken(TokenType tokenType, string token) { - switch (tokenType) + return tokenType switch { - case default(TokenType): - return token; - case TokenType.Bot: - return $"Bot {token}"; - case TokenType.Bearer: - return $"Bearer {token}"; - default: - throw new ArgumentException(message: "Unknown OAuth token type.", paramName: nameof(tokenType)); - } + default(TokenType) => token, + TokenType.Bot => $"Bot {token}", + TokenType.Bearer => $"Bearer {token}", + _ => throw new ArgumentException(message: "Unknown OAuth token type.", paramName: nameof(tokenType)), + }; } internal virtual void Dispose(bool disposing) { @@ -133,7 +129,7 @@ namespace Discord.API RestClient.SetCancelToken(_loginCancelToken.Token); AuthTokenType = tokenType; - AuthToken = token; + AuthToken = token?.TrimEnd(); if (tokenType != TokenType.Webhook) RestClient.SetHeader("authorization", GetPrefixedToken(AuthTokenType, AuthToken)); @@ -180,9 +176,9 @@ namespace Discord.API //Core internal Task SendAsync(string method, Expression> endpointExpr, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) - => SendAsync(method, GetEndpoint(endpointExpr), GetBucketId(ids, endpointExpr, funcName), clientBucket, options); + => SendAsync(method, GetEndpoint(endpointExpr), GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); public async Task SendAsync(string method, string endpoint, - string bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) + BucketId bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) { options = options ?? new RequestOptions(); options.HeaderOnly = true; @@ -194,9 +190,9 @@ namespace Discord.API internal Task SendJsonAsync(string method, Expression> endpointExpr, object payload, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) - => SendJsonAsync(method, GetEndpoint(endpointExpr), payload, GetBucketId(ids, endpointExpr, funcName), clientBucket, options); + => SendJsonAsync(method, GetEndpoint(endpointExpr), payload, GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); public async Task SendJsonAsync(string method, string endpoint, object payload, - string bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) + BucketId bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) { options = options ?? new RequestOptions(); options.HeaderOnly = true; @@ -209,9 +205,9 @@ namespace Discord.API internal Task SendMultipartAsync(string method, Expression> endpointExpr, IReadOnlyDictionary multipartArgs, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) - => SendMultipartAsync(method, GetEndpoint(endpointExpr), multipartArgs, GetBucketId(ids, endpointExpr, funcName), clientBucket, options); + => SendMultipartAsync(method, GetEndpoint(endpointExpr), multipartArgs, GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); public async Task SendMultipartAsync(string method, string endpoint, IReadOnlyDictionary multipartArgs, - string bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) + BucketId bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) { options = options ?? new RequestOptions(); options.HeaderOnly = true; @@ -223,9 +219,9 @@ namespace Discord.API internal Task SendAsync(string method, Expression> endpointExpr, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) where TResponse : class - => SendAsync(method, GetEndpoint(endpointExpr), GetBucketId(ids, endpointExpr, funcName), clientBucket, options); + => SendAsync(method, GetEndpoint(endpointExpr), GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); public async Task SendAsync(string method, string endpoint, - string bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) where TResponse : class + BucketId bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) where TResponse : class { options = options ?? new RequestOptions(); options.BucketId = bucketId; @@ -236,9 +232,9 @@ namespace Discord.API internal Task SendJsonAsync(string method, Expression> endpointExpr, object payload, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) where TResponse : class - => SendJsonAsync(method, GetEndpoint(endpointExpr), payload, GetBucketId(ids, endpointExpr, funcName), clientBucket, options); + => SendJsonAsync(method, GetEndpoint(endpointExpr), payload, GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); public async Task SendJsonAsync(string method, string endpoint, object payload, - string bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) where TResponse : class + BucketId bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) where TResponse : class { options = options ?? new RequestOptions(); options.BucketId = bucketId; @@ -250,9 +246,9 @@ namespace Discord.API internal Task SendMultipartAsync(string method, Expression> endpointExpr, IReadOnlyDictionary multipartArgs, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) - => SendMultipartAsync(method, GetEndpoint(endpointExpr), multipartArgs, GetBucketId(ids, endpointExpr, funcName), clientBucket, options); + => SendMultipartAsync(method, GetEndpoint(endpointExpr), multipartArgs, GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); public async Task SendMultipartAsync(string method, string endpoint, IReadOnlyDictionary multipartArgs, - string bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) + BucketId bucketId = null, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null) { options = options ?? new RequestOptions(); options.BucketId = bucketId; @@ -524,7 +520,8 @@ namespace Discord.API throw new ArgumentException(message: $"Message content is too long, length must be less or equal to {DiscordConfig.MaxMessageSize}.", paramName: nameof(args.Content)); options = RequestOptions.CreateOrClone(options); - return await SendJsonAsync("POST", () => $"webhooks/{webhookId}/{AuthToken}?wait=true", args, new BucketIds(), clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); + var ids = new BucketIds(webhookId: webhookId); + return await SendJsonAsync("POST", () => $"webhooks/{webhookId}/{AuthToken}?wait=true", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } /// Message content is too long, length must be less or equal to . public async Task UploadFileAsync(ulong channelId, UploadFileParams args, RequestOptions options = null) @@ -563,7 +560,8 @@ namespace Discord.API throw new ArgumentOutOfRangeException($"Message content is too long, length must be less or equal to {DiscordConfig.MaxMessageSize}.", nameof(args.Content)); } - return await SendMultipartAsync("POST", () => $"webhooks/{webhookId}/{AuthToken}?wait=true", args.ToDictionary(), new BucketIds(), clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); + var ids = new BucketIds(webhookId: webhookId); + return await SendMultipartAsync("POST", () => $"webhooks/{webhookId}/{AuthToken}?wait=true", args.ToDictionary(), ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } public async Task DeleteMessageAsync(ulong channelId, ulong messageId, RequestOptions options = null) { @@ -789,7 +787,7 @@ namespace Discord.API } //Guilds - public async Task GetGuildAsync(ulong guildId, RequestOptions options = null) + public async Task GetGuildAsync(ulong guildId, bool withCounts, RequestOptions options = null) { Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); @@ -797,7 +795,7 @@ namespace Discord.API try { var ids = new BucketIds(guildId: guildId); - return await SendAsync("GET", () => $"guilds/{guildId}", ids, options: options).ConfigureAwait(false); + return await SendAsync("GET", () => $"guilds/{guildId}?with_counts={(withCounts ? "true" : "false")}", ids, options: options).ConfigureAwait(false); } catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.NotFound) { return null; } } @@ -855,10 +853,11 @@ namespace Discord.API Preconditions.NotEqual(guildId, 0, nameof(guildId)); Preconditions.NotNull(args, nameof(args)); Preconditions.AtLeast(args.Days, 1, nameof(args.Days)); + string endpointRoleIds = args.IncludeRoleIds?.Length > 0 ? $"&include_roles={string.Join(",", args.IncludeRoleIds)}" : ""; options = RequestOptions.CreateOrClone(options); var ids = new BucketIds(guildId: guildId); - return await SendAsync("GET", () => $"guilds/{guildId}/prune?days={args.Days}", ids, options: options).ConfigureAwait(false); + return await SendAsync("GET", () => $"guilds/{guildId}/prune?days={args.Days}{endpointRoleIds}", ids, options: options).ConfigureAwait(false); } //Guild Bans @@ -876,8 +875,12 @@ namespace Discord.API Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); - var ids = new BucketIds(guildId: guildId); - return await SendAsync("GET", () => $"guilds/{guildId}/bans/{userId}", ids, options: options).ConfigureAwait(false); + try + { + var ids = new BucketIds(guildId: guildId); + return await SendAsync("GET", () => $"guilds/{guildId}/bans/{userId}", ids, options: options).ConfigureAwait(false); + } + catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.NotFound) { return null; } } /// /// and must not be equal to zero. @@ -935,6 +938,32 @@ namespace Discord.API return await SendJsonAsync("PATCH", () => $"guilds/{guildId}/embed", args, ids, options: options).ConfigureAwait(false); } + //Guild Widget + /// must not be equal to zero. + public async Task GetGuildWidgetAsync(ulong guildId, RequestOptions options = null) + { + Preconditions.NotEqual(guildId, 0, nameof(guildId)); + options = RequestOptions.CreateOrClone(options); + + try + { + var ids = new BucketIds(guildId: guildId); + return await SendAsync("GET", () => $"guilds/{guildId}/widget", ids, options: options).ConfigureAwait(false); + } + catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.NotFound) { return null; } + } + /// must not be equal to zero. + /// must not be . + public async Task ModifyGuildWidgetAsync(ulong guildId, Rest.ModifyGuildWidgetParams args, RequestOptions options = null) + { + Preconditions.NotNull(args, nameof(args)); + Preconditions.NotEqual(guildId, 0, nameof(guildId)); + options = RequestOptions.CreateOrClone(options); + + var ids = new BucketIds(guildId: guildId); + return await SendJsonAsync("PATCH", () => $"guilds/{guildId}/widget", args, ids, options: options).ConfigureAwait(false); + } + //Guild Integrations /// must not be equal to zero. public async Task> GetGuildIntegrationsAsync(ulong guildId, RequestOptions options = null) @@ -1470,21 +1499,39 @@ namespace Discord.API { public ulong GuildId { get; internal set; } public ulong ChannelId { get; internal set; } + public ulong WebhookId { get; internal set; } + public string HttpMethod { get; internal set; } - internal BucketIds(ulong guildId = 0, ulong channelId = 0) + internal BucketIds(ulong guildId = 0, ulong channelId = 0, ulong webhookId = 0) { GuildId = guildId; ChannelId = channelId; + WebhookId = webhookId; } + internal object[] ToArray() - => new object[] { GuildId, ChannelId }; + => new object[] { HttpMethod, GuildId, ChannelId, WebhookId }; + + internal Dictionary ToMajorParametersDictionary() + { + var dict = new Dictionary(); + if (GuildId != 0) + dict["GuildId"] = GuildId.ToString(); + if (ChannelId != 0) + dict["ChannelId"] = ChannelId.ToString(); + if (WebhookId != 0) + dict["WebhookId"] = WebhookId.ToString(); + return dict; + } internal static int? GetIndex(string name) { switch (name) { - case "guildId": return 0; - case "channelId": return 1; + case "httpMethod": return 0; + case "guildId": return 1; + case "channelId": return 2; + case "webhookId": return 3; default: return null; } @@ -1495,18 +1542,19 @@ namespace Discord.API { return endpointExpr.Compile()(); } - private static string GetBucketId(BucketIds ids, Expression> endpointExpr, string callingMethod) + private static BucketId GetBucketId(string httpMethod, BucketIds ids, Expression> endpointExpr, string callingMethod) { + ids.HttpMethod ??= httpMethod; return _bucketIdGenerators.GetOrAdd(callingMethod, x => CreateBucketId(endpointExpr))(ids); } - private static Func CreateBucketId(Expression> endpoint) + private static Func CreateBucketId(Expression> endpoint) { try { //Is this a constant string? if (endpoint.Body.NodeType == ExpressionType.Constant) - return x => (endpoint.Body as ConstantExpression).Value.ToString(); + return x => BucketId.Create(x.HttpMethod, (endpoint.Body as ConstantExpression).Value.ToString(), x.ToMajorParametersDictionary()); var builder = new StringBuilder(); var methodCall = endpoint.Body as MethodCallExpression; @@ -1543,7 +1591,7 @@ namespace Discord.API var mappedId = BucketIds.GetIndex(fieldName); - if(!mappedId.HasValue && rightIndex != endIndex && format.Length > rightIndex + 1 && format[rightIndex + 1] == '/') //Ignore the next slash + if (!mappedId.HasValue && rightIndex != endIndex && format.Length > rightIndex + 1 && format[rightIndex + 1] == '/') //Ignore the next slash rightIndex++; if (mappedId.HasValue) @@ -1556,7 +1604,7 @@ namespace Discord.API format = builder.ToString(); - return x => string.Format(format, x.ToArray()); + return x => BucketId.Create(x.HttpMethod, string.Format(format, x.ToArray()), x.ToMajorParametersDictionary()); } catch (Exception ex) { diff --git a/src/Discord.Net.Rest/DiscordRestClient.cs b/src/Discord.Net.Rest/DiscordRestClient.cs index 4c29d1625..48c40fdfa 100644 --- a/src/Discord.Net.Rest/DiscordRestClient.cs +++ b/src/Discord.Net.Rest/DiscordRestClient.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; @@ -28,10 +29,10 @@ namespace Discord.Rest internal DiscordRestClient(DiscordRestConfig config, API.DiscordRestApiClient api) : base(config, api) { } private static API.DiscordRestApiClient CreateApiClient(DiscordRestConfig config) - => new API.DiscordRestApiClient(config.RestClientProvider, - DiscordRestConfig.UserAgent, - rateLimitPrecision: config.RateLimitPrecision, - useSystemClock: config.UseSystemClock); + => new API.DiscordRestApiClient(config.RestClientProvider, + DiscordRestConfig.UserAgent, + rateLimitPrecision: config.RateLimitPrecision, + useSystemClock: config.UseSystemClock); internal override void Dispose(bool disposing) { @@ -76,15 +77,22 @@ namespace Discord.Rest => ClientHelper.GetInviteAsync(this, inviteId, options); public Task GetGuildAsync(ulong id, RequestOptions options = null) - => ClientHelper.GetGuildAsync(this, id, options); + => ClientHelper.GetGuildAsync(this, id, false, options); + public Task GetGuildAsync(ulong id, bool withCounts, RequestOptions options = null) + => ClientHelper.GetGuildAsync(this, id, withCounts, options); + [Obsolete("This endpoint is deprecated, use GetGuildWidgetAsync instead.")] public Task GetGuildEmbedAsync(ulong id, RequestOptions options = null) => ClientHelper.GetGuildEmbedAsync(this, id, options); + public Task GetGuildWidgetAsync(ulong id, RequestOptions options = null) + => ClientHelper.GetGuildWidgetAsync(this, id, options); public IAsyncEnumerable> GetGuildSummariesAsync(RequestOptions options = null) => ClientHelper.GetGuildSummariesAsync(this, null, null, options); public IAsyncEnumerable> GetGuildSummariesAsync(ulong fromGuildId, int limit, RequestOptions options = null) => ClientHelper.GetGuildSummariesAsync(this, fromGuildId, limit, options); public Task> GetGuildsAsync(RequestOptions options = null) - => ClientHelper.GetGuildsAsync(this, options); + => ClientHelper.GetGuildsAsync(this, false, options); + public Task> GetGuildsAsync(bool withCounts, RequestOptions options = null) + => ClientHelper.GetGuildsAsync(this, withCounts, options); public Task CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null) => ClientHelper.CreateGuildAsync(this, name, region, jpegIcon, options); diff --git a/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteCreateAuditLogData.cs b/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteCreateAuditLogData.cs index 215a3c164..b177b2435 100644 --- a/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteCreateAuditLogData.cs +++ b/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteCreateAuditLogData.cs @@ -36,13 +36,17 @@ namespace Discord.Rest var maxAge = maxAgeModel.NewValue.ToObject(discord.ApiClient.Serializer); var code = codeModel.NewValue.ToObject(discord.ApiClient.Serializer); var temporary = temporaryModel.NewValue.ToObject(discord.ApiClient.Serializer); - var inviterId = inviterIdModel.NewValue.ToObject(discord.ApiClient.Serializer); var channelId = channelIdModel.NewValue.ToObject(discord.ApiClient.Serializer); var uses = usesModel.NewValue.ToObject(discord.ApiClient.Serializer); var maxUses = maxUsesModel.NewValue.ToObject(discord.ApiClient.Serializer); - var inviterInfo = log.Users.FirstOrDefault(x => x.Id == inviterId); - var inviter = RestUser.Create(discord, inviterInfo); + RestUser inviter = null; + if (inviterIdModel != null) + { + var inviterId = inviterIdModel.NewValue.ToObject(discord.ApiClient.Serializer); + var inviterInfo = log.Users.FirstOrDefault(x => x.Id == inviterId); + inviter = RestUser.Create(discord, inviterInfo); + } return new InviteCreateAuditLogData(maxAge, code, temporary, inviter, channelId, uses, maxUses); } @@ -70,10 +74,10 @@ namespace Discord.Rest /// public bool Temporary { get; } /// - /// Gets the user that created this invite. + /// Gets the user that created this invite if available. /// /// - /// A user that created this invite. + /// A user that created this invite or . /// public IUser Creator { get; } /// diff --git a/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteDeleteAuditLogData.cs b/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteDeleteAuditLogData.cs index 5e49bb641..9d0aed12b 100644 --- a/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteDeleteAuditLogData.cs +++ b/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/InviteDeleteAuditLogData.cs @@ -36,13 +36,17 @@ namespace Discord.Rest var maxAge = maxAgeModel.OldValue.ToObject(discord.ApiClient.Serializer); var code = codeModel.OldValue.ToObject(discord.ApiClient.Serializer); var temporary = temporaryModel.OldValue.ToObject(discord.ApiClient.Serializer); - var inviterId = inviterIdModel.OldValue.ToObject(discord.ApiClient.Serializer); var channelId = channelIdModel.OldValue.ToObject(discord.ApiClient.Serializer); var uses = usesModel.OldValue.ToObject(discord.ApiClient.Serializer); var maxUses = maxUsesModel.OldValue.ToObject(discord.ApiClient.Serializer); - var inviterInfo = log.Users.FirstOrDefault(x => x.Id == inviterId); - var inviter = RestUser.Create(discord, inviterInfo); + RestUser inviter = null; + if (inviterIdModel != null) + { + var inviterId = inviterIdModel.OldValue.ToObject(discord.ApiClient.Serializer); + var inviterInfo = log.Users.FirstOrDefault(x => x.Id == inviterId); + inviter = RestUser.Create(discord, inviterInfo); + } return new InviteDeleteAuditLogData(maxAge, code, temporary, inviter, channelId, uses, maxUses); } @@ -70,10 +74,10 @@ namespace Discord.Rest /// public bool Temporary { get; } /// - /// Gets the user that created this invite. + /// Gets the user that created this invite if available. /// /// - /// A user that created this invite. + /// A user that created this invite or . /// public IUser Creator { get; } /// diff --git a/src/Discord.Net.Rest/Entities/Channels/ChannelHelper.cs b/src/Discord.Net.Rest/Entities/Channels/ChannelHelper.cs index 55b6f03a4..c1d0ac294 100644 --- a/src/Discord.Net.Rest/Entities/Channels/ChannelHelper.cs +++ b/src/Discord.Net.Rest/Entities/Channels/ChannelHelper.cs @@ -6,7 +6,6 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; -using UserModel = Discord.API.User; namespace Discord.Rest { @@ -28,7 +27,16 @@ namespace Discord.Rest { Name = args.Name, Position = args.Position, - CategoryId = args.CategoryId + CategoryId = args.CategoryId, + Overwrites = args.PermissionOverwrites.IsSpecified + ? args.PermissionOverwrites.Value.Select(overwrite => new API.Overwrite + { + TargetId = overwrite.TargetId, + TargetType = overwrite.TargetType, + Allow = overwrite.Permissions.AllowValue, + Deny = overwrite.Permissions.DenyValue + }).ToArray() + : Optional.Create(), }; return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } @@ -46,6 +54,15 @@ namespace Discord.Rest Topic = args.Topic, IsNsfw = args.IsNsfw, SlowModeInterval = args.SlowModeInterval, + Overwrites = args.PermissionOverwrites.IsSpecified + ? args.PermissionOverwrites.Value.Select(overwrite => new API.Overwrite + { + TargetId = overwrite.TargetId, + TargetType = overwrite.TargetType, + Allow = overwrite.Permissions.AllowValue, + Deny = overwrite.Permissions.DenyValue + }).ToArray() + : Optional.Create(), }; return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } @@ -61,7 +78,16 @@ namespace Discord.Rest Name = args.Name, Position = args.Position, CategoryId = args.CategoryId, - UserLimit = args.UserLimit.IsSpecified ? (args.UserLimit.Value ?? 0) : Optional.Create() + UserLimit = args.UserLimit.IsSpecified ? (args.UserLimit.Value ?? 0) : Optional.Create(), + Overwrites = args.PermissionOverwrites.IsSpecified + ? args.PermissionOverwrites.Value.Select(overwrite => new API.Overwrite + { + TargetId = overwrite.TargetId, + TargetType = overwrite.TargetType, + Allow = overwrite.Permissions.AllowValue, + Deny = overwrite.Permissions.DenyValue + }).ToArray() + : Optional.Create(), }; return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } @@ -103,7 +129,7 @@ namespace Discord.Rest var model = await client.ApiClient.GetChannelMessageAsync(channel.Id, id, options).ConfigureAwait(false); if (model == null) return null; - var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); + var author = MessageHelper.GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); return RestMessage.Create(client, channel, author, model); } public static IAsyncEnumerable> GetMessagesAsync(IMessageChannel channel, BaseDiscordClient client, @@ -138,7 +164,7 @@ namespace Discord.Rest var builder = ImmutableArray.CreateBuilder(); foreach (var model in models) { - var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); + var author = MessageHelper.GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); builder.Add(RestMessage.Create(client, channel, author, model)); } return builder.ToImmutable(); @@ -166,7 +192,7 @@ namespace Discord.Rest var builder = ImmutableArray.CreateBuilder(); foreach (var model in models) { - var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); + var author = MessageHelper.GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable()); builder.Add(RestMessage.Create(client, channel, author, model)); } return builder.ToImmutable(); @@ -174,7 +200,7 @@ namespace Discord.Rest /// Message content is too long, length must be less or equal to . public static async Task SendMessageAsync(IMessageChannel channel, BaseDiscordClient client, - string text, bool isTTS, Embed embed, AllowedMentions allowedMentions, RequestOptions options) + string text, bool isTTS, Embed embed, AllowedMentions allowedMentions, MessageReference messageReference, RequestOptions options) { Preconditions.AtMost(allowedMentions?.RoleIds?.Count ?? 0, 100, nameof(allowedMentions.RoleIds), "A max of 100 role Ids are allowed."); Preconditions.AtMost(allowedMentions?.UserIds?.Count ?? 0, 100, nameof(allowedMentions.UserIds), "A max of 100 user Ids are allowed."); @@ -195,7 +221,7 @@ namespace Discord.Rest } } - var args = new CreateMessageParams(text) { IsTTS = isTTS, Embed = embed?.ToModel(), AllowedMentions = allowedMentions?.ToModel() }; + var args = new CreateMessageParams(text) { IsTTS = isTTS, Embed = embed?.ToModel(), AllowedMentions = allowedMentions?.ToModel(), MessageReference = messageReference?.ToModel() }; var model = await client.ApiClient.CreateMessageAsync(channel.Id, args, options).ConfigureAwait(false); return RestUserMessage.Create(client, channel, client.CurrentUser, model); } @@ -225,16 +251,16 @@ namespace Discord.Rest /// An I/O error occurred while opening the file. /// Message content is too long, length must be less or equal to . public static async Task SendFileAsync(IMessageChannel channel, BaseDiscordClient client, - string filePath, string text, bool isTTS, Embed embed, AllowedMentions allowedMentions, RequestOptions options, bool isSpoiler) + string filePath, string text, bool isTTS, Embed embed, AllowedMentions allowedMentions, MessageReference messageReference, RequestOptions options, bool isSpoiler) { string filename = Path.GetFileName(filePath); using (var file = File.OpenRead(filePath)) - return await SendFileAsync(channel, client, file, filename, text, isTTS, embed, allowedMentions, options, isSpoiler).ConfigureAwait(false); + return await SendFileAsync(channel, client, file, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler).ConfigureAwait(false); } /// Message content is too long, length must be less or equal to . public static async Task SendFileAsync(IMessageChannel channel, BaseDiscordClient client, - Stream stream, string filename, string text, bool isTTS, Embed embed, AllowedMentions allowedMentions, RequestOptions options, bool isSpoiler) + Stream stream, string filename, string text, bool isTTS, Embed embed, AllowedMentions allowedMentions, MessageReference messageReference, RequestOptions options, bool isSpoiler) { Preconditions.AtMost(allowedMentions?.RoleIds?.Count ?? 0, 100, nameof(allowedMentions.RoleIds), "A max of 100 role Ids are allowed."); Preconditions.AtMost(allowedMentions?.UserIds?.Count ?? 0, 100, nameof(allowedMentions.UserIds), "A max of 100 user Ids are allowed."); @@ -255,7 +281,7 @@ namespace Discord.Rest } } - var args = new UploadFileParams(stream) { Filename = filename, Content = text, IsTTS = isTTS, Embed = embed?.ToModel() ?? Optional.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional.Unspecified, IsSpoiler = isSpoiler }; + var args = new UploadFileParams(stream) { Filename = filename, Content = text, IsTTS = isTTS, Embed = embed?.ToModel() ?? Optional.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional.Unspecified, MessageReference = messageReference?.ToModel() ?? Optional.Unspecified, IsSpoiler = isSpoiler }; var model = await client.ApiClient.UploadFileAsync(channel.Id, args, options).ConfigureAwait(false); return RestUserMessage.Create(client, channel, client.CurrentUser, model); } @@ -413,7 +439,8 @@ namespace Discord.Rest var apiArgs = new ModifyGuildChannelParams { Overwrites = category.PermissionOverwrites - .Select(overwrite => new API.Overwrite{ + .Select(overwrite => new API.Overwrite + { TargetId = overwrite.TargetId, TargetType = overwrite.TargetType, Allow = overwrite.Permissions.AllowValue, @@ -422,16 +449,5 @@ namespace Discord.Rest }; await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); } - - //Helpers - private static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId) - { - IUser author = null; - if (guild != null) - author = guild.GetUserAsync(model.Id, CacheMode.CacheOnly).Result; - if (author == null) - author = RestUser.Create(client, guild, model, webhookId); - return author; - } } } diff --git a/src/Discord.Net.Rest/Entities/Channels/IRestMessageChannel.cs b/src/Discord.Net.Rest/Entities/Channels/IRestMessageChannel.cs index d02b293ef..09404d836 100644 --- a/src/Discord.Net.Rest/Entities/Channels/IRestMessageChannel.cs +++ b/src/Discord.Net.Rest/Entities/Channels/IRestMessageChannel.cs @@ -24,17 +24,18 @@ namespace Discord.Rest /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - new Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null); + new Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Sends a file to this message channel with an optional caption. /// /// /// This method follows the same behavior as described in - /// . Please visit + /// . Please visit /// its documentation for more details on this method. /// /// The file path of the file. @@ -47,16 +48,17 @@ namespace Discord.Rest /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - new Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null); + new Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Sends a file to this message channel with an optional caption. /// /// - /// This method follows the same behavior as described in . + /// This method follows the same behavior as described in . /// Please visit its documentation for more details on this method. /// /// The of the file to be sent. @@ -70,11 +72,12 @@ namespace Discord.Rest /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - new Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null); + new Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Gets a message from this message channel. diff --git a/src/Discord.Net.Rest/Entities/Channels/RestDMChannel.cs b/src/Discord.Net.Rest/Entities/Channels/RestDMChannel.cs index 0f29f9d77..d59a10fb5 100644 --- a/src/Discord.Net.Rest/Entities/Channels/RestDMChannel.cs +++ b/src/Discord.Net.Rest/Entities/Channels/RestDMChannel.cs @@ -93,8 +93,8 @@ namespace Discord.Rest /// /// Message content is too long, length must be less or equal to . - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) - => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, options); + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// /// @@ -121,12 +121,12 @@ namespace Discord.Rest /// is in an invalid format. /// An I/O error occurred while opening the file. /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) @@ -200,14 +200,14 @@ namespace Discord.Rest async Task> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions) - => await SendMessageAsync(text, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IChannel /// diff --git a/src/Discord.Net.Rest/Entities/Channels/RestGroupChannel.cs b/src/Discord.Net.Rest/Entities/Channels/RestGroupChannel.cs index 4361fd281..666d6a4f4 100644 --- a/src/Discord.Net.Rest/Entities/Channels/RestGroupChannel.cs +++ b/src/Discord.Net.Rest/Entities/Channels/RestGroupChannel.cs @@ -95,8 +95,8 @@ namespace Discord.Rest /// /// Message content is too long, length must be less or equal to . - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) - => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, options); + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// /// @@ -123,12 +123,12 @@ namespace Discord.Rest /// is in an invalid format. /// An I/O error occurred while opening the file. /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// public Task TriggerTypingAsync(RequestOptions options = null) @@ -178,14 +178,14 @@ namespace Discord.Rest async Task> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); - async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); - async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); - async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions) - => await SendMessageAsync(text, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IAudioChannel /// diff --git a/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs b/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs index 8a334fae5..fad3358dc 100644 --- a/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs +++ b/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs @@ -12,7 +12,7 @@ namespace Discord.Rest /// Represents a REST-based news channel in a guild that has the same properties as a . /// [DebuggerDisplay(@"{DebuggerDisplay,nq}")] - public class RestNewsChannel : RestTextChannel + public class RestNewsChannel : RestTextChannel, INewsChannel { internal RestNewsChannel(BaseDiscordClient discord, IGuild guild, ulong id) :base(discord, guild, id) diff --git a/src/Discord.Net.Rest/Entities/Channels/RestTextChannel.cs b/src/Discord.Net.Rest/Entities/Channels/RestTextChannel.cs index c7ff7fa65..fdc4b7988 100644 --- a/src/Discord.Net.Rest/Entities/Channels/RestTextChannel.cs +++ b/src/Discord.Net.Rest/Entities/Channels/RestTextChannel.cs @@ -42,7 +42,8 @@ namespace Discord.Rest base.Update(model); CategoryId = model.CategoryId; Topic = model.Topic.Value; - SlowModeInterval = model.SlowMode.Value; + if (model.SlowMode.IsSpecified) + SlowModeInterval = model.SlowMode.Value; IsNsfw = model.Nsfw.GetValueOrDefault(); } @@ -101,8 +102,8 @@ namespace Discord.Rest /// /// Message content is too long, length must be less or equal to . - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) - => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, options); + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// /// @@ -129,13 +130,13 @@ namespace Discord.Rest /// is in an invalid format. /// An I/O error occurred while opening the file. /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) @@ -266,15 +267,15 @@ namespace Discord.Rest => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions) - => await SendMessageAsync(text, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IGuildChannel /// diff --git a/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs b/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs index 675847b58..04ec27930 100644 --- a/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs +++ b/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using EmbedModel = Discord.API.GuildEmbed; +using WidgetModel = Discord.API.GuildWidget; using Model = Discord.API.Guild; using RoleModel = Discord.API.Role; using ImageModel = Discord.API.Image; @@ -99,6 +100,27 @@ namespace Discord.Rest return await client.ApiClient.ModifyGuildEmbedAsync(guild.Id, apiArgs, options).ConfigureAwait(false); } + /// is null. + public static async Task ModifyWidgetAsync(IGuild guild, BaseDiscordClient client, + Action func, RequestOptions options) + { + if (func == null) + throw new ArgumentNullException(nameof(func)); + + var args = new GuildWidgetProperties(); + func(args); + var apiArgs = new API.Rest.ModifyGuildWidgetParams + { + Enabled = args.Enabled + }; + + if (args.Channel.IsSpecified) + apiArgs.ChannelId = args.Channel.Value?.Id; + else if (args.ChannelId.IsSpecified) + apiArgs.ChannelId = args.ChannelId.Value; + + return await client.ApiClient.ModifyGuildWidgetAsync(guild.Id, apiArgs, options).ConfigureAwait(false); + } public static async Task ReorderChannelsAsync(IGuild guild, BaseDiscordClient client, IEnumerable args, RequestOptions options) { @@ -132,7 +154,7 @@ namespace Discord.Rest public static async Task GetBanAsync(IGuild guild, BaseDiscordClient client, ulong userId, RequestOptions options) { var model = await client.ApiClient.GetGuildBanAsync(guild.Id, userId, options).ConfigureAwait(false); - return RestBan.Create(client, model); + return model == null ? null : RestBan.Create(client, model); } public static async Task AddBanAsync(IGuild guild, BaseDiscordClient client, @@ -176,7 +198,17 @@ namespace Discord.Rest CategoryId = props.CategoryId, Topic = props.Topic, IsNsfw = props.IsNsfw, - Position = props.Position + Position = props.Position, + SlowModeInterval = props.SlowModeInterval, + Overwrites = props.PermissionOverwrites.IsSpecified + ? props.PermissionOverwrites.Value.Select(overwrite => new API.Overwrite + { + TargetId = overwrite.TargetId, + TargetType = overwrite.TargetType, + Allow = overwrite.Permissions.AllowValue, + Deny = overwrite.Permissions.DenyValue + }).ToArray() + : Optional.Create(), }; var model = await client.ApiClient.CreateGuildChannelAsync(guild.Id, args, options).ConfigureAwait(false); return RestTextChannel.Create(client, guild, model); @@ -195,7 +227,16 @@ namespace Discord.Rest CategoryId = props.CategoryId, Bitrate = props.Bitrate, UserLimit = props.UserLimit, - Position = props.Position + Position = props.Position, + Overwrites = props.PermissionOverwrites.IsSpecified + ? props.PermissionOverwrites.Value.Select(overwrite => new API.Overwrite + { + TargetId = overwrite.TargetId, + TargetType = overwrite.TargetType, + Allow = overwrite.Permissions.AllowValue, + Deny = overwrite.Permissions.DenyValue + }).ToArray() + : Optional.Create(), }; var model = await client.ApiClient.CreateGuildChannelAsync(guild.Id, args, options).ConfigureAwait(false); return RestVoiceChannel.Create(client, guild, model); @@ -211,7 +252,16 @@ namespace Discord.Rest var args = new CreateGuildChannelParams(name, ChannelType.Category) { - Position = props.Position + Position = props.Position, + Overwrites = props.PermissionOverwrites.IsSpecified + ? props.PermissionOverwrites.Value.Select(overwrite => new API.Overwrite + { + TargetId = overwrite.TargetId, + TargetType = overwrite.TargetType, + Allow = overwrite.Permissions.AllowValue, + Deny = overwrite.Permissions.DenyValue + }).ToArray() + : Optional.Create(), }; var model = await client.ApiClient.CreateGuildChannelAsync(guild.Id, args, options).ConfigureAwait(false); @@ -376,9 +426,9 @@ namespace Discord.Rest ); } public static async Task PruneUsersAsync(IGuild guild, BaseDiscordClient client, - int days, bool simulate, RequestOptions options) + int days, bool simulate, RequestOptions options, IEnumerable includeRoleIds) { - var args = new GuildPruneParams(days); + var args = new GuildPruneParams(days, includeRoleIds?.ToArray()); GetGuildPruneCountResponse model; if (simulate) model = await client.ApiClient.GetGuildPruneCountAsync(guild.Id, args, options).ConfigureAwait(false); @@ -451,7 +501,7 @@ namespace Discord.Rest var emote = await client.ApiClient.GetGuildEmoteAsync(guild.Id, id, options).ConfigureAwait(false); return emote.ToEntity(); } - public static async Task CreateEmoteAsync(IGuild guild, BaseDiscordClient client, string name, Image image, Optional> roles, + public static async Task CreateEmoteAsync(IGuild guild, BaseDiscordClient client, string name, Image image, Optional> roles, RequestOptions options) { var apiargs = new CreateGuildEmoteParams @@ -466,7 +516,7 @@ namespace Discord.Rest return emote.ToEntity(); } /// is null. - public static async Task ModifyEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, Action func, + public static async Task ModifyEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, Action func, RequestOptions options) { if (func == null) throw new ArgumentNullException(paramName: nameof(func)); @@ -484,7 +534,7 @@ namespace Discord.Rest var emote = await client.ApiClient.ModifyGuildEmoteAsync(guild.Id, id, apiargs, options).ConfigureAwait(false); return emote.ToEntity(); } - public static Task DeleteEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options) + public static Task DeleteEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options) => client.ApiClient.DeleteGuildEmoteAsync(guild.Id, id, options); } } diff --git a/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs b/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs index f0b5be0f7..c74e128a8 100644 --- a/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs +++ b/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs @@ -7,6 +7,7 @@ using System.Globalization; using System.Linq; using System.Threading.Tasks; using EmbedModel = Discord.API.GuildEmbed; +using WidgetModel = Discord.API.GuildWidget; using Model = Discord.API.Guild; namespace Discord.Rest @@ -28,6 +29,8 @@ namespace Discord.Rest /// public bool IsEmbeddable { get; private set; } /// + public bool IsWidgetEnabled { get; private set; } + /// public VerificationLevel VerificationLevel { get; private set; } /// public MfaLevel MfaLevel { get; private set; } @@ -41,8 +44,14 @@ namespace Discord.Rest /// public ulong? EmbedChannelId { get; private set; } /// + public ulong? WidgetChannelId { get; private set; } + /// public ulong? SystemChannelId { get; private set; } /// + public ulong? RulesChannelId { get; private set; } + /// + public ulong? PublicUpdatesChannelId { get; private set; } + /// public ulong OwnerId { get; private set; } /// public string VoiceRegionId { get; private set; } @@ -50,6 +59,8 @@ namespace Discord.Rest public string IconId { get; private set; } /// public string SplashId { get; private set; } + /// + public string DiscoverySplashId { get; private set; } internal bool Available { get; private set; } /// public ulong? ApplicationId { get; private set; } @@ -67,6 +78,16 @@ namespace Discord.Rest public int PremiumSubscriptionCount { get; private set; } /// public string PreferredLocale { get; private set; } + /// + public int? MaxPresences { get; private set; } + /// + public int? MaxMembers { get; private set; } + /// + public int? MaxVideoChannelUsers { get; private set; } + /// + public int? ApproximateMemberCount { get; private set; } + /// + public int? ApproximatePresenceCount { get; private set; } /// public CultureInfo PreferredCulture { get; private set; } @@ -81,6 +102,8 @@ namespace Discord.Rest /// public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId); /// + public string DiscoverySplashUrl => CDN.GetGuildDiscoverySplashUrl(Id, DiscoverySplashId); + /// public string BannerUrl => CDN.GetGuildBannerUrl(Id, BannerId); /// @@ -110,15 +133,24 @@ namespace Discord.Rest internal void Update(Model model) { AFKChannelId = model.AFKChannelId; - EmbedChannelId = model.EmbedChannelId; + if (model.EmbedChannelId.IsSpecified) + EmbedChannelId = model.EmbedChannelId.Value; + if (model.WidgetChannelId.IsSpecified) + WidgetChannelId = model.WidgetChannelId.Value; SystemChannelId = model.SystemChannelId; + RulesChannelId = model.RulesChannelId; + PublicUpdatesChannelId = model.PublicUpdatesChannelId; AFKTimeout = model.AFKTimeout; - IsEmbeddable = model.EmbedEnabled; + if (model.EmbedEnabled.IsSpecified) + IsEmbeddable = model.EmbedEnabled.Value; + if (model.WidgetEnabled.IsSpecified) + IsWidgetEnabled = model.WidgetEnabled.Value; IconId = model.Icon; Name = model.Name; OwnerId = model.OwnerId; VoiceRegionId = model.Region; SplashId = model.Splash; + DiscoverySplashId = model.DiscoverySplash; VerificationLevel = model.VerificationLevel; MfaLevel = model.MfaLevel; DefaultMessageNotifications = model.DefaultMessageNotifications; @@ -130,8 +162,18 @@ namespace Discord.Rest SystemChannelFlags = model.SystemChannelFlags; Description = model.Description; PremiumSubscriptionCount = model.PremiumSubscriptionCount.GetValueOrDefault(); + if (model.MaxPresences.IsSpecified) + MaxPresences = model.MaxPresences.Value ?? 25000; + if (model.MaxMembers.IsSpecified) + MaxMembers = model.MaxMembers.Value; + if (model.MaxVideoChannelUsers.IsSpecified) + MaxVideoChannelUsers = model.MaxVideoChannelUsers.Value; PreferredLocale = model.PreferredLocale; PreferredCulture = new CultureInfo(PreferredLocale); + if (model.ApproximateMemberCount.IsSpecified) + ApproximateMemberCount = model.ApproximateMemberCount.Value; + if (model.ApproximatePresenceCount.IsSpecified) + ApproximatePresenceCount = model.ApproximatePresenceCount.Value; if (model.Emojis != null) { @@ -163,17 +205,36 @@ namespace Discord.Rest EmbedChannelId = model.ChannelId; IsEmbeddable = model.Enabled; } + internal void Update(WidgetModel model) + { + WidgetChannelId = model.ChannelId; + IsWidgetEnabled = model.Enabled; + } //General /// public async Task UpdateAsync(RequestOptions options = null) - => Update(await Discord.ApiClient.GetGuildAsync(Id, options).ConfigureAwait(false)); + => Update(await Discord.ApiClient.GetGuildAsync(Id, false, options).ConfigureAwait(false)); + /// + /// Updates this object's properties with its current state. + /// + /// + /// If true, and + /// will be updated as well. + /// + /// The options to be used when sending the request. + /// + /// If is true, and + /// will be updated as well. + /// + public async Task UpdateAsync(bool withCounts, RequestOptions options = null) + => Update(await Discord.ApiClient.GetGuildAsync(Id, withCounts, options).ConfigureAwait(false)); /// public Task DeleteAsync(RequestOptions options = null) => GuildHelper.DeleteAsync(this, Discord, options); /// - /// is null. + /// is . public async Task ModifyAsync(Action func, RequestOptions options = null) { var model = await GuildHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false); @@ -181,7 +242,8 @@ namespace Discord.Rest } /// - /// is null. + /// is . + [Obsolete("This endpoint is deprecated, use ModifyWidgetAsync instead.")] public async Task ModifyEmbedAsync(Action func, RequestOptions options = null) { var model = await GuildHelper.ModifyEmbedAsync(this, Discord, func, options).ConfigureAwait(false); @@ -189,7 +251,15 @@ namespace Discord.Rest } /// - /// is null. + /// is . + public async Task ModifyWidgetAsync(Action func, RequestOptions options = null) + { + var model = await GuildHelper.ModifyWidgetAsync(this, Discord, func, options).ConfigureAwait(false); + Update(model); + } + + /// + /// is . public async Task ReorderChannelsAsync(IEnumerable args, RequestOptions options = null) { var arr = args.ToArray(); @@ -205,7 +275,7 @@ namespace Discord.Rest role?.Update(model); } } - + /// public Task LeaveAsync(RequestOptions options = null) => GuildHelper.LeaveAsync(this, Discord, options); @@ -230,7 +300,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains a ban object, which - /// contains the user information and the reason for the ban; null if the ban entry cannot be found. + /// contains the user information and the reason for the ban; if the ban entry cannot be found. /// public Task GetBanAsync(IUser user, RequestOptions options = null) => GuildHelper.GetBanAsync(this, Discord, user.Id, options); @@ -241,7 +311,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains a ban object, which - /// contains the user information and the reason for the ban; null if the ban entry cannot be found. + /// contains the user information and the reason for the ban; if the ban entry cannot be found. /// public Task GetBanAsync(ulong userId, RequestOptions options = null) => GuildHelper.GetBanAsync(this, Discord, userId, options); @@ -279,7 +349,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the generic channel - /// associated with the specified ; null if none is found. + /// associated with the specified ; if none is found. /// public Task GetChannelAsync(ulong id, RequestOptions options = null) => GuildHelper.GetChannelAsync(this, Discord, id, options); @@ -291,7 +361,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the text channel - /// associated with the specified ; null if none is found. + /// associated with the specified ; if none is found. /// public async Task GetTextChannelAsync(ulong id, RequestOptions options = null) { @@ -320,7 +390,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the voice channel associated - /// with the specified ; null if none is found. + /// with the specified ; if none is found. /// public async Task GetVoiceChannelAsync(ulong id, RequestOptions options = null) { @@ -362,7 +432,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the voice channel that the - /// AFK users will be moved to after they have idled for too long; null if none is set. + /// AFK users will be moved to after they have idled for too long; if none is set. /// public async Task GetAFKChannelAsync(RequestOptions options = null) { @@ -381,7 +451,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the first viewable text - /// channel in this guild; null if none is found. + /// channel in this guild; if none is found. /// public async Task GetDefaultChannelAsync(RequestOptions options = null) { @@ -399,8 +469,9 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the embed channel set - /// within the server's widget settings; null if none is set. + /// within the server's widget settings; if none is set. /// + [Obsolete("This endpoint is deprecated, use GetWidgetChannelAsync instead.")] public async Task GetEmbedChannelAsync(RequestOptions options = null) { var embedId = EmbedChannelId; @@ -410,12 +481,28 @@ namespace Discord.Rest } /// - /// Gets the first viewable text channel in this guild. + /// Gets the widget channel (i.e. the channel set in the guild's widget settings) in this guild. /// /// The options to be used when sending the request. /// - /// A task that represents the asynchronous get operation. The task result contains the first viewable text - /// channel in this guild; null if none is found. + /// A task that represents the asynchronous get operation. The task result contains the widget channel set + /// within the server's widget settings; if none is set. + /// + public async Task GetWidgetChannelAsync(RequestOptions options = null) + { + var widgetChannelId = WidgetChannelId; + if (widgetChannelId.HasValue) + return await GuildHelper.GetChannelAsync(this, Discord, widgetChannelId.Value, options).ConfigureAwait(false); + return null; + } + + /// + /// Gets the text channel where guild notices such as welcome messages and boost events are posted. + /// + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains the text channel + /// where guild notices such as welcome messages and boost events are poste; if none is found. /// public async Task GetSystemChannelAsync(RequestOptions options = null) { @@ -427,6 +514,45 @@ namespace Discord.Rest } return null; } + + /// + /// Gets the text channel where Community guilds can display rules and/or guidelines. + /// + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains the text channel + /// where Community guilds can display rules and/or guidelines; if none is set. + /// + public async Task GetRulesChannelAsync(RequestOptions options = null) + { + var rulesChannelId = RulesChannelId; + if (rulesChannelId.HasValue) + { + var channel = await GuildHelper.GetChannelAsync(this, Discord, rulesChannelId.Value, options).ConfigureAwait(false); + return channel as RestTextChannel; + } + return null; + } + + /// + /// Gets the text channel channel where admins and moderators of Community guilds receive notices from Discord. + /// + /// The options to be used when sending the request. + /// + /// A task that represents the asynchronous get operation. The task result contains the text channel channel where + /// admins and moderators of Community guilds receive notices from Discord; if none is set. + /// + public async Task GetPublicUpdatesChannelAsync(RequestOptions options = null) + { + var publicUpdatesChannelId = PublicUpdatesChannelId; + if (publicUpdatesChannelId.HasValue) + { + var channel = await GuildHelper.GetChannelAsync(this, Discord, publicUpdatesChannelId.Value, options).ConfigureAwait(false); + return channel as RestTextChannel; + } + return null; + } + /// /// Creates a new text channel in this guild. /// @@ -458,7 +584,7 @@ namespace Discord.Rest /// The name of the new channel. /// The delegate containing the properties to be applied to the channel upon its creation. /// The options to be used when sending the request. - /// is null. + /// is . /// /// The created voice channel. /// @@ -470,7 +596,7 @@ namespace Discord.Rest /// The name of the new channel. /// The delegate containing the properties to be applied to the channel upon its creation. /// The options to be used when sending the request. - /// is null. + /// is . /// /// The created category channel. /// @@ -521,7 +647,7 @@ namespace Discord.Rest /// /// The snowflake identifier for the role. /// - /// A role that is associated with the specified ; null if none is found. + /// A role that is associated with the specified ; if none is found. /// public RestRole GetRole(ulong id) { @@ -585,7 +711,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the guild user - /// associated with the specified ; null if none is found. + /// associated with the specified ; if none is found. /// public Task GetUserAsync(ulong id, RequestOptions options = null) => GuildHelper.GetUserAsync(this, Discord, id, options); @@ -631,8 +757,8 @@ namespace Discord.Rest /// A task that represents the asynchronous prune operation. The task result contains the number of users to /// be or has been removed from this guild. /// - public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null) - => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options); + public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null, IEnumerable includeRoleIds = null) + => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options, includeRoleIds); /// /// Gets a collection of users in this guild that the name or nickname starts with the @@ -675,7 +801,7 @@ namespace Discord.Rest /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the webhook with the - /// specified ; null if none is found. + /// specified ; if none is found. /// public Task GetWebhookAsync(ulong id, RequestOptions options = null) => GuildHelper.GetWebhookAsync(this, Discord, id, options); @@ -708,7 +834,7 @@ namespace Discord.Rest public Task CreateEmoteAsync(string name, Image image, Optional> roles = default(Optional>), RequestOptions options = null) => GuildHelper.CreateEmoteAsync(this, Discord, name, image, roles, options); /// - /// is null. + /// is . public Task ModifyEmoteAsync(GuildEmote emote, Action func, RequestOptions options = null) => GuildHelper.ModifyEmoteAsync(this, Discord, emote.Id, func, options); /// @@ -808,6 +934,7 @@ namespace Discord.Rest return null; } /// + [Obsolete("This endpoint is deprecated, use GetWidgetChannelAsync instead.")] async Task IGuild.GetEmbedChannelAsync(CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) @@ -816,6 +943,14 @@ namespace Discord.Rest return null; } /// + async Task IGuild.GetWidgetChannelAsync(CacheMode mode, RequestOptions options) + { + if (mode == CacheMode.AllowDownload) + return await GetWidgetChannelAsync(options).ConfigureAwait(false); + else + return null; + } + /// async Task IGuild.GetSystemChannelAsync(CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) @@ -824,6 +959,22 @@ namespace Discord.Rest return null; } /// + async Task IGuild.GetRulesChannelAsync(CacheMode mode, RequestOptions options) + { + if (mode == CacheMode.AllowDownload) + return await GetRulesChannelAsync(options).ConfigureAwait(false); + else + return null; + } + /// + async Task IGuild.GetPublicUpdatesChannelAsync(CacheMode mode, RequestOptions options) + { + if (mode == CacheMode.AllowDownload) + return await GetPublicUpdatesChannelAsync(options).ConfigureAwait(false); + else + return null; + } + /// async Task IGuild.CreateTextChannelAsync(string name, Action func, RequestOptions options) => await CreateTextChannelAsync(name, func, options).ConfigureAwait(false); /// diff --git a/src/Discord.Net.Rest/Entities/Guilds/RestGuildWidget.cs b/src/Discord.Net.Rest/Entities/Guilds/RestGuildWidget.cs new file mode 100644 index 000000000..065739c57 --- /dev/null +++ b/src/Discord.Net.Rest/Entities/Guilds/RestGuildWidget.cs @@ -0,0 +1,25 @@ +using System.Diagnostics; +using Model = Discord.API.GuildWidget; + +namespace Discord.Rest +{ + [DebuggerDisplay(@"{DebuggerDisplay,nq}")] + public struct RestGuildWidget + { + public bool IsEnabled { get; private set; } + public ulong? ChannelId { get; private set; } + + internal RestGuildWidget(bool isEnabled, ulong? channelId) + { + ChannelId = channelId; + IsEnabled = isEnabled; + } + internal static RestGuildWidget Create(Model model) + { + return new RestGuildWidget(model.Enabled, model.ChannelId); + } + + public override string ToString() => ChannelId?.ToString() ?? "Unknown"; + private string DebuggerDisplay => $"{ChannelId} ({(IsEnabled ? "Enabled" : "Disabled")})"; + } +} diff --git a/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs b/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs index 153eb6c41..95b454c20 100644 --- a/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs +++ b/src/Discord.Net.Rest/Entities/Invites/RestInvite.cs @@ -21,6 +21,12 @@ namespace Discord.Rest public ulong ChannelId { get; private set; } /// public ulong? GuildId { get; private set; } + /// + public IUser Inviter { get; private set; } + /// + public IUser TargetUser { get; private set; } + /// + public TargetUserType TargetUserType { get; private set; } internal IChannel Channel { get; } internal IGuild Guild { get; } @@ -50,6 +56,9 @@ namespace Discord.Rest MemberCount = model.MemberCount.IsSpecified ? model.MemberCount.Value : null; PresenceCount = model.PresenceCount.IsSpecified ? model.PresenceCount.Value : null; ChannelType = (ChannelType)model.Channel.Type; + Inviter = model.Inviter.IsSpecified ? RestUser.Create(Discord, model.Inviter.Value) : null; + TargetUser = model.TargetUser.IsSpecified ? RestUser.Create(Discord, model.TargetUser.Value) : null; + TargetUserType = model.TargetUserType.IsSpecified ? model.TargetUserType.Value : TargetUserType.Undefined; } /// diff --git a/src/Discord.Net.Rest/Entities/Invites/RestInviteMetadata.cs b/src/Discord.Net.Rest/Entities/Invites/RestInviteMetadata.cs index 55acd5f45..07ee5851c 100644 --- a/src/Discord.Net.Rest/Entities/Invites/RestInviteMetadata.cs +++ b/src/Discord.Net.Rest/Entities/Invites/RestInviteMetadata.cs @@ -6,9 +6,10 @@ namespace Discord.Rest /// Represents additional information regarding the REST-based invite object. public class RestInviteMetadata : RestInvite, IInviteMetadata { - private long? _createdAtTicks; + private long _createdAtTicks; /// + [Obsolete("This property doesn't exist anymore and shouldn't be used.")] public bool IsRevoked { get; private set; } /// public bool IsTemporary { get; private set; } @@ -18,10 +19,6 @@ namespace Discord.Rest public int? MaxUses { get; private set; } /// public int? Uses { get; private set; } - /// - /// Gets the user that created this invite. - /// - public RestUser Inviter { get; private set; } /// public DateTimeOffset? CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); @@ -39,16 +36,11 @@ namespace Discord.Rest internal void Update(Model model) { base.Update(model); - Inviter = model.Inviter != null ? RestUser.Create(Discord, model.Inviter) : null; - IsRevoked = model.Revoked; IsTemporary = model.Temporary; - MaxAge = model.MaxAge.IsSpecified ? model.MaxAge.Value : (int?)null; - MaxUses = model.MaxUses.IsSpecified ? model.MaxUses.Value : (int?)null; - Uses = model.Uses.IsSpecified ? model.Uses.Value : (int?)null; - _createdAtTicks = model.CreatedAt.IsSpecified ? model.CreatedAt.Value.UtcTicks : (long?)null; + MaxAge = model.MaxAge; + MaxUses = model.MaxUses; + Uses = model.Uses; + _createdAtTicks = model.CreatedAt.UtcTicks; } - - /// - IUser IInviteMetadata.Inviter => Inviter; } } diff --git a/src/Discord.Net.Rest/Entities/Messages/Attachment.cs b/src/Discord.Net.Rest/Entities/Messages/Attachment.cs index abe049180..1cd73518a 100644 --- a/src/Discord.Net.Rest/Entities/Messages/Attachment.cs +++ b/src/Discord.Net.Rest/Entities/Messages/Attachment.cs @@ -3,7 +3,7 @@ using Model = Discord.API.Attachment; namespace Discord { - /// + /// [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class Attachment : IAttachment { diff --git a/src/Discord.Net.Rest/Entities/Messages/MessageHelper.cs b/src/Discord.Net.Rest/Entities/Messages/MessageHelper.cs index d6a718b3a..e22ae71cd 100644 --- a/src/Discord.Net.Rest/Entities/Messages/MessageHelper.cs +++ b/src/Discord.Net.Rest/Entities/Messages/MessageHelper.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Model = Discord.API.Message; +using UserModel = Discord.API.User; namespace Discord.Rest { @@ -26,21 +27,46 @@ namespace Discord.Rest public static async Task ModifyAsync(IMessage msg, BaseDiscordClient client, Action func, RequestOptions options) { - if (msg.Author.Id != client.CurrentUser.Id) - throw new InvalidOperationException("Only the author of a message may modify the message."); - var args = new MessageProperties(); func(args); + if (msg.Author.Id != client.CurrentUser.Id && (args.Content.IsSpecified || args.Embed.IsSpecified || args.AllowedMentions.IsSpecified)) + throw new InvalidOperationException("Only the author of a message may modify the message content, embed, or allowed mentions."); + bool hasText = args.Content.IsSpecified ? !string.IsNullOrEmpty(args.Content.Value) : !string.IsNullOrEmpty(msg.Content); bool hasEmbed = args.Embed.IsSpecified ? args.Embed.Value != null : msg.Embeds.Any(); if (!hasText && !hasEmbed) Preconditions.NotNullOrEmpty(args.Content.IsSpecified ? args.Content.Value : string.Empty, nameof(args.Content)); + if (args.AllowedMentions.IsSpecified) + { + AllowedMentions allowedMentions = args.AllowedMentions.Value; + Preconditions.AtMost(allowedMentions?.RoleIds?.Count ?? 0, 100, nameof(allowedMentions.RoleIds), "A max of 100 role Ids are allowed."); + Preconditions.AtMost(allowedMentions?.UserIds?.Count ?? 0, 100, nameof(allowedMentions.UserIds), "A max of 100 user Ids are allowed."); + + // check that user flag and user Id list are exclusive, same with role flag and role Id list + if (allowedMentions != null && allowedMentions.AllowedTypes.HasValue) + { + if (allowedMentions.AllowedTypes.Value.HasFlag(AllowedMentionTypes.Users) && + allowedMentions.UserIds != null && allowedMentions.UserIds.Count > 0) + { + throw new ArgumentException("The Users flag is mutually exclusive with the list of User Ids.", nameof(allowedMentions)); + } + + if (allowedMentions.AllowedTypes.Value.HasFlag(AllowedMentionTypes.Roles) && + allowedMentions.RoleIds != null && allowedMentions.RoleIds.Count > 0) + { + throw new ArgumentException("The Roles flag is mutually exclusive with the list of Role Ids.", nameof(allowedMentions)); + } + } + } + var apiArgs = new API.Rest.ModifyMessageParams { Content = args.Content, - Embed = args.Embed.IsSpecified ? args.Embed.Value.ToModel() : Optional.Create() + Embed = args.Embed.IsSpecified ? args.Embed.Value.ToModel() : Optional.Create(), + Flags = args.Flags.IsSpecified ? args.Flags.Value : Optional.Create(), + AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value.ToModel() : Optional.Create(), }; return await client.ApiClient.ModifyMessageAsync(msg.Channel.Id, msg.Id, apiArgs, options).ConfigureAwait(false); } @@ -65,12 +91,12 @@ namespace Discord.Rest public static async Task AddReactionAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options) { - await client.ApiClient.AddReactionAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : emote.Name, options).ConfigureAwait(false); + await client.ApiClient.AddReactionAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false); } public static async Task RemoveReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options) { - await client.ApiClient.RemoveReactionAsync(msg.Channel.Id, msg.Id, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : emote.Name, options).ConfigureAwait(false); + await client.ApiClient.RemoveReactionAsync(msg.Channel.Id, msg.Id, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false); } public static async Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options) @@ -80,14 +106,14 @@ namespace Discord.Rest public static async Task RemoveAllReactionsForEmoteAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options) { - await client.ApiClient.RemoveAllReactionsForEmoteAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : emote.Name, options).ConfigureAwait(false); + await client.ApiClient.RemoveAllReactionsForEmoteAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false); } public static IAsyncEnumerable> GetReactionUsersAsync(IMessage msg, IEmote emote, int? limit, BaseDiscordClient client, RequestOptions options) { Preconditions.NotNull(emote, nameof(emote)); - var emoji = (emote is Emote e ? $"{e.Name}:{e.Id}" : emote.Name); + var emoji = (emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name)); return new PagedAsyncEnumerable( DiscordConfig.MaxUserReactionsPerBatch, @@ -114,7 +140,15 @@ namespace Discord.Rest }, count: limit ); + } + private static string UrlEncode(string text) + { +#if NET461 + return System.Net.WebUtility.UrlEncode(text); +#else + return System.Web.HttpUtility.UrlEncode(text); +#endif } public static async Task PinAsync(IMessage msg, BaseDiscordClient client, @@ -282,7 +316,7 @@ namespace Discord.Rest public static MessageSource GetSource(Model msg) { - if (msg.Type != MessageType.Default) + if (msg.Type != MessageType.Default && msg.Type != MessageType.Reply) return MessageSource.System; else if (msg.WebhookId.IsSpecified) return MessageSource.Webhook; @@ -299,5 +333,15 @@ namespace Discord.Rest { await client.ApiClient.CrosspostAsync(channelId, msgId, options).ConfigureAwait(false); } + + public static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId) + { + IUser author = null; + if (guild != null) + author = guild.GetUserAsync(model.Id, CacheMode.CacheOnly).Result; + if (author == null) + author = RestUser.Create(client, guild, model, webhookId); + return author; + } } } diff --git a/src/Discord.Net.Rest/Entities/Messages/RestMessage.cs b/src/Discord.Net.Rest/Entities/Messages/RestMessage.cs index 809a55e9c..b2a745980 100644 --- a/src/Discord.Net.Rest/Entities/Messages/RestMessage.cs +++ b/src/Discord.Net.Rest/Entities/Messages/RestMessage.cs @@ -37,6 +37,9 @@ namespace Discord.Rest public virtual bool IsSuppressed => false; /// public virtual DateTimeOffset? EditedTimestamp => null; + /// + public virtual bool MentionedEveryone => false; + /// /// Gets a collection of the 's on the message. /// @@ -64,6 +67,8 @@ namespace Discord.Rest public MessageApplication Application { get; private set; } /// public MessageReference Reference { get; private set; } + /// + public MessageFlags? Flags { get; private set; } internal RestMessage(BaseDiscordClient discord, ulong id, IMessageChannel channel, IUser author, MessageSource source) : base(discord, id) @@ -74,7 +79,7 @@ namespace Discord.Rest } internal static RestMessage Create(BaseDiscordClient discord, IMessageChannel channel, IUser author, Model model) { - if (model.Type == MessageType.Default) + if (model.Type == MessageType.Default || model.Type == MessageType.Reply) return RestUserMessage.Create(discord, channel, author, model); else return RestSystemMessage.Create(discord, channel, author, model); @@ -116,11 +121,14 @@ namespace Discord.Rest Reference = new MessageReference { GuildId = model.Reference.Value.GuildId, - ChannelId = model.Reference.Value.ChannelId, + InternalChannelId = model.Reference.Value.ChannelId, MessageId = model.Reference.Value.MessageId }; } + if (model.Flags.IsSpecified) + Flags = model.Flags.Value; + if (model.Reactions.IsSpecified) { var value = model.Reactions.Value; diff --git a/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs b/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs index ad2a65615..cf025aea1 100644 --- a/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs +++ b/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs @@ -13,32 +13,39 @@ namespace Discord.Rest [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class RestUserMessage : RestMessage, IUserMessage { - private bool _isMentioningEveryone, _isTTS, _isPinned, _isSuppressed; + private bool _isMentioningEveryone, _isTTS, _isPinned; private long? _editedTimestampTicks; + private IUserMessage _referencedMessage; private ImmutableArray _attachments = ImmutableArray.Create(); private ImmutableArray _embeds = ImmutableArray.Create(); private ImmutableArray _tags = ImmutableArray.Create(); + private ImmutableArray _roleMentionIds = ImmutableArray.Create(); + private ImmutableArray _userMentions = ImmutableArray.Create(); /// public override bool IsTTS => _isTTS; /// public override bool IsPinned => _isPinned; /// - public override bool IsSuppressed => _isSuppressed; + public override bool IsSuppressed => Flags.HasValue && Flags.Value.HasFlag(MessageFlags.SuppressEmbeds); /// public override DateTimeOffset? EditedTimestamp => DateTimeUtils.FromTicks(_editedTimestampTicks); /// + public override bool MentionedEveryone => _isMentioningEveryone; + /// public override IReadOnlyCollection Attachments => _attachments; /// public override IReadOnlyCollection Embeds => _embeds; /// public override IReadOnlyCollection MentionedChannelIds => MessageHelper.FilterTagsByKey(TagType.ChannelMention, _tags); /// - public override IReadOnlyCollection MentionedRoleIds => MessageHelper.FilterTagsByKey(TagType.RoleMention, _tags); + public override IReadOnlyCollection MentionedRoleIds => _roleMentionIds; /// - public override IReadOnlyCollection MentionedUsers => MessageHelper.FilterTagsByValue(TagType.UserMention, _tags); + public override IReadOnlyCollection MentionedUsers => _userMentions; /// public override IReadOnlyCollection Tags => _tags; + /// + public IUserMessage ReferencedMessage => _referencedMessage; internal RestUserMessage(BaseDiscordClient discord, ulong id, IMessageChannel channel, IUser author, MessageSource source) : base(discord, id, channel, author, source) @@ -63,10 +70,8 @@ namespace Discord.Rest _editedTimestampTicks = model.EditedTimestamp.Value?.UtcTicks; if (model.MentionEveryone.IsSpecified) _isMentioningEveryone = model.MentionEveryone.Value; - if (model.Flags.IsSpecified) - { - _isSuppressed = model.Flags.Value.HasFlag(API.MessageFlags.Suppressed); - } + if (model.RoleMentions.IsSpecified) + _roleMentionIds = model.RoleMentions.Value.ToImmutableArray(); if (model.Attachments.IsSpecified) { @@ -96,31 +101,37 @@ namespace Discord.Rest _embeds = ImmutableArray.Create(); } - ImmutableArray mentions = ImmutableArray.Create(); if (model.UserMentions.IsSpecified) { var value = model.UserMentions.Value; if (value.Length > 0) { - var newMentions = ImmutableArray.CreateBuilder(value.Length); + var newMentions = ImmutableArray.CreateBuilder(value.Length); for (int i = 0; i < value.Length; i++) { var val = value[i]; if (val.Object != null) newMentions.Add(RestUser.Create(Discord, val.Object)); } - mentions = newMentions.ToImmutable(); + _userMentions = newMentions.ToImmutable(); } } + var guildId = (Channel as IGuildChannel)?.GuildId; + var guild = guildId != null ? (Discord as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).Result : null; if (model.Content.IsSpecified) { var text = model.Content.Value; - var guildId = (Channel as IGuildChannel)?.GuildId; - var guild = guildId != null ? (Discord as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).Result : null; - _tags = MessageHelper.ParseTags(text, null, guild, mentions); + _tags = MessageHelper.ParseTags(text, null, guild, _userMentions); model.Content = text; } + + if (model.ReferencedMessage.IsSpecified && model.ReferencedMessage.Value != null) + { + var refMsg = model.ReferencedMessage.Value; + IUser refMsgAuthor = MessageHelper.GetAuthor(Discord, guild, refMsg.Author.Value, refMsg.WebhookId.ToNullable()); + _referencedMessage = RestUserMessage.Create(Discord, Channel, refMsgAuthor, refMsg); + } } /// @@ -149,10 +160,10 @@ namespace Discord.Rest => MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling); /// - /// This operation may only be called on a channel. + /// This operation may only be called on a channel. public async Task CrosspostAsync(RequestOptions options = null) { - if (!(Channel is RestNewsChannel)) + if (!(Channel is INewsChannel)) { throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels."); } diff --git a/src/Discord.Net.Rest/Entities/RestApplication.cs b/src/Discord.Net.Rest/Entities/RestApplication.cs index d033978d0..5c2f872cf 100644 --- a/src/Discord.Net.Rest/Entities/RestApplication.cs +++ b/src/Discord.Net.Rest/Entities/RestApplication.cs @@ -21,6 +21,12 @@ namespace Discord.Rest public string[] RPCOrigins { get; private set; } /// public ulong Flags { get; private set; } + /// + public bool IsBotPublic { get; private set; } + /// + public bool BotRequiresCodeGrant { get; private set; } + /// + public ITeam Team { get; private set; } /// public IUser Owner { get; private set; } @@ -46,11 +52,15 @@ namespace Discord.Rest RPCOrigins = model.RPCOrigins; Name = model.Name; _iconId = model.Icon; + IsBotPublic = model.IsBotPublic; + BotRequiresCodeGrant = model.BotRequiresCodeGrant; if (model.Flags.IsSpecified) Flags = model.Flags.Value; //TODO: Do we still need this? if (model.Owner.IsSpecified) Owner = RestUser.Create(Discord, model.Owner.Value); + if (model.Team != null) + Team = RestTeam.Create(Discord, model.Team); } /// Unable to update this object from a different application token. diff --git a/src/Discord.Net.Rest/Entities/Roles/RestRole.cs b/src/Discord.Net.Rest/Entities/Roles/RestRole.cs index 7c1a3aaa2..aa33ae7e5 100644 --- a/src/Discord.Net.Rest/Entities/Roles/RestRole.cs +++ b/src/Discord.Net.Rest/Entities/Roles/RestRole.cs @@ -26,6 +26,8 @@ namespace Discord.Rest public GuildPermissions Permissions { get; private set; } /// public int Position { get; private set; } + /// + public RoleTags Tags { get; private set; } /// public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id); @@ -56,6 +58,8 @@ namespace Discord.Rest Position = model.Position; Color = new Color(model.Color); Permissions = new GuildPermissions(model.Permissions); + if (model.Tags.IsSpecified) + Tags = model.Tags.Value.ToEntity(); } /// diff --git a/src/Discord.Net.Rest/Entities/Teams/RestTeam.cs b/src/Discord.Net.Rest/Entities/Teams/RestTeam.cs new file mode 100644 index 000000000..2343f8b5d --- /dev/null +++ b/src/Discord.Net.Rest/Entities/Teams/RestTeam.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Model = Discord.API.Team; + +namespace Discord.Rest +{ + public class RestTeam : RestEntity, ITeam + { + /// + public string IconUrl => _iconId != null ? CDN.GetTeamIconUrl(Id, _iconId) : null; + /// + public IReadOnlyList TeamMembers { get; private set; } + /// + public ulong OwnerUserId { get; private set; } + + private string _iconId; + + internal RestTeam(BaseDiscordClient discord, ulong id) + : base(discord, id) + { + } + internal static RestTeam Create(BaseDiscordClient discord, Model model) + { + var entity = new RestTeam(discord, model.Id); + entity.Update(model); + return entity; + } + internal virtual void Update(Model model) + { + if (model.Icon.IsSpecified) + _iconId = model.Icon.Value; + OwnerUserId = model.OwnerUserId; + TeamMembers = model.TeamMembers.Select(x => new RestTeamMember(Discord, x)).ToImmutableArray(); + } + } +} diff --git a/src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs b/src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs new file mode 100644 index 000000000..322bb6a3f --- /dev/null +++ b/src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs @@ -0,0 +1,30 @@ +using System; +using Model = Discord.API.TeamMember; + +namespace Discord.Rest +{ + public class RestTeamMember : ITeamMember + { + /// + public MembershipState MembershipState { get; } + /// + public string[] Permissions { get; } + /// + public ulong TeamId { get; } + /// + public IUser User { get; } + + internal RestTeamMember(BaseDiscordClient discord, Model model) + { + MembershipState = model.MembershipState switch + { + API.MembershipState.Invited => MembershipState.Invited, + API.MembershipState.Accepted => MembershipState.Accepted, + _ => throw new InvalidOperationException("Invalid membership state"), + }; + Permissions = model.Permissions; + TeamId = model.TeamId; + User = RestUser.Create(discord, model.User); + } + } +} diff --git a/src/Discord.Net.Rest/Entities/Users/RestGuildUser.cs b/src/Discord.Net.Rest/Entities/Users/RestGuildUser.cs index d6a8c2eda..4a6bc1025 100644 --- a/src/Discord.Net.Rest/Entities/Users/RestGuildUser.cs +++ b/src/Discord.Net.Rest/Entities/Users/RestGuildUser.cs @@ -29,6 +29,8 @@ namespace Discord.Rest public DateTimeOffset? PremiumSince => DateTimeUtils.FromTicks(_premiumSinceTicks); /// public ulong GuildId => Guild.Id; + /// + public bool? IsPending { get; private set; } /// /// Resolving permissions requires the parent guild to be downloaded. @@ -73,6 +75,8 @@ namespace Discord.Rest UpdateRoles(model.Roles.Value); if (model.PremiumSince.IsSpecified) _premiumSinceTicks = model.PremiumSince.Value?.UtcTicks; + if (model.Pending.IsSpecified) + IsPending = model.Pending.Value; } private void UpdateRoles(ulong[] roleIds) { diff --git a/src/Discord.Net.Rest/Entities/Users/RestUser.cs b/src/Discord.Net.Rest/Entities/Users/RestUser.cs index d5fffca94..131a4ec73 100644 --- a/src/Discord.Net.Rest/Entities/Users/RestUser.cs +++ b/src/Discord.Net.Rest/Entities/Users/RestUser.cs @@ -21,6 +21,8 @@ namespace Discord.Rest public ushort DiscriminatorValue { get; private set; } /// public string AvatarId { get; private set; } + /// + public UserProperties? PublicFlags { get; private set; } /// public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id); @@ -35,6 +37,8 @@ namespace Discord.Rest /// public virtual IImmutableSet ActiveClients => ImmutableHashSet.Empty; /// + public virtual IImmutableList Activities => ImmutableList.Empty; + /// public virtual bool IsWebhook => false; internal RestUser(BaseDiscordClient discord, ulong id) @@ -63,6 +67,8 @@ namespace Discord.Rest IsBot = model.Bot.Value; if (model.Username.IsSpecified) Username = model.Username.Value; + if (model.PublicFlags.IsSpecified) + PublicFlags = model.PublicFlags.Value; } /// diff --git a/src/Discord.Net.Rest/Entities/Users/RestWebhookUser.cs b/src/Discord.Net.Rest/Entities/Users/RestWebhookUser.cs index 8462cb8d4..a06916c9b 100644 --- a/src/Discord.Net.Rest/Entities/Users/RestWebhookUser.cs +++ b/src/Discord.Net.Rest/Entities/Users/RestWebhookUser.cs @@ -52,6 +52,8 @@ namespace Discord.Rest /// string IGuildUser.Nickname => null; /// + bool? IGuildUser.IsPending => null; + /// GuildPermissions IGuildUser.GuildPermissions => GuildPermissions.Webhook; /// diff --git a/src/Discord.Net.Rest/Extensions/EntityExtensions.cs b/src/Discord.Net.Rest/Extensions/EntityExtensions.cs index abdfc9d4f..f8676c783 100644 --- a/src/Discord.Net.Rest/Extensions/EntityExtensions.cs +++ b/src/Discord.Net.Rest/Extensions/EntityExtensions.cs @@ -34,6 +34,13 @@ namespace Discord.Rest model.Thumbnail.IsSpecified ? model.Thumbnail.Value.ToEntity() : (EmbedThumbnail?)null, model.Fields.IsSpecified ? model.Fields.Value.Select(x => x.ToEntity()).ToImmutableArray() : ImmutableArray.Create()); } + public static RoleTags ToEntity(this API.RoleTags model) + { + return new RoleTags( + model.BotId.IsSpecified ? model.BotId.Value : null, + model.IntegrationId.IsSpecified ? model.IntegrationId.Value : null, + model.IsPremiumSubscriber.IsSpecified ? true : false); + } public static API.Embed ToModel(this Embed entity) { if (entity == null) return null; @@ -68,6 +75,16 @@ namespace Discord.Rest Parse = entity.AllowedTypes?.EnumerateMentionTypes().ToArray(), Roles = entity.RoleIds?.ToArray(), Users = entity.UserIds?.ToArray(), + RepliedUser = entity.MentionRepliedUser ?? Optional.Create(), + }; + } + public static API.MessageReference ToModel(this MessageReference entity) + { + return new API.MessageReference() + { + ChannelId = entity.InternalChannelId, + GuildId = entity.GuildId, + MessageId = entity.MessageId, }; } public static IEnumerable EnumerateMentionTypes(this AllowedMentionTypes mentionTypes) diff --git a/src/Discord.Net.Rest/Net/Queue/ClientBucket.cs b/src/Discord.Net.Rest/Net/Queue/ClientBucket.cs index cd9d8aa54..e726a08cf 100644 --- a/src/Discord.Net.Rest/Net/Queue/ClientBucket.cs +++ b/src/Discord.Net.Rest/Net/Queue/ClientBucket.cs @@ -10,14 +10,14 @@ namespace Discord.Net.Queue internal struct ClientBucket { private static readonly ImmutableDictionary DefsByType; - private static readonly ImmutableDictionary DefsById; + private static readonly ImmutableDictionary DefsById; static ClientBucket() { var buckets = new[] { - new ClientBucket(ClientBucketType.Unbucketed, "", 10, 10), - new ClientBucket(ClientBucketType.SendEdit, "", 10, 10) + new ClientBucket(ClientBucketType.Unbucketed, BucketId.Create(null, "", null), 10, 10), + new ClientBucket(ClientBucketType.SendEdit, BucketId.Create(null, "", null), 10, 10) }; var builder = ImmutableDictionary.CreateBuilder(); @@ -25,21 +25,21 @@ namespace Discord.Net.Queue builder.Add(bucket.Type, bucket); DefsByType = builder.ToImmutable(); - var builder2 = ImmutableDictionary.CreateBuilder(); + var builder2 = ImmutableDictionary.CreateBuilder(); foreach (var bucket in buckets) builder2.Add(bucket.Id, bucket); DefsById = builder2.ToImmutable(); } public static ClientBucket Get(ClientBucketType type) => DefsByType[type]; - public static ClientBucket Get(string id) => DefsById[id]; + public static ClientBucket Get(BucketId id) => DefsById[id]; public ClientBucketType Type { get; } - public string Id { get; } + public BucketId Id { get; } public int WindowCount { get; } public int WindowSeconds { get; } - public ClientBucket(ClientBucketType type, string id, int count, int seconds) + public ClientBucket(ClientBucketType type, BucketId id, int count, int seconds) { Type = type; Id = id; diff --git a/src/Discord.Net.Rest/Net/Queue/GatewayBucket.cs b/src/Discord.Net.Rest/Net/Queue/GatewayBucket.cs new file mode 100644 index 000000000..aa849018a --- /dev/null +++ b/src/Discord.Net.Rest/Net/Queue/GatewayBucket.cs @@ -0,0 +1,53 @@ +using System.Collections.Immutable; + +namespace Discord.Net.Queue +{ + public enum GatewayBucketType + { + Unbucketed = 0, + Identify = 1, + PresenceUpdate = 2, + } + internal struct GatewayBucket + { + private static readonly ImmutableDictionary DefsByType; + private static readonly ImmutableDictionary DefsById; + + static GatewayBucket() + { + var buckets = new[] + { + // Limit is 120/60s, but 3 will be reserved for heartbeats (2 for possible heartbeats in the same timeframe and a possible failure) + new GatewayBucket(GatewayBucketType.Unbucketed, BucketId.Create(null, "", null), 117, 60), + new GatewayBucket(GatewayBucketType.Identify, BucketId.Create(null, "", null), 1, 5), + new GatewayBucket(GatewayBucketType.PresenceUpdate, BucketId.Create(null, "", null), 5, 60), + }; + + var builder = ImmutableDictionary.CreateBuilder(); + foreach (var bucket in buckets) + builder.Add(bucket.Type, bucket); + DefsByType = builder.ToImmutable(); + + var builder2 = ImmutableDictionary.CreateBuilder(); + foreach (var bucket in buckets) + builder2.Add(bucket.Id, bucket); + DefsById = builder2.ToImmutable(); + } + + public static GatewayBucket Get(GatewayBucketType type) => DefsByType[type]; + public static GatewayBucket Get(BucketId id) => DefsById[id]; + + public GatewayBucketType Type { get; } + public BucketId Id { get; } + public int WindowCount { get; set; } + public int WindowSeconds { get; set; } + + public GatewayBucket(GatewayBucketType type, BucketId id, int count, int seconds) + { + Type = type; + Id = id; + WindowCount = count; + WindowSeconds = seconds; + } + } +} diff --git a/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs b/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs index 4baf76433..2bf8e20b0 100644 --- a/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs +++ b/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs @@ -12,9 +12,9 @@ namespace Discord.Net.Queue { internal class RequestQueue : IDisposable { - public event Func RateLimitTriggered; + public event Func RateLimitTriggered; - private readonly ConcurrentDictionary _buckets; + private readonly ConcurrentDictionary _buckets; private readonly SemaphoreSlim _tokenLock; private readonly CancellationTokenSource _cancelTokenSource; //Dispose token private CancellationTokenSource _clearToken; @@ -34,7 +34,7 @@ namespace Discord.Net.Queue _requestCancelToken = CancellationToken.None; _parentToken = CancellationToken.None; - _buckets = new ConcurrentDictionary(); + _buckets = new ConcurrentDictionary(); _cleanupTask = RunCleanup(); } @@ -82,16 +82,25 @@ namespace Discord.Net.Queue else request.Options.CancelToken = _requestCancelToken; - var bucket = GetOrCreateBucket(request.Options.BucketId, request); + var bucket = GetOrCreateBucket(request.Options, request); var result = await bucket.SendAsync(request).ConfigureAwait(false); createdTokenSource?.Dispose(); return result; } public async Task SendAsync(WebSocketRequest request) { - //TODO: Re-impl websocket buckets - request.CancelToken = _requestCancelToken; - await request.SendAsync().ConfigureAwait(false); + CancellationTokenSource createdTokenSource = null; + if (request.Options.CancelToken.CanBeCanceled) + { + createdTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_requestCancelToken, request.Options.CancelToken); + request.Options.CancelToken = createdTokenSource.Token; + } + else + request.Options.CancelToken = _requestCancelToken; + + var bucket = GetOrCreateBucket(request.Options, request); + await bucket.SendAsync(request).ConfigureAwait(false); + createdTokenSource?.Dispose(); } internal async Task EnterGlobalAsync(int id, RestRequest request) @@ -109,14 +118,53 @@ namespace Discord.Net.Queue { _waitUntil = DateTimeOffset.UtcNow.AddMilliseconds(info.RetryAfter.Value + (info.Lag?.TotalMilliseconds ?? 0.0)); } + internal async Task EnterGlobalAsync(int id, WebSocketRequest request) + { + //If this is a global request (unbucketed), it'll be dealt in EnterAsync + var requestBucket = GatewayBucket.Get(request.Options.BucketId); + if (requestBucket.Type == GatewayBucketType.Unbucketed) + return; + + //It's not a global request, so need to remove one from global (per-session) + var globalBucketType = GatewayBucket.Get(GatewayBucketType.Unbucketed); + var options = RequestOptions.CreateOrClone(request.Options); + options.BucketId = globalBucketType.Id; + var globalRequest = new WebSocketRequest(null, null, false, false, options); + var globalBucket = GetOrCreateBucket(options, globalRequest); + await globalBucket.TriggerAsync(id, globalRequest); + } - private RequestBucket GetOrCreateBucket(string id, RestRequest request) + private RequestBucket GetOrCreateBucket(RequestOptions options, IRequest request) + { + var bucketId = options.BucketId; + object obj = _buckets.GetOrAdd(bucketId, x => new RequestBucket(this, request, x)); + if (obj is BucketId hashBucket) + { + options.BucketId = hashBucket; + return (RequestBucket)_buckets.GetOrAdd(hashBucket, x => new RequestBucket(this, request, x)); + } + return (RequestBucket)obj; + } + internal async Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint) { - return _buckets.GetOrAdd(id, x => new RequestBucket(this, request, x)); + await RateLimitTriggered(bucketId, info, endpoint).ConfigureAwait(false); } - internal async Task RaiseRateLimitTriggered(string bucketId, RateLimitInfo? info) + internal (RequestBucket, BucketId) UpdateBucketHash(BucketId id, string discordHash) + { + if (!id.IsHashBucket) + { + var bucket = BucketId.Create(discordHash, id); + var hashReqQueue = (RequestBucket)_buckets.GetOrAdd(bucket, _buckets[id]); + _buckets.AddOrUpdate(id, bucket, (oldBucket, oldObj) => bucket); + return (hashReqQueue, bucket); + } + return (null, null); + } + + public void ClearGatewayBuckets() { - await RateLimitTriggered(bucketId, info).ConfigureAwait(false); + foreach (var gwBucket in (GatewayBucketType[])Enum.GetValues(typeof(GatewayBucketType))) + _buckets.TryRemove(GatewayBucket.Get(gwBucket).Id, out _); } private async Task RunCleanup() @@ -126,10 +174,15 @@ namespace Discord.Net.Queue while (!_cancelTokenSource.IsCancellationRequested) { var now = DateTimeOffset.UtcNow; - foreach (var bucket in _buckets.Select(x => x.Value)) + foreach (var bucket in _buckets.Where(x => x.Value is RequestBucket).Select(x => (RequestBucket)x.Value)) { if ((now - bucket.LastAttemptAt).TotalMinutes > 1.0) + { + if (bucket.Id.IsHashBucket) + foreach (var redirectBucket in _buckets.Where(x => x.Value == bucket.Id).Select(x => (BucketId)x.Value)) + _buckets.TryRemove(redirectBucket, out _); //remove redirections if hash bucket _buckets.TryRemove(bucket.Id, out _); + } } await Task.Delay(60000, _cancelTokenSource.Token).ConfigureAwait(false); //Runs each minute } diff --git a/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs b/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs index 771923cd4..3fb45e55d 100644 --- a/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs +++ b/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs @@ -19,12 +19,13 @@ namespace Discord.Net.Queue private readonly RequestQueue _queue; private int _semaphore; private DateTimeOffset? _resetTick; + private RequestBucket _redirectBucket; - public string Id { get; private set; } + public BucketId Id { get; private set; } public int WindowCount { get; private set; } public DateTimeOffset LastAttemptAt { get; private set; } - public RequestBucket(RequestQueue queue, RestRequest request, string id) + public RequestBucket(RequestQueue queue, IRequest request, BucketId id) { _queue = queue; Id = id; @@ -33,6 +34,8 @@ namespace Discord.Net.Queue if (request.Options.IsClientBucket) WindowCount = ClientBucket.Get(request.Options.BucketId).WindowCount; + else if (request.Options.IsGatewayBucket) + WindowCount = GatewayBucket.Get(request.Options.BucketId).WindowCount; else WindowCount = 1; //Only allow one request until we get a header back _semaphore = WindowCount; @@ -52,6 +55,8 @@ namespace Discord.Net.Queue { await _queue.EnterGlobalAsync(id, request).ConfigureAwait(false); await EnterAsync(id, request).ConfigureAwait(false); + if (_redirectBucket != null) + return await _redirectBucket.SendAsync(request); #if DEBUG_LIMITS Debug.WriteLine($"[{id}] Sending..."); @@ -81,7 +86,7 @@ namespace Discord.Net.Queue #endif UpdateRateLimit(id, request, info, true); } - await _queue.RaiseRateLimitTriggered(Id, info).ConfigureAwait(false); + await _queue.RaiseRateLimitTriggered(Id, info, $"{request.Method} {request.Endpoint}").ConfigureAwait(false); continue; //Retry case HttpStatusCode.BadGateway: //502 #if DEBUG_LIMITS @@ -151,8 +156,68 @@ namespace Discord.Net.Queue } } } + public async Task SendAsync(WebSocketRequest request) + { + int id = Interlocked.Increment(ref nextId); +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Start"); +#endif + LastAttemptAt = DateTimeOffset.UtcNow; + while (true) + { + await _queue.EnterGlobalAsync(id, request).ConfigureAwait(false); + await EnterAsync(id, request).ConfigureAwait(false); + +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Sending..."); +#endif + try + { + await request.SendAsync().ConfigureAwait(false); + return; + } + catch (TimeoutException) + { +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Timeout"); +#endif + if ((request.Options.RetryMode & RetryMode.RetryTimeouts) == 0) + throw; - private async Task EnterAsync(int id, RestRequest request) + await Task.Delay(500).ConfigureAwait(false); + continue; //Retry + } + /*catch (Exception) + { +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Error"); +#endif + if ((request.Options.RetryMode & RetryMode.RetryErrors) == 0) + throw; + + await Task.Delay(500); + continue; //Retry + }*/ + finally + { + UpdateRateLimit(id, request, default(RateLimitInfo), false); +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Stop"); +#endif + } + } + } + + internal async Task TriggerAsync(int id, IRequest request) + { +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Trigger Bucket"); +#endif + await EnterAsync(id, request).ConfigureAwait(false); + UpdateRateLimit(id, request, default(RateLimitInfo), false); + } + + private async Task EnterAsync(int id, IRequest request) { int windowCount; DateTimeOffset? resetAt; @@ -160,6 +225,9 @@ namespace Discord.Net.Queue while (true) { + if (_redirectBucket != null) + break; + if (DateTimeOffset.UtcNow > request.TimeoutAt || request.Options.CancelToken.IsCancellationRequested) { if (!isRateLimited) @@ -175,12 +243,36 @@ namespace Discord.Net.Queue } DateTimeOffset? timeoutAt = request.TimeoutAt; - if (windowCount > 0 && Interlocked.Decrement(ref _semaphore) < 0) + int semaphore = Interlocked.Decrement(ref _semaphore); + if (windowCount > 0 && semaphore < 0) { if (!isRateLimited) { + bool ignoreRatelimit = false; isRateLimited = true; - await _queue.RaiseRateLimitTriggered(Id, null).ConfigureAwait(false); + switch (request) + { + case RestRequest restRequest: + await _queue.RaiseRateLimitTriggered(Id, null, $"{restRequest.Method} {restRequest.Endpoint}").ConfigureAwait(false); + break; + case WebSocketRequest webSocketRequest: + if (webSocketRequest.IgnoreLimit) + { + ignoreRatelimit = true; + break; + } + await _queue.RaiseRateLimitTriggered(Id, null, Id.Endpoint).ConfigureAwait(false); + break; + default: + throw new InvalidOperationException("Unknown request type"); + } + if (ignoreRatelimit) + { +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Ignoring ratelimit"); +#endif + break; + } } ThrowRetryLimit(request); @@ -210,20 +302,52 @@ namespace Discord.Net.Queue } #if DEBUG_LIMITS else - Debug.WriteLine($"[{id}] Entered Semaphore ({_semaphore}/{WindowCount} remaining)"); + Debug.WriteLine($"[{id}] Entered Semaphore ({semaphore}/{WindowCount} remaining)"); #endif break; } } - private void UpdateRateLimit(int id, RestRequest request, RateLimitInfo info, bool is429) + private void UpdateRateLimit(int id, IRequest request, RateLimitInfo info, bool is429, bool redirected = false) { if (WindowCount == 0) return; lock (_lock) { + if (redirected) + { + Interlocked.Decrement(ref _semaphore); //we might still hit a real ratelimit if all tickets were already taken, can't do much about it since we didn't know they were the same +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Decrease Semaphore"); +#endif + } bool hasQueuedReset = _resetTick != null; + + if (info.Bucket != null && !redirected) + { + (RequestBucket, BucketId) hashBucket = _queue.UpdateBucketHash(Id, info.Bucket); + if (!(hashBucket.Item1 is null) && !(hashBucket.Item2 is null)) + { + if (hashBucket.Item1 == this) //this bucket got promoted to a hash queue + { + Id = hashBucket.Item2; +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Promoted to Hash Bucket ({hashBucket.Item2})"); +#endif + } + else + { + _redirectBucket = hashBucket.Item1; //this request should be part of another bucket, this bucket will be disabled, redirect everything + _redirectBucket.UpdateRateLimit(id, request, info, is429, redirected: true); //update the hash bucket ratelimit +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Redirected to {_redirectBucket.Id}"); +#endif + return; + } + } + } + if (info.Limit.HasValue && WindowCount != info.Limit.Value) { WindowCount = info.Limit.Value; @@ -233,7 +357,6 @@ namespace Discord.Net.Queue #endif } - var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); DateTimeOffset? resetTick = null; //Using X-RateLimit-Remaining causes a race condition @@ -250,16 +373,18 @@ namespace Discord.Net.Queue Debug.WriteLine($"[{id}] Retry-After: {info.RetryAfter.Value} ({info.RetryAfter.Value} ms)"); #endif } - else if (info.ResetAfter.HasValue && (request.Options.UseSystemClock.HasValue ? !request.Options.UseSystemClock.Value : false)) - { - resetTick = DateTimeOffset.UtcNow.Add(info.ResetAfter.Value); - } + else if (info.ResetAfter.HasValue && (request.Options.UseSystemClock.HasValue ? !request.Options.UseSystemClock.Value : false)) + { + resetTick = DateTimeOffset.UtcNow.Add(info.ResetAfter.Value); +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Reset-After: {info.ResetAfter.Value} ({info.ResetAfter?.TotalMilliseconds} ms)"); +#endif + } else if (info.Reset.HasValue) { resetTick = info.Reset.Value.AddSeconds(info.Lag?.TotalSeconds ?? 1.0); - /* millisecond precision makes this unnecessary, retaining in case of regression - + /* millisecond precision makes this unnecessary, retaining in case of regression if (request.Options.IsReactionBucket) resetTick = DateTimeOffset.Now.AddMilliseconds(250); */ @@ -269,17 +394,34 @@ namespace Discord.Net.Queue Debug.WriteLine($"[{id}] X-RateLimit-Reset: {info.Reset.Value.ToUnixTimeSeconds()} ({diff} ms, {info.Lag?.TotalMilliseconds} ms lag)"); #endif } - else if (request.Options.IsClientBucket && request.Options.BucketId != null) + else if (request.Options.IsClientBucket && Id != null) + { + resetTick = DateTimeOffset.UtcNow.AddSeconds(ClientBucket.Get(Id).WindowSeconds); +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Client Bucket ({ClientBucket.Get(Id).WindowSeconds * 1000} ms)"); +#endif + } + else if (request.Options.IsGatewayBucket && request.Options.BucketId != null) { - resetTick = DateTimeOffset.UtcNow.AddSeconds(ClientBucket.Get(request.Options.BucketId).WindowSeconds); + resetTick = DateTimeOffset.UtcNow.AddSeconds(GatewayBucket.Get(request.Options.BucketId).WindowSeconds); +#if DEBUG_LIMITS + Debug.WriteLine($"[{id}] Gateway Bucket ({GatewayBucket.Get(request.Options.BucketId).WindowSeconds * 1000} ms)"); +#endif + if (!hasQueuedReset) + { + _resetTick = resetTick; + LastAttemptAt = resetTick.Value; #if DEBUG_LIMITS - Debug.WriteLine($"[{id}] Client Bucket ({ClientBucket.Get(request.Options.BucketId).WindowSeconds * 1000} ms)"); + Debug.WriteLine($"[{id}] Reset in {(int)Math.Ceiling((resetTick - DateTimeOffset.UtcNow).Value.TotalMilliseconds)} ms"); #endif + var _ = QueueReset(id, (int)Math.Ceiling((_resetTick.Value - DateTimeOffset.UtcNow).TotalMilliseconds), request); + } + return; } if (resetTick == null) { - WindowCount = 0; //No rate limit info, disable limits on this bucket (should only ever happen with a user token) + WindowCount = 0; //No rate limit info, disable limits on this bucket #if DEBUG_LIMITS Debug.WriteLine($"[{id}] Disabled Semaphore"); #endif @@ -296,12 +438,12 @@ namespace Discord.Net.Queue if (!hasQueuedReset) { - var _ = QueueReset(id, (int)Math.Ceiling((_resetTick.Value - DateTimeOffset.UtcNow).TotalMilliseconds)); + var _ = QueueReset(id, (int)Math.Ceiling((_resetTick.Value - DateTimeOffset.UtcNow).TotalMilliseconds), request); } } } } - private async Task QueueReset(int id, int millis) + private async Task QueueReset(int id, int millis, IRequest request) { while (true) { @@ -323,7 +465,7 @@ namespace Discord.Net.Queue } } - private void ThrowRetryLimit(RestRequest request) + private void ThrowRetryLimit(IRequest request) { if ((request.Options.RetryMode & RetryMode.RetryRatelimit) == 0) throw new RateLimitedException(request); diff --git a/src/Discord.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs b/src/Discord.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs index 81eb40b31..ebebd7bef 100644 --- a/src/Discord.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs +++ b/src/Discord.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs @@ -9,22 +9,22 @@ namespace Discord.Net.Queue public class WebSocketRequest : IRequest { public IWebSocketClient Client { get; } - public string BucketId { get; } public byte[] Data { get; } public bool IsText { get; } + public bool IgnoreLimit { get; } public DateTimeOffset? TimeoutAt { get; } public TaskCompletionSource Promise { get; } public RequestOptions Options { get; } public CancellationToken CancelToken { get; internal set; } - public WebSocketRequest(IWebSocketClient client, string bucketId, byte[] data, bool isText, RequestOptions options) + public WebSocketRequest(IWebSocketClient client, byte[] data, bool isText, bool ignoreLimit, RequestOptions options) { Preconditions.NotNull(options, nameof(options)); Client = client; - BucketId = bucketId; Data = data; IsText = isText; + IgnoreLimit = ignoreLimit; Options = options; TimeoutAt = options.Timeout.HasValue ? DateTimeOffset.UtcNow.AddMilliseconds(options.Timeout.Value) : (DateTimeOffset?)null; Promise = new TaskCompletionSource(); diff --git a/src/Discord.Net.Rest/Net/RateLimitInfo.cs b/src/Discord.Net.Rest/Net/RateLimitInfo.cs index 13e9e39a7..6a7df7b01 100644 --- a/src/Discord.Net.Rest/Net/RateLimitInfo.cs +++ b/src/Discord.Net.Rest/Net/RateLimitInfo.cs @@ -11,7 +11,8 @@ namespace Discord.Net public int? Remaining { get; } public int? RetryAfter { get; } public DateTimeOffset? Reset { get; } - public TimeSpan? ResetAfter { get; } + public TimeSpan? ResetAfter { get; } + public string Bucket { get; } public TimeSpan? Lag { get; } internal RateLimitInfo(Dictionary headers) @@ -26,8 +27,9 @@ namespace Discord.Net double.TryParse(temp, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var reset) ? DateTimeOffset.FromUnixTimeMilliseconds((long)(reset * 1000)) : (DateTimeOffset?)null; RetryAfter = headers.TryGetValue("Retry-After", out temp) && int.TryParse(temp, NumberStyles.None, CultureInfo.InvariantCulture, out var retryAfter) ? retryAfter : (int?)null; - ResetAfter = headers.TryGetValue("X-RateLimit-Reset-After", out temp) && - float.TryParse(temp, out var resetAfter) ? TimeSpan.FromMilliseconds((long)(resetAfter * 1000)) : (TimeSpan?)null; + ResetAfter = headers.TryGetValue("X-RateLimit-Reset-After", out temp) && + double.TryParse(temp, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var resetAfter) ? TimeSpan.FromMilliseconds((long)(resetAfter * 1000)) : (TimeSpan?)null; + Bucket = headers.TryGetValue("X-RateLimit-Bucket", out temp) ? temp : null; Lag = headers.TryGetValue("Date", out temp) && DateTimeOffset.TryParse(temp, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? DateTimeOffset.UtcNow - date : (TimeSpan?)null; } diff --git a/src/Discord.Net.WebSocket/API/Gateway/IdentifyParams.cs b/src/Discord.Net.WebSocket/API/Gateway/IdentifyParams.cs index e3e24491d..92a494b71 100644 --- a/src/Discord.Net.WebSocket/API/Gateway/IdentifyParams.cs +++ b/src/Discord.Net.WebSocket/API/Gateway/IdentifyParams.cs @@ -15,6 +15,8 @@ namespace Discord.API.Gateway public int LargeThreshold { get; set; } [JsonProperty("shard")] public Optional ShardingParams { get; set; } + [JsonProperty("presence")] + public Optional Presence { get; set; } [JsonProperty("guild_subscriptions")] public Optional GuildSubscriptions { get; set; } [JsonProperty("intents")] diff --git a/src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs b/src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs new file mode 100644 index 000000000..e2ddd8816 --- /dev/null +++ b/src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs @@ -0,0 +1,31 @@ +using Newtonsoft.Json; +using System; + +namespace Discord.API.Gateway +{ + internal class InviteCreateEvent + { + [JsonProperty("channel_id")] + public ulong ChannelId { get; set; } + [JsonProperty("code")] + public string Code { get; set; } + [JsonProperty("created_at")] + public DateTimeOffset CreatedAt { get; set; } + [JsonProperty("guild_id")] + public Optional GuildId { get; set; } + [JsonProperty("inviter")] + public Optional Inviter { get; set; } + [JsonProperty("max_age")] + public int MaxAge { get; set; } + [JsonProperty("max_uses")] + public int MaxUses { get; set; } + [JsonProperty("target_user")] + public Optional TargetUser { get; set; } + [JsonProperty("target_user_type")] + public Optional TargetUserType { get; set; } + [JsonProperty("temporary")] + public bool Temporary { get; set; } + [JsonProperty("uses")] + public int Uses { get; set; } + } +} diff --git a/src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs b/src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs new file mode 100644 index 000000000..54bc75595 --- /dev/null +++ b/src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace Discord.API.Gateway +{ + internal class InviteDeleteEvent + { + [JsonProperty("channel_id")] + public ulong ChannelId { get; set; } + [JsonProperty("code")] + public string Code { get; set; } + [JsonProperty("guild_id")] + public Optional GuildId { get; set; } + } +} diff --git a/src/Discord.Net.WebSocket/API/Gateway/StatusUpdateParams.cs b/src/Discord.Net.WebSocket/API/Gateway/StatusUpdateParams.cs index fc0964c17..5fec8b4bd 100644 --- a/src/Discord.Net.WebSocket/API/Gateway/StatusUpdateParams.cs +++ b/src/Discord.Net.WebSocket/API/Gateway/StatusUpdateParams.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API.Gateway diff --git a/src/Discord.Net.WebSocket/Audio/AudioClient.cs b/src/Discord.Net.WebSocket/Audio/AudioClient.cs index 2210e019f..3549fb106 100644 --- a/src/Discord.Net.WebSocket/Audio/AudioClient.cs +++ b/src/Discord.Net.WebSocket/Audio/AudioClient.cs @@ -99,6 +99,12 @@ namespace Discord.Audio _token = token; await _connection.StartAsync().ConfigureAwait(false); } + + public IReadOnlyDictionary GetStreams() + { + return _streams.ToDictionary(pair => pair.Key, pair => pair.Value.Reader); + } + public async Task StopAsync() { await _connection.StopAsync().ConfigureAwait(false); @@ -379,7 +385,7 @@ namespace Discord.Audio private async Task RunHeartbeatAsync(int intervalMillis, CancellationToken cancelToken) { - //TODO: Clean this up when Discord's session patch is live + // TODO: Clean this up when Discord's session patch is live try { await _audioLogger.DebugAsync("Heartbeat Started").ConfigureAwait(false); diff --git a/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs index 16ad0ae89..a2de252a2 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs @@ -61,14 +61,17 @@ namespace Discord.Audio.Streams _task = Run(); } + protected override void Dispose(bool disposing) { if (disposing) { _disposeTokenSource?.Cancel(); _disposeTokenSource?.Dispose(); + _cancelTokenSource?.Cancel(); _cancelTokenSource?.Dispose(); _queueLock?.Dispose(); + _next.Dispose(); } base.Dispose(disposing); } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs index 1861e3554..ad1c285e8 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs @@ -68,10 +68,12 @@ namespace Discord.Audio.Streams protected override void Dispose(bool disposing) { - base.Dispose(disposing); - if (disposing) + { _decoder.Dispose(); + _next.Dispose(); + } + base.Dispose(disposing); } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs index 035b92b30..05d12b490 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; @@ -89,10 +89,12 @@ namespace Discord.Audio.Streams protected override void Dispose(bool disposing) { - base.Dispose(disposing); - if (disposing) + { _encoder.Dispose(); + _next.Dispose(); + } + base.Dispose(disposing); } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs index 120f67e0d..1002502b6 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs @@ -76,5 +76,12 @@ namespace Discord.Audio.Streams (buffer[extensionOffset + 3]); return extensionOffset + 4 + (extensionLength * 4); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs index ce407eada..7ecb56bee 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; @@ -69,5 +69,12 @@ namespace Discord.Audio.Streams { await _next.ClearAsync(cancelToken).ConfigureAwait(false); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs index 2b1a97f04..40cd6864e 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs @@ -44,5 +44,12 @@ namespace Discord.Audio.Streams { await _next.ClearAsync(cancelToken).ConfigureAwait(false); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs index 8b3f0e302..fa1d34de5 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs @@ -60,5 +60,12 @@ namespace Discord.Audio.Streams { await _next.ClearAsync(cancelToken).ConfigureAwait(false); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs b/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs index 221067d22..110517999 100644 --- a/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs +++ b/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs @@ -405,5 +405,47 @@ namespace Discord.WebSocket remove { _recipientRemovedEvent.Remove(value); } } internal readonly AsyncEvent> _recipientRemovedEvent = new AsyncEvent>(); + + //Invites + /// + /// Fired when an invite is created. + /// + /// + /// + /// This event is fired when an invite is created. The event handler must return a + /// and accept a as its parameter. + /// + /// + /// The invite created will be passed into the parameter. + /// + /// + public event Func InviteCreated + { + add { _inviteCreatedEvent.Add(value); } + remove { _inviteCreatedEvent.Remove(value); } + } + internal readonly AsyncEvent> _inviteCreatedEvent = new AsyncEvent>(); + /// + /// Fired when an invite is deleted. + /// + /// + /// + /// This event is fired when an invite is deleted. The event handler must return + /// a and accept a and + /// as its parameter. + /// + /// + /// The channel where this invite was created will be passed into the parameter. + /// + /// + /// The code of the deleted invite will be passed into the parameter. + /// + /// + public event Func InviteDeleted + { + add { _inviteDeletedEvent.Add(value); } + remove { _inviteDeletedEvent.Remove(value); } + } + internal readonly AsyncEvent> _inviteDeletedEvent = new AsyncEvent>(); } } diff --git a/src/Discord.Net.WebSocket/BaseSocketClient.cs b/src/Discord.Net.WebSocket/BaseSocketClient.cs index 548bb75bf..425889613 100644 --- a/src/Discord.Net.WebSocket/BaseSocketClient.cs +++ b/src/Discord.Net.WebSocket/BaseSocketClient.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; @@ -75,6 +76,7 @@ namespace Discord.WebSocket /// /// A read-only collection of voice regions that the user has access to. /// + [Obsolete("This property is obsolete, use the GetVoiceRegionsAsync method instead.")] public abstract IReadOnlyCollection VoiceRegions { get; } internal BaseSocketClient(DiscordSocketConfig config, DiscordRestApiClient client) @@ -169,7 +171,26 @@ namespace Discord.WebSocket /// A REST-based voice region associated with the identifier; null if the voice region is not /// found. /// + [Obsolete("This method is obsolete, use GetVoiceRegionAsync instead.")] public abstract RestVoiceRegion GetVoiceRegion(string id); + /// + /// Gets all voice regions. + /// + /// The options to be used when sending the request. + /// + /// A task that contains a read-only collection of REST-based voice regions. + /// + public abstract ValueTask> GetVoiceRegionsAsync(RequestOptions options = null); + /// + /// Gets a voice region. + /// + /// The identifier of the voice region (e.g. eu-central ). + /// The options to be used when sending the request. + /// + /// A task that contains a REST-based voice region associated with the identifier; null if the + /// voice region is not found. + /// + public abstract ValueTask GetVoiceRegionAsync(string id, RequestOptions options = null); /// public abstract Task StartAsync(); /// diff --git a/src/Discord.Net.WebSocket/ConnectionManager.cs b/src/Discord.Net.WebSocket/ConnectionManager.cs index 8c9c743cb..2237e2d1f 100644 --- a/src/Discord.Net.WebSocket/ConnectionManager.cs +++ b/src/Discord.Net.WebSocket/ConnectionManager.cs @@ -44,6 +44,8 @@ namespace Discord var ex2 = ex as WebSocketClosedException; if (ex2?.CloseCode == 4006) CriticalError(new Exception("WebSocket session expired", ex)); + else if (ex2?.CloseCode == 4014) + CriticalError(new Exception("WebSocket connection was closed", ex)); else Error(new Exception("WebSocket connection was closed", ex)); } @@ -141,7 +143,16 @@ namespace Discord catch (OperationCanceledException) { } }); - await _onConnecting().ConfigureAwait(false); + try + { + await _onConnecting().ConfigureAwait(false); + } + catch (TaskCanceledException ex) + { + Exception innerEx = ex.InnerException ?? new OperationCanceledException("Failed to connect."); + Error(innerEx); + throw innerEx; + } await _logger.InfoAsync("Connected").ConfigureAwait(false); State = ConnectionState.Connected; diff --git a/src/Discord.Net.WebSocket/Discord.Net.WebSocket.csproj b/src/Discord.Net.WebSocket/Discord.Net.WebSocket.csproj index 26a249097..01aece130 100644 --- a/src/Discord.Net.WebSocket/Discord.Net.WebSocket.csproj +++ b/src/Discord.Net.WebSocket/Discord.Net.WebSocket.csproj @@ -1,5 +1,6 @@ + Discord.Net.WebSocket Discord.WebSocket diff --git a/src/Discord.Net.WebSocket/DiscordShardedClient.cs b/src/Discord.Net.WebSocket/DiscordShardedClient.cs index 930ea1585..4c94b14e8 100644 --- a/src/Discord.Net.WebSocket/DiscordShardedClient.cs +++ b/src/Discord.Net.WebSocket/DiscordShardedClient.cs @@ -12,12 +12,14 @@ namespace Discord.WebSocket public partial class DiscordShardedClient : BaseSocketClient, IDiscordClient { private readonly DiscordSocketConfig _baseConfig; - private readonly SemaphoreSlim _connectionGroupLock; private readonly Dictionary _shardIdsToIndex; private readonly bool _automaticShards; private int[] _shardIds; private DiscordSocketClient[] _shards; private int _totalShards; + private SemaphoreSlim[] _identifySemaphores; + private object _semaphoreResetLock; + private Task _semaphoreResetTask; private bool _isDisposed; @@ -35,6 +37,7 @@ namespace Discord.WebSocket public override IReadOnlyCollection PrivateChannels => GetPrivateChannels().ToReadOnlyCollection(GetPrivateChannelCount); public IReadOnlyCollection Shards => _shards; /// + [Obsolete("This property is obsolete, use the GetVoiceRegionsAsync method instead.")] public override IReadOnlyCollection VoiceRegions => _shards[0].VoiceRegions; /// @@ -62,10 +65,10 @@ namespace Discord.WebSocket if (ids != null && config.TotalShards == null) throw new ArgumentException($"Custom ids are not supported when {nameof(config.TotalShards)} is not specified."); + _semaphoreResetLock = new object(); _shardIdsToIndex = new Dictionary(); config.DisplayInitialLog = false; _baseConfig = config; - _connectionGroupLock = new SemaphoreSlim(1, 1); if (config.TotalShards == null) _automaticShards = true; @@ -74,12 +77,15 @@ namespace Discord.WebSocket _totalShards = config.TotalShards.Value; _shardIds = ids ?? Enumerable.Range(0, _totalShards).ToArray(); _shards = new DiscordSocketClient[_shardIds.Length]; + _identifySemaphores = new SemaphoreSlim[config.IdentifyMaxConcurrency]; + for (int i = 0; i < config.IdentifyMaxConcurrency; i++) + _identifySemaphores[i] = new SemaphoreSlim(1, 1); for (int i = 0; i < _shardIds.Length; i++) { _shardIdsToIndex.Add(_shardIds[i], i); var newConfig = config.Clone(); newConfig.ShardId = _shardIds[i]; - _shards[i] = new DiscordSocketClient(newConfig, _connectionGroupLock, i != 0 ? _shards[0] : null); + _shards[i] = new DiscordSocketClient(newConfig, this, i != 0 ? _shards[0] : null); RegisterEvents(_shards[i], i == 0); } } @@ -88,21 +94,53 @@ namespace Discord.WebSocket => new API.DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, rateLimitPrecision: config.RateLimitPrecision); + internal async Task AcquireIdentifyLockAsync(int shardId, CancellationToken token) + { + int semaphoreIdx = shardId % _baseConfig.IdentifyMaxConcurrency; + await _identifySemaphores[semaphoreIdx].WaitAsync(token).ConfigureAwait(false); + } + + internal void ReleaseIdentifyLock() + { + lock (_semaphoreResetLock) + { + if (_semaphoreResetTask == null) + _semaphoreResetTask = ResetSemaphoresAsync(); + } + } + + private async Task ResetSemaphoresAsync() + { + await Task.Delay(5000).ConfigureAwait(false); + lock (_semaphoreResetLock) + { + foreach (var semaphore in _identifySemaphores) + if (semaphore.CurrentCount == 0) + semaphore.Release(); + _semaphoreResetTask = null; + } + } + internal override async Task OnLoginAsync(TokenType tokenType, string token) { if (_automaticShards) { - var shardCount = await GetRecommendedShardCountAsync().ConfigureAwait(false); - _shardIds = Enumerable.Range(0, shardCount).ToArray(); + var botGateway = await GetBotGatewayAsync().ConfigureAwait(false); + _shardIds = Enumerable.Range(0, botGateway.Shards).ToArray(); _totalShards = _shardIds.Length; _shards = new DiscordSocketClient[_shardIds.Length]; + int maxConcurrency = botGateway.SessionStartLimit.MaxConcurrency; + _baseConfig.IdentifyMaxConcurrency = maxConcurrency; + _identifySemaphores = new SemaphoreSlim[maxConcurrency]; + for (int i = 0; i < maxConcurrency; i++) + _identifySemaphores[i] = new SemaphoreSlim(1, 1); for (int i = 0; i < _shardIds.Length; i++) { _shardIdsToIndex.Add(_shardIds[i], i); var newConfig = _baseConfig.Clone(); newConfig.ShardId = _shardIds[i]; newConfig.TotalShards = _totalShards; - _shards[i] = new DiscordSocketClient(newConfig, _connectionGroupLock, i != 0 ? _shards[0] : null); + _shards[i] = new DiscordSocketClient(newConfig, this, i != 0 ? _shards[0] : null); RegisterEvents(_shards[i], i == 0); } } @@ -227,9 +265,22 @@ namespace Discord.WebSocket } /// + [Obsolete("This method is obsolete, use GetVoiceRegionAsync instead.")] public override RestVoiceRegion GetVoiceRegion(string id) => _shards[0].GetVoiceRegion(id); + /// + public override async ValueTask> GetVoiceRegionsAsync(RequestOptions options = null) + { + return await _shards[0].GetVoiceRegionsAsync().ConfigureAwait(false); + } + + /// + public override async ValueTask GetVoiceRegionAsync(string id, RequestOptions options = null) + { + return await _shards[0].GetVoiceRegionAsync(id, options).ConfigureAwait(false); + } + /// /// is public override async Task DownloadUsersAsync(IEnumerable guilds) @@ -338,6 +389,9 @@ namespace Discord.WebSocket client.UserIsTyping += (oldUser, newUser) => _userIsTypingEvent.InvokeAsync(oldUser, newUser); client.RecipientAdded += (user) => _recipientAddedEvent.InvokeAsync(user); client.RecipientRemoved += (user) => _recipientRemovedEvent.InvokeAsync(user); + + client.InviteCreated += (invite) => _inviteCreatedEvent.InvokeAsync(invite); + client.InviteDeleted += (channel, invite) => _inviteDeletedEvent.InvokeAsync(channel, invite); } //IDiscordClient @@ -395,7 +449,6 @@ namespace Discord.WebSocket foreach (var client in _shards) client?.Dispose(); } - _connectionGroupLock?.Dispose(); } _isDisposed = true; diff --git a/src/Discord.Net.WebSocket/DiscordSocketApiClient.cs b/src/Discord.Net.WebSocket/DiscordSocketApiClient.cs index 1b21bd666..d14a314d6 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketApiClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketApiClient.cs @@ -12,6 +12,7 @@ using System.IO.Compression; using System.Text; using System.Threading; using System.Threading.Tasks; +using GameModel = Discord.API.Game; namespace Discord.API { @@ -132,6 +133,8 @@ namespace Discord.API if (WebSocketClient == null) throw new NotSupportedException("This client is not configured with WebSocket support."); + RequestQueue.ClearGatewayBuckets(); + //Re-create streams to reset the zlib state _compressed?.Dispose(); _decompressor?.Dispose(); @@ -205,11 +208,15 @@ namespace Discord.API payload = new SocketFrame { Operation = (int)opCode, Payload = payload }; if (payload != null) bytes = Encoding.UTF8.GetBytes(SerializeJson(payload)); - await RequestQueue.SendAsync(new WebSocketRequest(WebSocketClient, null, bytes, true, options)).ConfigureAwait(false); + + options.IsGatewayBucket = true; + if (options.BucketId == null) + options.BucketId = GatewayBucket.Get(GatewayBucketType.Unbucketed).Id; + await RequestQueue.SendAsync(new WebSocketRequest(WebSocketClient, bytes, true, opCode == GatewayOpCode.Heartbeat, options)).ConfigureAwait(false); await _sentGatewayMessageEvent.InvokeAsync(opCode).ConfigureAwait(false); } - public async Task SendIdentifyAsync(int largeThreshold = 100, int shardID = 0, int totalShards = 1, bool guildSubscriptions = true, GatewayIntents? gatewayIntents = null, RequestOptions options = null) + public async Task SendIdentifyAsync(int largeThreshold = 100, int shardID = 0, int totalShards = 1, bool guildSubscriptions = true, GatewayIntents? gatewayIntents = null, (UserStatus, bool, long?, GameModel)? presence = null, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); var props = new Dictionary @@ -225,11 +232,24 @@ namespace Discord.API if (totalShards > 1) msg.ShardingParams = new int[] { shardID, totalShards }; + options.BucketId = GatewayBucket.Get(GatewayBucketType.Identify).Id; + if (gatewayIntents.HasValue) msg.Intents = (int)gatewayIntents.Value; else msg.GuildSubscriptions = guildSubscriptions; + if (presence.HasValue) + { + msg.Presence = new StatusUpdateParams + { + Status = presence.Value.Item1, + IsAFK = presence.Value.Item2, + IdleSince = presence.Value.Item3, + Game = presence.Value.Item4, + }; + } + await SendGatewayAsync(GatewayOpCode.Identify, msg, options: options).ConfigureAwait(false); } public async Task SendResumeAsync(string sessionId, int lastSeq, RequestOptions options = null) @@ -248,7 +268,7 @@ namespace Discord.API options = RequestOptions.CreateOrClone(options); await SendGatewayAsync(GatewayOpCode.Heartbeat, lastSeq, options: options).ConfigureAwait(false); } - public async Task SendStatusUpdateAsync(UserStatus status, bool isAFK, long? since, Game game, RequestOptions options = null) + public async Task SendStatusUpdateAsync(UserStatus status, bool isAFK, long? since, GameModel game, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); var args = new StatusUpdateParams @@ -258,6 +278,7 @@ namespace Discord.API IsAFK = isAFK, Game = game }; + options.BucketId = GatewayBucket.Get(GatewayBucketType.PresenceUpdate).Id; await SendGatewayAsync(GatewayOpCode.StatusUpdate, args, options: options).ConfigureAwait(false); } public async Task SendRequestMembersAsync(IEnumerable guildIds, RequestOptions options = null) diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index d3a6f5e74..f3a8a6c2e 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -26,7 +26,7 @@ namespace Discord.WebSocket { private readonly ConcurrentQueue _largeGuilds; private readonly JsonSerializer _serializer; - private readonly SemaphoreSlim _connectionGroupLock; + private readonly DiscordShardedClient _shardedClient; private readonly DiscordSocketClient _parentClient; private readonly ConcurrentQueue _heartbeatTimes; private readonly ConnectionManager _connection; @@ -57,9 +57,11 @@ namespace Discord.WebSocket /// public override int Latency { get; protected set; } /// - public override UserStatus Status { get; protected set; } = UserStatus.Online; + public override UserStatus Status { get => _status ?? UserStatus.Online; protected set => _status = value; } + private UserStatus? _status; /// - public override IActivity Activity { get; protected set; } + public override IActivity Activity { get => _activity.GetValueOrDefault(); protected set => _activity = Optional.Create(value); } + private Optional _activity; //From DiscordSocketConfig internal int TotalShards { get; private set; } @@ -108,7 +110,8 @@ namespace Discord.WebSocket public IReadOnlyCollection GroupChannels => State.PrivateChannels.OfType().ToImmutableArray(); /// - public override IReadOnlyCollection VoiceRegions => _voiceRegions.ToReadOnlyCollection(); + [Obsolete("This property is obsolete, use the GetVoiceRegionsAsync method instead.")] + public override IReadOnlyCollection VoiceRegions => GetVoiceRegionsAsync().GetAwaiter().GetResult(); /// /// Initializes a new REST/WebSocket-based Discord client. @@ -120,9 +123,9 @@ namespace Discord.WebSocket /// The configuration to be used with the client. #pragma warning disable IDISP004 public DiscordSocketClient(DiscordSocketConfig config) : this(config, CreateApiClient(config), null, null) { } - internal DiscordSocketClient(DiscordSocketConfig config, SemaphoreSlim groupLock, DiscordSocketClient parentClient) : this(config, CreateApiClient(config), groupLock, parentClient) { } + internal DiscordSocketClient(DiscordSocketConfig config, DiscordShardedClient shardedClient, DiscordSocketClient parentClient) : this(config, CreateApiClient(config), shardedClient, parentClient) { } #pragma warning restore IDISP004 - private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client, SemaphoreSlim groupLock, DiscordSocketClient parentClient) + private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client, DiscordShardedClient shardedClient, DiscordSocketClient parentClient) : base(config, client) { ShardId = config.ShardId ?? 0; @@ -148,7 +151,7 @@ namespace Discord.WebSocket _connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex); _nextAudioId = 1; - _connectionGroupLock = groupLock; + _shardedClient = shardedClient; _parentClient = parentClient; _serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() }; @@ -176,7 +179,6 @@ namespace Discord.WebSocket return Task.Delay(0); }; - _voiceRegions = ImmutableDictionary.Create(); _largeGuilds = new ConcurrentQueue(); } private static API.DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config) @@ -202,13 +204,6 @@ namespace Discord.WebSocket /// internal override async Task OnLoginAsync(TokenType tokenType, string token) { - if (_parentClient == null) - { - var voiceRegions = await ApiClient.GetVoiceRegionsAsync(new RequestOptions { IgnoreState = true, RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false); - _voiceRegions = voiceRegions.Select(x => RestVoiceRegion.Create(this, x)).ToImmutableDictionary(x => x.Id); - } - else - _voiceRegions = _parentClient._voiceRegions; await Rest.OnLoginAsync(tokenType, token); } /// @@ -216,7 +211,7 @@ namespace Discord.WebSocket { await StopAsync().ConfigureAwait(false); _applicationInfo = null; - _voiceRegions = ImmutableDictionary.Create(); + _voiceRegions = null; await Rest.OnLogoutAsync(); } @@ -229,8 +224,12 @@ namespace Discord.WebSocket private async Task OnConnectingAsync() { - if (_connectionGroupLock != null) - await _connectionGroupLock.WaitAsync(_connection.CancelToken).ConfigureAwait(false); + bool locked = false; + if (_shardedClient != null && _sessionId == null) + { + await _shardedClient.AcquireIdentifyLockAsync(ShardId, _connection.CancelToken).ConfigureAwait(false); + locked = true; + } try { await _gatewayLogger.DebugAsync("Connecting ApiClient").ConfigureAwait(false); @@ -244,23 +243,17 @@ namespace Discord.WebSocket else { await _gatewayLogger.DebugAsync("Identifying").ConfigureAwait(false); - await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, guildSubscriptions: _guildSubscriptions, gatewayIntents: _gatewayIntents).ConfigureAwait(false); + await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, guildSubscriptions: _guildSubscriptions, gatewayIntents: _gatewayIntents, presence: BuildCurrentStatus()).ConfigureAwait(false); } - - //Wait for READY - await _connection.WaitAsync().ConfigureAwait(false); - - await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false); - await SendStatusAsync().ConfigureAwait(false); } finally { - if (_connectionGroupLock != null) - { - await Task.Delay(5000).ConfigureAwait(false); - _connectionGroupLock.Release(); - } + if (locked) + _shardedClient.ReleaseIdentifyLock(); } + + //Wait for READY + await _connection.WaitAsync().ConfigureAwait(false); } private async Task OnDisconnectingAsync(Exception ex) { @@ -342,7 +335,7 @@ namespace Discord.WebSocket { var user = SocketGlobalUser.Create(this, state, model); user.GlobalUser.AddRef(); - user.Presence = new SocketPresence(UserStatus.Online, null, null); + user.Presence = new SocketPresence(UserStatus.Online, null, null, null); return user; }); } @@ -350,11 +343,39 @@ namespace Discord.WebSocket => State.RemoveUser(id); /// + [Obsolete("This method is obsolete, use GetVoiceRegionAsync instead.")] public override RestVoiceRegion GetVoiceRegion(string id) + => GetVoiceRegionAsync(id).GetAwaiter().GetResult(); + + /// + public override async ValueTask> GetVoiceRegionsAsync(RequestOptions options = null) + { + if (_parentClient == null) + { + if (_voiceRegions == null) + { + options = RequestOptions.CreateOrClone(options); + options.IgnoreState = true; + var voiceRegions = await ApiClient.GetVoiceRegionsAsync(options).ConfigureAwait(false); + _voiceRegions = voiceRegions.Select(x => RestVoiceRegion.Create(this, x)).ToImmutableDictionary(x => x.Id); + } + return _voiceRegions.ToReadOnlyCollection(); + } + return await _parentClient.GetVoiceRegionsAsync().ConfigureAwait(false); + } + + /// + public override async ValueTask GetVoiceRegionAsync(string id, RequestOptions options = null) { - if (_voiceRegions.TryGetValue(id, out RestVoiceRegion region)) - return region; - return null; + if (_parentClient == null) + { + if (_voiceRegions == null) + await GetVoiceRegionsAsync().ConfigureAwait(false); + if (_voiceRegions.TryGetValue(id, out RestVoiceRegion region)) + return region; + return null; + } + return await _parentClient.GetVoiceRegionAsync(id, options).ConfigureAwait(false); } /// @@ -370,7 +391,7 @@ namespace Discord.WebSocket { var cachedGuilds = guilds.ToImmutableArray(); - const short batchSize = 100; //TODO: Gateway Intents will limit to a maximum of 1 guild_id + const short batchSize = 1; ulong[] batchIds = new ulong[Math.Min(batchSize, cachedGuilds.Length)]; Task[] batchTasks = new Task[batchIds.Length]; int batchCount = (cachedGuilds.Length + (batchSize - 1)) / batchSize; @@ -448,28 +469,47 @@ namespace Discord.WebSocket { if (CurrentUser == null) return; - var status = Status; + CurrentUser.Presence = new SocketPresence(Status, Activity, null, null); + + var presence = BuildCurrentStatus() ?? (UserStatus.Online, false, null, null); + + await ApiClient.SendStatusUpdateAsync( + status: presence.Item1, + isAFK: presence.Item2, + since: presence.Item3, + game: presence.Item4).ConfigureAwait(false); + } + + private (UserStatus, bool, long?, GameModel)? BuildCurrentStatus() + { + var status = _status; var statusSince = _statusSince; - CurrentUser.Presence = new SocketPresence(status, Activity, null); + var activity = _activity; - var gameModel = new GameModel(); + if (status == null && !activity.IsSpecified) + return null; + + GameModel game = null; // Discord only accepts rich presence over RPC, don't even bother building a payload - if (Activity is RichGame) - throw new NotSupportedException("Outgoing Rich Presences are not supported via WebSocket."); - if (Activity != null) + if (activity.GetValueOrDefault() != null) { + var gameModel = new GameModel(); + if (activity.Value is RichGame) + throw new NotSupportedException("Outgoing Rich Presences are not supported via WebSocket."); gameModel.Name = Activity.Name; gameModel.Type = Activity.Type; if (Activity is StreamingGame streamGame) gameModel.StreamUrl = streamGame.Url; + game = gameModel; } + else if (activity.IsSpecified) + game = null; - await ApiClient.SendStatusUpdateAsync( - status, - status == UserStatus.AFK, - statusSince != null ? _statusSince.Value.ToUnixTimeMilliseconds() : (long?)null, - gameModel).ConfigureAwait(false); + return (status ?? UserStatus.Online, + status == UserStatus.AFK, + statusSince != null ? _statusSince.Value.ToUnixTimeMilliseconds() : (long?)null, + game); } private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string type, object payload) @@ -519,7 +559,20 @@ namespace Discord.WebSocket _sessionId = null; _lastSeq = 0; - await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, guildSubscriptions: _guildSubscriptions, gatewayIntents: _gatewayIntents).ConfigureAwait(false); + if (_shardedClient != null) + { + await _shardedClient.AcquireIdentifyLockAsync(ShardId, _connection.CancelToken).ConfigureAwait(false); + try + { + await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, guildSubscriptions: _guildSubscriptions, gatewayIntents: _gatewayIntents, presence: BuildCurrentStatus()).ConfigureAwait(false); + } + finally + { + _shardedClient.ReleaseIdentifyLock(); + } + } + else + await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, guildSubscriptions: _guildSubscriptions, gatewayIntents: _gatewayIntents, presence: BuildCurrentStatus()).ConfigureAwait(false); } break; case GatewayOpCode.Reconnect: @@ -542,6 +595,7 @@ namespace Discord.WebSocket var state = new ClientState(data.Guilds.Length, data.PrivateChannels.Length); var currentUser = SocketSelfUser.Create(this, state, data.User); + currentUser.Presence = new SocketPresence(Status, Activity, null, null); ApiClient.CurrentUserId = currentUser.Id; int unavailableGuilds = 0; for (int i = 0; i < data.Guilds.Length; i++) @@ -903,6 +957,13 @@ namespace Discord.WebSocket if (user != null) { + var globalBefore = user.GlobalUser.Clone(); + if (user.GlobalUser.Update(State, data.User)) + { + //Global data was updated, trigger UserUpdated + await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false); + } + var before = user.Clone(); user.Update(State, data); await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), before, user).ConfigureAwait(false); @@ -1736,6 +1797,64 @@ namespace Discord.WebSocket } break; + //Invites + case "INVITE_CREATE": + { + await _gatewayLogger.DebugAsync("Received Dispatch (INVITE_CREATE)").ConfigureAwait(false); + + var data = (payload as JToken).ToObject(_serializer); + if (State.GetChannel(data.ChannelId) is SocketGuildChannel channel) + { + var guild = channel.Guild; + if (!guild.IsSynced) + { + await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false); + return; + } + + SocketGuildUser inviter = data.Inviter.IsSpecified + ? (guild.GetUser(data.Inviter.Value.Id) ?? guild.AddOrUpdateUser(data.Inviter.Value)) + : null; + + SocketUser target = data.TargetUser.IsSpecified + ? (guild.GetUser(data.TargetUser.Value.Id) ?? (SocketUser)SocketUnknownUser.Create(this, State, data.TargetUser.Value)) + : null; + + var invite = SocketInvite.Create(this, guild, channel, inviter, target, data); + + await TimedInvokeAsync(_inviteCreatedEvent, nameof(InviteCreated), invite).ConfigureAwait(false); + } + else + { + await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false); + return; + } + } + break; + case "INVITE_DELETE": + { + await _gatewayLogger.DebugAsync("Received Dispatch (INVITE_DELETE)").ConfigureAwait(false); + + var data = (payload as JToken).ToObject(_serializer); + if (State.GetChannel(data.ChannelId) is SocketGuildChannel channel) + { + var guild = channel.Guild; + if (!guild.IsSynced) + { + await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false); + return; + } + + await TimedInvokeAsync(_inviteDeletedEvent, nameof(InviteDeleted), channel, data.Code).ConfigureAwait(false); + } + else + { + await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false); + return; + } + } + break; + //Ignored (User only) case "CHANNEL_PINS_ACK": await _gatewayLogger.DebugAsync("Ignored Dispatch (CHANNEL_PINS_ACK)").ConfigureAwait(false); @@ -2077,11 +2196,11 @@ namespace Discord.WebSocket => Task.FromResult(GetUser(username, discriminator)); /// - Task> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options) - => Task.FromResult>(VoiceRegions); + async Task> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options) + => await GetVoiceRegionsAsync(options).ConfigureAwait(false); /// - Task IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options) - => Task.FromResult(GetVoiceRegion(id)); + async Task IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options) + => await GetVoiceRegionAsync(id, options).ConfigureAwait(false); /// async Task IDiscordClient.StartAsync() diff --git a/src/Discord.Net.WebSocket/DiscordSocketConfig.cs b/src/Discord.Net.WebSocket/DiscordSocketConfig.cs index 877ccd875..a45d4f5be 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketConfig.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketConfig.cs @@ -45,6 +45,7 @@ namespace Discord.WebSocket /// Gets or sets the ID for this shard. Must be less than . /// public int? ShardId { get; set; } = null; + /// /// Gets or sets the total number of shards for this application. /// @@ -55,9 +56,10 @@ namespace Discord.WebSocket /// disables the message cache entirely. /// public int MessageCacheSize { get; set; } = 0; + /// /// Gets or sets the max number of users a guild may have for offline users to be included in the READY - /// packet. Max is 250. + /// packet. The maximum value allowed is 250. /// public int LargeThreshold { get; set; } = 250; @@ -65,6 +67,7 @@ namespace Discord.WebSocket /// Gets or sets the provider used to generate new WebSocket connections. /// public WebSocketProvider WebSocketProvider { get; set; } + /// /// Gets or sets the provider used to generate new UDP sockets. /// @@ -87,7 +90,7 @@ namespace Discord.WebSocket /// /// /// For more information, please see - /// Request Guild Members + /// Request Guild Members /// on the official Discord API documentation. /// /// @@ -95,28 +98,33 @@ namespace Discord.WebSocket /// traffic. If you are using the command system, the default user TypeReader may fail to find the user /// due to this issue. This may be resolved at v3 of the library. Until then, you may want to consider /// overriding the TypeReader and use - /// + /// /// or /// as a backup. /// /// public bool AlwaysDownloadUsers { get; set; } = false; + /// - /// Gets or sets the timeout for event handlers, in milliseconds, after which a warning will be logged. Null - /// disables this check. + /// Gets or sets the timeout for event handlers, in milliseconds, after which a warning will be logged. + /// Setting this property to nulldisables this check. /// public int? HandlerTimeout { get; set; } = 3000; /// /// Gets or sets the behavior for on bulk deletes. - /// - /// If true, the event will not be raised for bulk deletes, and - /// only the will be raised. - /// - /// If false, both events will be raised. - /// - /// If unset, both events will be raised, but a warning will be raised the first time a bulk delete event is received. /// + /// + /// + /// If true, the event will not be raised for bulk + /// deletes, and only the will be raised. If false + /// , both events will be raised. + /// + /// + /// If unset, both events will be raised, but a warning will be raised the first time a bulk delete event is + /// received. + /// + /// public bool? ExclusiveBulkDelete { get; set; } = null; /// @@ -125,32 +133,45 @@ namespace Discord.WebSocket /// public bool GuildSubscriptions { get; set; } = true; + /// + /// Gets or sets the maximum identify concurrency. + /// + /// + /// This information is provided by Discord. + /// It is only used when using a and auto-sharding is disabled. + /// + public int IdentifyMaxConcurrency { get; set; } = 1; + /// /// Gets or sets the maximum wait time in milliseconds between GUILD_AVAILABLE events before firing READY. - /// /// If zero, READY will fire as soon as it is received and all guilds will be unavailable. /// /// - /// This property is measured in milliseconds, negative values will throw an exception. + /// This property is measured in milliseconds; negative values will throw an exception. /// If a guild is not received before READY, it will be unavailable. /// /// - /// The maximum wait time in milliseconds between GUILD_AVAILABLE events before firing READY. + /// A representing the maximum wait time in milliseconds between GUILD_AVAILABLE events + /// before firing READY. /// /// Value must be at least 0. - public int MaxWaitBetweenGuildAvailablesBeforeReady { + public int MaxWaitBetweenGuildAvailablesBeforeReady + { get { - return _maxWaitForGuildAvailable; + return this.maxWaitForGuildAvailable; } + set { - Preconditions.AtLeast(value, 0, nameof(MaxWaitBetweenGuildAvailablesBeforeReady)); - _maxWaitForGuildAvailable = value; + Preconditions.AtLeast(value, 0, nameof(this.MaxWaitBetweenGuildAvailablesBeforeReady)); + this.maxWaitForGuildAvailable = value; } } - private int _maxWaitForGuildAvailable = 10000; - + + private int maxWaitForGuildAvailable = 10000; + + /// /// Gets or sets gateway intents to limit what events are sent from Discord. Allows for more granular control than the property. /// /// @@ -161,7 +182,7 @@ namespace Discord.WebSocket public GatewayIntents? GatewayIntents { get; set; } /// - /// Initializes a default configuration. + /// Initializes a new instance of the class with the default configuration. /// public DiscordSocketConfig() { diff --git a/src/Discord.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs index e8511f1f5..b4625f799 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs @@ -33,16 +33,17 @@ namespace Discord.WebSocket /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - new Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null); + new Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Sends a file to this message channel with an optional caption. /// /// - /// This method follows the same behavior as described in . + /// This method follows the same behavior as described in . /// Please visit its documentation for more details on this method. /// /// The file path of the file. @@ -55,16 +56,17 @@ namespace Discord.WebSocket /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - new Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null); + new Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Sends a file to this message channel with an optional caption. /// /// - /// This method follows the same behavior as described in . + /// This method follows the same behavior as described in . /// Please visit its documentation for more details on this method. /// /// The of the file to be sent. @@ -78,11 +80,12 @@ namespace Discord.WebSocket /// Specifies if notifications are sent for mentioned users and roles in the message . /// If null, all mentioned roles and users will be notified. /// + /// The message references to be included. Used to reply to specific messages. /// /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the sent message. /// - new Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null); + new Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null); /// /// Gets a cached message from this channel. diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketDMChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketDMChannel.cs index 527685578..c123a9d4e 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketDMChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketDMChannel.cs @@ -135,16 +135,16 @@ namespace Discord.WebSocket /// /// Message content is too long, length must be less or equal to . - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) - => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, options); + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// - public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options); @@ -229,14 +229,14 @@ namespace Discord.WebSocket async Task> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions) - => await SendMessageAsync(text, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IChannel /// diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketGroupChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketGroupChannel.cs index b95bbffc1..dc5ac4222 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketGroupChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketGroupChannel.cs @@ -163,15 +163,15 @@ namespace Discord.WebSocket /// /// Message content is too long, length must be less or equal to . - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) - => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, options); + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// - public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// - public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) @@ -293,14 +293,14 @@ namespace Discord.WebSocket => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions) - => await SendMessageAsync(text, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IAudioChannel /// diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs index c65f3be05..3cc8496d9 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs @@ -125,7 +125,6 @@ namespace Discord.WebSocket public virtual async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options = null) { await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, permissions, options).ConfigureAwait(false); - _overwrites = _overwrites.Add(new Overwrite(user.Id, PermissionTarget.User, new OverwritePermissions(permissions.AllowValue, permissions.DenyValue))); } /// @@ -140,7 +139,6 @@ namespace Discord.WebSocket public virtual async Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options = null) { await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, permissions, options).ConfigureAwait(false); - _overwrites = _overwrites.Add(new Overwrite(role.Id, PermissionTarget.Role, new OverwritePermissions(permissions.AllowValue, permissions.DenyValue))); } /// /// Removes the permission overwrite for the given user, if one exists. @@ -153,15 +151,6 @@ namespace Discord.WebSocket public virtual async Task RemovePermissionOverwriteAsync(IUser user, RequestOptions options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, user, options).ConfigureAwait(false); - - for (int i = 0; i < _overwrites.Length; i++) - { - if (_overwrites[i].TargetId == user.Id) - { - _overwrites = _overwrites.RemoveAt(i); - return; - } - } } /// /// Removes the permission overwrite for the given role, if one exists. @@ -174,15 +163,6 @@ namespace Discord.WebSocket public virtual async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, role, options).ConfigureAwait(false); - - for (int i = 0; i < _overwrites.Length; i++) - { - if (_overwrites[i].TargetId == role.Id) - { - _overwrites = _overwrites.RemoveAt(i); - return; - } - } } public new virtual SocketGuildUser GetUser(ulong id) => null; diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs index 815a99ce7..944dd2d7f 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs @@ -15,7 +15,7 @@ namespace Discord.WebSocket /// /// [DebuggerDisplay(@"{DebuggerDisplay,nq}")] - public class SocketNewsChannel : SocketTextChannel + public class SocketNewsChannel : SocketTextChannel, INewsChannel { internal SocketNewsChannel(DiscordSocketClient discord, ulong id, SocketGuild guild) :base(discord, id, guild) diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs index e49e3ed37..d7d918f9f 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs @@ -161,17 +161,17 @@ namespace Discord.WebSocket /// /// Message content is too long, length must be less or equal to . - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) - => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, options); + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// - public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// /// Message content is too long, length must be less or equal to . - public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) - => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, options, isSpoiler); + public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) + => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// public Task DeleteMessagesAsync(IEnumerable messages, RequestOptions options = null) @@ -302,14 +302,14 @@ namespace Discord.WebSocket => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions) - => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// - async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions) - => await SendMessageAsync(text, isTTS, embed, options, allowedMentions).ConfigureAwait(false); + async Task IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) + => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); // INestedChannel /// diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs index 9fff6c207..bf4a63c9f 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs @@ -34,7 +34,12 @@ namespace Discord.WebSocket public Task SyncPermissionsAsync(RequestOptions options = null) => ChannelHelper.SyncPermissionsAsync(this, Discord, options); - /// + /// + /// Gets a collection of users that are currently connected to this voice channel. + /// + /// + /// A read-only collection of users that are currently connected to this voice channel. + /// public override IReadOnlyCollection Users => Guild.Users.Where(x => x.VoiceChannel?.Id == Id).ToImmutableArray(); diff --git a/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs b/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs index 58a07ff33..59dfbed2d 100644 --- a/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs +++ b/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs @@ -49,6 +49,8 @@ namespace Discord.WebSocket /// public bool IsEmbeddable { get; private set; } /// + public bool IsWidgetEnabled { get; private set; } + /// public VerificationLevel VerificationLevel { get; private set; } /// public MfaLevel MfaLevel { get; private set; } @@ -84,7 +86,10 @@ namespace Discord.WebSocket internal ulong? AFKChannelId { get; private set; } internal ulong? EmbedChannelId { get; private set; } + internal ulong? WidgetChannelId { get; private set; } internal ulong? SystemChannelId { get; private set; } + internal ulong? RulesChannelId { get; private set; } + internal ulong? PublicUpdatesChannelId { get; private set; } /// public ulong OwnerId { get; private set; } /// Gets the user that owns this guild. @@ -96,6 +101,8 @@ namespace Discord.WebSocket /// public string SplashId { get; private set; } /// + public string DiscoverySplashId { get; private set; } + /// public PremiumTier PremiumTier { get; private set; } /// public string BannerId { get; private set; } @@ -109,6 +116,12 @@ namespace Discord.WebSocket public int PremiumSubscriptionCount { get; private set; } /// public string PreferredLocale { get; private set; } + /// + public int? MaxPresences { get; private set; } + /// + public int? MaxMembers { get; private set; } + /// + public int? MaxVideoChannelUsers { get; private set; } /// public CultureInfo PreferredCulture { get; private set; } @@ -120,9 +133,11 @@ namespace Discord.WebSocket /// public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId); /// + public string DiscoverySplashUrl => CDN.GetGuildDiscoverySplashUrl(Id, DiscoverySplashId); + /// public string BannerUrl => CDN.GetGuildBannerUrl(Id, BannerId); /// Indicates whether the client has all the members downloaded to the local guild cache. - public bool HasAllMembers => MemberCount == DownloadedMemberCount;// _downloaderPromise.Task.IsCompleted; + public bool HasAllMembers => MemberCount <= DownloadedMemberCount;// _downloaderPromise.Task.IsCompleted; /// Indicates whether the guild cache is synced to this guild. public bool IsSynced => _syncPromise.Task.IsCompleted; public Task SyncPromise => _syncPromise.Task; @@ -153,7 +168,7 @@ namespace Discord.WebSocket /// /// /// A that the AFK users will be moved to after they have idled for too - /// long; null if none is set. + /// long; if none is set. /// public SocketVoiceChannel AFKChannel { @@ -164,11 +179,32 @@ namespace Discord.WebSocket } } /// + /// Gets the max bitrate for voice channels in this guild. + /// + /// + /// A representing the maximum bitrate value allowed by Discord in this guild. + /// + public int MaxBitrate + { + get + { + var maxBitrate = PremiumTier switch + { + PremiumTier.Tier1 => 128000, + PremiumTier.Tier2 => 256000, + PremiumTier.Tier3 => 384000, + _ => 96000, + }; + return maxBitrate; + } + } + /// /// Gets the embed channel (i.e. the channel set in the guild's widget settings) in this guild. /// /// - /// A channel set within the server's widget settings; null if none is set. + /// A channel set within the server's widget settings; if none is set. /// + [Obsolete("This property is deprecated, use WidgetChannel instead.")] public SocketGuildChannel EmbedChannel { get @@ -178,10 +214,24 @@ namespace Discord.WebSocket } } /// + /// Gets the widget channel (i.e. the channel set in the guild's widget settings) in this guild. + /// + /// + /// A channel set within the server's widget settings; if none is set. + /// + public SocketGuildChannel WidgetChannel + { + get + { + var id = WidgetChannelId; + return id.HasValue ? GetChannel(id.Value) : null; + } + } + /// /// Gets the system channel where randomized welcome messages are sent in this guild. /// /// - /// A text channel where randomized welcome messages will be sent to; null if none is set. + /// A text channel where randomized welcome messages will be sent to; if none is set. /// public SocketTextChannel SystemChannel { @@ -192,6 +242,36 @@ namespace Discord.WebSocket } } /// + /// Gets the channel with the guild rules. + /// + /// + /// A text channel with the guild rules; if none is set. + /// + public SocketTextChannel RulesChannel + { + get + { + var id = RulesChannelId; + return id.HasValue ? GetTextChannel(id.Value) : null; + } + } + /// + /// Gets the channel where admins and moderators of Community guilds receive + /// notices from Discord. + /// + /// + /// A text channel where admins and moderators of Community guilds receive + /// notices from Discord; if none is set. + /// + public SocketTextChannel PublicUpdatesChannel + { + get + { + var id = PublicUpdatesChannelId; + return id.HasValue ? GetTextChannel(id.Value) : null; + } + } + /// /// Gets a collection of all text channels in this guild. /// /// @@ -362,15 +442,24 @@ namespace Discord.WebSocket internal void Update(ClientState state, Model model) { AFKChannelId = model.AFKChannelId; - EmbedChannelId = model.EmbedChannelId; + if (model.EmbedChannelId.IsSpecified) + EmbedChannelId = model.EmbedChannelId.Value; + if (model.WidgetChannelId.IsSpecified) + WidgetChannelId = model.WidgetChannelId.Value; SystemChannelId = model.SystemChannelId; + RulesChannelId = model.RulesChannelId; + PublicUpdatesChannelId = model.PublicUpdatesChannelId; AFKTimeout = model.AFKTimeout; - IsEmbeddable = model.EmbedEnabled; + if (model.EmbedEnabled.IsSpecified) + IsEmbeddable = model.EmbedEnabled.Value; + if (model.WidgetEnabled.IsSpecified) + IsWidgetEnabled = model.WidgetEnabled.Value; IconId = model.Icon; Name = model.Name; OwnerId = model.OwnerId; VoiceRegionId = model.Region; SplashId = model.Splash; + DiscoverySplashId = model.DiscoverySplash; VerificationLevel = model.VerificationLevel; MfaLevel = model.MfaLevel; DefaultMessageNotifications = model.DefaultMessageNotifications; @@ -382,8 +471,14 @@ namespace Discord.WebSocket SystemChannelFlags = model.SystemChannelFlags; Description = model.Description; PremiumSubscriptionCount = model.PremiumSubscriptionCount.GetValueOrDefault(); + if (model.MaxPresences.IsSpecified) + MaxPresences = model.MaxPresences.Value ?? 25000; + if (model.MaxMembers.IsSpecified) + MaxMembers = model.MaxMembers.Value; + if (model.MaxVideoChannelUsers.IsSpecified) + MaxVideoChannelUsers = model.MaxVideoChannelUsers.Value; PreferredLocale = model.PreferredLocale; - PreferredCulture = new CultureInfo(PreferredLocale); + PreferredCulture = PreferredLocale == null ? null : new CultureInfo(PreferredLocale); if (model.Emojis != null) { @@ -449,15 +544,20 @@ namespace Discord.WebSocket => GuildHelper.DeleteAsync(this, Discord, options); /// - /// is null. + /// is . public Task ModifyAsync(Action func, RequestOptions options = null) => GuildHelper.ModifyAsync(this, Discord, func, options); /// - /// is null. + /// is . + [Obsolete("This endpoint is deprecated, use ModifyWidgetAsync instead.")] public Task ModifyEmbedAsync(Action func, RequestOptions options = null) => GuildHelper.ModifyEmbedAsync(this, Discord, func, options); /// + /// is . + public Task ModifyWidgetAsync(Action func, RequestOptions options = null) + => GuildHelper.ModifyWidgetAsync(this, Discord, func, options); + /// public Task ReorderChannelsAsync(IEnumerable args, RequestOptions options = null) => GuildHelper.ReorderChannelsAsync(this, Discord, args, options); /// @@ -487,7 +587,7 @@ namespace Discord.WebSocket /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains a ban object, which - /// contains the user information and the reason for the ban; null if the ban entry cannot be found. + /// contains the user information and the reason for the ban; if the ban entry cannot be found. /// public Task GetBanAsync(IUser user, RequestOptions options = null) => GuildHelper.GetBanAsync(this, Discord, user.Id, options); @@ -498,7 +598,7 @@ namespace Discord.WebSocket /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains a ban object, which - /// contains the user information and the reason for the ban; null if the ban entry cannot be found. + /// contains the user information and the reason for the ban; if the ban entry cannot be found. /// public Task GetBanAsync(ulong userId, RequestOptions options = null) => GuildHelper.GetBanAsync(this, Discord, userId, options); @@ -539,7 +639,7 @@ namespace Discord.WebSocket /// /// The snowflake identifier for the channel. /// - /// A generic channel associated with the specified ; null if none is found. + /// A generic channel associated with the specified ; if none is found. /// public SocketGuildChannel GetChannel(ulong id) { @@ -553,7 +653,7 @@ namespace Discord.WebSocket /// /// The snowflake identifier for the text channel. /// - /// A text channel associated with the specified ; null if none is found. + /// A text channel associated with the specified ; if none is found. /// public SocketTextChannel GetTextChannel(ulong id) => GetChannel(id) as SocketTextChannel; @@ -562,7 +662,7 @@ namespace Discord.WebSocket /// /// The snowflake identifier for the voice channel. /// - /// A voice channel associated with the specified ; null if none is found. + /// A voice channel associated with the specified ; if none is found. /// public SocketVoiceChannel GetVoiceChannel(ulong id) => GetChannel(id) as SocketVoiceChannel; @@ -571,7 +671,7 @@ namespace Discord.WebSocket /// /// The snowflake identifier for the category channel. /// - /// A category channel associated with the specified ; null if none is found. + /// A category channel associated with the specified ; if none is found. /// public SocketCategoryChannel GetCategoryChannel(ulong id) => GetChannel(id) as SocketCategoryChannel; @@ -607,7 +707,7 @@ namespace Discord.WebSocket /// The new name for the voice channel. /// The delegate containing the properties to be applied to the channel upon its creation. /// The options to be used when sending the request. - /// is null. + /// is . /// /// A task that represents the asynchronous creation operation. The task result contains the newly created /// voice channel. @@ -620,7 +720,7 @@ namespace Discord.WebSocket /// The new name for the category. /// The delegate containing the properties to be applied to the channel upon its creation. /// The options to be used when sending the request. - /// is null. + /// is . /// /// A task that represents the asynchronous creation operation. The task result contains the newly created /// category channel. @@ -684,7 +784,7 @@ namespace Discord.WebSocket /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the partial metadata of - /// the vanity invite found within this guild; null if none is found. + /// the vanity invite found within this guild; if none is found. /// public Task GetVanityInviteAsync(RequestOptions options = null) => GuildHelper.GetVanityInviteAsync(this, Discord, options); @@ -695,7 +795,7 @@ namespace Discord.WebSocket /// /// The snowflake identifier for the role. /// - /// A role that is associated with the specified ; null if none is found. + /// A role that is associated with the specified ; if none is found. /// public SocketRole GetRole(ulong id) { @@ -717,7 +817,7 @@ namespace Discord.WebSocket /// Whether the role is separated from others on the sidebar. /// Whether the role can be mentioned. /// The options to be used when sending the request. - /// is null. + /// is . /// /// A task that represents the asynchronous creation operation. The task result contains the newly created /// role. @@ -749,13 +849,13 @@ namespace Discord.WebSocket /// /// This method retrieves a user found within this guild. /// - /// This may return null in the WebSocket implementation due to incomplete user collection in + /// This may return in the WebSocket implementation due to incomplete user collection in /// large guilds. /// /// /// The snowflake identifier of the user. /// - /// A guild user associated with the specified ; null if none is found. + /// A guild user associated with the specified ; if none is found. /// public SocketGuildUser GetUser(ulong id) { @@ -764,8 +864,8 @@ namespace Discord.WebSocket return null; } /// - public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null) - => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options); + public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null, IEnumerable includeRoleIds = null) + => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options, includeRoleIds); internal SocketGuildUser AddOrUpdateUser(UserModel model) { @@ -909,7 +1009,7 @@ namespace Discord.WebSocket /// The options to be used when sending the request. /// /// A task that represents the asynchronous get operation. The task result contains the webhook with the - /// specified ; null if none is found. + /// specified ; if none is found. /// public Task GetWebhookAsync(ulong id, RequestOptions options = null) => GuildHelper.GetWebhookAsync(this, Discord, id, options); @@ -932,7 +1032,7 @@ namespace Discord.WebSocket public Task CreateEmoteAsync(string name, Image image, Optional> roles = default(Optional>), RequestOptions options = null) => GuildHelper.CreateEmoteAsync(this, Discord, name, image, roles, options); /// - /// is null. + /// is . public Task ModifyEmoteAsync(GuildEmote emote, Action func, RequestOptions options = null) => GuildHelper.ModifyEmoteAsync(this, Discord, emote.Id, func, options); /// @@ -1151,11 +1251,21 @@ namespace Discord.WebSocket /// ulong? IGuild.EmbedChannelId => EmbedChannelId; /// + ulong? IGuild.WidgetChannelId => WidgetChannelId; + /// ulong? IGuild.SystemChannelId => SystemChannelId; /// + ulong? IGuild.RulesChannelId => RulesChannelId; + /// + ulong? IGuild.PublicUpdatesChannelId => PublicUpdatesChannelId; + /// IRole IGuild.EveryoneRole => EveryoneRole; /// IReadOnlyCollection IGuild.Roles => Roles; + /// + int? IGuild.ApproximateMemberCount => null; + /// + int? IGuild.ApproximatePresenceCount => null; /// async Task> IGuild.GetBansAsync(RequestOptions options) @@ -1195,12 +1305,22 @@ namespace Discord.WebSocket Task IGuild.GetDefaultChannelAsync(CacheMode mode, RequestOptions options) => Task.FromResult(DefaultChannel); /// + [Obsolete("This method is deprecated, use GetWidgetChannelAsync instead.")] Task IGuild.GetEmbedChannelAsync(CacheMode mode, RequestOptions options) => Task.FromResult(EmbedChannel); /// + Task IGuild.GetWidgetChannelAsync(CacheMode mode, RequestOptions options) + => Task.FromResult(WidgetChannel); + /// Task IGuild.GetSystemChannelAsync(CacheMode mode, RequestOptions options) => Task.FromResult(SystemChannel); /// + Task IGuild.GetRulesChannelAsync(CacheMode mode, RequestOptions options) + => Task.FromResult(RulesChannel); + /// + Task IGuild.GetPublicUpdatesChannelAsync(CacheMode mode, RequestOptions options) + => Task.FromResult(PublicUpdatesChannel); + /// async Task IGuild.CreateTextChannelAsync(string name, Action func, RequestOptions options) => await CreateTextChannelAsync(name, func, options).ConfigureAwait(false); /// diff --git a/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs b/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs new file mode 100644 index 000000000..5dc53a833 --- /dev/null +++ b/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs @@ -0,0 +1,146 @@ +using Discord.Rest; +using System; +using System.Diagnostics; +using System.Threading.Tasks; +using Model = Discord.API.Gateway.InviteCreateEvent; + +namespace Discord.WebSocket +{ + [DebuggerDisplay(@"{DebuggerDisplay,nq}")] + public class SocketInvite : SocketEntity, IInviteMetadata + { + private long _createdAtTicks; + + /// + public ulong ChannelId { get; private set; } + /// + /// Gets the channel where this invite was created. + /// + public SocketGuildChannel Channel { get; private set; } + /// + public ulong? GuildId { get; private set; } + /// + /// Gets the guild where this invite was created. + /// + public SocketGuild Guild { get; private set; } + /// + ChannelType IInvite.ChannelType + { + get + { + switch (Channel) + { + case IVoiceChannel voiceChannel: return ChannelType.Voice; + case ICategoryChannel categoryChannel: return ChannelType.Category; + case IDMChannel dmChannel: return ChannelType.DM; + case IGroupChannel groupChannel: return ChannelType.Group; + case INewsChannel newsChannel: return ChannelType.News; + case ITextChannel textChannel: return ChannelType.Text; + default: throw new InvalidOperationException("Invalid channel type."); + } + } + } + /// + string IInvite.ChannelName => Channel.Name; + /// + string IInvite.GuildName => Guild.Name; + /// + int? IInvite.PresenceCount => throw new NotImplementedException(); + /// + int? IInvite.MemberCount => throw new NotImplementedException(); + /// + [Obsolete("This property doesn't exist anymore and shouldn't be used.")] + bool IInviteMetadata.IsRevoked => throw new NotImplementedException(); + /// + public bool IsTemporary { get; private set; } + /// + int? IInviteMetadata.MaxAge { get => MaxAge; } + /// + int? IInviteMetadata.MaxUses { get => MaxUses; } + /// + int? IInviteMetadata.Uses { get => Uses; } + /// + /// Gets the time (in seconds) until the invite expires. + /// + public int MaxAge { get; private set; } + /// + /// Gets the max number of uses this invite may have. + /// + public int MaxUses { get; private set; } + /// + /// Gets the number of times this invite has been used. + /// + public int Uses { get; private set; } + /// + /// Gets the user that created this invite if available. + /// + public SocketGuildUser Inviter { get; private set; } + /// + DateTimeOffset? IInviteMetadata.CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); + /// + /// Gets when this invite was created. + /// + public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); + /// + /// Gets the user targeted by this invite if available. + /// + public SocketUser TargetUser { get; private set; } + /// + /// Gets the type of the user targeted by this invite. + /// + public TargetUserType TargetUserType { get; private set; } + + /// + public string Code => Id; + /// + public string Url => $"{DiscordConfig.InviteUrl}{Code}"; + + internal SocketInvite(DiscordSocketClient discord, SocketGuild guild, SocketGuildChannel channel, SocketGuildUser inviter, SocketUser target, string id) + : base(discord, id) + { + Guild = guild; + Channel = channel; + Inviter = inviter; + TargetUser = target; + } + internal static SocketInvite Create(DiscordSocketClient discord, SocketGuild guild, SocketGuildChannel channel, SocketGuildUser inviter, SocketUser target, Model model) + { + var entity = new SocketInvite(discord, guild, channel, inviter, target, model.Code); + entity.Update(model); + return entity; + } + internal void Update(Model model) + { + ChannelId = model.ChannelId; + GuildId = model.GuildId.IsSpecified ? model.GuildId.Value : Guild.Id; + IsTemporary = model.Temporary; + MaxAge = model.MaxAge; + MaxUses = model.MaxUses; + Uses = model.Uses; + _createdAtTicks = model.CreatedAt.UtcTicks; + TargetUserType = model.TargetUserType.IsSpecified ? model.TargetUserType.Value : TargetUserType.Undefined; + } + + /// + public Task DeleteAsync(RequestOptions options = null) + => InviteHelper.DeleteAsync(this, Discord, options); + + /// + /// Gets the URL of the invite. + /// + /// + /// A string that resolves to the Url of the invite. + /// + public override string ToString() => Url; + private string DebuggerDisplay => $"{Url} ({Guild?.Name} / {Channel.Name})"; + + /// + IGuild IInvite.Guild => Guild; + /// + IChannel IInvite.Channel => Channel; + /// + IUser IInvite.Inviter => Inviter; + /// + IUser IInvite.TargetUser => TargetUser; + } +} diff --git a/src/Discord.Net.WebSocket/Entities/Messages/SocketMessage.cs b/src/Discord.Net.WebSocket/Entities/Messages/SocketMessage.cs index f392614ad..2ca53cbb9 100644 --- a/src/Discord.Net.WebSocket/Entities/Messages/SocketMessage.cs +++ b/src/Discord.Net.WebSocket/Entities/Messages/SocketMessage.cs @@ -46,6 +46,8 @@ namespace Discord.WebSocket public virtual bool IsSuppressed => false; /// public virtual DateTimeOffset? EditedTimestamp => null; + /// + public virtual bool MentionedEveryone => false; /// public MessageActivity Activity { get; private set; } @@ -56,6 +58,9 @@ namespace Discord.WebSocket /// public MessageReference Reference { get; private set; } + /// + public MessageFlags? Flags { get; private set; } + /// /// Returns all attachments included in this message. /// @@ -108,7 +113,7 @@ namespace Discord.WebSocket } internal static SocketMessage Create(DiscordSocketClient discord, ClientState state, SocketUser author, ISocketMessageChannel channel, Model model) { - if (model.Type == MessageType.Default) + if (model.Type == MessageType.Default || model.Type == MessageType.Reply) return SocketUserMessage.Create(discord, state, author, channel, model); else return SocketSystemMessage.Create(discord, state, author, channel, model); @@ -150,10 +155,13 @@ namespace Discord.WebSocket Reference = new MessageReference { GuildId = model.Reference.Value.GuildId, - ChannelId = model.Reference.Value.ChannelId, + InternalChannelId = model.Reference.Value.ChannelId, MessageId = model.Reference.Value.MessageId }; } + + if (model.Flags.IsSpecified) + Flags = model.Flags.Value; } /// diff --git a/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs b/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs index e1f0f74dc..859b1b80a 100644 --- a/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs +++ b/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs @@ -15,21 +15,26 @@ namespace Discord.WebSocket [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class SocketUserMessage : SocketMessage, IUserMessage { - private bool _isMentioningEveryone, _isTTS, _isPinned, _isSuppressed; + private bool _isMentioningEveryone, _isTTS, _isPinned; private long? _editedTimestampTicks; + private IUserMessage _referencedMessage; private ImmutableArray _attachments = ImmutableArray.Create(); private ImmutableArray _embeds = ImmutableArray.Create(); private ImmutableArray _tags = ImmutableArray.Create(); - + private ImmutableArray _roleMentions = ImmutableArray.Create(); + private ImmutableArray _userMentions = ImmutableArray.Create(); + /// public override bool IsTTS => _isTTS; /// public override bool IsPinned => _isPinned; /// - public override bool IsSuppressed => _isSuppressed; + public override bool IsSuppressed => Flags.HasValue && Flags.Value.HasFlag(MessageFlags.SuppressEmbeds); /// public override DateTimeOffset? EditedTimestamp => DateTimeUtils.FromTicks(_editedTimestampTicks); /// + public override bool MentionedEveryone => _isMentioningEveryone; + /// public override IReadOnlyCollection Attachments => _attachments; /// public override IReadOnlyCollection Embeds => _embeds; @@ -38,9 +43,11 @@ namespace Discord.WebSocket /// public override IReadOnlyCollection MentionedChannels => MessageHelper.FilterTagsByValue(TagType.ChannelMention, _tags); /// - public override IReadOnlyCollection MentionedRoles => MessageHelper.FilterTagsByValue(TagType.RoleMention, _tags); + public override IReadOnlyCollection MentionedRoles => _roleMentions; /// - public override IReadOnlyCollection MentionedUsers => MessageHelper.FilterTagsByValue(TagType.UserMention, _tags); + public override IReadOnlyCollection MentionedUsers => _userMentions; + /// + public IUserMessage ReferencedMessage => _referencedMessage; internal SocketUserMessage(DiscordSocketClient discord, ulong id, ISocketMessageChannel channel, SocketUser author, MessageSource source) : base(discord, id, channel, author, source) @@ -57,6 +64,8 @@ namespace Discord.WebSocket { base.Update(state, model); + SocketGuild guild = (Channel as SocketGuildChannel)?.Guild; + if (model.IsTextToSpeech.IsSpecified) _isTTS = model.IsTextToSpeech.Value; if (model.Pinned.IsSpecified) @@ -65,10 +74,8 @@ namespace Discord.WebSocket _editedTimestampTicks = model.EditedTimestamp.Value?.UtcTicks; if (model.MentionEveryone.IsSpecified) _isMentioningEveryone = model.MentionEveryone.Value; - if (model.Flags.IsSpecified) - { - _isSuppressed = model.Flags.Value.HasFlag(API.MessageFlags.Suppressed); - } + if (model.RoleMentions.IsSpecified) + _roleMentions = model.RoleMentions.Value.Select(x => guild.GetRole(x)).ToImmutableArray(); if (model.Attachments.IsSpecified) { @@ -98,30 +105,59 @@ namespace Discord.WebSocket _embeds = ImmutableArray.Create(); } - IReadOnlyCollection mentions = ImmutableArray.Create(); //Is passed to ParseTags to get real mention collection if (model.UserMentions.IsSpecified) { var value = model.UserMentions.Value; if (value.Length > 0) { - var newMentions = ImmutableArray.CreateBuilder(value.Length); + var newMentions = ImmutableArray.CreateBuilder(value.Length); for (int i = 0; i < value.Length; i++) { var val = value[i]; if (val.Object != null) - newMentions.Add(SocketUnknownUser.Create(Discord, state, val.Object)); + { + var user = Channel.GetUserAsync(val.Object.Id, CacheMode.CacheOnly).GetAwaiter().GetResult() as SocketUser; + if (user != null) + newMentions.Add(user); + else + newMentions.Add(SocketUnknownUser.Create(Discord, state, val.Object)); + } } - mentions = newMentions.ToImmutable(); + _userMentions = newMentions.ToImmutable(); } } if (model.Content.IsSpecified) { var text = model.Content.Value; - var guild = (Channel as SocketGuildChannel)?.Guild; - _tags = MessageHelper.ParseTags(text, Channel, guild, mentions); + _tags = MessageHelper.ParseTags(text, Channel, guild, _userMentions); model.Content = text; } + + if (model.ReferencedMessage.IsSpecified && model.ReferencedMessage.Value != null) + { + var refMsg = model.ReferencedMessage.Value; + ulong? webhookId = refMsg.WebhookId.ToNullable(); + SocketUser refMsgAuthor = null; + if (refMsg.Author.IsSpecified) + { + if (guild != null) + { + if (webhookId != null) + refMsgAuthor = SocketWebhookUser.Create(guild, state, refMsg.Author.Value, webhookId.Value); + else + refMsgAuthor = guild.GetUser(refMsg.Author.Value.Id); + } + else + refMsgAuthor = (Channel as SocketChannel).GetUser(refMsg.Author.Value.Id); + if (refMsgAuthor == null) + refMsgAuthor = SocketUnknownUser.Create(Discord, state, refMsg.Author.Value); + } + else + // Message author wasn't specified in the payload, so create a completely anonymous unknown user + refMsgAuthor = new SocketUnknownUser(Discord, id: 0); + _referencedMessage = SocketUserMessage.Create(Discord, state, refMsgAuthor, Channel, refMsg); + } } /// @@ -149,10 +185,10 @@ namespace Discord.WebSocket => MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling); /// - /// This operation may only be called on a channel. + /// This operation may only be called on a channel. public async Task CrosspostAsync(RequestOptions options = null) { - if (!(Channel is SocketNewsChannel)) + if (!(Channel is INewsChannel)) { throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels."); } diff --git a/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs b/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs index b5e26ad78..e6aac2c04 100644 --- a/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs +++ b/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs @@ -36,6 +36,8 @@ namespace Discord.WebSocket public GuildPermissions Permissions { get; private set; } /// public int Position { get; private set; } + /// + public RoleTags Tags { get; private set; } /// public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id); @@ -71,6 +73,8 @@ namespace Discord.WebSocket Position = model.Position; Color = new Color(model.Color); Permissions = new GuildPermissions(model.Permissions); + if (model.Tags.IsSpecified) + Tags = model.Tags.Value.ToEntity(); } /// diff --git a/src/Discord.Net.WebSocket/Entities/Users/SocketGuildUser.cs b/src/Discord.Net.WebSocket/Entities/Users/SocketGuildUser.cs index e5dbfa01d..c0a681d9d 100644 --- a/src/Discord.Net.WebSocket/Entities/Users/SocketGuildUser.cs +++ b/src/Discord.Net.WebSocket/Entities/Users/SocketGuildUser.cs @@ -57,6 +57,8 @@ namespace Discord.WebSocket /// public bool IsStreaming => VoiceState?.IsStreaming ?? false; /// + public bool? IsPending { get; private set; } + /// public DateTimeOffset? JoinedAt => DateTimeUtils.FromTicks(_joinedAtTicks); /// /// Returns a collection of roles that the user possesses. @@ -142,6 +144,8 @@ namespace Discord.WebSocket UpdateRoles(model.Roles.Value); if (model.PremiumSince.IsSpecified) _premiumSinceTicks = model.PremiumSince.Value?.UtcTicks; + if (model.Pending.IsSpecified) + IsPending = model.Pending.Value; } internal void Update(ClientState state, PresenceModel model, bool updatePresence) { @@ -154,6 +158,8 @@ namespace Discord.WebSocket Nickname = model.Nick.Value; if (model.Roles.IsSpecified) UpdateRoles(model.Roles.Value); + if (model.PremiumSince.IsSpecified) + _premiumSinceTicks = model.PremiumSince.Value?.UtcTicks; } private void UpdateRoles(ulong[] roleIds) { diff --git a/src/Discord.Net.WebSocket/Entities/Users/SocketPresence.cs b/src/Discord.Net.WebSocket/Entities/Users/SocketPresence.cs index 52f111303..407e14419 100644 --- a/src/Discord.Net.WebSocket/Entities/Users/SocketPresence.cs +++ b/src/Discord.Net.WebSocket/Entities/Users/SocketPresence.cs @@ -18,16 +18,20 @@ namespace Discord.WebSocket public IActivity Activity { get; } /// public IImmutableSet ActiveClients { get; } - internal SocketPresence(UserStatus status, IActivity activity, IImmutableSet activeClients) + /// + public IImmutableList Activities { get; } + internal SocketPresence(UserStatus status, IActivity activity, IImmutableSet activeClients, IImmutableList activities) { Status = status; - Activity= activity; - ActiveClients = activeClients; + Activity = activity; + ActiveClients = activeClients ?? ImmutableHashSet.Empty; + Activities = activities ?? ImmutableList.Empty; } internal static SocketPresence Create(Model model) { var clients = ConvertClientTypesDict(model.ClientStatus.GetValueOrDefault()); - return new SocketPresence(model.Status, model.Game?.ToEntity(), clients); + var activities = ConvertActivitiesList(model.Activities); + return new SocketPresence(model.Status, model.Game?.ToEntity(), clients, activities); } /// /// Creates a new containing all of the client types @@ -53,6 +57,25 @@ namespace Discord.WebSocket } return set.ToImmutableHashSet(); } + /// + /// Creates a new containing all the activities + /// that a user has from the data supplied in the Presence update frame. + /// + /// + /// A list of . + /// + /// + /// A list of all that this user currently has available. + /// + private static IImmutableList ConvertActivitiesList(IList activities) + { + if (activities == null || activities.Count == 0) + return ImmutableList.Empty; + var list = new List(); + foreach (var activity in activities) + list.Add(activity.ToEntity()); + return list.ToImmutableList(); + } /// /// Gets the status of the user. diff --git a/src/Discord.Net.WebSocket/Entities/Users/SocketUnknownUser.cs b/src/Discord.Net.WebSocket/Entities/Users/SocketUnknownUser.cs index 840a1c30b..dd2e747b4 100644 --- a/src/Discord.Net.WebSocket/Entities/Users/SocketUnknownUser.cs +++ b/src/Discord.Net.WebSocket/Entities/Users/SocketUnknownUser.cs @@ -25,7 +25,7 @@ namespace Discord.WebSocket /// public override bool IsWebhook => false; /// - internal override SocketPresence Presence { get { return new SocketPresence(UserStatus.Offline, null, null); } set { } } + internal override SocketPresence Presence { get { return new SocketPresence(UserStatus.Offline, null, null, null); } set { } } /// /// This field is not supported for an unknown user. internal override SocketGlobalUser GlobalUser => diff --git a/src/Discord.Net.WebSocket/Entities/Users/SocketUser.cs b/src/Discord.Net.WebSocket/Entities/Users/SocketUser.cs index b830ce79c..4e6d4b3f8 100644 --- a/src/Discord.Net.WebSocket/Entities/Users/SocketUser.cs +++ b/src/Discord.Net.WebSocket/Entities/Users/SocketUser.cs @@ -26,6 +26,8 @@ namespace Discord.WebSocket public abstract string AvatarId { get; internal set; } /// public abstract bool IsWebhook { get; } + /// + public UserProperties? PublicFlags { get; private set; } internal abstract SocketGlobalUser GlobalUser { get; } internal abstract SocketPresence Presence { get; set; } @@ -41,6 +43,8 @@ namespace Discord.WebSocket public UserStatus Status => Presence.Status; /// public IImmutableSet ActiveClients => Presence.ActiveClients ?? ImmutableHashSet.Empty; + /// + public IImmutableList Activities => Presence.Activities ?? ImmutableList.Empty; /// /// Gets mutual guilds shared with this user. /// @@ -81,6 +85,11 @@ namespace Discord.WebSocket Username = model.Username.Value; hasChanges = true; } + if (model.PublicFlags.IsSpecified && model.PublicFlags.Value != PublicFlags) + { + PublicFlags = model.PublicFlags.Value; + hasChanges = true; + } return hasChanges; } diff --git a/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs b/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs index 8819fe1b4..5103aa8b3 100644 --- a/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs +++ b/src/Discord.Net.WebSocket/Entities/Users/SocketWebhookUser.cs @@ -30,7 +30,7 @@ namespace Discord.WebSocket /// public override bool IsWebhook => true; /// - internal override SocketPresence Presence { get { return new SocketPresence(UserStatus.Offline, null, null); } set { } } + internal override SocketPresence Presence { get { return new SocketPresence(UserStatus.Offline, null, null, null); } set { } } internal override SocketGlobalUser GlobalUser => throw new NotSupportedException(); @@ -65,6 +65,8 @@ namespace Discord.WebSocket /// DateTimeOffset? IGuildUser.PremiumSince => null; /// + bool? IGuildUser.IsPending => null; + /// GuildPermissions IGuildUser.GuildPermissions => GuildPermissions.Webhook; /// diff --git a/src/Discord.Net.WebSocket/GatewayReconnectException.cs b/src/Discord.Net.WebSocket/GatewayReconnectException.cs index 1a8024558..c5b15e007 100644 --- a/src/Discord.Net.WebSocket/GatewayReconnectException.cs +++ b/src/Discord.Net.WebSocket/GatewayReconnectException.cs @@ -3,18 +3,15 @@ using System; namespace Discord.WebSocket { /// - /// An exception thrown when the gateway client has been requested to - /// reconnect. + /// The exception thrown when the gateway client has been requested to reconnect. /// public class GatewayReconnectException : Exception { /// - /// Creates a new instance of the - /// type. + /// Initializes a new instance of the class with the reconnection + /// message. /// - /// - /// The reason why the gateway has been requested to reconnect. - /// + /// The reason why the gateway has been requested to reconnect. public GatewayReconnectException(string message) : base(message) { } diff --git a/src/Discord.Net.Webhook/Discord.Net.Webhook.csproj b/src/Discord.Net.Webhook/Discord.Net.Webhook.csproj index f1db66363..24ae442d7 100644 --- a/src/Discord.Net.Webhook/Discord.Net.Webhook.csproj +++ b/src/Discord.Net.Webhook/Discord.Net.Webhook.csproj @@ -1,5 +1,6 @@ + Discord.Net.Webhook Discord.Webhook diff --git a/src/Discord.Net.Webhook/DiscordWebhookClient.cs b/src/Discord.Net.Webhook/DiscordWebhookClient.cs index 353345ded..a6d4ef183 100644 --- a/src/Discord.Net.Webhook/DiscordWebhookClient.cs +++ b/src/Discord.Net.Webhook/DiscordWebhookClient.cs @@ -33,7 +33,7 @@ namespace Discord.Webhook : this(webhookUrl, new DiscordRestConfig()) { } // regex pattern to match webhook urls - private static Regex WebhookUrlRegex = new Regex(@"^.*(discord|discordapp)\.com\/api\/webhooks\/([\d]+)\/([a-z0-9_-]+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private static Regex WebhookUrlRegex = new Regex(@"^.*(discord|discordapp)\.com\/api\/webhooks\/([\d]+)\/([a-z0-9_-]+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); /// Creates a new Webhook Discord client. public DiscordWebhookClient(ulong webhookId, string webhookToken, DiscordRestConfig config) @@ -74,12 +74,12 @@ namespace Discord.Webhook _restLogger = LogManager.CreateLogger("Rest"); - ApiClient.RequestQueue.RateLimitTriggered += async (id, info) => + ApiClient.RequestQueue.RateLimitTriggered += async (id, info, endpoint) => { if (info == null) - await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {id ?? "null"}").ConfigureAwait(false); + await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); else - await _restLogger.WarningAsync($"Rate limit triggered: {id ?? "null"}").ConfigureAwait(false); + await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); }; ApiClient.SentRequest += async (method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false); } @@ -88,19 +88,21 @@ namespace Discord.Webhook /// Sends a message to the channel for this webhook. /// Returns the ID of the created message. public Task SendMessageAsync(string text = null, bool isTTS = false, IEnumerable embeds = null, - string username = null, string avatarUrl = null, RequestOptions options = null) - => WebhookClientHelper.SendMessageAsync(this, text, isTTS, embeds, username, avatarUrl, options); + string username = null, string avatarUrl = null, RequestOptions options = null, AllowedMentions allowedMentions = null) + => WebhookClientHelper.SendMessageAsync(this, text, isTTS, embeds, username, avatarUrl, allowedMentions, options); /// Sends a message to the channel for this webhook with an attachment. /// Returns the ID of the created message. public Task SendFileAsync(string filePath, string text, bool isTTS = false, - IEnumerable embeds = null, string username = null, string avatarUrl = null, RequestOptions options = null, bool isSpoiler = false) - => WebhookClientHelper.SendFileAsync(this, filePath, text, isTTS, embeds, username, avatarUrl, options, isSpoiler); + IEnumerable embeds = null, string username = null, string avatarUrl = null, + RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + => WebhookClientHelper.SendFileAsync(this, filePath, text, isTTS, embeds, username, avatarUrl, allowedMentions, options, isSpoiler); /// Sends a message to the channel for this webhook with an attachment. /// Returns the ID of the created message. public Task SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, - IEnumerable embeds = null, string username = null, string avatarUrl = null, RequestOptions options = null, bool isSpoiler = false) - => WebhookClientHelper.SendFileAsync(this, stream, filename, text, isTTS, embeds, username, avatarUrl, options, isSpoiler); + IEnumerable embeds = null, string username = null, string avatarUrl = null, + RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + => WebhookClientHelper.SendFileAsync(this, stream, filename, text, isTTS, embeds, username, avatarUrl, allowedMentions, options, isSpoiler); /// Modifies the properties of this webhook. public Task ModifyWebhookAsync(Action func, RequestOptions options = null) diff --git a/src/Discord.Net.Webhook/WebhookClientHelper.cs b/src/Discord.Net.Webhook/WebhookClientHelper.cs index 311d58bda..4bc2eaca9 100644 --- a/src/Discord.Net.Webhook/WebhookClientHelper.cs +++ b/src/Discord.Net.Webhook/WebhookClientHelper.cs @@ -21,7 +21,7 @@ namespace Discord.Webhook return RestInternalWebhook.Create(client, model); } public static async Task SendMessageAsync(DiscordWebhookClient client, - string text, bool isTTS, IEnumerable embeds, string username, string avatarUrl, RequestOptions options) + string text, bool isTTS, IEnumerable embeds, string username, string avatarUrl, AllowedMentions allowedMentions, RequestOptions options) { var args = new CreateWebhookMessageParams(text) { IsTTS = isTTS }; if (embeds != null) @@ -30,19 +30,21 @@ namespace Discord.Webhook args.Username = username; if (avatarUrl != null) args.AvatarUrl = avatarUrl; + if (allowedMentions != null) + args.AllowedMentions = allowedMentions.ToModel(); var model = await client.ApiClient.CreateWebhookMessageAsync(client.Webhook.Id, args, options: options).ConfigureAwait(false); return model.Id; } public static async Task SendFileAsync(DiscordWebhookClient client, string filePath, string text, bool isTTS, - IEnumerable embeds, string username, string avatarUrl, RequestOptions options, bool isSpoiler) + IEnumerable embeds, string username, string avatarUrl, AllowedMentions allowedMentions, RequestOptions options, bool isSpoiler) { string filename = Path.GetFileName(filePath); using (var file = File.OpenRead(filePath)) - return await SendFileAsync(client, file, filename, text, isTTS, embeds, username, avatarUrl, options, isSpoiler).ConfigureAwait(false); + return await SendFileAsync(client, file, filename, text, isTTS, embeds, username, avatarUrl, allowedMentions, options, isSpoiler).ConfigureAwait(false); } public static async Task SendFileAsync(DiscordWebhookClient client, Stream stream, string filename, string text, bool isTTS, - IEnumerable embeds, string username, string avatarUrl, RequestOptions options, bool isSpoiler) + IEnumerable embeds, string username, string avatarUrl, AllowedMentions allowedMentions, RequestOptions options, bool isSpoiler) { var args = new UploadWebhookFileParams(stream) { Filename = filename, Content = text, IsTTS = isTTS, IsSpoiler = isSpoiler }; if (username != null) @@ -51,6 +53,8 @@ namespace Discord.Webhook args.AvatarUrl = avatarUrl; if (embeds != null) args.Embeds = embeds.Select(x => x.ToModel()).ToArray(); + if(allowedMentions != null) + args.AllowedMentions = allowedMentions.ToModel(); var msg = await client.ApiClient.UploadWebhookFileAsync(client.Webhook.Id, args, options).ConfigureAwait(false); return msg.Id; } diff --git a/src/Discord.Net/Discord.Net.nuspec b/src/Discord.Net/Discord.Net.nuspec index 5c5ea4072..494e3ea43 100644 --- a/src/Discord.Net/Discord.Net.nuspec +++ b/src/Discord.Net/Discord.Net.nuspec @@ -2,7 +2,7 @@ Discord.Net - 2.3.0-dev$suffix$ + 2.3.1-dev$suffix$ Discord.Net Discord.Net Contributors foxbot @@ -14,25 +14,25 @@ https://github.com/RogueException/Discord.Net/raw/dev/docs/marketing/logo/PackageLogo.png - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + diff --git a/stylecop.json b/stylecop.json new file mode 100644 index 000000000..bb9056963 --- /dev/null +++ b/stylecop.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "indentation": { + "indentationSize": 4, + "tabSize": 4, + "useTabs": false + }, + "documentationRules": { + "documentExposedElements": true, + "documentInternalElements": false, + "documentPrivateElements": false, + "documentInterfaces": true, + "documentPrivateFields": true, + "xmlHeader": false, + "documentationCulture": "en-US" + } + } +} diff --git a/test/Discord.Net.Analyzers.Tests/Discord.Net.Analyzers.Tests.csproj b/test/Discord.Net.Analyzers.Tests/Discord.Net.Analyzers.Tests.csproj index bc587657c..8f69672f9 100644 --- a/test/Discord.Net.Analyzers.Tests/Discord.Net.Analyzers.Tests.csproj +++ b/test/Discord.Net.Analyzers.Tests/Discord.Net.Analyzers.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp3.0 + netcoreapp3.1 false @@ -11,7 +11,7 @@ - + diff --git a/test/Discord.Net.Tests.Unit/Discord.Net.Tests.Unit.csproj b/test/Discord.Net.Tests.Unit/Discord.Net.Tests.Unit.csproj index 357bf9531..866041696 100644 --- a/test/Discord.Net.Tests.Unit/Discord.Net.Tests.Unit.csproj +++ b/test/Discord.Net.Tests.Unit/Discord.Net.Tests.Unit.csproj @@ -1,7 +1,7 @@  - netcoreapp3.0 + netcoreapp3.1 false @@ -10,7 +10,7 @@ - + diff --git a/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs b/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs index f0611fa24..cd29b2606 100644 --- a/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs +++ b/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs @@ -69,6 +69,7 @@ namespace Discord AssertFlag(() => new GuildPermissions(manageGuild: true), GuildPermission.ManageGuild); AssertFlag(() => new GuildPermissions(addReactions: true), GuildPermission.AddReactions); AssertFlag(() => new GuildPermissions(viewAuditLog: true), GuildPermission.ViewAuditLog); + AssertFlag(() => new GuildPermissions(viewGuildInsights: true), GuildPermission.ViewGuildInsights); AssertFlag(() => new GuildPermissions(viewChannel: true), GuildPermission.ViewChannel); AssertFlag(() => new GuildPermissions(sendMessages: true), GuildPermission.SendMessages); AssertFlag(() => new GuildPermissions(sendTTSMessages: true), GuildPermission.SendTTSMessages); @@ -141,6 +142,7 @@ namespace Discord AssertUtil(GuildPermission.ManageGuild, x => x.ManageGuild, (p, enable) => p.Modify(manageGuild: enable)); AssertUtil(GuildPermission.AddReactions, x => x.AddReactions, (p, enable) => p.Modify(addReactions: enable)); AssertUtil(GuildPermission.ViewAuditLog, x => x.ViewAuditLog, (p, enable) => p.Modify(viewAuditLog: enable)); + AssertUtil(GuildPermission.ViewGuildInsights, x => x.ViewGuildInsights, (p, enable) => p.Modify(viewGuildInsights: enable)); AssertUtil(GuildPermission.ViewChannel, x => x.ViewChannel, (p, enable) => p.Modify(viewChannel: enable)); AssertUtil(GuildPermission.SendMessages, x => x.SendMessages, (p, enable) => p.Modify(sendMessages: enable)); AssertUtil(GuildPermission.SendTTSMessages, x => x.SendTTSMessages, (p, enable) => p.Modify(sendTTSMessages: enable)); diff --git a/test/Discord.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs b/test/Discord.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs index 870c05812..f169fb717 100644 --- a/test/Discord.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs +++ b/test/Discord.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs @@ -73,17 +73,17 @@ namespace Discord throw new NotImplementedException(); } - public Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + public Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } - public Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + public Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } diff --git a/test/Discord.Net.Tests.Unit/MockedEntities/MockedGroupChannel.cs b/test/Discord.Net.Tests.Unit/MockedEntities/MockedGroupChannel.cs index 31df719da..e662d628a 100644 --- a/test/Discord.Net.Tests.Unit/MockedEntities/MockedGroupChannel.cs +++ b/test/Discord.Net.Tests.Unit/MockedEntities/MockedGroupChannel.cs @@ -81,17 +81,17 @@ namespace Discord throw new NotImplementedException(); } - public Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + public Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } - public Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + public Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } diff --git a/test/Discord.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs b/test/Discord.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs index a95a91f5c..fbaaf9a18 100644 --- a/test/Discord.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs +++ b/test/Discord.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs @@ -167,17 +167,17 @@ namespace Discord throw new NotImplementedException(); } - public Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + public Task SendFileAsync(string filePath, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } - public Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null) + public Task SendFileAsync(Stream stream, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } - public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null) + public Task SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) { throw new NotImplementedException(); } diff --git a/test/Discord.Net.Tests.Unit/TokenUtilsTests.cs b/test/Discord.Net.Tests.Unit/TokenUtilsTests.cs index bbfbfe754..e9526b761 100644 --- a/test/Discord.Net.Tests.Unit/TokenUtilsTests.cs +++ b/test/Discord.Net.Tests.Unit/TokenUtilsTests.cs @@ -83,7 +83,7 @@ namespace Discord public void BotTokenDoesNotThrowExceptions(string token) { // This example token is pulled from the Discord Docs - // https://discordapp.com/developers/docs/reference#authentication-example-bot-token-authorization-header + // https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header // should not throw any exception TokenUtils.ValidateToken(TokenType.Bot, token); } diff --git a/test/Discord.Net.Tests/Tests.DiscordWebhookClient.cs b/test/Discord.Net.Tests/Tests.DiscordWebhookClient.cs index 039525afc..52c39005b 100644 --- a/test/Discord.Net.Tests/Tests.DiscordWebhookClient.cs +++ b/test/Discord.Net.Tests/Tests.DiscordWebhookClient.cs @@ -12,18 +12,18 @@ namespace Discord public class DiscordWebhookClientTests { [Theory] - [InlineData("https://discordapp.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", + [InlineData("https://discord.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", 123412347732897802, "_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK")] // ptb, canary, etc will have slightly different urls - [InlineData("https://ptb.discordapp.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", + [InlineData("https://ptb.discord.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", 123412347732897802, "_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK")] - [InlineData("https://canary.discordapp.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", + [InlineData("https://canary.discord.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", 123412347732897802, "_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK")] // don't care about https - [InlineData("http://canary.discordapp.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", + [InlineData("http://canary.discord.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", 123412347732897802, "_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK")] // this is the minimum that the regex cares about - [InlineData("discordapp.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", + [InlineData("discord.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK", 123412347732897802, "_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK")] public void TestWebhook_Valid(string webhookurl, ulong expectedId, string expectedToken) { @@ -48,7 +48,7 @@ namespace Discord [Theory] [InlineData("123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK")] // trailing slash - [InlineData("https://discordapp.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK/")] + [InlineData("https://discord.com/api/webhooks/123412347732897802/_abcde123456789-ABCDEFGHIJKLMNOP12345678-abcdefghijklmnopABCDEFGHIJK/")] public void TestWebhook_Invalid(string webhookurl) { Assert.Throws(() =>