Skip to content

Commit

Permalink
Squashed commit of the following:
Browse files Browse the repository at this point in the history
commit ff0bbbd
Merge: 41b4686 19a66bf
Author: quin lynch <lynchquin@gmail.com>
Date:   Sat Nov 27 08:39:35 2021 -0400

    Merge branch 'dev' of https://github.com/discord-net/Discord.Net into dev

commit 19a66bf
Author: Daniel Baynton <49287178+230Daniel@users.noreply.github.com>
Date:   Fri Nov 26 15:41:55 2021 +0000

    feature: Add method to clear guild user cache (discord-net#1767)

    * Add method to clear a SocketGuild's user cache

    * Add optional predicate

    * Compress overload to be consistant

    * Fix global user not clearing (may cause other issues)

    * Remove debug code and add param documentation

    * Standardise doc string

    * Remove old hack-fix

    * Rename new method for consistency

    * Add missing line to reset downloaderPromise

    * Undo accidental whitespace changes

    * Rider better actually keep the tab this time

    Co-authored-by: Quin Lynch <49576606+quinchs@users.noreply.github.com>

commit b9274d1
Author: Monica S <FiniteReality@users.noreply.github.com>
Date:   Fri Nov 26 15:41:08 2021 +0000

    Add characters commonly use in links to Sanitize (discord-net#1152)

    Co-authored-by: Quin Lynch <49576606+quinchs@users.noreply.github.com>

commit 51e06e9
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Fri Nov 26 11:30:19 2021 -0400

    feature: warn on invalid gateway intents (discord-net#1948)

commit 82276e3
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Fri Nov 26 11:29:53 2021 -0400

    feature: default application games (discord-net#1949)

    * Initial implementation

    * Add missing summary

commit 4f1fe2b
Merge: 9d6dc62 3cd9f39
Author: quin lynch <lynchquin@gmail.com>
Date:   Fri Nov 26 11:23:32 2021 -0400

    Merge branch 'siscodeorg-commands/validate-get-best-match' into dev

commit 3cd9f39
Merge: 9d6dc62 adf3a9c
Author: quin lynch <lynchquin@gmail.com>
Date:   Fri Nov 26 11:23:05 2021 -0400

    Merge branch 'commands/validate-get-best-match' of https://github.com/siscodeorg/Discord.Net into siscodeorg-commands/validate-get-best-match

commit adf3a9c
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Fri Nov 26 09:26:53 2021 -0300

    Fix incorrect casing on `HandleCommandPipeline`

commit a92ec56
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Thu Nov 25 16:42:18 2021 -0300

    Add requested changes

    Changes:
    - Use IResult instead of Optional CommandMatch

    - Rework branching workflow

commit d1b31c8
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Thu Nov 25 15:31:48 2021 -0300

    Add `MatchResult`

commit 9d6dc62
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Thu Nov 25 11:25:19 2021 -0400

    Update socket presence and add new presence event (discord-net#1945)

commit 10afd96
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Thu Nov 25 11:24:44 2021 -0400

    feature: Handle bidirectional usernames (discord-net#1943)

    * Initial implementation

    * Update summary

commit 143ca6d
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Thu Nov 25 11:23:33 2021 -0400

    fix NRE when adding parameters thru builders (discord-net#1946)

commit d5f5ae1
Author: Cenk Ergen <57065323+Cenngo@users.noreply.github.com>
Date:   Thu Nov 25 18:22:50 2021 +0300

    fix sharded client current user (discord-net#1947)

commit b5c150d
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Wed Nov 24 12:53:39 2021 -0400

    Add Voice binaries (discord-net#1944)

    * Add binaries and read me

    * Update sending voice docs

    * Undo markdown formatting

commit bc440ab
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Wed Nov 24 12:52:55 2021 -0400

    Implement multi-file upload to webhooks (discord-net#1942)

commit f7a07ae
Author: Paulo <pnmanjos@hotmail.com>
Date:   Wed Nov 24 09:57:06 2021 -0300

    Add default nullable enum typereader (discord-net#1518)

commit 6abdfcb
Author: Slate <kristian.f@hotmail.co.uk>
Date:   Wed Nov 24 12:55:07 2021 +0000

    Added negative TimeSpan handling (discord-net#1666)

    - Added unit tests for the TimeSpanTypeReader
    - Fixes discord-net#1657

commit e0dbe7c
Author: Paulo <pnmanjos@hotmail.com>
Date:   Wed Nov 24 09:43:57 2021 -0300

    Add MaxBitrate to the interface (discord-net#1861)

    Co-authored-by: Quin Lynch <49576606+quinchs@users.noreply.github.com>

commit 3cb662f
Author: d4n <dan3436@hotmail.com>
Date:   Tue Nov 23 10:49:31 2021 -0500

    Add null check to AllowedMentions.ToModel() (discord-net#1865)

commit 900c1f4
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Tue Nov 23 11:46:18 2021 -0400

    Fix emoto try parse (discord-net#1941)

commit 933ea42
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Tue Nov 23 09:58:05 2021 -0400

    Merge Labs 3.X into dev (discord-net#1923)

    * meta: bump version

    * Null or empty fix (discord-net#176)

    * Add components and stickers to ReplyAsync extension

    * Fixed null or empty

    * Changed Label to Description

    * -||-

    Co-authored-by: quin lynch <lynchquin@gmail.com>

    * More regions (discord-net#177)

    * Preconditions

    * ChannelHelper

    * RestDMChannel

    * RestGroupChannel

    * RestBan

    * RestGroupUser

    * EntityExtensions

    * DiscordSocketClient

    * DiscordSocketClient

    * Discord.net.core.xml fix (discord-net#178)

    * Changed Label to Description

    * Added Discord- .MessageComponent .ISticker[]

    ,Discord.MessageComponent,Discord.ISticker[] to ReplyAsync

    * Remove references to labs

    * Update Discord.Net.sln

    * Added SendMessagesInThreads and StartEmbeddedActivities. (discord-net#175)

    * Added SendMessagesInThreads and StartEmbeddedActivities.

    Adjusted owner perms.
    Change UsePublicThreads -> CreatePublicThreads
    Change UsePrivateThreads -> CreatePrivateThreads

    * removed extra ///

    * Added UsePublicThreads and UsePrivateThreads back with Obsolete Attribute

    * removed 'false' from Obsolete Attribute

    * Squashed commit of the following:

    commit dca41a348e36a9b4e7006ef3a76377eb32aad276
    Author: quin lynch <lynchquin@gmail.com>
    Date:   Thu Sep 23 07:02:19 2021 -0300

        Autocomplete commands

    * meta: xml. closes discord-net#171

    * Revert user agent and $device to dnet

    * meta: bump version

    * meta: bump vers

    * Fix sticker args

    * Grammer fix (discord-net#179)

    * Made IVoiceChannel mentionable

    * Embeds array for send message async (discord-net#181)

    * meta: bump version

    * meta: bump vers

    * Fix sticker args

    * Grammer fix (discord-net#179)

    * Added embeds for SendMessageAsync

    * [JsonProperty("embed")] forgot to remove this

     public Optional<Embed> Embed { get; set; }

    * It has been done as requested.

    * Changed the old way of handeling single embeds

    * Moved embeds param and added options param

    * xmls

    Co-authored-by: quin lynch <lynchquin@gmail.com>

    * Fix thread permissions (discord-net#183)

    * Update GuildPermissionsTests.cs

    * Update GuildPermissions.cs

    * Use compound assignment (discord-net#186)

    * Used compound assignment

    * -||-

    * -||-

    * Remove unnecessary suppression (discord-net#188)

    * Inlined variable declarations (discord-net#185)

    * Fixed some warnings (discord-net#184)

    * Fixed some warnings

    * Another fixed warning

    * Changed the SSendFileAsync to SendFileAsync

    * Removed para AlwaysAcknowledgeInteractions

    * Moved it back to the previous version

    * Added periods to the end like quin requested!! :((

    Co-authored-by: MrCakeSlayer <13650699+MrCakeSlayer@users.noreply.github.com>

    * Object initialization can be simplified fixed (discord-net#189)

    * Conditional-expression-simplification (discord-net#193)

    * Capitlazation fixes (discord-net#192)

    * Removed-this. (discord-net#191)

    * Use 'switch' expression (discord-net#187)

    * Use 'switch' expression

    * Reverted it to the old switch case

    * Fixed-compiler-error (discord-net#194)

    * Submitting updates to include new permissions. (discord-net#195)

    * Submitting updates to include new permissions.

    * Make old permissions obsolete and update tests

    Co-authored-by: quin lynch <lynchquin@gmail.com>

    * Update azure-pipelines.yml

    * Update azure-pipelines.yml

    * Update azure-pipelines.yml

    * Add support for long in autocomplete option

    * Add support for sending files with multiple embeds (discord-net#196)

    * Add support for sending files with multiple embeds

    * Simplify prepending single embed to embed array

    * Consistency for embeds endpoints (discord-net#197)

    * Changed the way of handling prepending of embeds.

    For consistency.

    * reformatted the summary

    * Revert pipeline

    * Fix duplicate merge conflicts

    * Changed minimum slash command name length to 1 per Discord API docs (discord-net#198)

    * Channel endpoints requirements correction (discord-net#199)

    * Added some requirements to channels for topic

    * Changed check from NotNullOrEmpty to NotNullOrEmpty

    * Added some requirements to channels for name

    Preconditions.LessThan

    * Formatting of file

    * Added restriction for description not being null (discord-net#200)

    * Update azure-pipelines.yml

    * Update deploy.yml

    * Remove version tag from proj

    * Update deploy.yml

    * Removed versions from project files

    * Removed style of the nuget badge and added logo (discord-net#201)

    The style was not properly added to it and the plastic version does not look good with the discord badge.
    I thought it would look better with a logo

    * Fix Type not being set in SocketApplicationCommand

    * Remove useless GuildId property

    * meta: update XML

    * Add Autocomplete to SlashCommandOptionBuilder

    * Added autocomplete in SlashCommandOptionBuilder. (discord-net#206)

    Co-authored-by: Quin Lynch <49576606+quinchs@users.noreply.github.com>

    * Fix duplicate autocomplete

    * Fix discord-net#208

    * Fix sub commands being interpreted as a parameter for autocomplete

    * Fix exposed optional

    * Support the discord:// protocol in buttons (discord-net#207)

    * Update UrlValidation.cs

    * Update ComponentBuilder.cs

    * Add docs and better error messages.

    * Fix wonky intentation

    * Add competing activity status type (discord-net#205)

    * Update GuildPermissionsTests.cs

    * Update GuildPermissions.cs

    * Add competing status type

    * Add Icons to IRole (discord-net#204)

    * Added icon field to IRole

    * Added GetGuildRoleIconUrl()

    * Added Clean Content Function (discord-net#174)

    * Added Clean Content Function

    * Fixed Spelling problems and bad var handling

    * Add StripMarkDown Method

    * Clean Content Expanded (discord-net#212)

    * Implement CleanContent In IMessage & RestMessage

    * Update Spelling and Documentation

    * Add SanatizeMessage to MessageHelper and Refactor Rest and Socket Message

    * Add event for autocomplete interaction (discord-net#214)

    * Spelling corrections (discord-net#215)

    * Remove null collections

    * Followup with file async warnings (discord-net#216)

    * Changed from NotNullOrWhitespace to NotNullOrEmpty

    * Added NotNullOrEmpty on filename

    * Added system to interpret from the path

    * Added a check for if it contains a period

    * It has been done, how ever it will break stuff

    * Changed to use ??= how ever still added error check

    * Added space under check

    * Changed from with a period to valid file extension

    * Added checks for SendFileAsync

    * Removed filename != null &&

    * Add channel types in application command options. (discord-net#217)

    * add channel types in application command options

    * Indent Docs

    * Stage instance audit logs as well as thread audit log type

    * Update azure-pipelines.yml

    * Update azure-pipelines.yml

    * Fix system messages not including mentioned users. Added ContextMenuCommand message type

    * Remove file extension check (discord-net#218)

    * Fix NRE in modify guild channel

    * Fix 429's not being accounted for in ratelimit updates

    * meta: add net5 framework

    Co-Authored-By: MrCakeSlayer <13650699+MrCakeSlayer@users.noreply.github.com>

    * Proper doc logos (discord-net#221)

    * Update GuildPermissionsTests.cs

    * Update GuildPermissions.cs

    * Add competing activity status type

    * logo changes

    * logo text as path

    * add missing logo

    * Update package logo and favicon

    * Update docfx references

    * Remove XML files and use original pipeline format

    * Remove console writeline

    * Remove Console.WriteLine

    * Remove useless log

    * Rename Available sticker field to IsAvailable

    * Rename Available to IsAvailable in stickers

    * Add summary indent for role members

    * Add summary indent to SocketInvite

    * Rename DefaultPermission to IsDefaultPermission

    * Rename Default to IsDefault and Required to IsRequired in IApplicationCommandOption

    * Rename Default and Required to IsDefault and IsRequired in IApplicationCommandOption. Rename DefaultPermission to IsDefaultPermission in IApplicationCommand

    * Remove extra white spaces

    * Renamed Joined, Archived, and Locked to HasJoined, IsArchived, and IsLocked

    * Rename Live and DiscoverableDisabled to IsDiscoverableDisabled and IsLive in IStageChannel

    * Remove newline

    * Add indent to summaries

    * Remove unnecessary json serializer field

    * Fix ToEntity for roletags incorrectly using IsPremiumSubscriber

    * Update RestChannel for new channel types

    * Fix different rest channels not deserializing properly

    * fully qualify internal for UrlValidation and add indent to summary

    * Add missing periods to InteractionResponseType

    * Fix summary in IApplicationCommandOptionChoice

    * Update IApplicationCommandOption summaries

    * Update IApplicationCommandInteractionDataOption summaries

    * Update IApplicationCommandInteractionData summaries

    * Update IApplicationCommand summaries

    * Update ApplicationCommandType summaries

    * rename DefaultPermission to IsDefaultPermission in ApplicationCommandProperties

    * update ApplicationCommandOptionChoiceProperties summaries

    * Rename Default, Required, and Autocomplete to IsDefault, IsRequired, and IsAutocomplete in ApplicationCommandOptionProperties

    * Update SlashCommandProperties summaries

    * update SlashCommandBuilder boolean field names, summaries, and choice parameters

    * Update SelectMenuOption summaries, Rename Default to IsDefault in SelectMenuOption

    * update SelectMenuComponent summaries. Rename Disabled to IsDisabled in SelectMenuComponent

    * update ComponentBuilder summaries and boolean fields.

    * Update ButtonComponent summaries and boolean fields

    * update ActionRowComponent summaries

    * Update UserCommandBuilder

    * Update MessageCommandBuilder summaries and boolean properties

    * Update IGuild summary

    * Update IGuild summaries

    * Update StagePrivacyLevel summary

    * update IThreadChannel summaries

    * Update IStageChannel summaries

    * Refactor summaries and boolean property names

    * General cleanup (discord-net#223)

    * General cleanup

    * Add Async suffix to SendAutocompleteResult

    * Fix more formatting

    * Fix unused RequestOptions in GetActiveThreadsAsync

    * Add message to ArgumentNullException

    * Ephemeral attachments

    * Add missing jsonproperty attribute

    * Add IMessage.Interaction

    * Update attachment checks for embed urls

    * meta: bump version

    * Remove old package configs and update image

    * Update package logos

    * Fix logo reference for azure

    * Deprecate old package definitions in favor for target file

    * Deprecate old package definitions in favor for target file

    Co-authored-by: Jared L <48422312+lhjt@users.noreply.github.com>

    * Update package ids

    * Fix url validation

    * meta: bump version

    * Fix assignment of UserMentions (discord-net#233)

    * Fix CleanContent (discord-net#231)

    * Fix SocketSlashCommandData access modifier. (discord-net#237)

    Fixes discord-net#229

    * Update README with better header (discord-net#232)

    * Update README with better header

    Adds HTML elements that implement the main logo & improve the redirection tag positions.

    * Resolving border issue in light-mode

    * Update sponsor section

    * Implement checks for interaction respond times and multiple interaction responses. closes discord-net#236, discord-net#235

    * Add response check to socket auto complete

    * meta: bump versions

    * Fix discord-net#239

    * meta: bump version

    * meta: update logo

    * meta: bump versions

    * Revert received at time, confirmed by discord staff to be accurate

    * Merge branch 'release/3.x' of https://github.com/Discord-Net-Labs/Discord.Net-Labs into merger-labs

    Update requested changes of obsolete and references to labs.

    Added `Interaction` to `IMessage`
    Fixed grammar
    Fixed bugs relating to interactions.

    * Update docs

    * Update CHANGELOG.md

    * meta: docs building

    * Update docs.yml

    * Update docs.yml

    * Fix docfx version

    * Update docs.yml

    * Update docs.bat

    * Rename docs repo for clone

    * update docfx version

    * Update docs.bat

    * Update docfx version

    * Remove docs from pipeline

    * FAQ revamped, metadata updated (discord-net#241)

    * FAQ revamped, metadata updated

    * Update FAQ.md

    * Update README.md

    * Docs index improvement

    * Fix InvalidOperationException in modify channel

    * feature: guild avatars, closes discord-net#238

    * feature: modify role icons

    * meta: changelog

    * meta: bump version

    * Update README.md

    * Fix non value type options not being included in autocomplete

    * Add new activity flags (discord-net#254)

    * Add new activity flags

    * Add missing commas

    * Added support for GUILD_JOIN_REQUEST_DELETE event (discord-net#253)

    Fixes discord-net#247

    * Adding BotHTTPInteraction user flag (discord-net#252)

    * animated guild banner support (discord-net#255)

    * Docs work (WIP) (discord-net#242)

    * Main page work

    * Metadata logo dir

    * More main page edits

    * Naming change

    * Dnet guide entries pruned

    * Add student hub guild directory channel (discord-net#256)

    * animated guild banner support

    * Add guild directory channel

    * Fix followup with file overwrite having incorrect parameter locations

    * Merge labs 3.x

    * Update GUILD_JOIN_REQUEST_DELETE event

    * Update head.tmpl.partial

    * Removed BannerId and AccentColor  (discord-net#260)

    * Removed BannerId property, GetBannerURL method, and AccentColor property from IUser and socket entities.

    * Fixed errors in IUser.cs

    * Added back summary for GetAvatarUrl method in IUser.cs

    * Support Guild Boost Progress Bars (discord-net#262)

    * Support Guild Boost Progress Bars

    * Update SocketChannel.cs

    * Fix non-optional and unnecessary values.

    * Spelling

    * Reordering and consistency.

    * Remove log for reconnect

    * Add missing flags to SystemChannelMessageDeny (discord-net#267)

    * Fix labs reference in analyzer project and provider project

    * Rename new activity flags

    * Guild feature revamp and smart gateway intent checks

    * Get thread user implementation

    * Amend creating slash command guide (discord-net#269)

    * Adding BotHTTPInteraction user flag

    * Added comments explaining the Global command create stipulations.

    * Fix numeric type check for options

    * Add state checking to ConnectionManager.StartAsync (discord-net#272)

    * initial interface changes

    * Multi file upload + attachment editing

    * meta: bump versions

    * Update CHANGELOG.md

    * Update CHANGELOG.md

    * Support Min and Max values on ApplicationCommandOptions (discord-net#273)

    * Support Min and Max values on ApplicationCommandOptions

    * Support decimal min/max values

    * Docs imrpovments + use ToNullable

    * Logomark, doc settings edit (discord-net#258)

    * Logomark, doc settings edit

    * Replace standard logo

    * Bumping docfx plugins to latest release

    * Bump version metadata

    * Logo svg fix

    * Change default sticker behavior and add AlwaysResolveSticker to the config

    * Implement rest based interactions. Added ED25519 checks. Updated summaries.

    * Update package logo

    * Automatically fix ordering of optional command options (discord-net#276)

    * auto fix optional command option order

    * clean up indentation

    * Fix maximum number of Select Menu Options (discord-net#282)

    As of https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-menu-structure the maximum number of options is 25, not less than 25. Hopefully the change catches all necessary locations

    * Add voice region to modify voice channels

    * Update summaries on rest interactions

    * Interaction Specific Interfaces (discord-net#283)

    * added interaction specific interfaces

    * fix build error

    * implement change requests

    * Update application

    * Add Guild Scheduled Events (discord-net#279)

    * guild events initial

    * sharded events

    * Add new gateway intents and fix bugs

    * More work on new changes to guild events

    * Update guild scheduled events

    * Added events to extended guild and add event start event

    * Update preconditions

    * Implement breaking changes guild guild events. Add guild event permissions

    * Update tests and change privacy level requirements

    * Update summaries and add docs for guild events

    * meta: bump version

    * Increment meta version (discord-net#285)

    * Increment meta version

    * Update docfx.json

    * Fix discord-net#289 and add configureawaits to rest based interactions

    * meta: bump version

    * Add GUILD_SCHEDULED_EVENT_USER_ADD and GUILD_SCHEDULED_EVENT_USER_REMOVE (discord-net#287)

    * Remove newline

    * Fix autocomplete result value

    * meta: bump versions

    * Add `GuildScheduledEventUserAdd` and `GuildScheduledEventUserRemove` to sharded client

    * Make RestUserCommand public (discord-net#292)

    * Fix Components not showing on FUWF (discord-net#288) (discord-net#293)

    Adds Components to Payload JSON Generation

    * Implement smarter rest resolvable interaction data. Fixes discord-net#294

    * Add UseInteractionSnowflakeDate to config discord-net#286

    * Implement Better Discord Errors (discord-net#291)

    * Initial error parsing

    * Implement better errors

    * Add missing error codes

    * Add voice disconnect opcodes

    * Remove unused class, add summaries to discordjsonerror, and remove public constructor of slash command properties

    * Add error code summary

    * Update error message summary

    * Update src/Discord.Net.Core/DiscordJsonError.cs

    Co-authored-by: Jared L <48422312+lhjt@users.noreply.github.com>

    * Update src/Discord.Net.WebSocket/API/Voice/VoiceCloseCode.cs

    Co-authored-by: Jared L <48422312+lhjt@users.noreply.github.com>

    * Fix autocomplete result value

    Co-authored-by: Jared L <48422312+lhjt@users.noreply.github.com>

    * Change the minimum length of slash commands to 1 (discord-net#284)

    * Change the minimum length of slash commands to 1. This is the correct value according to the docs and it has been changed after user feedback.

    * Fix the limit in 3 other places

    Co-authored-by: quin lynch <lynchquin@gmail.com>

    * Add new thread creation properties

    * Add role emoji. Fixes discord-net#295

    * Fix mocked text channel

    * Fix precondition checks. Closes discord-net#281

    * Initial fix (discord-net#297)

    * meta: bump version

    * Update from release/3.x

    * Remove more labs references

    * Remove doc file for Discord.Net.Analyzers

    Co-authored-by: Simon Hjorthøj <sh2@live.dk>
    Co-authored-by: drobbins329 <drobbins329@gmail.com>
    Co-authored-by: MrCakeSlayer <13650699+MrCakeSlayer@users.noreply.github.com>
    Co-authored-by: d4n3436 <dan3436@hotmail.com>
    Co-authored-by: Will <WilliamWelsh@users.noreply.github.com>
    Co-authored-by: Eugene Garbuzov <kkxo.mail@gmail.com>
    Co-authored-by: CottageDwellingCat <80918250+CottageDwellingCat@users.noreply.github.com>
    Co-authored-by: Emily <89871431+emillly-b@users.noreply.github.com>
    Co-authored-by: marens101 <marens101@gmail.com>
    Co-authored-by: Jared L <48422312+lhjt@users.noreply.github.com>
    Co-authored-by: Armano den Boef <68127614+Rozen4334@users.noreply.github.com>
    Co-authored-by: Bill <billchirico@gmail.com>
    Co-authored-by: Liege72 <65319395+Liege72@users.noreply.github.com>
    Co-authored-by: Floowey <floowey@gmx.at>
    Co-authored-by: Cenk Ergen <57065323+Cenngo@users.noreply.github.com>
    Co-authored-by: exsersewo <exsersewo@systemexit.co.uk>
    Co-authored-by: Dennis Fischer <fischer_dennis@live.de>

commit 3395700
Author: Nikon <47792796+INikonI@users.noreply.github.com>
Date:   Mon Aug 23 02:00:18 2021 +0500

    feature: IVoiceChannel implements IMentionable (discord-net#1896)

commit 41b4686
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Tue Aug 3 20:43:10 2021 -0300

    Update README.md

commit 5fc3145
Author: Quin Lynch <49576606+quinchs@users.noreply.github.com>
Date:   Tue Aug 3 20:28:15 2021 -0300

    Update README.md

commit 56d1639
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Fri Nov 27 18:42:23 2020 -0300

    Fixes Azure linux build failing due to a CS8652.

commit c455b50
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Fri Nov 27 14:10:39 2020 -0300

    Make use of new ValidateAndGetBestMatch api on ExecuteAsync

commit 7955a09
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Fri Nov 27 13:52:53 2020 -0300

    Creates ValidateAndGetBestMatch function

    This function will validate all commands from a SearchResult and return the result of said validation, along with the command matched, if a valid match was found.

commit 574b503
Author: roridev <t3ctotalmenterandom1@outlook.com>
Date:   Fri Nov 27 13:38:00 2020 -0300

    Moves CalculateScore function to outer scope.
  • Loading branch information
quinchs committed Nov 27, 2021
1 parent 5ee55c6 commit 5ffedc2
Show file tree
Hide file tree
Showing 69 changed files with 735 additions and 258 deletions.
2 changes: 1 addition & 1 deletion docs/guides/concepts/ratelimits.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Ratelimits

Ratelimits are a core concept of the discord api, each verified library must follow the ratelimit guidelines. Labs introduces a ratelimit exposure system to help you follow these ratelimits in your own code.
Ratelimits are a core concept of any API - Discords API is no exception. each verified library must follow the ratelimit guidelines.

### Using the ratelimit callback

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Introduction to slash commands

# Getting started with application commands.

Welcome! This guide will show you how to use application commands. If you have extra questions that aren't covered here you can come to our [Discord](https://discord.com/invite/dvSfUTet3K) server and ask around there.
Welcome! This guide will show you how to use application commands.

## What is an application command?

Expand Down
2 changes: 1 addition & 1 deletion docs/guides/voice/sending-voice.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ when developing on .NET Core, this is where you execute `dotnet run`
from; typically the same directory as your csproj).

For Windows Users, precompiled binaries are available for your
convienence [here](https://discord.foxbot.me/binaries/).
convienence [here](https://github.com/discord-net/Discord.Net/tree/dev/voice-natives).

For Linux Users, you will need to compile [Sodium] and [Opus] from
source, or install them from your package manager.
Expand Down
2 changes: 1 addition & 1 deletion src/Discord.Net.Commands/Builders/ParameterBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ internal void SetType(Type type)
if (type.GetTypeInfo().IsValueType)
DefaultValue = Activator.CreateInstance(type);
else if (type.IsArray)
type = ParameterType.GetElementType();
DefaultValue = Array.CreateInstance(type.GetElementType(), 0);
ParameterType = type;
}

Expand Down
136 changes: 90 additions & 46 deletions src/Discord.Net.Commands/CommandService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,13 @@ internal TypeReader GetDefaultTypeReader(Type type)
_defaultTypeReaders[type] = reader;
return reader;
}
var underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null && underlyingType.IsEnum)
{
reader = NullableTypeReader.Create(underlyingType, EnumTypeReader.GetReader(underlyingType));
_defaultTypeReaders[type] = reader;
return reader;
}

//Is this an entity?
for (int i = 0; i < _entityTypeReaders.Count; i++)
Expand Down Expand Up @@ -510,19 +517,83 @@ public async Task<IResult> ExecuteAsync(ICommandContext context, string input, I
services ??= EmptyServiceProvider.Instance;

var searchResult = Search(input);
if (!searchResult.IsSuccess)

var validationResult = await ValidateAndGetBestMatch(searchResult, context, services, multiMatchHandling);

if (validationResult is SearchResult result)
{
await _commandExecutedEvent.InvokeAsync(Optional.Create<CommandInfo>(), context, result).ConfigureAwait(false);
return result;
}

if (validationResult is MatchResult matchResult)
{
return await HandleCommandPipeline(matchResult, context, services);
}

return validationResult;
}

private async Task<IResult> HandleCommandPipeline(MatchResult matchResult, ICommandContext context, IServiceProvider services)
{
if (!matchResult.IsSuccess)
return matchResult;

if (matchResult.Pipeline is ParseResult parseResult)
{
var executeResult = await matchResult.Match.Value.ExecuteAsync(context, parseResult, services);

if (!executeResult.IsSuccess && !(executeResult is RuntimeResult || executeResult is ExecuteResult)) // succesful results raise the event in CommandInfo#ExecuteInternalAsync (have to raise it there b/c deffered execution)
await _commandExecutedEvent.InvokeAsync(matchResult.Match.Value.Command, context, executeResult);
return executeResult;
}

if (matchResult.Pipeline is PreconditionResult preconditionResult)
{
await _commandExecutedEvent.InvokeAsync(matchResult.Match.Value.Command, context, preconditionResult).ConfigureAwait(false);
}

return matchResult;
}

// Calculates the 'score' of a command given a parse result
float CalculateScore(CommandMatch match, ParseResult parseResult)
{
float argValuesScore = 0, paramValuesScore = 0;

if (match.Command.Parameters.Count > 0)
{
await _commandExecutedEvent.InvokeAsync(Optional.Create<CommandInfo>(), context, searchResult).ConfigureAwait(false);
return searchResult;
var argValuesSum = parseResult.ArgValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
var paramValuesSum = parseResult.ParamValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;

argValuesScore = argValuesSum / match.Command.Parameters.Count;
paramValuesScore = paramValuesSum / match.Command.Parameters.Count;
}

var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
return match.Command.Priority + totalArgsScore * 0.99f;
}

/// <summary>
/// Validates and gets the best <see cref="CommandMatch"/> from a specified <see cref="SearchResult"/>
/// </summary>
/// <param name="matches">The SearchResult.</param>
/// <param name="context">The context of the command.</param>
/// <param name="provider">The service provider to be used on the command's dependency injection.</param>
/// <param name="multiMatchHandling">The handling mode when multiple command matches are found.</param>
/// <returns>A task that represents the asynchronous validation operation. The task result contains the result of the
/// command validation as a <see cref="MatchResult"/> or a <see cref="SearchResult"/> if no matches were found.</returns>
public async Task<IResult> ValidateAndGetBestMatch(SearchResult matches, ICommandContext context, IServiceProvider provider, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
{
if (!matches.IsSuccess)
return matches;

var commands = searchResult.Commands;
var commands = matches.Commands;
var preconditionResults = new Dictionary<CommandMatch, PreconditionResult>();

foreach (var match in commands)
foreach (var command in commands)
{
preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services).ConfigureAwait(false);
preconditionResults[command] = await command.CheckPreconditionsAsync(context, provider);
}

var successfulPreconditions = preconditionResults
Expand All @@ -533,19 +604,16 @@ public async Task<IResult> ExecuteAsync(ICommandContext context, string input, I
{
//All preconditions failed, return the one from the highest priority command
var bestCandidate = preconditionResults
.OrderByDescending(x => x.Key.Command.Priority)
.FirstOrDefault(x => !x.Value.IsSuccess);

await _commandExecutedEvent.InvokeAsync(bestCandidate.Key.Command, context, bestCandidate.Value).ConfigureAwait(false);
return bestCandidate.Value;
.OrderByDescending(x => x.Key.Command.Priority)
.FirstOrDefault(x => !x.Value.IsSuccess);
return MatchResult.FromSuccess(bestCandidate.Key,bestCandidate.Value);
}

//If we get this far, at least one precondition was successful.
var parseResults = new Dictionary<CommandMatch, ParseResult>();

var parseResultsDict = new Dictionary<CommandMatch, ParseResult>();
foreach (var pair in successfulPreconditions)
{
var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services).ConfigureAwait(false);
var parseResult = await pair.Key.ParseAsync(context, matches, pair.Value, provider).ConfigureAwait(false);

if (parseResult.Error == CommandError.MultipleMatches)
{
Expand All @@ -560,51 +628,27 @@ public async Task<IResult> ExecuteAsync(ICommandContext context, string input, I
}
}

parseResultsDict[pair.Key] = parseResult;
parseResults[pair.Key] = parseResult;
}

// Calculates the 'score' of a command given a parse result
float CalculateScore(CommandMatch match, ParseResult parseResult)
{
float argValuesScore = 0, paramValuesScore = 0;

if (match.Command.Parameters.Count > 0)
{
var argValuesSum = parseResult.ArgValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
var paramValuesSum = parseResult.ParamValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
var weightedParseResults = parseResults
.OrderByDescending(x => CalculateScore(x.Key, x.Value));

argValuesScore = argValuesSum / match.Command.Parameters.Count;
paramValuesScore = paramValuesSum / match.Command.Parameters.Count;
}

var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
return match.Command.Priority + totalArgsScore * 0.99f;
}

//Order the parse results by their score so that we choose the most likely result to execute
var parseResults = parseResultsDict
.OrderByDescending(x => CalculateScore(x.Key, x.Value));

var successfulParses = parseResults
var successfulParses = weightedParseResults
.Where(x => x.Value.IsSuccess)
.ToArray();

if (successfulParses.Length == 0)
if(successfulParses.Length == 0)
{
//All parses failed, return the one from the highest priority command, using score as a tie breaker
var bestMatch = parseResults
.FirstOrDefault(x => !x.Value.IsSuccess);

await _commandExecutedEvent.InvokeAsync(bestMatch.Key.Command, context, bestMatch.Value).ConfigureAwait(false);
return bestMatch.Value;
return MatchResult.FromSuccess(bestMatch.Key,bestMatch.Value);
}

//If we get this far, at least one parse was successful. Execute the most likely overload.
var chosenOverload = successfulParses[0];
var result = await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
if (!result.IsSuccess && !(result is RuntimeResult || result is ExecuteResult)) // successful results raise the event in CommandInfo#ExecuteInternalAsync (have to raise it there b/c deferred execution)
await _commandExecutedEvent.InvokeAsync(chosenOverload.Key.Command, context, result);
return result;

return MatchResult.FromSuccess(chosenOverload.Key,chosenOverload.Value);
}
#endregion

Expand Down
58 changes: 39 additions & 19 deletions src/Discord.Net.Commands/Readers/TimeSpanTypeReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,50 @@ namespace Discord.Commands
{
internal class TimeSpanTypeReader : TypeReader
{
private static readonly string[] Formats = {
"%d'd'%h'h'%m'm'%s's'", //4d3h2m1s
"%d'd'%h'h'%m'm'", //4d3h2m
"%d'd'%h'h'%s's'", //4d3h 1s
"%d'd'%h'h'", //4d3h
"%d'd'%m'm'%s's'", //4d 2m1s
"%d'd'%m'm'", //4d 2m
"%d'd'%s's'", //4d 1s
"%d'd'", //4d
"%h'h'%m'm'%s's'", // 3h2m1s
"%h'h'%m'm'", // 3h2m
"%h'h'%s's'", // 3h 1s
"%h'h'", // 3h
"%m'm'%s's'", // 2m1s
"%m'm'", // 2m
"%s's'", // 1s
/// <summary>
/// TimeSpan try parse formats.
/// </summary>
private static readonly string[] Formats =
{
"%d'd'%h'h'%m'm'%s's'", // 4d3h2m1s
"%d'd'%h'h'%m'm'", // 4d3h2m
"%d'd'%h'h'%s's'", // 4d3h 1s
"%d'd'%h'h'", // 4d3h
"%d'd'%m'm'%s's'", // 4d 2m1s
"%d'd'%m'm'", // 4d 2m
"%d'd'%s's'", // 4d 1s
"%d'd'", // 4d
"%h'h'%m'm'%s's'", // 3h2m1s
"%h'h'%m'm'", // 3h2m
"%h'h'%s's'", // 3h 1s
"%h'h'", // 3h
"%m'm'%s's'", // 2m1s
"%m'm'", // 2m
"%s's'", // 1s
};

/// <inheritdoc />
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
return (TimeSpan.TryParseExact(input.ToLowerInvariant(), Formats, CultureInfo.InvariantCulture, out var timeSpan))
? Task.FromResult(TypeReaderResult.FromSuccess(timeSpan))
: Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Failed to parse TimeSpan"));
if (string.IsNullOrEmpty(input))
throw new ArgumentException(message: $"{nameof(input)} must not be null or empty.", paramName: nameof(input));

var isNegative = input[0] == '-'; // Char for CultureInfo.InvariantCulture.NumberFormat.NegativeSign
if (isNegative)
{
input = input.Substring(1);
}

if (TimeSpan.TryParseExact(input.ToLowerInvariant(), Formats, CultureInfo.InvariantCulture, out var timeSpan))
{
return isNegative
? Task.FromResult(TypeReaderResult.FromSuccess(-timeSpan))
: Task.FromResult(TypeReaderResult.FromSuccess(timeSpan));
}
else
{
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Failed to parse TimeSpan"));
}
}
}
}
47 changes: 47 additions & 0 deletions src/Discord.Net.Commands/Results/MatchResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;

namespace Discord.Commands
{
public class MatchResult : IResult
{
/// <summary>
/// Gets the command that may have matched during the command execution.
/// </summary>
public CommandMatch? Match { get; }

/// <summary>
/// Gets on which pipeline stage the command may have matched or failed.
/// </summary>
public IResult? Pipeline { get; }

/// <inheritdoc />
public CommandError? Error { get; }
/// <inheritdoc />
public string ErrorReason { get; }
/// <inheritdoc />
public bool IsSuccess => !Error.HasValue;

private MatchResult(CommandMatch? match, IResult? pipeline, CommandError? error, string errorReason)
{
Match = match;
Error = error;
Pipeline = pipeline;
ErrorReason = errorReason;
}

public static MatchResult FromSuccess(CommandMatch match, IResult pipeline)
=> new MatchResult(match,pipeline,null, null);
public static MatchResult FromError(CommandError error, string reason)
=> new MatchResult(null,null,error, reason);
public static MatchResult FromError(Exception ex)
=> FromError(CommandError.Exception, ex.Message);
public static MatchResult FromError(IResult result)
=> new MatchResult(null, null,result.Error, result.ErrorReason);
public static MatchResult FromError(IResult pipeline, CommandError error, string reason)
=> new MatchResult(null, pipeline, error, reason);

public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}";
private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}";

}
}
2 changes: 1 addition & 1 deletion src/Discord.Net.Core/Discord.Net.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
</ItemGroup>
</Project>
</Project>
Loading

0 comments on commit 5ffedc2

Please sign in to comment.