From 35583e3034c7b45d8ef5f9816952561e4ec14926 Mon Sep 17 00:00:00 2001 From: Ge Date: Sat, 24 Aug 2024 17:00:18 +0800 Subject: [PATCH] Rewrite XML docs in Simplified Chinese (#17) * AudioClient and AudioStream * Command & Activity * Working head * Working head * Working head * Working head * wording * Invite and Intimacy * Elements * modules and card * Messages * Fixes tests * Messages - Added `TagUtil` - Changed `Tag` to `Tag` - Adjusted the results of `IUserMessage.Resolve` * Permissinos * Users * More Users * Users and entities * Rest Channels * Update doc * Intimacy remarks * Rest entities * incoming audio * REST * Socket Channels * SocketDMChannel * SocketGuild * Extract LoginAsync and LogoutAsync to IKookClient (#20) * IKookClient * Socket entities * Socket clients * Webhook * Extensions misc * CardMarkup and Commands * Experimental with removing invalid implementations * Missed docs * Fixes EveryoneMention and HereMention tags contain signed zero as value --- THIRD-PARTY-NOTICES.txt | 7 + docs/guides/voice/sending-voice.md | 2 +- docs/quick_reference/http_api/oauth.md | 7 +- .../Modules/MusicModule.cs | 2 - samples/Kook.Net.Samples.FSharp/Program.fs | 2 +- samples/Kook.Net.Samples.SimpleBot/Program.cs | 2 +- .../Kook.Net.Samples.VisualBasic/Program.vb | 2 +- .../CardMarkupSerializer.cs | 95 +- .../Attributes/AliasAttribute.cs | 17 +- .../Attributes/CommandAttribute.cs | 46 +- .../Attributes/DontAutoLoadAttribute.cs | 7 +- .../Attributes/DontInjectAttribute.cs | 10 +- .../Attributes/GroupAttribute.cs | 12 +- .../Attributes/NameAttribute.cs | 9 +- .../Attributes/NamedArgumentTypeAttribute.cs | 24 +- .../Attributes/OverrideTypeReaderAttribute.cs | 34 +- .../ParameterPreconditionAttribute.cs | 15 +- .../Attributes/PreconditionAttribute.cs | 29 +- .../RequireBotPermissionAttribute.cs | 32 +- .../Preconditions/RequireContextAttribute.cs | 40 +- .../Preconditions/RequireRoleAttribute.cs | 19 +- .../Preconditions/RequireUserAttribute.cs | 20 +- .../RequireUserPermissionAttribute.cs | 32 +- .../Attributes/PriorityAttribute.cs | 14 +- .../Attributes/RemainderAttribute.cs | 2 +- .../Attributes/RemarksAttribute.cs | 9 +- .../Attributes/SummaryAttribute.cs | 9 +- .../Builders/CommandBuilder.cs | 126 +- .../Builders/ModuleBuilder.cs | 128 +- .../Builders/ModuleClassBuilder.cs | 1 - .../Builders/ParameterBuilder.cs | 93 +- src/Kook.Net.Commands/CommandContext.cs | 12 +- src/Kook.Net.Commands/CommandError.cs | 41 +- src/Kook.Net.Commands/CommandException.cs | 20 +- src/Kook.Net.Commands/CommandMatch.cs | 58 +- src/Kook.Net.Commands/CommandService.cs | 281 ++-- src/Kook.Net.Commands/CommandServiceConfig.cs | 55 +- .../Extensions/CommandServiceExtensions.cs | 38 +- .../Extensions/IEnumerableExtensions.cs | 18 +- .../Extensions/MessageExtensions.cs | 35 +- src/Kook.Net.Commands/IModuleBase.cs | 30 +- src/Kook.Net.Commands/Info/CommandInfo.cs | 81 +- src/Kook.Net.Commands/Info/ModuleInfo.cs | 26 +- src/Kook.Net.Commands/Info/ParameterInfo.cs | 42 +- src/Kook.Net.Commands/ModuleBase.cs | 154 +- src/Kook.Net.Commands/MultiMatchHandling.cs | 10 +- .../Readers/ChannelTypeReader.cs | 10 +- .../Readers/MessageTypeReader.cs | 4 +- .../Readers/RoleTypeReader.cs | 4 +- src/Kook.Net.Commands/Readers/TypeReader.cs | 14 +- .../Readers/UserTypeReader.cs | 4 +- .../Results/ExecuteResult.cs | 50 +- src/Kook.Net.Commands/Results/IResult.cs | 18 +- src/Kook.Net.Commands/Results/MatchResult.cs | 44 +- src/Kook.Net.Commands/Results/ParseResult.cs | 66 +- .../Results/PreconditionGroupResult.cs | 32 +- .../Results/PreconditionResult.cs | 32 +- .../Results/RuntimeResult.cs | 12 +- src/Kook.Net.Commands/Results/SearchResult.cs | 31 +- .../Results/TypeReaderResult.cs | 53 +- src/Kook.Net.Commands/RunMode.cs | 10 +- .../Utilities/QuotationAliasUtils.cs | 12 +- .../Utilities/ReflectionUtils.cs | 3 +- src/Kook.Net.Core/Audio/AudioApplication.cs | 8 +- src/Kook.Net.Core/Audio/AudioInStream.cs | 13 +- src/Kook.Net.Core/Audio/AudioOutStream.cs | 5 +- src/Kook.Net.Core/Audio/AudioStream.cs | 36 +- src/Kook.Net.Core/Audio/IAudioClient.cs | 119 +- src/Kook.Net.Core/Audio/RtpFrame.cs | 16 +- src/Kook.Net.Core/Commands/ICommandContext.cs | 12 +- src/Kook.Net.Core/ConnectionState.cs | 20 +- .../Entities/Activities/ActivityType.cs | 6 +- .../Entities/Activities/GameCreationSource.cs | 6 +- .../Entities/Activities/GameProperties.cs | 8 +- .../Entities/Activities/GameType.cs | 8 +- .../Entities/Activities/IActivity.cs | 2 +- .../Entities/Activities/IGame.cs | 50 +- .../Entities/Activities/Music.cs | 8 +- .../Entities/Activities/MusicProvider.cs | 10 +- .../Entities/Audio/PeerPermissionInfo.cs | 14 +- .../Entities/Audio/SoundtrackInfo.cs | 8 +- .../Entities/Badges/BadgeStyle.cs | 8 +- src/Kook.Net.Core/Entities/CacheMode.cs | 6 +- .../Entities/Channels/ChannelType.cs | 12 +- .../CreateCategoryChannelProperties.cs | 4 +- .../Channels/CreateGuildChannelProperties.cs | 2 +- .../Channels/CreateTextChannelProperties.cs | 11 +- .../Channels/CreateVoiceChannelProperties.cs | 8 +- .../Entities/Channels/Direction.cs | 19 +- .../Entities/Channels/IAudioChannel.cs | 41 +- .../Entities/Channels/ICategoryChannel.cs | 2 +- .../Entities/Channels/IChannel.cs | 47 +- .../Entities/Channels/IDMChannel.cs | 95 +- .../Entities/Channels/IGuildChannel.cs | 185 +-- .../Entities/Channels/IMessageChannel.cs | 282 ++-- .../Entities/Channels/INestedChannel.cs | 69 +- .../Entities/Channels/IPrivateChannel.cs | 7 +- .../Entities/Channels/ITextChannel.cs | 38 +- .../Entities/Channels/IVoiceChannel.cs | 45 +- .../Entities/Channels/MessageSource.cs | 8 +- .../Channels/ModifyGuildChannelProperties.cs | 21 +- .../Channels/ModifyTextChannelProperties.cs | 21 +- .../Channels/ModifyVoiceChannelProperties.cs | 40 +- .../Entities/Channels/SlowModeInterval.cs | 30 +- .../Entities/Channels/VoiceQuality.cs | 24 +- src/Kook.Net.Core/Entities/Emotes/Emoji.cs | 94 +- .../Entities/Emotes/EmojiType.cs | 6 +- src/Kook.Net.Core/Entities/Emotes/Emote.cs | 69 +- .../Entities/Emotes/GuildEmote.cs | 24 +- src/Kook.Net.Core/Entities/Emotes/IEmote.cs | 7 +- .../Entities/Guilds/BoostLevel.cs | 16 +- .../Entities/Guilds/GuildCertification.cs | 10 +- .../Entities/Guilds/GuildCertificationType.cs | 10 +- .../Entities/Guilds/GuildFeature.cs | 10 +- .../Entities/Guilds/GuildFeatures.cs | 29 +- src/Kook.Net.Core/Entities/Guilds/IBan.cs | 17 +- src/Kook.Net.Core/Entities/Guilds/IGuild.cs | 687 ++++----- .../Entities/Guilds/IRecommendInfo.cs | 63 +- .../Entities/Guilds/NotifyType.cs | 10 +- src/Kook.Net.Core/Entities/IDeletable.cs | 6 +- src/Kook.Net.Core/Entities/IEntity.cs | 6 +- src/Kook.Net.Core/Entities/IMentionable.cs | 12 +- src/Kook.Net.Core/Entities/IUpdateable.cs | 16 +- src/Kook.Net.Core/Entities/Image.cs | 44 +- .../Entities/Intimacies/IIntimacy.cs | 52 +- .../Entities/Intimacies/IntimacyImage.cs | 17 +- .../Entities/Intimacies/IntimacyProperties.cs | 25 +- src/Kook.Net.Core/Entities/Invites/IInvite.cs | 99 +- .../Entities/Invites/InviteMaxAge.cs | 16 +- .../Entities/Invites/InviteMaxUses.cs | 16 +- .../Entities/Messages/AttachmentType.cs | 10 +- .../Entities/Messages/Cards/Card.cs | 39 +- .../Entities/Messages/Cards/CardBuilder.cs | 136 +- .../Entities/Messages/Cards/CardSize.cs | 12 +- .../Entities/Messages/Cards/CardTheme.cs | 52 +- .../Entities/Messages/Cards/CardType.cs | 4 +- .../Elements/Builders/ButtonElementBuilder.cs | 173 +-- .../Elements/Builders/IElementBuilder.cs | 13 +- .../Elements/Builders/ImageElementBuilder.cs | 145 +- .../Builders/KMarkdownElementBuilder.cs | 69 +- .../Builders/ParagraphStructBuilder.cs | 107 +- .../Builders/PlainTextElementBuilder.cs | 96 +- .../Cards/Elements/ButtonClickEventType.cs | 8 +- .../Messages/Cards/Elements/ButtonElement.cs | 50 +- .../Messages/Cards/Elements/ButtonTheme.cs | 36 +- .../Messages/Cards/Elements/ElementType.cs | 12 +- .../Messages/Cards/Elements/IElement.cs | 4 +- .../Messages/Cards/Elements/ImageElement.cs | 48 +- .../Messages/Cards/Elements/ImageSize.cs | 6 +- .../Cards/Elements/KMarkdownElement.cs | 31 +- .../Cards/Elements/ParagraphStruct.cs | 36 +- .../Cards/Elements/PlainTextElement.cs | 38 +- .../Messages/Cards/Elements/TextTheme.cs | 71 +- .../Entities/Messages/Cards/ICard.cs | 12 +- .../Entities/Messages/Cards/ICardBuilder.cs | 10 +- .../Cards/Modules/ActionGroupModule.cs | 24 +- .../Messages/Cards/Modules/AudioModule.cs | 32 +- .../Builders/ActionGroupModuleBuilder.cs | 66 +- .../Modules/Builders/AudioModuleBuilder.cs | 89 +- .../Builders/ContainerModuleBuilder.cs | 63 +- .../Modules/Builders/ContextModuleBuilder.cs | 89 +- .../Builders/CountdownModuleBuilder.cs | 91 +- .../Modules/Builders/DividerModuleBuilder.cs | 32 +- .../Modules/Builders/FileModuleBuilder.cs | 71 +- .../Modules/Builders/HeaderModuleBuilder.cs | 91 +- .../Cards/Modules/Builders/IModuleBuilder.cs | 13 +- .../Builders/ImageGroupModuleBuilder.cs | 72 +- .../Modules/Builders/InviteModuleBuilder.cs | 61 +- .../Modules/Builders/SectionModuleBuilder.cs | 180 +-- .../Modules/Builders/VideoModuleBuilder.cs | 71 +- .../Messages/Cards/Modules/ContainerModule.cs | 24 +- .../Messages/Cards/Modules/ContextModule.cs | 24 +- .../Messages/Cards/Modules/CountdownMode.cs | 8 +- .../Messages/Cards/Modules/CountdownModule.cs | 38 +- .../Messages/Cards/Modules/DividerModule.cs | 19 +- .../Messages/Cards/Modules/FileModule.cs | 33 +- .../Messages/Cards/Modules/HeaderModule.cs | 24 +- .../Messages/Cards/Modules/IMediaModule.cs | 12 +- .../Messages/Cards/Modules/IModule.cs | 7 +- .../Cards/Modules/ImageGroupModule.cs | 28 +- .../Messages/Cards/Modules/InviteModule.cs | 27 +- .../Messages/Cards/Modules/ModuleType.cs | 26 +- .../Cards/Modules/SectionAccessoryMode.cs | 6 +- .../Messages/Cards/Modules/SectionModule.cs | 39 +- .../Messages/Cards/Modules/VideoModule.cs | 33 +- .../Entities/Messages/CreateAttachmentMode.cs | 9 +- .../Messages/Embeds/BilibiliVideoEmbed.cs | 33 +- .../Entities/Messages/Embeds/CardEmbed.cs | 6 +- .../Entities/Messages/Embeds/EmbedType.cs | 12 +- .../Entities/Messages/Embeds/IEmbed.cs | 9 +- .../Entities/Messages/Embeds/ImageEmbed.cs | 16 +- .../Entities/Messages/Embeds/LinkEmbed.cs | 32 +- .../Messages/Embeds/NotImplementedEmbed.cs | 47 +- .../Entities/Messages/FileAttachment.cs | 85 +- .../Entities/Messages/IAttachment.cs | 47 +- .../Entities/Messages/IMessage.cs | 142 +- src/Kook.Net.Core/Entities/Messages/IQuote.cs | 4 +- .../Entities/Messages/IReaction.cs | 4 +- .../Entities/Messages/ISystemMessage.cs | 16 +- src/Kook.Net.Core/Entities/Messages/ITag.cs | 19 +- .../Entities/Messages/IUserMessage.cs | 35 +- .../Entities/Messages/MessageProperties.cs | 29 +- .../Entities/Messages/MessageReference.cs | 14 +- .../Entities/Messages/MessageType.cs | 20 +- .../Entities/Messages/Pokes/IPoke.cs | 20 +- .../Entities/Messages/Pokes/IPokeAction.cs | 8 +- .../Entities/Messages/Pokes/PokeIcon.cs | 10 +- .../Entities/Messages/Pokes/PokeLabel.cs | 10 +- .../Entities/Messages/Pokes/PokeQuality.cs | 14 +- .../Pokes/PokeResources/IPokeResource.cs | 4 +- .../ImageAnimationPokeResource.cs | 20 +- .../NotImplementedPokeResource.cs | 47 +- .../Pokes/PokeResources/PokeResourceType.cs | 6 +- src/Kook.Net.Core/Entities/Messages/Quote.cs | 34 +- .../Entities/Messages/ReactionMetadata.cs | 12 +- .../Entities/Messages/SystemMessageType.cs | 6 +- src/Kook.Net.Core/Entities/Messages/Tag.cs | 32 +- .../Entities/Messages/TagHandling.cs | 104 +- .../Entities/Messages/TagMode.cs | 6 +- .../Entities/Messages/TagType.cs | 28 +- .../Entities/Permissions/ChannelPermission.cs | 78 +- .../Permissions/ChannelPermissions.cs | 135 +- .../Entities/Permissions/GuildPermission.cs | 147 +- .../Entities/Permissions/GuildPermissions.cs | 223 ++- .../Permissions/IPermissionOverwrite.cs | 10 +- .../Permissions/OverwritePermissions.cs | 156 +- .../Entities/Permissions/PermValue.cs | 16 +- .../Permissions/RolePermissionOverwrite.cs | 12 +- .../Permissions/UserPermissionOverwrite.cs | 12 +- .../Entities/Roles/AlphaColor.cs | 214 +-- src/Kook.Net.Core/Entities/Roles/Color.cs | 304 ++-- src/Kook.Net.Core/Entities/Roles/ColorType.cs | 6 +- .../Entities/Roles/GradientColor.cs | 35 +- src/Kook.Net.Core/Entities/Roles/IRole.cs | 103 +- .../Entities/Roles/RoleProperties.cs | 46 +- .../Entities/{Guilds => Roles}/RoleType.cs | 10 +- src/Kook.Net.Core/Entities/SortMode.cs | 6 +- .../Users/BoostSubscriptionMetadata.cs | 10 +- .../Entities/Users/ClientType.cs | 10 +- .../Entities/Users/FriendState.cs | 8 +- .../Entities/Users/IFriendRequest.cs | 16 +- .../Entities/Users/IGuildUser.cs | 264 ++-- src/Kook.Net.Core/Entities/Users/IPresence.cs | 6 +- src/Kook.Net.Core/Entities/Users/ISelfUser.cs | 49 +- src/Kook.Net.Core/Entities/Users/IUser.cs | 124 +- .../Entities/Users/IVoiceState.cs | 31 +- src/Kook.Net.Core/Entities/Users/Nameplate.cs | 23 +- .../Entities/Users/RequestFriendSource.cs | 8 +- .../Users/SearchGuildMemberProperties.cs | 36 +- src/Kook.Net.Core/Entities/Users/UserTag.cs | 37 +- .../Extensions/AsyncEnumerableExtensions.cs | 18 +- .../Extensions/CardExtensions.cs | 44 +- .../Extensions/ChannelExtensions.cs | 16 +- .../Extensions/MessageExtensions.cs | 142 +- .../Extensions/UserExtensions.cs | 92 +- src/Kook.Net.Core/Format.cs | 250 ++-- src/Kook.Net.Core/IKookClient.cs | 171 +-- src/Kook.Net.Core/KookConfig.cs | 130 +- src/Kook.Net.Core/KookErrorCode.cs | 28 +- src/Kook.Net.Core/KookJsonError.cs | 12 +- src/Kook.Net.Core/Logging/LogManager.cs | 5 - src/Kook.Net.Core/Logging/LogMessage.cs | 51 +- src/Kook.Net.Core/Logging/LogSeverity.cs | 15 +- src/Kook.Net.Core/Logging/Logger.cs | 5 - src/Kook.Net.Core/LoginState.cs | 20 +- src/Kook.Net.Core/Net/BucketId.cs | 50 +- src/Kook.Net.Core/Net/HttpException.cs | 37 +- src/Kook.Net.Core/Net/IRequest.cs | 6 +- .../Net/Queue/BaseMessageQueue.cs | 20 +- src/Kook.Net.Core/Net/Queue/IMessageQueue.cs | 12 +- .../Net/Queue/MessageQueueProvider.cs | 2 +- .../Queue/SynchronousImmediateMessageQueue.cs | 7 +- ...ynchronousImmediateMessageQueueProvider.cs | 5 +- src/Kook.Net.Core/Net/RateLimitedException.cs | 8 +- src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs | 20 +- src/Kook.Net.Core/Net/Rest/IRestClient.cs | 58 +- .../Net/Rest/RestClientProvider.cs | 2 +- src/Kook.Net.Core/Net/Rest/RestResponse.cs | 10 +- src/Kook.Net.Core/Net/Udp/IUdpSocket.cs | 42 +- .../Net/Udp/UdpSocketProvider.cs | 2 +- .../Net/WebSocketClosedException.cs | 14 +- .../Net/WebSockets/IWebSocketClient.cs | 70 +- .../Net/WebSockets/WebSocketProvider.cs | 2 +- src/Kook.Net.Core/RequestOptions.cs | 43 +- src/Kook.Net.Core/RetryMode.cs | 32 +- src/Kook.Net.Core/TokenType.cs | 6 +- src/Kook.Net.Core/Utils/Cacheable.cs | 66 +- src/Kook.Net.Core/Utils/MentionUtils.cs | 97 +- src/Kook.Net.Core/Utils/Permissions.cs | 1 - src/Kook.Net.Core/Utils/Preconditions.cs | 232 +-- src/Kook.Net.Core/Utils/TagUtils.cs | 59 + src/Kook.Net.Core/Utils/TokenUtils.cs | 80 +- src/Kook.Net.Core/Utils/UrlValidation.cs | 29 +- .../Configurators/IKookClientConfigurator.cs | 20 +- .../IKookClientConfiguratorCompleter.cs | 4 +- .../IKookClientServiceConfigurator.cs | 26 +- .../Configurators/KookClientConfigurator.cs | 6 +- .../KookClientConfiguratorExtensions.cs | 26 +- .../KookClientServiceConfigurator.cs | 2 +- .../KookConfiguratorExtensions.cs | 12 +- .../KookRestClientConfigurator.cs | 5 +- .../KookSocketClientConfigurator.cs | 5 +- .../KookWebhookClientConfigurator.cs | 7 +- ...KookClientDependencyInjectionExtensions.cs | 137 +- .../Core/Entities/Guilds/GuildProperties.cs | 84 -- .../Core/Entities/Guilds/IVoiceRegion.cs | 45 - .../Rest/API/Common/VoiceRegion.cs | 18 - .../Rest/API/Rest/CreateGuildParams.cs | 23 - .../Rest/API/Rest/DeleteGuildParams.cs | 11 - .../Rest/API/Rest/DisconnectUserParams.cs | 12 - .../Rest/API/Rest/ModifyGuildParams.cs | 24 - .../Channels/ExperimentalChannelHelper.cs | 35 - .../RestTextChannelExperimentalExtensions.cs | 24 - .../RestVoiceChannelExperimentalExtensions.cs | 42 - .../Guilds/ExperimentalGuildHelper.cs | 49 - .../Guilds/RestGuildExperimentalExtensions.cs | 40 - .../Rest/Entities/Guilds/RestVoiceRegion.cs | 51 - .../Rest/ExperimentalClientHelper.cs | 31 - ...KookRestApiClientExperimentalExtensions.cs | 85 -- .../KookRestClientExperimentalExtensions.cs | 116 +- .../Converters/ImageBase64DataUriConverter.cs | 46 - .../BaseSocketClientExperimentalExtensions.cs | 32 - ...ocketVoiceChannelExperimentalExtensions.cs | 27 - .../SocketGuildExperimentalExtensions.cs | 43 - .../KookClientConfiguratorExtensions.cs | 127 +- .../KookClientHostExtensions.cs | 226 +-- .../InMemoryMessageQueueProvider.cs | 4 +- .../DefaultMassTransitMessageQueueProvider.cs | 8 +- .../KookMessageQueueMassTransitConsumer.cs | 10 +- .../KookMessageQueueMassTransitExtensions.cs | 27 +- src/Kook.Net.Rest/API/Common/Role.cs | 4 +- .../API/Rest/ModifyGuildRoleParams.cs | 4 +- src/Kook.Net.Rest/BaseKookClient.cs | 44 +- .../Entities/Channels/ChannelHelper.cs | 1 - .../Entities/Channels/IRestAudioChannel.cs | 2 +- .../Entities/Channels/IRestMessageChannel.cs | 106 +- .../Entities/Channels/IRestPrivateChannel.cs | 6 +- .../Entities/Channels/RestCategoryChannel.cs | 6 +- .../Entities/Channels/RestChannel.cs | 2 +- .../Entities/Channels/RestDMChannel.cs | 112 +- .../Entities/Channels/RestGuildChannel.cs | 105 +- .../Entities/Channels/RestTextChannel.cs | 65 +- .../Entities/Channels/RestVoiceChannel.cs | 29 +- src/Kook.Net.Rest/Entities/Games/RestGame.cs | 2 +- .../Entities/Guilds/RecommendInfo.cs | 2 +- src/Kook.Net.Rest/Entities/Guilds/RestBan.cs | 15 +- .../Entities/Guilds/RestGuild.cs | 361 ++--- .../Entities/Intimacies/RestIntimacy.cs | 6 +- .../Entities/Invites/RestInvite.cs | 10 +- .../Entities/Messages/Attachment.cs | 12 +- .../Entities/Messages/MessageHelper.cs | 22 +- src/Kook.Net.Rest/Entities/Messages/Poke.cs | 10 +- .../Entities/Messages/RestMessage.cs | 46 +- .../Entities/Messages/RestPokeAction.cs | 14 +- .../Entities/Messages/RestReaction.cs | 6 +- .../Entities/Messages/RestSystemMessage.cs | 8 +- .../Entities/Messages/RestUserMessage.cs | 32 +- src/Kook.Net.Rest/Entities/RestEntity.cs | 12 +- src/Kook.Net.Rest/Entities/Roles/RestRole.cs | 54 +- .../Entities/Roles/RoleHelper.cs | 4 +- .../Entities/Users/RestFriendRequest.cs | 2 +- .../Entities/Users/RestGuildUser.cs | 62 +- .../Entities/Users/RestPresence.cs | 11 +- .../Entities/Users/RestSelfUser.cs | 4 +- src/Kook.Net.Rest/Entities/Users/RestUser.cs | 26 +- .../Extensions/CardJsonExtension.cs | 56 +- .../Extensions/EntityExtensions.cs | 1 - src/Kook.Net.Rest/KookRestClient.cs | 260 ++-- src/Kook.Net.Rest/KookRestConfig.cs | 7 +- src/Kook.Net.Rest/Net/DefaultRestClient.cs | 4 - .../Net/DefaultRestClientProvider.cs | 13 +- src/Kook.Net.Rest/Net/Queue/RequestQueue.cs | 2 - .../Net/Queue/RequestQueueBucket.cs | 14 +- src/Kook.Net.Rest/Net/RateLimitInfo.cs | 2 +- src/Kook.Net.WebSocket/Audio/AudioClient.cs | 7 +- .../Audio/Opus/OpusApplication.cs | 18 +- .../Audio/Opus/OpusConverter.cs | 16 +- src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs | 12 +- .../Audio/Opus/OpusError.cs | 18 +- .../Audio/Opus/OpusSignal.cs | 10 +- .../Audio/Streams/BufferedWriteStream.cs | 4 +- .../Audio/Streams/InputStream.cs | 4 +- .../Audio/Streams/OpusDecodeStream.cs | 18 +- .../Audio/Streams/OpusEncodeStream.cs | 22 +- .../Audio/Streams/OutputStream.cs | 4 +- .../Audio/Streams/RtpReadStream.cs | 18 +- .../Audio/Streams/RtpWriteStream.cs | 14 +- .../BaseSocketClient.Event.cs | 1312 +++++++---------- src/Kook.Net.WebSocket/BaseSocketClient.cs | 148 +- .../Commands/SocketCommandContext.cs | 20 +- .../Entities/Channels/ISocketAudioChannel.cs | 2 +- .../Channels/ISocketMessageChannel.cs | 110 +- .../Channels/ISocketPrivateChannel.cs | 9 +- .../Channels/SocketCategoryChannel.cs | 8 +- .../Entities/Channels/SocketChannel.cs | 15 +- .../Entities/Channels/SocketChannelHelper.cs | 3 +- .../Entities/Channels/SocketDMChannel.cs | 241 ++- .../Entities/Channels/SocketGuildChannel.cs | 128 +- .../Entities/Channels/SocketTextChannel.cs | 139 +- .../Entities/Channels/SocketVoiceChannel.cs | 45 +- .../Entities/Guilds/SocketGuild.cs | 396 ++--- .../Entities/Invites/SocketInvite.cs | 21 +- .../Entities/Messages/SocketMessage.cs | 65 +- .../Entities/Messages/SocketPokeAction.cs | 2 +- .../Entities/Messages/SocketReaction.cs | 49 +- .../Entities/Messages/SocketSystemMessage.cs | 8 +- .../Entities/Messages/SocketUserMessage.cs | 26 +- .../Entities/Roles/SocketRole.cs | 54 +- .../Entities/SocketEntity.cs | 12 +- .../Entities/Users/LiveStreamStatus.cs | 28 +- .../Entities/Users/SocketGuildUser.cs | 120 +- .../Entities/Users/SocketPresence.cs | 11 +- .../Entities/Users/SocketSelfUser.cs | 11 +- .../Entities/Users/SocketUnknownUser.cs | 7 +- .../Entities/Users/SocketUser.cs | 26 +- .../Entities/Users/SocketVoiceState.cs | 27 +- .../GatewayReconnectException.cs | 7 +- .../KookSocketClient.Events.cs | 28 +- src/Kook.Net.WebSocket/KookSocketClient.cs | 97 +- src/Kook.Net.WebSocket/KookSocketConfig.cs | 99 +- .../KookSocketRestClient.cs | 15 +- src/Kook.Net.WebSocket/KookVoiceAPIClient.cs | 7 - .../Net/DefaultUdpSocket.cs | 1 - .../Net/DefaultUdpSocketProvider.cs | 6 +- .../Net/DefaultWebSocketClientProvider.cs | 17 +- .../StartupCacheFetchMode.cs | 48 +- .../KookAspNetWebhookClient.cs | 15 +- .../KookAspNetWebhookConfig.cs | 15 +- .../KookWebhookClientExtension.cs | 64 +- .../AspNet/DefaultAspNetWebhookProvider.cs | 10 +- .../Net/AspNet/IAspNetWebhookClient.cs | 6 +- .../KookHttpListenerWebhookClient.cs | 10 +- .../KookHttpListenerWebhookConfig.cs | 22 +- .../DefaultHttpListenerWebhookProvider.cs | 10 +- .../IHttpListenerWebhookClient.cs | 14 +- src/Kook.Net.Webhook/KookWebhookClient.cs | 10 +- src/Kook.Net.Webhook/KookWebhookConfig.cs | 21 +- .../Net/Webhook/IWebhookClient.cs | 46 +- .../Net/Webhook/WebhookProvider.cs | 2 +- .../Fixtures/RestGuildFixture.cs | 23 +- .../MessageInTextTests.cs | 8 +- .../MessageInVoiceTests.cs | 8 +- .../RoleTests.cs | 4 +- .../Fixtures/SocketGuildFixture.cs | 35 +- .../MessageTests.cs | 4 +- test/Kook.Net.Tests.Unit/EmojiTests.cs | 2 +- .../MockedEntities/MockedVoiceChannel.cs | 5 +- test/Kook.Net.Tests.Unit/TokenUtilsTests.cs | 2 +- test/Kook.Net.Tests.Unit/TypeReaderTests.cs | 8 +- .../Kook.Net.Tests.Unit/UrlValidationTests.cs | 1 - 450 files changed, 8373 insertions(+), 11140 deletions(-) rename src/Kook.Net.Core/Entities/{Guilds => Roles}/RoleType.cs (51%) create mode 100644 src/Kook.Net.Core/Utils/TagUtils.cs delete mode 100644 src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs delete mode 100644 src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs delete mode 100644 src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs delete mode 100644 src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs delete mode 100644 src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs delete mode 100644 src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs delete mode 100644 src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Entities/Guilds/RestGuildExperimentalExtensions.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs delete mode 100644 src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs delete mode 100644 src/Kook.Net.Experimental/WebSocket/BaseSocketClientExperimentalExtensions.cs delete mode 100644 src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs delete mode 100644 src/Kook.Net.Experimental/WebSocket/Entities/Guilds/SocketGuildExperimentalExtensions.cs diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 204af25f..2fc68128 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -126,6 +126,13 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +License notice for MassTransit +------------------------------------ + +Licensed under the Apache License, Version 2.0. +Available at +https://github.com/MassTransit/MassTransit/blob/develop/LICENSE + License notice for Microsoft.NET.Test.Sdk ------------------------------------ diff --git a/docs/guides/voice/sending-voice.md b/docs/guides/voice/sending-voice.md index d16181f4..31dafdde 100644 --- a/docs/guides/voice/sending-voice.md +++ b/docs/guides/voice/sending-voice.md @@ -66,7 +66,7 @@ opus 在同一位置),参见 [FFmpeg 的下载页面],或使用操作系 [IAudioClient]: xref:Kook.Audio.IAudioClient [AudioOutStream]: xref:Kook.Audio.AudioOutStream -[IAudioClient.CreatePCMStream]: xref:Kook.Audio.IAudioClient#Kook_Audio_IAudioClient_CreatePcmStream_Kook_Audio_AudioApplication_System_Int32_System_Int32_System_Int32_ +[IAudioClient.CreatePCMStream]: xref:Kook.Audio.IAudioClient#Kook_Audio_IAudioClient_CreatePcmStream_Kook_Audio_AudioApplication_System_Nullable_System_Int32__System_Int32_System_Int32_ 最后,音频需要从 FFmpeg 的标准输出流传输到你的 AudioOutStream 对象中。 根据你的业务需要,这个步骤中间可能会进行某些处理,但在大多数情况下,使用 [Stream.CopyToAsync] 即可。 diff --git a/docs/quick_reference/http_api/oauth.md b/docs/quick_reference/http_api/oauth.md index c86b1ce3..766c3014 100644 --- a/docs/quick_reference/http_api/oauth.md +++ b/docs/quick_reference/http_api/oauth.md @@ -16,10 +16,9 @@ readonly KookRestClient _restClient = null; POST `/api/oauth2/token` -无公开 API,请使用 `AspNet.Security.OAuth.Kook`,请参考: +无公开 API。可参考以下类库: -* NuGet: -* GitHub: -* 文档: +- **AspNet.Security.OAuth.Kook**:[NuGet](https://www.nuget.org/packages/AspNet.Security.OAuth.Kook/),[GitHub](https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers),[文档](https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers/blob/dev/docs/kook.md) +- **OpenIddict**:[NuGet](https://www.nuget.org/packages/OpenIddict/),[GitHub](https://github.com/openiddict/openiddict-core),[文档](https://documentation.openiddict.com/) [获取 AccessToken]: https://developer.kookapp.cn/doc/http/oauth#获取AccessToken diff --git a/samples/Kook.Net.Samples.Audio/Modules/MusicModule.cs b/samples/Kook.Net.Samples.Audio/Modules/MusicModule.cs index 0ad8a7b1..65c0e883 100644 --- a/samples/Kook.Net.Samples.Audio/Modules/MusicModule.cs +++ b/samples/Kook.Net.Samples.Audio/Modules/MusicModule.cs @@ -17,8 +17,6 @@ public class MusicModule : ModuleBase private readonly MusicService _musicService; private readonly IHttpClientFactory _httpClientFactory; - - /// /// Initializes a new instance of the class. /// diff --git a/samples/Kook.Net.Samples.FSharp/Program.fs b/samples/Kook.Net.Samples.FSharp/Program.fs index 3af8ffa8..902db2da 100644 --- a/samples/Kook.Net.Samples.FSharp/Program.fs +++ b/samples/Kook.Net.Samples.FSharp/Program.fs @@ -7,7 +7,7 @@ open Kook.WebSocket // 这是一个使用 Kook.Net 的 F# 简单示例 // Kook.Net 的所有文档均以 C# 编写,但是 Kook.Net 也支持 F# -// 如果要编写带有命令的机器人,我们建议使用 Kook.Net.Commands 框架 +// 如果要编写带有命令的 Bot,我们建议使用 Kook.Net.Commands 框架 // 而不是像在这个示例中一样自己处理它们。 // 您可以在以下位置找到使用命令框架的示例: diff --git a/samples/Kook.Net.Samples.SimpleBot/Program.cs b/samples/Kook.Net.Samples.SimpleBot/Program.cs index 2ba75246..f7cf24ed 100644 --- a/samples/Kook.Net.Samples.SimpleBot/Program.cs +++ b/samples/Kook.Net.Samples.SimpleBot/Program.cs @@ -3,7 +3,7 @@ // 这是一个使用 Kook.Net 的 C# 简单示例 -// 如果要编写带有命令的机器人,我们建议使用 Kook.Net.Commands 框架 +// 如果要编写带有命令的 Bot,我们建议使用 Kook.Net.Commands 框架 // 而不是像在这个示例中一样自己处理它们。 // 您可以在以下位置找到使用命令框架的示例: diff --git a/samples/Kook.Net.Samples.VisualBasic/Program.vb b/samples/Kook.Net.Samples.VisualBasic/Program.vb index 208e59e7..c3db07c6 100644 --- a/samples/Kook.Net.Samples.VisualBasic/Program.vb +++ b/samples/Kook.Net.Samples.VisualBasic/Program.vb @@ -4,7 +4,7 @@ Imports Kook.WebSocket ' 这是一个使用 Kook.Net 的 Visual Basic 简单示例 ' Kook.Net 的所有文档均以 C# 编写,但是 Kook.Net 也支持 Visual Basic -' 如果要编写带有命令的机器人,我们建议使用 Kook.Net.Commands 框架 +' 如果要编写带有命令的 Bot,我们建议使用 Kook.Net.Commands 框架 ' 而不是像在这个示例中一样自己处理它们。 ' 您可以在以下位置找到使用命令框架的示例: diff --git a/src/Kook.Net.CardMarkup/CardMarkupSerializer.cs b/src/Kook.Net.CardMarkup/CardMarkupSerializer.cs index c9becf83..11ed3255 100644 --- a/src/Kook.Net.CardMarkup/CardMarkupSerializer.cs +++ b/src/Kook.Net.CardMarkup/CardMarkupSerializer.cs @@ -7,20 +7,19 @@ namespace Kook.CardMarkup; /// -/// Serializer for Card Message XML markup +/// 提供用于从 XML 标记语言创建卡片消息的序列化器。 /// public static class CardMarkupSerializer { #region Async /// - /// Deserialize a Card Message XML markup file to a list. - /// One XML markup file has one card-message element, which can - /// contain multiple card elements. + /// 将卡片消息 XML 标记文件反序列化为 列表,每个 XML 文件包含一个 card-message + /// 元素,可以包含多个 card 元素。 /// - /// UTF-8 encoded XML file - /// Cancellation token - /// enumerable + /// UTF-8 编码的 XML 文件 + /// 取消令牌。 + /// 一个表示异步解析操作的任务。任务的结果包含一个可用于枚举 成员的 public static async Task> DeserializeAsync(FileInfo file, CancellationToken token = default) { #if NETSTANDARD2_0 || NET462 @@ -32,13 +31,12 @@ public static async Task> DeserializeAsync(FileInfo file, Can } /// - /// Deserialize a Card Message XML markup text to a list. - /// One XML markup file has one card-message element, which can - /// contain multiple card elements. + /// 将卡片消息 XML 标记文本反序列化为 列表,每个 XML 文件包含一个 card-message + /// 元素,可以包含多个 card 元素。 /// - /// UTF-8 encoded XML text - /// Cancellation token - /// enumerable + /// UTF-8 编码的 XML 文本。 + /// 取消令牌。 + /// 一个表示异步解析操作的任务。任务的结果包含一个可用于枚举 成员的 public static async Task> DeserializeAsync(string xmlText, CancellationToken token = default) { using MemoryStream xmlStream = new(Encoding.UTF8.GetBytes(xmlText)); @@ -46,13 +44,12 @@ public static async Task> DeserializeAsync(string xmlText, Ca } /// - /// Deserialize a Card Message XML stream to a list. - /// One XML markup file has one card-message element, which can - /// contain multiple card elements. + /// 将卡片消息 XML 标记文本流反序列化为 列表,每个 XML 文件包含一个 card-message + /// 元素,可以包含多个 card 元素。 /// - /// UTF-8 encoded XML stream - /// Cancellation token - /// enumerable + /// UTF-8 编码的 XML 流。 + /// 取消令牌。 + /// 一个表示异步解析操作的任务。任务的结果包含一个可用于枚举 成员的 public static async Task> DeserializeAsync(Stream xmlStream, CancellationToken token = default) { using XmlReader xmlReader = XmlReader.Create(xmlStream, new XmlReaderSettings @@ -121,12 +118,11 @@ public static async Task> DeserializeAsync(Stream xmlStream, #region Sync /// - /// Deserialize a Card Message XML markup file to a list. - /// One XML markup file has one card-message element, which can - /// contain multiple card elements. + /// 将卡片消息 XML 标记文件反序列化为 列表,每个 XML 文件包含一个 card-message + /// 元素,可以包含多个 card 元素。 /// - /// UTF-8 encoded XML file - /// enumerable + /// UTF-8 编码的 XML 文件 + /// 一个可用于枚举 成员的 public static IEnumerable Deserialize(FileInfo file) { using FileStream fs = file.OpenRead(); @@ -134,12 +130,11 @@ public static IEnumerable Deserialize(FileInfo file) } /// - /// Deserialize a Card Message XML markup text to a list. - /// One XML markup file has one card-message element, which can - /// contain multiple card elements. + /// 将卡片消息 XML 标记文本反序列化为 列表,每个 XML 文件包含一个 card-message + /// 元素,可以包含多个 card 元素。 /// - /// UTF-8 encoded XML text - /// enumerable + /// UTF-8 编码的 XML 文本。 + /// 一个可用于枚举 成员的 public static IEnumerable Deserialize(string xmlText) { using MemoryStream xmlStream = new(Encoding.UTF8.GetBytes(xmlText)); @@ -147,12 +142,11 @@ public static IEnumerable Deserialize(string xmlText) } /// - /// Deserialize a Card Message XML markup file to a list. - /// One XML markup file has one card-message element, which can - /// contain multiple card elements. + /// 将卡片消息 XML 标记文本流反序列化为 列表,每个 XML 文件包含一个 card-message + /// 元素,可以包含多个 card 元素。 /// - /// UTF-8 encoded XML stream - /// enumerable + /// UTF-8 编码的 XML 流。 + /// 一个可用于枚举 成员的 public static IEnumerable Deserialize(Stream xmlStream) { using XmlReader xmlReader = XmlReader.Create(xmlStream, new XmlReaderSettings @@ -220,11 +214,14 @@ public static IEnumerable Deserialize(Stream xmlStream) #nullable enable /// - /// Try to deserialize a Card Message XML markup file to a list. + /// 尝试将卡片消息 XML 标记文件反序列化为 列表。 /// - /// UTF-8 encoded XML file - /// enumerable, will be null if return value is false - /// True if deserialization is successful, otherwise false + /// UTF-8 编码的 XML 文件。 + /// + /// 如果反序列化操作成功,则为一个可用于枚举 成员的 + /// ;否则为 null。 + /// + /// 如果反序列化操作成功,则为 true;否则为 false public static bool TryDeserialize(FileInfo file, [NotNullWhen(true)] out IEnumerable? cards) { try @@ -240,11 +237,14 @@ public static bool TryDeserialize(FileInfo file, [NotNullWhen(true)] out IEnumer } /// - /// Try to deserialize a Card Message XML markup file to a list. + /// 尝试将卡片消息 XML 标记文本反序列化为 列表。 /// - /// UTF-8 encoded XML text - /// enumerable, will be null if return value is false - /// True if deserialization is successful, otherwise false + /// UTF-8 编码的 XML 文本。 + /// + /// 如果反序列化操作成功,则为一个可用于枚举 成员的 + /// ;否则为 null。 + /// + /// 如果反序列化操作成功,则为 true;否则为 false public static bool TryDeserialize(string xmlText, [NotNullWhen(true)] out IEnumerable? cards) { try @@ -260,11 +260,14 @@ public static bool TryDeserialize(string xmlText, [NotNullWhen(true)] out IEnume } /// - /// Try to deserialize a Card Message XML markup file to a list. + /// 尝试将卡片消息 XML 标记文本流反序列化为 列表。 /// - /// UTF-8 encoded XML stream - /// enumerable, will be null if return value is false - /// True if deserialization is successful, otherwise false + /// UTF-8 编码的 XML 文本流。 + /// + /// 如果反序列化操作成功,则为一个可用于枚举 成员的 + /// ;否则为 null。 + /// + /// 如果反序列化操作成功,则为 true;否则为 false public static bool TryDeserialize(Stream xmlStream, [NotNullWhen(true)] out IEnumerable? cards) { try diff --git a/src/Kook.Net.Commands/Attributes/AliasAttribute.cs b/src/Kook.Net.Commands/Attributes/AliasAttribute.cs index 564b2516..0a75e8f1 100644 --- a/src/Kook.Net.Commands/Attributes/AliasAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/AliasAttribute.cs @@ -1,22 +1,19 @@ namespace Kook.Commands; /// -/// Marks the aliases for a command. +/// 为命令指定别名。 /// /// -/// This attribute allows a command to have one or multiple aliases. In other words, the base command can have -/// multiple aliases when triggering the command itself, giving the end-user more freedom of choices when giving -/// hot-words to trigger the desired command. See the example for a better illustration. +/// 此特性允许命令具有一个或多个别名,在指定命令的基本名称的同时,还可以指定多个别名,以便用户可以使用多个熟悉的词汇来触发相同的命令。 /// /// -/// In the following example, the command can be triggered with the base name, "stats", or either "stat" or -/// "info". +/// 以下示例中,要调用此命令,除了可以使用基本名称“stats”,还使用“stat”或“info”。 /// /// [Command("stats")] /// [Alias("stat", "info")] -/// public async Task GetStatsAsync(IUser user) +/// public async Task GetStatsAsync(IUser user) /// { -/// // ...pull stats +/// await ReplyTextAsync($"{user.Username} has 1000 score!"); /// } /// /// @@ -24,12 +21,12 @@ namespace Kook.Commands; public class AliasAttribute : Attribute { /// - /// Gets the aliases which have been defined for the command. + /// 获取为命令定义的别名。 /// public string[] Aliases { get; } /// - /// Creates a new with the given aliases. + /// 初始化一个 类的新实例。 /// public AliasAttribute(params string[] aliases) { diff --git a/src/Kook.Net.Commands/Attributes/CommandAttribute.cs b/src/Kook.Net.Commands/Attributes/CommandAttribute.cs index c8d1e4d5..005966ee 100644 --- a/src/Kook.Net.Commands/Attributes/CommandAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/CommandAttribute.cs @@ -1,73 +1,79 @@ namespace Kook.Commands; /// -/// Marks the execution information for a command. +/// 为命令标记执行信息。 /// [AttributeUsage(AttributeTargets.Method)] public class CommandAttribute : Attribute { /// - /// Gets the text that has been set to be recognized as a command. + /// 获取此命令的基本名称。 /// + /// + /// 特性重写此属性的值。 + /// public string? Text { get; } /// - /// Specifies the of the command. This affects how the command is executed. + /// 获取或设置命令的运行模式。 /// + /// public RunMode RunMode { get; set; } = RunMode.Default; /// - /// Indicates whether extra arguments should be ignored for this command. + /// 获取或设置是否忽略此命令的额外参数。 /// + /// public bool? IgnoreExtraArgs { get; } /// - /// Attaches a summary to your command. + /// 获取或设置命令的摘要。 /// /// - /// overrides the value of this property if present. + /// 特性重写此属性的值。 /// public string? Summary { get; set; } /// - /// Marks the aliases for a command. + /// 获取或设置命令的别名。 /// /// - /// extends the base value of this if present. + /// 特性的值会与此属性的值合并。 /// public string?[]? Aliases { get; set; } /// - /// Attaches remarks to your commands. + /// 获取或设置命令的备注。 /// /// - /// overrides the value of this property if present. + /// 特性重写此属性的值。 /// public string? Remarks { get; set; } - /// + /// + /// 初始化一个 类的新实例。 + /// public CommandAttribute() { } /// - /// Initializes a new attribute with the specified name. + /// 初始化一个 类的新实例。 /// - /// The name of the command. + /// 命令的基本名称。 public CommandAttribute(string text) { Text = text; } /// - /// Initializes a new attribute with the specified name - /// and mode of whether to ignore extra arguments. + /// 初始化一个 类的新实例。 /// - /// The name of the command. - /// Whether to ignore extra arguments. - /// The summary of the command. - /// The aliases of the command. - /// The remarks of the command. + /// 命令的基本名称。 + /// 是否忽略此命令的额外参数。 + /// 命令的摘要。 + /// 命令的别名。 + /// 命令的备注。 public CommandAttribute(string text, bool ignoreExtraArgs, string? summary = null, string?[]? aliases = null, string? remarks = null) { diff --git a/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs b/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs index cf689d2f..4703f3f1 100644 --- a/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs @@ -1,12 +1,11 @@ namespace Kook.Commands; /// -/// Prevents the marked module from being loaded automatically. +/// 标记指定的模块不应被自动加载。 /// /// -/// This attribute tells to ignore the marked module from being loaded -/// automatically (e.g. the method). If a non-public module marked -/// with this attribute is attempted to be loaded manually, the loading process will also fail. +/// 此属性告诉 在自动加载模块是忽略被此特性标记的模块。 +/// 需要注意的是,如果尝试手动加载被此特性标记的非公共模块,加载过程也会失败。 /// [AttributeUsage(AttributeTargets.Class)] public class DontAutoLoadAttribute : Attribute; diff --git a/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs b/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs index c742cc76..83520d79 100644 --- a/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs @@ -1,20 +1,18 @@ namespace Kook.Commands; /// -/// Prevents the marked property from being injected into a module. +/// 标记指定的成员不应被注入到其父模块。 /// /// -/// This attribute prevents the marked member from being injected into its parent module. Useful when you have a -/// public property that you do not wish to invoke the library's dependency injection service. +/// 此特性阻止被标记的成员被注入到其父模块。当存在一个公共属性但不希望为该属性自动注入服务时,请标记此特性。 /// /// -/// In the following example, DatabaseService will not be automatically injected into the module and will -/// not throw an error message if the dependency fails to be resolved. +/// 以下示例代码中,DatabaseService 将不会自动注入服务,如果依赖项无法解析,也不会抛出错误消息。 /// /// public class MyModule : ModuleBase /// { /// [DontInject] -/// public DatabaseService DatabaseService; +/// public DatabaseService DatabaseService { get; } /// public MyModule() /// { /// DatabaseService = DatabaseFactory.Generate(); diff --git a/src/Kook.Net.Commands/Attributes/GroupAttribute.cs b/src/Kook.Net.Commands/Attributes/GroupAttribute.cs index f6f29391..15519d33 100644 --- a/src/Kook.Net.Commands/Attributes/GroupAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/GroupAttribute.cs @@ -1,26 +1,28 @@ namespace Kook.Commands; /// -/// Marks the module as a command group. +/// 标记模块为命令组。 /// [AttributeUsage(AttributeTargets.Class)] public class GroupAttribute : Attribute { /// - /// Gets the prefix set for the module. + /// 获取模块组命令的前缀。 /// public string? Prefix { get; } - /// + /// + /// 初始化一个 类的新实例。 + /// public GroupAttribute() { Prefix = null; } /// - /// Initializes a new with the provided prefix. + /// 初始化一个 类的新实例。 /// - /// The prefix of the module group. + /// 模块组命令的前缀。 public GroupAttribute(string prefix) { Prefix = prefix; diff --git a/src/Kook.Net.Commands/Attributes/NameAttribute.cs b/src/Kook.Net.Commands/Attributes/NameAttribute.cs index a5e289c8..1c9fea2a 100644 --- a/src/Kook.Net.Commands/Attributes/NameAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/NameAttribute.cs @@ -1,21 +1,20 @@ namespace Kook.Commands; -// Override public name of command/module /// -/// Marks the public name of a command, module, or parameter. +/// 标记命令、模块或参数的基本名称。 /// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Parameter)] public class NameAttribute : Attribute { /// - /// Gets the name of the command. + /// 获取基本名称。 /// public string Text { get; } /// - /// Marks the public name of a command, module, or parameter with the provided name. + /// 标记命令、模块或参数的基本名称。 /// - /// The public name of the object. + /// 基本名称。 public NameAttribute(string text) { Text = text; diff --git a/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs b/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs index c464b170..a51f0c3c 100644 --- a/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs @@ -1,8 +1,28 @@ namespace Kook.Commands; /// -/// Instructs the command system to treat command parameters of this type -/// as a collection of named arguments matching to its properties. +/// 指示命令系统将此类型的命令参数视为与其属性匹配的命名参数集合。 /// +/// +/// 以下示例代码中,ArgumentType 中的各个属性将被视为所支持的命名参数。 +/// +/// [NamedArgumentType] +/// public sealed class ArgumentType +/// { +/// public int? Foo { get; set; } +/// public string? Bar { get; set; } +/// public IEnumerable<int>? ManyInts { get; set; } +/// } +/// +/// 命令的参数中可以定义 ArgumentType 类型的参数。 +/// +/// [Command("test")] +/// public Task TestCommand(ArgumentType arg) => Task.CompletedTask; +/// +/// 则可以以以下的命名参数的形式传递参数,调用命令: +/// +/// foo: 3 bar: hello manyints: "1, 2, 3, 4, 5, 6, 7" +/// +/// [AttributeUsage(AttributeTargets.Class)] public sealed class NamedArgumentTypeAttribute : Attribute; diff --git a/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs b/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs index 35e1c0ee..fa262109 100644 --- a/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs @@ -3,26 +3,24 @@ namespace Kook.Commands; /// -/// Marks the to be read by the specified . +/// 标记指定的参数应有应由指定的 读取并解析。 /// /// -/// This attribute will override the to be used when parsing for the -/// desired type in the command. This is useful when one wishes to use a particular -/// without affecting other commands that are using the same target -/// type. +/// 此特性允许在解析命令参数时为指定的参数指定特定的 +/// ,可用于在不影响其他命令的情况下使用特定的命令解析器。 +///
/// -/// If the given type reader does not inherit from , an -/// will be thrown. +/// 标记此特性的类型解析器类型必须继承自 ,否则将引发 +/// 异常。 /// ///
/// -/// In this example, the will be read by a custom -/// , FriendlyTimeSpanTypeReader, instead of the -/// shipped by Kook.Net. +/// 在以下的示例中, 类型的 time 参数将由自定义的类型解析器 FriendlyTimeSpanTypeReader +/// 解析,而不是由内置的 解析。 /// /// [Command("time")] -/// public Task GetTimeAsync([OverrideTypeReader(typeof(FriendlyTimeSpanTypeReader))]TimeSpan time) -/// => ReplyAsync(time); +/// public Task GetTimeAsync([OverrideTypeReader(typeof(FriendlyTimeSpanTypeReader))] TimeSpan time) +/// => ReplyTextAsync(time); /// /// [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] @@ -31,17 +29,19 @@ public sealed class OverrideTypeReaderAttribute : Attribute private static readonly TypeInfo TypeReaderTypeInfo = typeof(TypeReader).GetTypeInfo(); /// - /// Gets the specified of the parameter. + /// 获取解析此参数所使用的类型解析器的类型。 /// public Type TypeReader { get; } - /// - /// The to be used with the parameter. - /// The given does not inherit from . + /// + /// 初始化一个 类的新实例。 + /// + /// 解析此参数所使用的类型解析器的类型。 + /// 所提供的类型解析器类型不是 的派生类。 public OverrideTypeReaderAttribute(Type overridenTypeReader) { if (!TypeReaderTypeInfo.IsAssignableFrom(overridenTypeReader.GetTypeInfo())) - throw new ArgumentException($"{nameof(overridenTypeReader)} must inherit from {nameof(TypeReader)}."); + throw new InvalidOperationException($"{nameof(overridenTypeReader)} must inherit from {nameof(TypeReader)}."); TypeReader = overridenTypeReader; } } diff --git a/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs b/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs index 5e387e7f..0d46c249 100644 --- a/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs @@ -1,19 +1,20 @@ namespace Kook.Commands; /// -/// Requires the parameter to pass the specified precondition before execution can begin. +/// 表示一个命令中的参数在其所属命令执行前需要符合的先决条件的基类。 /// -/// +/// [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true)] public abstract class ParameterPreconditionAttribute : Attribute { /// - /// Checks whether the condition is met before execution of the command. + /// 检查命令执行上下文中的此参数是否满足此先决条件。 /// - /// The context of the command. - /// The parameter of the command being checked against. - /// The raw value of the parameter. - /// The service collection used for dependency injection. + /// 命令执行上下文。 + /// 要检查的参数信息。 + /// 参数的原始值。 + /// 依赖注入服务容器。 + /// 一个表示异步检查操作的任务。任务的结果包含先决条件的结果。 public abstract Task CheckPermissionsAsync(ICommandContext context, ParameterInfo parameter, object? value, IServiceProvider services); } diff --git a/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs b/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs index 367868b2..969aad7c 100644 --- a/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs @@ -1,28 +1,28 @@ namespace Kook.Commands; /// -/// Requires the module or class to pass the specified precondition before execution can begin. +/// 表示一个模块或类中的命令在执行前需要符合的先决条件的基类。 /// -/// +/// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] public abstract class PreconditionAttribute : Attribute { /// - /// Specifies a group that this precondition belongs to. + /// 获取或设置此先决条件所属的分组。 /// /// - /// of the same group require only one of the preconditions to pass in order to - /// be successful (A || B). Specifying = null or not at all will - /// require *all* preconditions to pass, just like normal (A && B). + /// 此属性所设置的先决条件分组用于先决条件的析取。 + /// 同属于相同分组的所有先决条件中,存在一个满足条件的先决条件,则该组先决条件满足条件,组内的其它先决条件将被忽略(A || B)。 + /// 不设置此属性,或设置为 null,则表示该先决条件不属于任何分组,与其它的无分组先决条件或先决条件组的结果合取(A && B)。 /// public string? Group { get; set; } /// - /// When overridden in a derived class, uses the supplied string - /// as the error message if the precondition doesn't pass. - /// Setting this for a class that doesn't override - /// this property is a no-op. + /// 获取或设置错误消息。 /// + /// + /// 当在派生类中重写此虚属性时,用户代码设置在此属性的值将用于在报告错误时携带的错误,在未重写此属性的派生类中设置此属性为空操作。 + /// public virtual string? ErrorMessage { get => null; @@ -30,10 +30,11 @@ public virtual string? ErrorMessage } /// - /// Checks if the has the sufficient permission to be executed. + /// 检查命令执行上下文中的此命令是否满足此先决条件。 /// - /// The context of the command. - /// The command being executed. - /// The service collection used for dependency injection. + /// 命令执行上下文。 + /// 要执行的命令。 + /// 依赖注入服务容器。 + /// 一个表示异步检查操作的任务。任务的结果包含先决条件的结果。 public abstract Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services); } diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs index 07805af6..883d8348 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs @@ -1,40 +1,38 @@ namespace Kook.Commands; /// -/// Requires the bot to have a specific permission in the channel a command is invoked in. +/// 要求当前用户在命令调用所在的的频道或服务器拥有指定的权限。 /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class RequireBotPermissionAttribute : PreconditionAttribute { /// - /// Gets the specified of the precondition. + /// 获取此先决条件所要求的服务器权限。 /// public GuildPermission? GuildPermission { get; } /// - /// Gets the specified of the precondition. + /// 获取此先决条件所要求的频道权限。 /// public ChannelPermission? ChannelPermission { get; } - /// + /// + /// 获取或设置错误消息。 + /// public override string? ErrorMessage { get; set; } /// - /// Gets or sets the error message if the precondition - /// fails due to being run outside a Guild channel. + /// 获取或设置由于在服务器频道外执行命令而导致的先决条件失败的错误消息。 /// public string? NotAGuildErrorMessage { get; set; } /// - /// Requires the bot account to have a specific . + /// 初始化一个 类的新实例。 /// /// - /// This precondition will always fail if the command is being invoked in a . + /// 设置此先决条件将导致命令在私有频道中无法使用。 /// - /// - /// The that the bot must have. Multiple permissions can be specified - /// by ORing the permissions together. - /// + /// 所要求当前用户需要在命令调用所在的的服务器拥有的权限。 public RequireBotPermissionAttribute(GuildPermission permission) { GuildPermission = permission; @@ -42,12 +40,12 @@ public RequireBotPermissionAttribute(GuildPermission permission) } /// - /// Requires that the bot account to have a specific . + /// 初始化一个 类的新实例。 /// - /// - /// The that the bot must have. Multiple permissions can be - /// specified by ORing the permissions together. - /// + /// + /// 设置此先决条件将导致命令在私有频道中无法使用。 + /// + /// 所要求当前用户需要在命令调用所在的的服务器频道拥有的权限。 public RequireBotPermissionAttribute(ChannelPermission permission) { ChannelPermission = permission; diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs index 9bc832f3..5abf29c3 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs @@ -1,48 +1,52 @@ namespace Kook.Commands; /// -/// Defines the type of command context (i.e. where the command is being executed). +/// 表示一个运行命令支持的上下文类型。 /// [Flags] public enum ContextType { /// - /// Specifies the command to be executed within a guild. + /// 命令可以在服务器内执行。 /// Guild = 0x01, /// - /// Specifies the command to be executed within a DM. + /// 命令可以在私聊频道中执行。 /// DM = 0x02 } /// -/// Requires the command to be invoked in a specified context (e.g. in guild, DM). +/// 要求命令在指定的上下文类型中(例如在服务器内、私聊频道中)执行。 /// +/// +/// +/// [Command("secret")] +/// [RequireContext(ContextType.DM | ContextType.Group)] +/// public Task PrivateOnlyAsync() +/// { +/// return ReplyTextAsync("shh, this command is a secret"); +/// } +/// +/// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class RequireContextAttribute : PreconditionAttribute { /// - /// Gets the context required to execute the command. + /// 获取命令执行所需的上下文类型。 /// public ContextType Contexts { get; } - /// + /// + /// 获取或设置错误消息。 + /// public override string? ErrorMessage { get; set; } - /// Requires the command to be invoked in the specified context. - /// The type of context the command can be invoked in. Multiple contexts can be specified by ORing the contexts together. - /// - /// - /// [Command("secret")] - /// [RequireContext(ContextType.DM | ContextType.Group)] - /// public Task PrivateOnlyAsync() - /// { - /// return ReplyAsync("shh, this command is a secret"); - /// } - /// - /// + /// + /// 初始化一个 类的新实例。 + /// + /// 命令执行所需的上下文类型。 public RequireContextAttribute(ContextType contexts) { Contexts = contexts; diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireRoleAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireRoleAttribute.cs index 9aa75148..b38c9595 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireRoleAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireRoleAttribute.cs @@ -1,14 +1,8 @@ namespace Kook.Commands; /// -/// Requires the user invoking the command to have a specified role. +/// 要求调用命令的用户在命令调用所在的服务器拥有指定的角色。 /// -/// -/// This precondition will restrict the access of the command or module to a user with the specified role. -/// If the precondition fails to be met, an erroneous will be returned with the -/// message "Command can only be run by the specified user." For example, you can pass the guild manager role -/// to restrict the command to the guild managers to be able to use it. -/// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class RequireRoleAttribute : PreconditionAttribute { @@ -16,24 +10,23 @@ public class RequireRoleAttribute : PreconditionAttribute private readonly uint? _roleId; /// - /// Gets or sets the error message if the precondition - /// fails due to being run outside a Guild channel. + /// 获取或设置由于在服务器频道外执行命令而导致的先决条件失败的错误消息。 /// public string? NotAGuildErrorMessage { get; set; } /// - /// Requires that the user invoking the command to have a specific Role. + /// 初始化一个 类的新实例。 /// - /// Id of the role that the user must have. + /// 所要求调用命令的用户需要在命令调用所在的的服务器拥有的角色的 ID。 public RequireRoleAttribute(uint roleId) { _roleId = roleId; } /// - /// Requires that the user invoking the command to have a specific Role. + /// 初始化一个 类的新实例。 /// - /// Name of the role that the user must have. + /// 所要求调用命令的用户需要在命令调用所在的的服务器拥有的角色的名称。 public RequireRoleAttribute(string roleName) { _roleName = roleName; diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs index c6f09089..c13d0a49 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs @@ -1,17 +1,10 @@ namespace Kook.Commands; /// -/// Requires the command to be invoked by the specified user. +/// 要求调用命令的用户具有指定的 ID。 /// -/// -/// This precondition will restrict the access of the command or module to a specified user. -/// If the precondition fails to be met, an erroneous will be returned with the -/// message "Command can only be run by the specified user." For example, you can pass the owner of this bot -/// application to restrict the command to the bot owner to be able to use it. -/// /// -/// The following example restricts the command to a set of sensitive commands that only the specified user -/// should be able to access. +/// 以下代码示例将 admin 命令组限制为仅允许用户 ID 为 2810246202 的用户可以调用。 /// /// [RequireUser(2810246202)] /// [Group("admin")] @@ -20,6 +13,7 @@ namespace Kook.Commands; /// [Command("exit")] /// public async Task ExitAsync() /// { +/// await ReplyTextAsync("Goodbye!"); /// Environment.Exit(0); /// } /// } @@ -31,15 +25,17 @@ public class RequireUserAttribute : PreconditionAttribute private readonly ulong _userId; /// - /// Initializes a new attribute with the specified user identifier. + /// 初始化一个 类的新实例。 /// - /// The identifier of the user. + /// 所要求调用命令的用户应具有的 ID。 public RequireUserAttribute(ulong userId) { _userId = userId; } - /// + /// + /// 获取或设置错误消息。 + /// public override string? ErrorMessage { get; set; } /// diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs index 5719597e..39a553c1 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs @@ -1,40 +1,38 @@ namespace Kook.Commands; /// -/// Requires the user invoking the command to have a specified permission. +/// 要求调用命令的用户在命令调用所在的的频道或服务器拥有指定的权限。 /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class RequireUserPermissionAttribute : PreconditionAttribute { /// - /// Gets the specified of the precondition. + /// 获取此先决条件所要求的服务器权限。 /// public GuildPermission? GuildPermission { get; } /// - /// Gets the specified of the precondition. + /// 获取此先决条件所要求的频道权限。 /// public ChannelPermission? ChannelPermission { get; } - /// + /// + /// 获取或设置错误消息。 + /// public override string? ErrorMessage { get; set; } /// - /// Gets or sets the error message if the precondition - /// fails due to being run outside of a Guild channel. + /// 获取或设置由于在服务器频道外执行命令而导致的先决条件失败的错误消息。 /// public string? NotAGuildErrorMessage { get; set; } /// - /// Requires that the user invoking the command to have a specific . + /// 初始化一个 类的新实例。 /// /// - /// This precondition will always fail if the command is being invoked in a . + /// 设置此先决条件将导致命令在私有频道中无法使用。 /// - /// - /// The that the user must have. Multiple permissions can be - /// specified by ORing the permissions together. - /// + /// 所要求调用命令的用户需要在命令调用所在的的服务器拥有的权限。 public RequireUserPermissionAttribute(GuildPermission permission) { GuildPermission = permission; @@ -42,12 +40,12 @@ public RequireUserPermissionAttribute(GuildPermission permission) } /// - /// Requires that the user invoking the command to have a specific . + /// 初始化一个 类的新实例。 /// - /// - /// The that the user must have. Multiple permissions can be - /// specified by ORing the permissions together. - /// + /// + /// 设置此先决条件将导致命令在私有频道中无法使用。 + /// + /// 所要求当前用户需要在命令调用所在的的频道拥有的权限。 public RequireUserPermissionAttribute(ChannelPermission permission) { ChannelPermission = permission; diff --git a/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs b/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs index 1080cba6..b11b2d87 100644 --- a/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs @@ -1,19 +1,27 @@ namespace Kook.Commands; /// -/// Sets priority of commands. +/// 标记指定的命令的优先级。 /// [AttributeUsage(AttributeTargets.Method)] public class PriorityAttribute : Attribute { /// - /// Gets the priority which has been set for the command. + /// 获取为命令设置的优先级。 /// public int Priority { get; } /// - /// Initializes a new attribute with the given priority. + /// 初始化一个 类的新实例。 /// + /// 为命令设置的优先级。 + /// + /// 更大的数值表示更高的优先级。
+ /// 命令系统在命令匹配时,会根据输入参数的相似度和优先级来选择最匹配的命令。 + /// 例如,通过提及用户传入用户类型的参数,可以为该参数贡献 1.0 的匹配相似分,而仅通过用户昵称传入用户类型的参数则最低只贡献 0.5 的匹配相似分。 + /// 一般地,各个参数的匹配相似分均为不超过 1.0 的正数,命令系统将会对各个匹配的匹配相似分统计算术平均值,此平均值通常不会超过 1.0。 + /// 在此基础上,优先级分数值会被累加到匹配相似分算术平均值的 0.99 倍之上,这表示,通常情况下,为命令之间设置量级超过 1 的优先级均可以使自定义匹配优先级生效。 + ///
public PriorityAttribute(int priority) { Priority = priority; diff --git a/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs b/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs index f9fe76a0..23a28e1e 100644 --- a/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs @@ -1,7 +1,7 @@ namespace Kook.Commands; /// -/// Marks the input to not be parsed by the parser. +/// 标记指定的参数将接收剩余未解析的所有输入值。 /// [AttributeUsage(AttributeTargets.Parameter)] public class RemainderAttribute : Attribute; diff --git a/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs b/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs index 15020f36..80cab83d 100644 --- a/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs @@ -1,21 +1,20 @@ namespace Kook.Commands; -// Extension of the Cosmetic Summary, for Groups, Commands, and Parameters /// -/// Attaches remarks to your commands. +/// 标记命令的备注。 /// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class RemarksAttribute : Attribute { /// - /// Gets the remarks of the command. + /// 获取命令的备注。 /// public string Text { get; } /// - /// Initializes a new attribute with the specified remarks. + /// 初始化一个 类的新实例。 /// - /// + /// 命令的备注。 public RemarksAttribute(string text) { Text = text; diff --git a/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs b/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs index 16eb1d4a..3ce43d5b 100644 --- a/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs @@ -1,21 +1,20 @@ namespace Kook.Commands; -// Cosmetic Summary, for Groups and Commands /// -/// Attaches a summary to your command. +/// 标记命令的摘要。 /// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Parameter)] public class SummaryAttribute : Attribute { /// - /// Gets the summary of the command. + /// 获取命令的摘要。 /// public string Text { get; } /// - /// Initializes a new attribute with the specified summary. + /// 初始化一个 类的新实例。 /// - /// + /// 命令的摘要。 public SummaryAttribute(string text) { Text = text; diff --git a/src/Kook.Net.Commands/Builders/CommandBuilder.cs b/src/Kook.Net.Commands/Builders/CommandBuilder.cs index 5baadfd2..5784090b 100644 --- a/src/Kook.Net.Commands/Builders/CommandBuilder.cs +++ b/src/Kook.Net.Commands/Builders/CommandBuilder.cs @@ -1,7 +1,7 @@ namespace Kook.Commands.Builders; /// -/// Represents a command builder. +/// 表示一个命令构建器。 /// public class CommandBuilder { @@ -13,67 +13,68 @@ public class CommandBuilder private readonly List _aliases; /// - /// Gets the module builder that this command builder belongs to. + /// 获取此命令构建器所属的模块构建器。 /// public ModuleBuilder Module { get; } /// - /// Gets or sets the callback that is invoked when this command is executed. + /// 获取或设置当执行此命令时调用的回调。 /// internal Func? Callback { get; set; } /// - /// Gets or sets the name of this command. + /// 获取或设置此命令的基本名称。 /// public string? Name { get; set; } /// - /// Gets or sets the summary of this command. + /// 获取或设置此命令的摘要。 /// public string? Summary { get; set; } /// - /// Gets or sets the remarks of this command. + /// 获取或设置此命令的备注。 /// public string? Remarks { get; set; } /// - /// Gets or sets the primary alias of this command. + /// 获取或设置此命令的首要别名。 /// public string? PrimaryAlias { get; set; } /// - /// Gets or sets the run mode of this command. + /// 获取或设置此命令的运行模式。 /// public RunMode RunMode { get; set; } /// - /// Gets or sets the priority of this command. + /// 获取或设置此命令的优先级。 /// + /// public int Priority { get; set; } /// - /// Gets or sets whether the extra arguments should be ignored. + /// 获取或设置此命令是否忽略额外的参数。 /// public bool IgnoreExtraArgs { get; set; } /// - /// Gets the preconditions of this command. + /// 获取此命令的先决条件。 /// public IReadOnlyList Preconditions => _preconditions; /// - /// Gets the parameters of this command. + /// 获取此命令的参数构建器。 /// public IReadOnlyList Parameters => _parameters; /// - /// Gets the attributes of this command. + /// 获取此命令的特性。 /// public IReadOnlyList Attributes => _attributes; /// - /// Gets the aliases of this command. + /// 获取此命令的别名。 /// public IReadOnlyList Aliases => _aliases; @@ -81,10 +82,6 @@ public class CommandBuilder #region Automatic - /// - /// Initializes a new instance of the class. - /// - /// The module builder that this command builder belongs to. internal CommandBuilder(ModuleBuilder module) { Module = module; @@ -99,11 +96,11 @@ internal CommandBuilder(ModuleBuilder module) #region User-defined /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The module builder that this command builder belongs to. - /// The primary alias of this command. - /// The callback that is invoked when this command is executed. + /// 此命令构建器所属的模块构建器。 + /// 此命令的首要别名。 + /// 当执行此命令时调用的回调。 internal CommandBuilder(ModuleBuilder module, string? primaryAlias, Func callback) : this(module) @@ -117,10 +114,10 @@ internal CommandBuilder(ModuleBuilder module, string? primaryAlias, } /// - /// Sets the name of this command. + /// 设置此命令的基本名称。 /// - /// The name of this command. - /// This command builder. + /// 此命令的基本名称。 + /// 当前命令构建器。 public CommandBuilder WithName(string name) { Name = name; @@ -128,10 +125,10 @@ public CommandBuilder WithName(string name) } /// - /// Sets the summary of this command. + /// 设置此命令的摘要。 /// - /// The summary of this command. - /// This command builder. + /// 此命令的摘要。 + /// 当前命令构建器。 public CommandBuilder WithSummary(string summary) { Summary = summary; @@ -139,10 +136,10 @@ public CommandBuilder WithSummary(string summary) } /// - /// Sets the remarks of this command. + /// 设置此命令的备注。 /// - /// The remarks of this command. - /// This command builder. + /// 此命令的备注。 + /// 当前命令构建器。 public CommandBuilder WithRemarks(string remarks) { Remarks = remarks; @@ -150,10 +147,10 @@ public CommandBuilder WithRemarks(string remarks) } /// - /// Sets the run mode of this command. + /// 设置此命令的运行模式。 /// - /// The run mode of this command. - /// This command builder. + /// 此命令的运行模式。 + /// 当前命令构建器。 public CommandBuilder WithRunMode(RunMode runMode) { RunMode = runMode; @@ -161,10 +158,11 @@ public CommandBuilder WithRunMode(RunMode runMode) } /// - /// Sets the priority of this command. + /// 设置此命令的优先级。 /// - /// The priority of this command. - /// This command builder. + /// 此命令的优先级。 + /// 当前命令构建器。 + /// public CommandBuilder WithPriority(int priority) { Priority = priority; @@ -172,10 +170,10 @@ public CommandBuilder WithPriority(int priority) } /// - /// Adds aliases to this command. + /// 向此命令添加别名。 /// - /// An array containing the aliases to add. - /// This command builder. + /// 包含要添加的别名的数组。 + /// 当前命令构建器。 public CommandBuilder AddAliases(params string?[] aliases) { foreach (string? x in aliases) @@ -189,10 +187,10 @@ public CommandBuilder AddAliases(params string?[] aliases) } /// - /// Adds attributes to this command. + /// 添加特性到此命令。 /// - /// An array containing the attributes to add. - /// This command builder. + /// 要添加的特性。 + /// 当前命令构建器。 public CommandBuilder AddAttributes(params Attribute[] attributes) { _attributes.AddRange(attributes); @@ -200,10 +198,10 @@ public CommandBuilder AddAttributes(params Attribute[] attributes) } /// - /// Adds a precondition to this command. + /// 添加先决条件到此命令。 /// - /// The precondition to add. - /// This command builder. + /// 要添加的先决条件。 + /// 当前命令构建器。 public CommandBuilder AddPrecondition(PreconditionAttribute precondition) { _preconditions.Add(precondition); @@ -211,12 +209,12 @@ public CommandBuilder AddPrecondition(PreconditionAttribute precondition) } /// - /// Adds a parameter to this command. + /// 添加参数到此命令。 /// - /// The name of the parameter. - /// An action delegate that is invoked to create the parameter. - /// The type of the parameter. - /// This command builder. + /// 参数的名称。 + /// 一个创建参数构建器的委托。 + /// 参数的类型。 + /// 当前命令构建器。 public CommandBuilder AddParameter(string name, Action createFunc) { ParameterBuilder param = new(this, name, typeof(T)); @@ -226,12 +224,12 @@ public CommandBuilder AddParameter(string name, Action crea } /// - /// Adds a parameter to this command. + /// 添加参数到此命令。 /// - /// The name of the parameter. - /// The type of the parameter. - /// An action delegate that is invoked to create the parameter. - /// This command builder. + /// 参数的名称。 + /// 参数的类型。 + /// 一个创建参数构建器的委托。 + /// 当前命令构建器。 public CommandBuilder AddParameter(string name, Type type, Action createFunc) { ParameterBuilder param = new(this, name, type); @@ -241,10 +239,10 @@ public CommandBuilder AddParameter(string name, Type type, Action - /// Adds a parameter to this command. + /// 添加参数到此命令。 /// - /// An action delegate that is invoked to create the parameter. - /// This command builder. + /// 一个创建参数构建器的委托。 + /// 当前命令构建器。 internal CommandBuilder AddParameter(Action createFunc) { ParameterBuilder param = new(this); @@ -254,12 +252,12 @@ internal CommandBuilder AddParameter(Action createFunc) } /// - /// Builds the command. + /// 构建此命令构建器。 /// - /// The module info. - /// The command service. - /// The command info. - /// Only the last parameter in a command may have the Remainder or Multiple flag. + /// 此命令所属的模块信息。 + /// 此命令所属的命令服务。 + /// 此命令构建器构建的命令信息。 + /// 仅支持在最后一个参数上设置接收全部剩余参数或接收多个参数。 internal CommandInfo Build(ModuleInfo info, CommandService service) { // Default name to primary alias diff --git a/src/Kook.Net.Commands/Builders/ModuleBuilder.cs b/src/Kook.Net.Commands/Builders/ModuleBuilder.cs index d7c5ec1b..11c0f9ad 100644 --- a/src/Kook.Net.Commands/Builders/ModuleBuilder.cs +++ b/src/Kook.Net.Commands/Builders/ModuleBuilder.cs @@ -3,7 +3,7 @@ namespace Kook.Commands.Builders; /// -/// Represents a module builder. +/// 表示一个模块构建器。 /// public class ModuleBuilder { @@ -17,32 +17,32 @@ public class ModuleBuilder private readonly List _aliases; /// - /// Gets the command service that this module builder belongs to. + /// 获取此模块构建器所属的命令服务。 /// public CommandService Service { get; } /// - /// Gets the parent module builder that this module builder belongs to. + /// 获取此模块构建器所属的父模块构建器。 /// public ModuleBuilder? Parent { get; } /// - /// Gets or sets the name of this module. + /// 获取或设置此模块的基本名称。 /// public string? Name { get; set; } /// - /// Gets or sets the summary of this module. + /// 获取或设置此模块的摘要。 /// public string? Summary { get; set; } /// - /// Gets or sets the remarks of this module. + /// 获取或设置此模块的备注。 /// public string? Remarks { get; set; } /// - /// Gets or sets the group of this module. + /// 获取或设置此模块的分组。 /// public string? Group { @@ -57,27 +57,27 @@ public string? Group } /// - /// Gets a read-only list of commands that this module builder contains. + /// 获取此模块的别名。 /// public IReadOnlyList Commands => _commands; /// - /// Gets a read-only list of submodules that this module builder contains. + /// 获取此模块的子模块。 /// public IReadOnlyList Modules => _submodules; /// - /// Gets a read-only list of preconditions that this module builder contains. + /// 获取此模块的先决条件。 /// public IReadOnlyList Preconditions => _preconditions; /// - /// Gets a read-only list of attributes that this module builder contains. + /// 获取此模块的特性。 /// public IReadOnlyList Attributes => _attributes; /// - /// Gets a read-only list of aliases that this module builder contains. + /// 获取此模块的别名。 /// public IReadOnlyList Aliases => _aliases; @@ -87,11 +87,6 @@ public string? Group #region Automatic - /// - /// Initializes a new instance of the class. - /// - /// The command service that this module builder belongs to. - /// The parent module builder that this module builder belongs to. internal ModuleBuilder(CommandService service, ModuleBuilder? parent) { Service = service; @@ -109,11 +104,11 @@ internal ModuleBuilder(CommandService service, ModuleBuilder? parent) #region User-defined /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The command service that this module builder belongs to. - /// The parent module builder that this module builder belongs to. - /// The primary alias of this module. + /// 此模块构建器所属的命令服务。 + /// 此模块构建器所属的父模块构建器。 + /// 此模块的首要别名。 internal ModuleBuilder(CommandService service, ModuleBuilder? parent, string primaryAlias) : this(service, parent) { @@ -122,10 +117,10 @@ internal ModuleBuilder(CommandService service, ModuleBuilder? parent, string pri } /// - /// Sets the name of this module. + /// 设置此模块的名基本称。 /// - /// The name of this module. - /// This module builder. + /// 此模块的基本名称。 + /// 此模块构建器。 public ModuleBuilder WithName(string name) { Name = name; @@ -133,10 +128,10 @@ public ModuleBuilder WithName(string name) } /// - /// Sets the summary of this module. + /// 设置此模块的摘要。 /// - /// The summary of this module. - /// This module builder. + /// 此模块的摘要。 + /// 此模块构建器。 public ModuleBuilder WithSummary(string summary) { Summary = summary; @@ -144,10 +139,10 @@ public ModuleBuilder WithSummary(string summary) } /// - /// Sets the remarks of this module. + /// 设置此模块的备注。 /// - /// The remarks of this module. - /// This module builder. + /// 此模块的备注。 + /// 此模块构建器。 public ModuleBuilder WithRemarks(string remarks) { Remarks = remarks; @@ -155,10 +150,10 @@ public ModuleBuilder WithRemarks(string remarks) } /// - /// Adds aliases to this module. + /// 添加别名到此模块。 /// - /// An array of aliases to add to this module. - /// This module builder. + /// 要添加到此模块的别名数组。 + /// 此模块构建器。 public ModuleBuilder AddAliases(params string?[] aliases) { foreach (string? x in aliases) @@ -172,10 +167,10 @@ public ModuleBuilder AddAliases(params string?[] aliases) } /// - /// Adds a precondition to this module. + /// 添加特性到此模块。 /// - /// An array of attributes to add to this module. - /// This module builder. + /// 要添加到此模块的特性数组。 + /// 此模块构建器。 public ModuleBuilder AddAttributes(params Attribute[] attributes) { _attributes.AddRange(attributes); @@ -183,10 +178,10 @@ public ModuleBuilder AddAttributes(params Attribute[] attributes) } /// - /// Adds a precondition to this module. + /// 添加先决条件到此模块。 /// - /// The precondition to add to this module. - /// This module builder. + /// 要添加到此模块的先决条件。 + /// 此模块构建器。 public ModuleBuilder AddPrecondition(PreconditionAttribute precondition) { _preconditions.Add(precondition); @@ -194,12 +189,12 @@ public ModuleBuilder AddPrecondition(PreconditionAttribute precondition) } /// - /// Adds a command to this module. + /// 添加命令到此模块。 /// - /// The primary alias of this command. - /// The callback of this command. - /// The function delegate that creates this command. - /// This module builder. + /// 此命令的首要别名。 + /// 当执行此命令时调用的回调。 + /// 一个创建命令构建器的委托。 + /// 此模块构建器。 public ModuleBuilder AddCommand(string primaryAlias, Func callback, Action createFunc) @@ -211,10 +206,10 @@ public ModuleBuilder AddCommand(string primaryAlias, } /// - /// Adds a command to this module. + /// 添加命令到此模块。 /// - /// The function delegate that creates this command. - /// This module builder. + /// 一个创建命令构建器的委托。 + /// 此模块构建器。 internal ModuleBuilder AddCommand(Action createFunc) { CommandBuilder builder = new(this); @@ -224,11 +219,11 @@ internal ModuleBuilder AddCommand(Action createFunc) } /// - /// Adds a module to this module. + /// 添加子模块到此模块。 /// - /// The primary alias of this module. - /// The function delegate that creates this module. - /// This module builder. + /// 此模块的首要别名。 + /// 一个创建模块构建器的委托。 + /// 此模块构建器。 public ModuleBuilder AddModule(string primaryAlias, Action createFunc) { ModuleBuilder builder = new(Service, this, primaryAlias); @@ -238,10 +233,10 @@ public ModuleBuilder AddModule(string primaryAlias, Action create } /// - /// Adds a module to this module. + /// 添加子模块到此模块。 /// - /// The function delegate that creates this module. - /// This module builder. + /// 一个创建模块构建器的委托。 + /// 此模块构建器。 internal ModuleBuilder AddModule(Action createFunc) { ModuleBuilder builder = new(Service, this); @@ -250,13 +245,6 @@ internal ModuleBuilder AddModule(Action createFunc) return this; } - /// - /// Builds this module builder into a module. - /// - /// The command service that this module builder belongs to. - /// The service provider that this module builder belongs to. - /// The parent module that this module builder belongs to. - /// The built module. private ModuleInfo BuildImpl(CommandService service, IServiceProvider services, ModuleInfo? parent = null) { //Default name to first alias @@ -272,20 +260,20 @@ private ModuleInfo BuildImpl(CommandService service, IServiceProvider services, } /// - /// Builds this module builder into a module. + /// 构建此模块构建器为模块。 /// - /// The command service that this module builder belongs to. - /// The service provider that this module builder belongs to. - /// The built module. + /// 此模块构建器所属的命令服务。 + /// 此模块构建器所属的服务提供程序。 + /// 构建的模块。 public ModuleInfo Build(CommandService service, IServiceProvider services) => BuildImpl(service, services); /// - /// Builds this module builder into a module. + /// 构建此模块构建器为模块。 /// - /// The command service that this module builder belongs to. - /// The service provider that this module builder belongs to. - /// The parent module that this module builder belongs to. - /// The built module. + /// 此模块构建器所属的命令服务。 + /// 此模块构建器所属的服务提供程序。 + /// 此模块构建器所属的父模块。 + /// 构建的模块。 internal ModuleInfo Build(CommandService service, IServiceProvider services, ModuleInfo parent) => BuildImpl(service, services, parent); #endregion diff --git a/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs b/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs index 64c04fd1..e64183d9 100644 --- a/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs +++ b/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs @@ -33,7 +33,6 @@ bool IsLoadableModule(TypeInfo info) => && info.GetCustomAttribute() == null; } - public static Task> BuildAsync(CommandService service, IServiceProvider services, params TypeInfo[] validTypes) => BuildAsync(validTypes, service, services); diff --git a/src/Kook.Net.Commands/Builders/ParameterBuilder.cs b/src/Kook.Net.Commands/Builders/ParameterBuilder.cs index d5a148a3..3cfdf884 100644 --- a/src/Kook.Net.Commands/Builders/ParameterBuilder.cs +++ b/src/Kook.Net.Commands/Builders/ParameterBuilder.cs @@ -3,7 +3,7 @@ namespace Kook.Commands.Builders; /// -/// Represents a parameter builder. +/// 表示一个参数构建器。 /// public class ParameterBuilder { @@ -13,57 +13,57 @@ public class ParameterBuilder private readonly List _attributes; /// - /// Gets the command builder that this parameter builder belongs to. + /// 获取此参数构建器所属的命令构建器。 /// public CommandBuilder Command { get; } /// - /// Gets the name of this parameter. + /// 获取或设置此参数的名称。 /// public string Name { get; internal set; } /// - /// Gets the type of this parameter. + /// 获取或设置此参数的类型。 /// public Type? ParameterType { get; internal set; } /// - /// Gets the type reader of this parameter. + /// 获取或设置此参数的类型读取器。 /// public TypeReader? TypeReader { get; set; } /// - /// Gets or sets a value that indicates whether this parameter is an optional parameter or not. + /// 获取或设置此参数是否为可选参数。 /// public bool IsOptional { get; set; } /// - /// Gets or sets a value that indicates whether this parameter is a remainder parameter or not. + /// 获取或设置此参数是否接收全部剩余参数。 /// public bool IsRemainder { get; set; } /// - /// Gets or sets a value that indicates whether this parameter is a multiple parameter or not. + /// 获取或设置此参数是否为多值参数。 /// public bool IsMultiple { get; set; } /// - /// Gets or sets the default value of this parameter. + /// 获取或设置此参数的默认值。 /// public object? DefaultValue { get; set; } /// - /// Gets or sets the summary of this parameter. + /// 获取或设置此参数的摘要。 /// public string? Summary { get; set; } /// - /// Gets a read-only collection containing the preconditions of this parameter. + /// 获取此参数的先决条件。 /// public IReadOnlyList Preconditions => _preconditions; /// - /// Gets a read-only collection containing the attributes of this parameter. + /// 获取此参数的特性。 /// public IReadOnlyList Attributes => _attributes; @@ -71,10 +71,6 @@ public class ParameterBuilder #region Automatic - /// - /// Initializes a new instance of the class. - /// - /// The command builder that this parameter builder belongs to. internal ParameterBuilder(CommandBuilder command) { _preconditions = []; @@ -87,12 +83,6 @@ internal ParameterBuilder(CommandBuilder command) #region User-defined - /// - /// Initializes a new instance of the class. - /// - /// The command builder that this parameter builder belongs to. - /// The name of this parameter. - /// The type of this parameter. internal ParameterBuilder(CommandBuilder command, string name, Type type) : this(command) { @@ -101,10 +91,6 @@ internal ParameterBuilder(CommandBuilder command, string name, Type type) SetType(type); } - /// - /// Sets the type of this parameter. - /// - /// The type of this parameter. internal void SetType(Type type) { TypeReader = GetReader(type); @@ -115,12 +101,6 @@ internal void SetType(Type type) ParameterType = type; } - /// - /// Gets the type reader of this parameter. - /// - /// The type of this parameter. - /// The type reader of this parameter. - /// The type for the command must be a class with a public parameterless constructor to use as a NamedArgumentType. private TypeReader? GetReader(Type? type) { if (type is null) return null; @@ -151,16 +131,15 @@ internal void SetType(Type type) return reader; } - IDictionary? readers = commands.GetTypeReaders(type); return readers != null ? readers.FirstOrDefault().Value : commands.GetDefaultTypeReader(type); } /// - /// Sets the summary of this parameter. + /// 设置此参数的摘要。 /// - /// The summary of this parameter. - /// This parameter builder. + /// 此参数的摘要。 + /// 此参数构建器。 public ParameterBuilder WithSummary(string summary) { Summary = summary; @@ -168,10 +147,10 @@ public ParameterBuilder WithSummary(string summary) } /// - /// Sets the default value of this parameter. + /// 设置此参数的默认值。 /// - /// The default value of this parameter. - /// This parameter builder. + /// 此参数的默认值。 + /// 此参数构建器。 public ParameterBuilder WithDefault(object defaultValue) { DefaultValue = defaultValue; @@ -179,10 +158,10 @@ public ParameterBuilder WithDefault(object defaultValue) } /// - /// Sets whether this parameter is an optional parameter or not. + /// 设置此参数是否为可选参数。 /// - /// Whether this parameter is an optional parameter or not. - /// This parameter builder. + /// 此参数是否为可选参数。 + /// 此参数构建器。 public ParameterBuilder WithIsOptional(bool isOptional) { IsOptional = isOptional; @@ -190,10 +169,10 @@ public ParameterBuilder WithIsOptional(bool isOptional) } /// - /// Sets whether this parameter is a remainder parameter or not. + /// 设置此参数是否接收全部剩余参数。 /// - /// Whether this parameter is a remainder parameter or not. - /// This parameter builder. + /// 此参数是否接收全部剩余参数。 + /// 此参数构建器。 public ParameterBuilder WithIsRemainder(bool isRemainder) { IsRemainder = isRemainder; @@ -201,10 +180,10 @@ public ParameterBuilder WithIsRemainder(bool isRemainder) } /// - /// Sets whether this parameter is a multiple parameter or not. + /// 设置此参数是否为多值参数。 /// - /// Whether this parameter is a multiple parameter or not. - /// This parameter builder. + /// 此参数是否为多值参数。 + /// 此参数构建器。 public ParameterBuilder WithIsMultiple(bool isMultiple) { IsMultiple = isMultiple; @@ -212,10 +191,10 @@ public ParameterBuilder WithIsMultiple(bool isMultiple) } /// - /// Adds attributes to this parameter. + /// 添加特性到此参数。 /// - /// An array containing the attributes to add. - /// This parameter builder. + /// 要添加到此参数的特性数组。 + /// 此参数构建器。 public ParameterBuilder AddAttributes(params Attribute[] attributes) { _attributes.AddRange(attributes); @@ -223,22 +202,16 @@ public ParameterBuilder AddAttributes(params Attribute[] attributes) } /// - /// Adds a precondition to this parameter. + /// 添加先决条件到此参数。 /// - /// The precondition to add. - /// This parameter builder. + /// 要添加到此参数的先决条件。 + /// 此参数构建器。 public ParameterBuilder AddPrecondition(ParameterPreconditionAttribute precondition) { _preconditions.Add(precondition); return this; } - /// - /// Builds this parameter builder. - /// - /// The command info that this parameter belongs to. - /// The built parameter info. - /// No type reader was found for this parameter, which must be specified. internal ParameterInfo Build(CommandInfo info) { if ((TypeReader ??= GetReader(ParameterType)) is null) diff --git a/src/Kook.Net.Commands/CommandContext.cs b/src/Kook.Net.Commands/CommandContext.cs index 65367507..29e2f617 100644 --- a/src/Kook.Net.Commands/CommandContext.cs +++ b/src/Kook.Net.Commands/CommandContext.cs @@ -1,6 +1,6 @@ namespace Kook.Commands; -/// The context of a command which may contain the client, user, guild, channel, and message. +/// public class CommandContext : ICommandContext { /// @@ -18,14 +18,16 @@ public class CommandContext : ICommandContext /// public IUserMessage Message { get; } - /// Indicates whether the channel that the command is executed in is a private channel. + /// + /// 获取当前上下文是否为私有的执行上下文。 + /// public bool IsPrivate => Channel is IPrivateChannel; /// - /// Initializes a new class with the provided client and message. + /// 初始化一个包含指定客户端和消息的 类的新实例。 /// - /// The underlying client. - /// The underlying message. + /// 命令执行时所使用的客户端。 + /// 命令解析的源消息。 public CommandContext(IKookClient client, IUserMessage msg) { Client = client; diff --git a/src/Kook.Net.Commands/CommandError.cs b/src/Kook.Net.Commands/CommandError.cs index 605b035c..bef4b21e 100644 --- a/src/Kook.Net.Commands/CommandError.cs +++ b/src/Kook.Net.Commands/CommandError.cs @@ -1,52 +1,61 @@ namespace Kook.Commands; -/// Defines the type of error a command can throw. +/// +/// 表示命令执行的错误。 +/// public enum CommandError { - //Search + // 搜索 + /// - /// Thrown when the command is unknown. + /// 当命令未知时引发。 /// UnknownCommand = 1, - //Parse + // 解析 + /// - /// Thrown when the command fails to be parsed. + /// 当命令解析失败时引发。 /// ParseFailed, /// - /// Thrown when the input text has too few or too many arguments. + /// 当输入文本的参数过少或过多时引发。 /// BadArgCount, - //Parse (Type Reader) - //CastFailed, + // 解析 + + // CastFailed, + /// - /// Thrown when the object cannot be found by the . + /// 当对象未被 找到时引发。 /// ObjectNotFound, /// - /// Thrown when more than one object is matched by . + /// 当 匹配到多个对象时引发。 /// MultipleMatches, - //Preconditions + // 先决条件 + /// - /// Thrown when the command fails to meet a 's conditions. + /// 当命令未满足先决条件时引发。 /// UnmetPrecondition, - //Execute + // 执行 + /// - /// Thrown when an exception occurs mid-command execution. + /// 当命令执行时发生异常时引发。 /// Exception, - //Runtime + // 运行时 + /// - /// Thrown when the command is not successfully executed on runtime. + /// 当命令在运行时未成功执行时引发。 /// Unsuccessful } diff --git a/src/Kook.Net.Commands/CommandException.cs b/src/Kook.Net.Commands/CommandException.cs index ec8c0ac8..d07e2470 100644 --- a/src/Kook.Net.Commands/CommandException.cs +++ b/src/Kook.Net.Commands/CommandException.cs @@ -1,24 +1,26 @@ namespace Kook.Commands; /// -/// The exception that is thrown if another exception occurs during a command execution. +/// 表示一个命令执行过程中发生的异常。 /// public class CommandException : Exception { - /// Gets the command that caused the exception. + /// + /// 获取异常的命令信息。 + /// public CommandInfo Command { get; } - /// Gets the command context of the exception. + /// + /// 获取异常的命令上下文。 + /// public ICommandContext Context { get; } /// - /// Initializes a new instance of the class using a - /// information, a context, and the exception that - /// interrupted the execution. + /// 初始化一个 类的新实例。 /// - /// The command information. - /// The context of the command. - /// The exception that interrupted the command execution. + /// 引发异常的命令。 + /// 引发异常的命令上下文。 + /// 引发的异常。 public CommandException(CommandInfo command, ICommandContext context, Exception? ex) : base($"Error occurred executing {command.GetLogText(context)}.", ex) { diff --git a/src/Kook.Net.Commands/CommandMatch.cs b/src/Kook.Net.Commands/CommandMatch.cs index 73e2d4d7..bb6f6f9a 100644 --- a/src/Kook.Net.Commands/CommandMatch.cs +++ b/src/Kook.Net.Commands/CommandMatch.cs @@ -1,21 +1,25 @@ namespace Kook.Commands; /// -/// Represents a matched command. +/// 表示一个匹配的命令。 /// public struct CommandMatch { - /// The command that matches the search result. + /// + /// 获取与搜索结果相匹配的命令。 + /// public CommandInfo Command { get; } - /// The alias of the command. + /// + /// 获取命令的别名。 + /// public string Alias { get; } /// - /// Initializes a new instance of the struct. + /// 初始化一个 结构的新实例。 /// - /// The command that matches the search result. - /// The alias of the command. + /// 与搜索结果相匹配的命令。 + /// 命令的别名。 public CommandMatch(CommandInfo command, string alias) { Command = command; @@ -23,46 +27,46 @@ public CommandMatch(CommandInfo command, string alias) } /// - /// Checks the preconditions of this command. + /// 检查此命令的先决条件。 /// - /// The context of the command. - /// The services to use. - /// The result of the precondition check. + /// 命令的上下文。 + /// 用于检查先决条件的以来服务提供程序。 + /// 一个表示异步检查操作的任务。任务的结果包含先决条件的结果。 public Task CheckPreconditionsAsync(ICommandContext context, IServiceProvider? services = null) => Command.CheckPreconditionsAsync(context, services); /// - /// Parses this command. + /// 解析此命令。 /// - /// The context of the command. - /// The search result of the command. - /// The result of the precondition check. - /// The services to use. - /// The result of the parse. + /// 命令的上下文。 + /// 搜索结果。 + /// 先决条件的结果。 + /// 用于解析的服务提供程序。 + /// 一个表示异步解析操作的任务。任务的结果包含解析的结果。 public Task ParseAsync(ICommandContext context, SearchResult searchResult, PreconditionResult? preconditionResult = null, IServiceProvider? services = null) => Command.ParseAsync(context, Alias.Length, searchResult, preconditionResult, services); /// - /// Executes this command. + /// 执行此命令。 /// - /// The context of the command. - /// The arguments of the command. - /// The parameters of the command. - /// The services to use. - /// The result of the execution. + /// 命令的上下文。 + /// 命令的实参。 + /// 命令的形参。 + /// 用于执行的服务提供程序。 + /// 一个表示异步执行操作的任务。任务的结果包含执行的结果。 public Task ExecuteAsync(ICommandContext context, IEnumerable argList, IEnumerable paramList, IServiceProvider services) => Command.ExecuteAsync(context, argList, paramList, services); /// - /// Executes this command. + /// 执行此命令。 /// - /// The context of the command. - /// The result of the parse. - /// The services to use. - /// The result of the execution. + /// 命令的上下文。 + /// 解析的结果。 + /// 用于执行的服务提供程序。 + /// 一个表示异步执行操作的任务。任务的结果包含执行的结果。 public Task ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) => Command.ExecuteAsync(context, parseResult, services); } diff --git a/src/Kook.Net.Commands/CommandService.cs b/src/Kook.Net.Commands/CommandService.cs index 6e9a3407..1036cb7b 100644 --- a/src/Kook.Net.Commands/CommandService.cs +++ b/src/Kook.Net.Commands/CommandService.cs @@ -7,28 +7,26 @@ namespace Kook.Commands; /// -/// Provides a framework for building Kook commands. +/// 表示一个基于文本的命令服务。 /// /// -/// -/// The service provides a framework for building Kook commands both dynamically via runtime builders or -/// statically via compile-time modules. To create a command module at compile-time, see -/// (most common); otherwise, see . -/// -/// -/// This service also provides several events for monitoring command usages; such as -/// for any command-related log events, and -/// for information about commands that have -/// been successfully executed. -/// +/// 此类用于支持在运行时动态创建命令,或者在编译时静态创建命令。要在编译时创建命令模块,参见 +///
+/// 此服务还提供了几个事件,用于监视命令的使用情况;例如 用于任何与命令相关的日志事件, ///
public class CommandService : IDisposable { #region CommandService /// - /// Occurs when a command-related information is received. + /// 当产生与命令相关的日志信息时引发。 /// + /// + /// 事件参数: + /// + /// 参数是日志消息。 + /// + /// public event Func Log { add => _logEvent.Add(value); @@ -38,11 +36,17 @@ public event Func Log internal readonly AsyncEvent> _logEvent = new(); /// - /// Occurs when a command is executed. + /// 当命令执行时引发。 /// /// - /// This event is fired when a command has been executed, successfully or not. When a command fails to - /// execute during parsing or precondition stage, the CommandInfo may not be returned. + /// 此事件在命令执行后引发,既包含了执行成功的情况,也包含了执行失败的情况。 + ///
+ /// 事件参数: + /// + /// ? 参数是执行的命令,如果命令在解析或先决条件阶段失败,则可能为 null + /// 参数是命令的上下文。 + /// 参数是命令的结果。 + /// ///
public event Func CommandExecuted { @@ -70,36 +74,34 @@ public event Func Log internal bool _isDisposed; /// - /// Represents all modules loaded within . + /// 获取所有加载的模块。 /// public IEnumerable Modules => _moduleDefs.Select(x => x); /// - /// Represents all commands loaded within . + /// 获取所有加载的命令。 /// public IEnumerable Commands => _moduleDefs.SelectMany(x => x.Commands); /// - /// Represents all loaded within . + /// 获取所有加载的类型读取器。 /// public ILookup TypeReaders => _typeReaders .SelectMany(x => x.Value.Select(y => new { y.Key, y.Value })) .ToLookup(x => x.Key, x => x.Value); /// - /// Initializes a new class. + /// 初始化一个 类的新实例。 /// public CommandService() : this(new CommandServiceConfig()) { } /// - /// Initializes a new class with the provided configuration. + /// 初始化一个 类的新实例。 /// - /// The configuration class. - /// - /// The cannot be set to . - /// + /// 命令服务的配置。 + /// 默认运行模式不能设置为 public CommandService(CommandServiceConfig config) { _caseSensitive = config.CaseSensitiveCommands; @@ -155,11 +157,11 @@ public CommandService(CommandServiceConfig config) #region Modules /// - /// Creates a new module builder. + /// 创建一个命令模块。 /// - /// The primary alias for the module. - /// The action delegate to build the module. - /// A task that represents the asynchronous operation for creating the module. + /// 模块的首要别名。 + /// 一个构建模块的委托。 + /// 一个表示异步操作的任务。任务结果包含构建的模块。 public async Task CreateModuleAsync(string primaryAlias, Action buildFunc) { await _moduleLock.WaitAsync().ConfigureAwait(false); @@ -177,40 +179,30 @@ public async Task CreateModuleAsync(string primaryAlias, Action - /// Add a command module from a . + /// 添加一个命令模块。 /// + /// 要添加的模块的类型。 + /// 用于依赖注入的服务提供程序;如果不使用依赖注入,则传递 null。 + /// 一个表示异步添加操作的任务。任务结果包含添加的模块。 + /// 此模块已经添加。 + /// 无法构建 ;可能提供了无效的类型。 /// - /// The following example registers the module MyModule to commandService. + /// 以下示例代码将模块 MyModule 注册到 commandService 中。 /// - /// await commandService.AddModuleAsync<MyModule>(serviceProvider); + /// await commandService.AddModuleAsync<MyModule>(serviceProvider); /// /// - /// The type of module. - /// The for your dependency injection solution if using one; otherwise, pass null. - /// This module has already been added. - /// - /// The fails to be built; an invalid type may have been provided. - /// - /// - /// A task that represents the asynchronous operation for adding the module. The task result contains the - /// built module. - /// - public Task AddModuleAsync(IServiceProvider services) => AddModuleAsync(typeof(T), services); + public Task AddModuleAsync(IServiceProvider? services) => AddModuleAsync(typeof(T), services); /// - /// Adds a command module from a . + /// 添加一个命令模块。 /// - /// The type of module. - /// The for your dependency injection solution if using one; otherwise, pass null . - /// This module has already been added. - /// - /// The fails to be built; an invalid type may have been provided. - /// - /// - /// A task that represents the asynchronous operation for adding the module. The task result contains the - /// built module. - /// - public async Task AddModuleAsync(Type type, IServiceProvider services) + /// 要添加的模块的类型。 + /// 用于依赖注入的服务提供程序;如果不使用依赖注入,则传递 null。 + /// 一个表示异步添加操作的任务。任务结果包含添加的模块。 + /// 此模块已经添加。 + /// 无法构建 ;可能提供了无效的类型。 + public async Task AddModuleAsync(Type type, IServiceProvider? services) { services ??= EmptyServiceProvider.Instance; await _moduleLock.WaitAsync().ConfigureAwait(false); @@ -237,15 +229,12 @@ public async Task AddModuleAsync(Type type, IServiceProvider service } /// - /// Add command modules from an . + /// 添加程序集内的所有命令模块。 /// - /// The containing command modules. - /// The for your dependency injection solution if using one; otherwise, pass null. - /// - /// A task that represents the asynchronous operation for adding the command modules. The task result - /// contains an enumerable collection of modules added. - /// - public async Task> AddModulesAsync(Assembly assembly, IServiceProvider services) + /// 要添加其所有模块的程序集。 + /// 用于依赖注入的服务提供程序;如果不使用依赖注入,则传递 null。 + /// 一个表示异步添加操作的任务。任务结果包含所有添加的模块。 + public async Task> AddModulesAsync(Assembly assembly, IServiceProvider? services) { services ??= EmptyServiceProvider.Instance; @@ -280,13 +269,10 @@ private ModuleInfo LoadModuleInternal(ModuleInfo module) } /// - /// Removes the command module. + /// 移除命令模块。 /// - /// The to be removed from the service. - /// - /// A task that represents the asynchronous removal operation. The task result contains a value that - /// indicates whether the is successfully removed. - /// + /// 要移除的模块。 + /// 一个表示异步删除操作的任务。如果任务结果为 true,则表示模块已成功删除,否则表示模块不存在。 public async Task RemoveModuleAsync(ModuleInfo module) { await _moduleLock.WaitAsync().ConfigureAwait(false); @@ -301,23 +287,17 @@ public async Task RemoveModuleAsync(ModuleInfo module) } /// - /// Removes the command module. + /// 移除命令模块。 /// - /// The of the module. - /// - /// A task that represents the asynchronous removal operation. The task result contains a value that - /// indicates whether the module is successfully removed. - /// + /// 要移除的模块的类型。 + /// 一个表示异步删除操作的任务。如果任务结果为 true,则表示模块已成功删除,否则表示模块不存在。 public Task RemoveModuleAsync() => RemoveModuleAsync(typeof(T)); /// - /// Removes the command module. + /// 移除命令模块。 /// - /// The of the module. - /// - /// A task that represents the asynchronous removal operation. The task result contains a value that - /// indicates whether the module is successfully removed. - /// + /// 要移除的模块的类型。 + /// 一个表示异步删除操作的任务。如果任务结果为 true,则表示模块已成功删除,否则表示模块不存在。 public async Task RemoveModuleAsync(Type type) { await _moduleLock.WaitAsync().ConfigureAwait(false); @@ -348,27 +328,25 @@ private bool RemoveModuleInternal(ModuleInfo module) #region Type Readers /// - /// Adds a custom to this for the supplied object - /// type. - /// If is a , a nullable will - /// also be added. - /// If a default exists for , a warning will be logged - /// and the default will be replaced. + /// 添加一个自定义的类型读取器。 /// - /// The object type to be read by the . - /// An instance of the to be added. + /// + /// 如果 是一个值类型,那么一个读取对应可空值类型的 也会被添加。
+ /// 如果 的默认 已经存在,那么会记录一个警告,默认的 将会被替换。 + ///
+ /// 要读取的对象类型。 + /// 要添加的类型读取器的实例。 public void AddTypeReader(TypeReader reader) => AddTypeReader(typeof(T), reader); /// - /// Adds a custom to this for the supplied object - /// type. - /// If is a , a nullable for the - /// value type will also be added. - /// If a default exists for , a warning will be logged and - /// the default will be replaced. + /// 添加一个自定义的类型读取器。 /// - /// A instance for the type to be read. - /// An instance of the to be added. + /// + /// 如果 是一个值类型,那么一个读取对应可空值类型的 也会被添加。
+ /// 如果 的默认 已经存在,那么会记录一个警告,默认的 将会被替换。 + ///
+ /// 要读取的对象类型。 + /// 要添加的类型读取器的实例。 public void AddTypeReader(Type type, TypeReader reader) { if (_defaultTypeReaders.ContainsKey(type)) @@ -382,32 +360,26 @@ public void AddTypeReader(Type type, TypeReader reader) } /// - /// Adds a custom to this for the supplied object - /// type. - /// If is a , a nullable will - /// also be added. + /// 添加一个自定义的类型读取器。 /// - /// The object type to be read by the . - /// An instance of the to be added. - /// - /// Defines whether the should replace the default one for - /// if it exists. - /// + /// + /// 如果 是一个值类型,那么一个读取对应可空值类型的 也会被添加。 + /// + /// 要读取的对象类型。 + /// 要添加的类型读取器的实例。 + /// 是否替换默认的 。 public void AddTypeReader(TypeReader reader, bool replaceDefault) => AddTypeReader(typeof(T), reader, replaceDefault); /// - /// Adds a custom to this for the supplied object - /// type. - /// If is a , a nullable for the - /// value type will also be added. + /// 添加一个自定义的类型读取器。 /// - /// A instance for the type to be read. - /// An instance of the to be added. - /// - /// Defines whether the should replace the default one for if - /// it exists. - /// + /// + /// 如果 是一个值类型,那么一个读取对应可空值类型的 也会被添加。 + /// + /// 要读取的对象类型。 + /// 要添加的类型读取器的实例。 + /// 是否替换默认的 。 public void AddTypeReader(Type type, TypeReader reader, bool replaceDefault) { if (replaceDefault && HasDefaultTypeReader(type)) @@ -429,16 +401,16 @@ public void AddTypeReader(Type type, TypeReader reader, bool replaceDefault) } /// - /// Removes a type reader from the list of type readers. + /// 移除一个类型读取器。 /// /// - /// Removing a from the will not dereference the from the loaded module/command instances. - /// You need to reload the modules for the changes to take effect. + /// 从命令服务中移除一个 不会从已加载的模块与命令的实例中取消引用 + /// 。要使更改生效,您需要重新加载模块。 /// - /// The type to remove the readers from. - /// true if the default readers for should be removed; otherwise false. - /// The removed collection of type readers. - /// true if the remove operation was successful; otherwise false. + /// 要移除的类型读取器所读取的对象类型。 + /// 是否要移除默认的 。 + /// 移除的类型读取器。 + /// 如果成功移除,则为 true;否则为 false public bool TryRemoveTypeReader(Type type, bool isDefaultTypeReader, out IDictionary readers) { readers = new Dictionary(); @@ -529,27 +501,27 @@ internal void AddNullableTypeReader(Type valueType, TypeReader valueTypeReader) #region Execution /// - /// Searches for the command. + /// 搜索命令。 /// - /// The context of the command. - /// The position of which the command starts at. - /// The result containing the matching commands. + /// 命令的上下文。 + /// 命令的位置。 + /// 命令搜索的结果。 public SearchResult Search(ICommandContext context, int argPos) => Search(context.Message.Content.Substring(argPos)); /// - /// Searches for the command. + /// 搜索命令。 /// - /// The context of the command. - /// The command string. - /// The result containing the matching commands. + /// 命令的上下文。 + /// 命令字符串。 + /// 命令搜索的结果。 public SearchResult Search(ICommandContext context, string input) => Search(input); /// - /// Searches for the command. + /// 搜索命令。 /// - /// The command string. - /// The result containing the matching commands. + /// 命令字符串。 + /// 命令搜索的结果。 public SearchResult Search(string input) { string searchInput = _caseSensitive ? input : input.ToLowerInvariant(); @@ -561,15 +533,14 @@ public SearchResult Search(string input) } /// - /// Executes the command. + /// 执行命令。 /// - /// The context of the command. - /// The position of which the command starts at. - /// The service to be used in the command's dependency injection. - /// The handling mode when multiple command matches are found. + /// 命令的上下文。 + /// 命令的位置。 + /// 要用于命令执行的依赖注入服务。 + /// 当匹配到多个命令时的处理模式。 /// - /// A task that represents the asynchronous execution operation. The task result contains the result of the - /// command execution. + /// 一个表示异步执行操作的任务。任务的结果包含执行的结果。 /// public Task ExecuteAsync(ICommandContext context, int argPos, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) @@ -581,15 +552,14 @@ public Task ExecuteAsync(ICommandContext context, int argPos, IServiceP } /// - /// Executes the command. + /// 执行命令。 /// - /// The context of the command. - /// The command string. - /// The service to be used in the command's dependency injection. - /// The handling mode when multiple command matches are found. + /// 命令的上下文。 + /// 命令字符串。 + /// 要用于命令执行的依赖注入服务。 + /// 当匹配到多个命令时的处理模式。 /// - /// A task that represents the asynchronous execution operation. The task result contains the result of the - /// command execution. + /// 一个表示异步执行操作的任务。任务的结果包含执行的结果。 /// public async Task ExecuteAsync(ICommandContext context, string input, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) @@ -659,14 +629,13 @@ private float CalculateScore(CommandMatch match, ParseResult parseResult) } /// - /// Validates and gets the best from a specified + /// 从指定的搜索结果中验证先决条件并获取最佳匹配。 /// - /// The SearchResult. - /// The context of the command. - /// The service provider to be used on the command's dependency injection. - /// The handling mode when multiple command matches are found. - /// A task that represents the asynchronous validation operation. The task result contains the result of the - /// command validation as a or a if no matches were found. + /// 要验证的搜索结果。 + /// 命令的上下文。 + /// 要用于命令验证与解析的依赖注入服务。 + /// 当匹配到多个命令时的处理模式。 + /// 一个表示异步操作的任务。任务的结果包含验证与最佳匹配的结果。 public async Task ValidateAndGetBestMatch(SearchResult matches, ICommandContext context, IServiceProvider provider, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) { diff --git a/src/Kook.Net.Commands/CommandServiceConfig.cs b/src/Kook.Net.Commands/CommandServiceConfig.cs index 2e0c171c..12ecaaa6 100644 --- a/src/Kook.Net.Commands/CommandServiceConfig.cs +++ b/src/Kook.Net.Commands/CommandServiceConfig.cs @@ -1,59 +1,68 @@ namespace Kook.Commands; /// -/// Represents a configuration class for . +/// 表示一个用于 的配置类。 /// public class CommandServiceConfig { /// - /// Gets or sets the default commands should have, if one is not specified on the - /// Command attribute or builder. + /// 获取或设置命令的默认运行模式,如果在命令属性或构建器上未指定运行模式,则使用此值。 /// + /// + /// 如需在命令上重写默认行为,请使用 属性。 + /// public RunMode DefaultRunMode { get; set; } = RunMode.Sync; /// - /// Gets or sets the that separates an argument with another. + /// 获取或设置用于分隔参数的字符。 /// public char SeparatorChar { get; set; } = ' '; /// - /// Gets or sets whether commands should be case-sensitive. + /// 获取或设置命令是否区分大小写。 /// public bool CaseSensitiveCommands { get; set; } = false; /// - /// Gets or sets the minimum log level severity that will be sent to the event. + /// 获取或设置将引发 事件的最低日志级别严重性。 /// public LogSeverity LogLevel { get; set; } = LogSeverity.Info; /// - /// Gets or sets whether commands should push exceptions up to the caller. + /// 获取或设置同步执行的命令是否应将异常传递给调用者。 /// + /// + /// 同步命令指的是其运行模式为 的命令。 + /// public bool ThrowOnError { get; set; } = true; /// - /// Collection of aliases for matching pairs of string delimiters. - /// The dictionary stores the opening delimiter as a key, and the matching closing delimiter as the value. - /// If no value is supplied will be used, which contains - /// many regional equivalents. - /// Only values that are specified in this map will be used as string delimiters, so if " is removed then - /// it won't be used. - /// If this map is set to null or empty, the default delimiter of " will be used. + /// 获取或设置用于匹配字符串定界符的别名集合。 /// + /// + /// 如果为更改此属性,则将使用默认的内置别名集合,这可能包含了许多地区和 Unicode + /// 符号中可视为开闭对的符号。也可以在此默认集合的基础上进行修改。如果设置为空字典,则会使用 " 作为默认定界符。 + /// /// - /// - /// QuotationMarkAliasMap = new Dictionary<char, char>() - /// { - /// {'\"', '\"' }, - /// {'“', '”' }, - /// {'「', '」' }, - /// } - /// + /// 以下示例重新设置了定界符所使用的开闭对: + /// + /// QuotationMarkAliasMap = new Dictionary<char, char>() + /// { + /// {'\"', '\"' }, + /// {'“', '”' }, + /// {'「', '」' }, + /// } + /// /// public Dictionary QuotationMarkAliasMap { get; set; } = QuotationAliasUtils.DefaultAliasMap; /// - /// Gets or sets a value that indicates whether extra parameters should be ignored. + /// 获取或设置默认情况下是否应忽略额外的参数。 /// + /// + /// 如果设置为 ,则默认情况下命令将忽略额外的参数。否则,将引发 + /// + /// 错误。如需在命令上重写默认行为,请使用 属性。 + /// public bool IgnoreExtraArgs { get; set; } = false; } diff --git a/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs b/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs index 40bc0132..3d35ccec 100644 --- a/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs +++ b/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs @@ -1,19 +1,17 @@ namespace Kook.Commands; /// -/// Provides extension methods for the class. +/// 提供用于 的扩展方法。 /// public static class CommandServiceExtensions { /// - /// Returns commands that can be executed under the current context. + /// 获取可以在当前上下文下执行的命令。 /// - /// The set of commands to be checked against. - /// The current command context. - /// The service provider used for dependency injection upon precondition check. - /// - /// A read-only collection of commands that can be executed under the current context. - /// + /// 要检查的命令。 + /// 当前命令上下文。 + /// 用于检查时的依赖注入的服务提供程序。 + /// 所提供的命令中可以在当前上下文下执行的所有命令。 public static async Task> GetExecutableCommandsAsync(this ICollection commands, ICommandContext context, IServiceProvider provider) { @@ -33,27 +31,23 @@ public static async Task> GetExecutableCommands } /// - /// Returns commands that can be executed under the current context. + /// 获取可以在当前上下文下执行的命令。 /// - /// The desired command service class to check against. - /// The current command context. - /// The service provider used for dependency injection upon precondition check. - /// - /// A read-only collection of commands that can be executed under the current context. - /// + /// 要检查的命令服务。 + /// 当前命令上下文。 + /// 用于检查时的依赖注入的服务提供程序。 + /// 可以在当前上下文下执行的所有命令。 public static Task> GetExecutableCommandsAsync(this CommandService commandService, ICommandContext context, IServiceProvider provider) => GetExecutableCommandsAsync(commandService.Commands.ToArray(), context, provider); /// - /// Returns commands that can be executed under the current context. + /// 获取可以在当前上下文下执行的命令。 /// - /// The module to be checked against. - /// The current command context. - /// The service provider used for dependency injection upon precondition check. - /// - /// A read-only collection of commands that can be executed under the current context. - /// + /// 要检查的模块。 + /// 当前命令上下文。 + /// 用于检查时的依赖注入的服务提供程序。 + /// 所提供的模块中可以在当前上下文下执行的所有命令。 public static async Task> GetExecutableCommandsAsync(this ModuleInfo module, ICommandContext context, IServiceProvider provider) { diff --git a/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs b/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs index 036d4d02..b4cc2e81 100644 --- a/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs +++ b/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs @@ -1,20 +1,20 @@ namespace Kook.Commands; /// -/// Provides extension methods for . +/// 提供用于 的扩展方法。 /// public static class IEnumerableExtensions { /// - /// Generates all possible combinations of elements from two collections and applies a specified function to each combination to produce a result. + /// 生成两个集合中所有可能的元素组合,并将指定的函数应用于每个组合以生成结果。 /// - /// The type of elements in the first collection. - /// The type of elements in the second collection. - /// The type of the results produced by the specified function. - /// The first collection of elements to use to generate the combinations. - /// The second collection of elements to use to generate the combinations. - /// The function to apply to each combination of elements to produce a result. - /// An of values generated by applying the specified function to each combination of elements. + /// 第一个集合中的元素类型。 + /// 第二个集合中的元素类型。 + /// 结果的类型。 + /// 用于生成组合的第一个元素集合。 + /// 用于生成组合的第二个元素集合。 + /// 用于生成结果的函数。 + /// 所有可能的元素组合的结果。 public static IEnumerable Permutate( this IEnumerable set, IEnumerable others, diff --git a/src/Kook.Net.Commands/Extensions/MessageExtensions.cs b/src/Kook.Net.Commands/Extensions/MessageExtensions.cs index 23459d10..f451bfb2 100644 --- a/src/Kook.Net.Commands/Extensions/MessageExtensions.cs +++ b/src/Kook.Net.Commands/Extensions/MessageExtensions.cs @@ -3,19 +3,17 @@ namespace Kook.Commands; /// -/// Provides extension methods for that relates to commands. +/// 提供用于 与命令相关的扩展方法。 /// public static class MessageExtensions { /// - /// Gets whether the message starts with the provided character. + /// 获取消息是否以提供的字符开头。 /// - /// The message to check against. - /// The char prefix. - /// References where the command starts. - /// - /// true if the message begins with the char ; otherwise false. - /// + /// 要检查的消息。 + /// 要检查的前导字符。 + /// 开始检查的位置。 + /// 如果消息以指定的字符开头,则为 true;否则为 false public static bool HasCharPrefix(this IUserMessage msg, char c, ref int argPos) { string text; @@ -51,8 +49,13 @@ public static bool HasCharPrefix(this IUserMessage msg, char c, ref int argPos) } /// - /// Gets whether the message starts with the provided string. + /// 获取消息是否以提供的字符串开头。 /// + /// 要检查的消息。 + /// 要检查的前导字符。 + /// 开始检查的位置。 + /// 字符串比较模式。 + /// 如果消息以指定的字符串开头,则为 true;否则为 false public static bool HasStringPrefix(this IUserMessage msg, string str, ref int argPos, StringComparison comparisonType = StringComparison.Ordinal) { @@ -89,8 +92,12 @@ public static bool HasStringPrefix(this IUserMessage msg, string str, } /// - /// Gets whether the message starts with the user's mention string. + /// 获取消息是否以提供的用户提及开头。 /// + /// 要检查的消息。 + /// 要检查的用户。 + /// 开始检查的位置。 + /// 如果消息以指定的用户提及开头,则为 true;否则为 false public static bool HasMentionPrefix(this IUserMessage msg, IUser user, ref int argPos) { string text; @@ -178,11 +185,11 @@ public static bool HasMentionPrefix(this IUserMessage msg, IUser user, ref int a } /// - /// Tries to expand the content of the card into a single string. + /// 尝试将卡片的内容展开为单个字符串。 /// - /// The message to expand the content of. - /// The expanded content of the card. - /// true if the content was successfully expanded; otherwise, false. + /// 要展开的消息。 + /// 展开的内容。 + /// 如果成功展开,则为 true;否则为 false public static bool TryExpandCardContent(this IUserMessage msg, [NotNullWhen(true)] out string? expandedContent) { diff --git a/src/Kook.Net.Commands/IModuleBase.cs b/src/Kook.Net.Commands/IModuleBase.cs index a2628d22..c95c0778 100644 --- a/src/Kook.Net.Commands/IModuleBase.cs +++ b/src/Kook.Net.Commands/IModuleBase.cs @@ -3,44 +3,46 @@ namespace Kook.Commands; /// -/// Represents a generic module base. +/// 表示一个通用的模块基类。 /// public interface IModuleBase { /// - /// Sets the context of this module base. + /// 设置此模块基类的上下文。 /// - /// The context to set. + /// 此模块基类的上下文。 void SetContext(ICommandContext context); /// - /// Executed asynchronously before a command is run in this module base. + /// 当此模块中的命令在运行之前异步执行。 /// - /// The command thats about to run. + /// 即将运行的命令。 + /// 一个表示异步操作的任务。 Task BeforeExecuteAsync(CommandInfo command); /// - /// Executed before a command is run in this module base. + /// 当此模块中的命令在运行之前执行。 /// - /// The command that's about to run. + /// 即将运行的命令。 void BeforeExecute(CommandInfo command); /// - /// Executed after a command is run in this module base. + /// 当此模块中的命令运行后执行。 /// - /// The command that ran. + /// 执行的命令。 void AfterExecute(CommandInfo command); /// - /// Executed asynchronously after a command is run in this module base. + /// 当此模块中的命令运行后异步执行。 /// - /// The command that's about to run. + /// 执行的命令。 + /// 一个表示异步操作的任务。 Task AfterExecuteAsync(CommandInfo command); /// - /// Executed when this module is building. + /// 当构建此模块时执行。 /// - /// The command service that is building this module. - /// The builder constructing this module. + /// 创建此模块的命令服务。 + /// 用于构建此模块的构建器。 void OnModuleBuilding(CommandService commandService, ModuleBuilder builder); } diff --git a/src/Kook.Net.Commands/Info/CommandInfo.cs b/src/Kook.Net.Commands/Info/CommandInfo.cs index d3bfcff2..53f6bea8 100644 --- a/src/Kook.Net.Commands/Info/CommandInfo.cs +++ b/src/Kook.Net.Commands/Info/CommandInfo.cs @@ -8,11 +8,10 @@ namespace Kook.Commands; /// -/// Provides the information of a command. +/// 表示一个命令的信息。 /// /// -/// This object contains the information of a command. This can include the module of the command, various -/// descriptions regarding the command, and its . +/// 此对象包含命令的信息。这可能包括命令的模块、有关命令的各种描述以及执行模式等。 /// [DebuggerDisplay("{Name,nq}")] public class CommandInfo @@ -27,71 +26,69 @@ public class CommandInfo private readonly Func? _action; /// - /// Gets the module that the command belongs in. + /// 获取此命令所属的模块。 /// public ModuleInfo Module { get; } /// - /// Gets the name of the command. If none is set, the first alias is used. + /// 获取此命令的名称。如果未设置基本名称,则返回首要别名。 /// public string Name { get; } /// - /// Gets the summary of the command. + /// 获取此命令的摘要。 /// /// - /// This field returns the summary of the command. and can be - /// useful in help commands and various implementation that fetches details of the command for the user. + /// 此字段返回命令的摘要。 可以用于帮助命令中,为用户提供命令的详细信息。 /// public string? Summary { get; } /// - /// Gets the remarks of the command. + /// 获取此命令的备注。 /// /// - /// This field returns the summary of the command. and can be - /// useful in help commands and various implementation that fetches details of the command for the user. + /// 此字段返回命令的摘要。 可以用于帮助命令中,为用户提供命令的详细信息。 /// public string? Remarks { get; } /// - /// Gets the priority of the command. This is used when there are multiple overloads of the command. + /// 获取此命令的优先级。当命令匹配多个重载时,此优先级将用于确定要执行的重载。 /// + /// public int Priority { get; } /// - /// Indicates whether the command accepts a params [] for its - /// parameter. + /// 获取此命令是否可变数量的参数。 /// public bool HasVarArgs { get; } /// - /// Indicates whether extra arguments should be ignored for this command. + /// 获取此命令是否应忽略额外的参数。 /// public bool IgnoreExtraArgs { get; } /// - /// Gets the that is being used for the command. + /// 获取此命令的执行模式。 /// public RunMode RunMode { get; } /// - /// Gets a list of aliases defined by the of the command. + /// 获取此命令的所有别名。 /// public IReadOnlyList Aliases { get; } /// - /// Gets a list of information about the parameters of the command. + /// 获取此命令的所有参数的信息。 /// public IReadOnlyList Parameters { get; } /// - /// Gets a list of preconditions defined by the of the command. + /// 获取此命令的所有先决条件。 /// public IReadOnlyList Preconditions { get; } /// - /// Gets a list of attributes of the command. + /// 获取此命令的所有特性。 /// public IReadOnlyList Attributes { get; } @@ -128,11 +125,11 @@ internal CommandInfo(CommandBuilder builder, ModuleInfo module, CommandService s } /// - /// Checks the preconditions of the command. + /// 检查命令在指定的上下文中是否可以执行。 /// - /// The context of the command. - /// The services to be used for precondition checking. - /// A that indicates whether the precondition check was successful. + /// 命令的上下文。 + /// 用于检查的服务提供程序。 + /// 一个表示异步检查操作的任务。任务的结果包含先决条件的结果。 public async Task CheckPreconditionsAsync(ICommandContext context, IServiceProvider? services = null) { services ??= EmptyServiceProvider.Instance; @@ -174,14 +171,14 @@ async Task CheckGroups(IEnumerable pr } /// - /// Parses the arguments of the command. + /// 解析命令的参数。 /// - /// The context of the command. - /// The index to start parsing from. - /// The search result of the command. - /// The result of the precondition check. - /// The services to be used for parsing. - /// A that indicates whether the parsing was successful. + /// 命令执行上下文。 + /// 解析的起始索引。 + /// 命令搜索结果。 + /// 先决条件的检查结果。 + /// 用于解析的服务提供程序。 + /// 一个表示异步解析操作的任务。任务的结果包含解析的结果。 public async Task ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult? preconditionResult = null, IServiceProvider? services = null) { @@ -199,12 +196,12 @@ public async Task ParseAsync(ICommandContext context, int startInde } /// - /// Executes the command. + /// 执行命令。 /// - /// The context of the command. - /// The result of the parsing. - /// The services to be used for execution. - /// An that indicates whether the execution was successful. + /// 命令执行上下文。 + /// 命令的参数解析结果。 + /// 用于执行的服务提供程序。 + /// 一个表示异步执行操作的任务。任务的结果包含命令执行的结果。 public Task ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) { if (!parseResult.IsSuccess) @@ -230,13 +227,13 @@ public Task ExecuteAsync(ICommandContext context, ParseResult parseResu } /// - /// Executes the command. + /// 执行命令。 /// - /// The context of the command. - /// The arguments of the command. - /// The parameters of the command. - /// The services to be used for execution. - /// An that indicates whether the execution was successful. + /// 命令执行上下文。 + /// 命令的实参列表。 + /// 命令的形参列表。 + /// 用于执行的服务提供程序。 + /// 一个表示异步执行操作的任务。任务的结果包含命令执行的结果。 public async Task ExecuteAsync(ICommandContext context, IEnumerable argList, IEnumerable paramList, IServiceProvider services) { diff --git a/src/Kook.Net.Commands/Info/ModuleInfo.cs b/src/Kook.Net.Commands/Info/ModuleInfo.cs index fcc72332..e051b6d2 100644 --- a/src/Kook.Net.Commands/Info/ModuleInfo.cs +++ b/src/Kook.Net.Commands/Info/ModuleInfo.cs @@ -3,67 +3,67 @@ namespace Kook.Commands; /// -/// Provides the information of a module. +/// 表示一个模块的信息。 /// public class ModuleInfo { /// - /// Gets the command service associated with this module. + /// 获取与此模块关联的命令服务。 /// public CommandService Service { get; } /// - /// Gets the name of this module. + /// 获取此模块的名称。 /// public string? Name { get; } /// - /// Gets the summary of this module. + /// 获取此模块的摘要。 /// public string? Summary { get; } /// - /// Gets the remarks of this module. + /// 获取此模块的备注。 /// public string? Remarks { get; } /// - /// Gets the group name (main prefix) of this module. + /// 获取此模块的分组。 /// public string? Group { get; } /// - /// Gets a read-only list of aliases associated with this module. + /// 获取此模块的所有别名。 /// public IReadOnlyList Aliases { get; } /// - /// Gets a read-only list of commands associated with this module. + /// 获取此模块的所有命令。 /// public IReadOnlyList Commands { get; } /// - /// Gets a read-only list of preconditions that apply to this module. + /// 获取此模块的所有先决条件。 /// public IReadOnlyList Preconditions { get; } /// - /// Gets a read-only list of attributes that apply to this module. + /// 获取此模块的所有特性。 /// public IReadOnlyList Attributes { get; } /// - /// Gets a read-only list of submodules associated with this module. + /// 获取此模块的所有子模块。 /// public IReadOnlyList Submodules { get; } /// - /// Gets the parent module of this submodule if applicable. + /// 获取此模块的父模块。 /// public ModuleInfo? Parent { get; } /// - /// Gets a value that indicates whether this module is a submodule or not. + /// 获取此模块是否为子模块。 /// public bool IsSubmodule => Parent != null; diff --git a/src/Kook.Net.Commands/Info/ParameterInfo.cs b/src/Kook.Net.Commands/Info/ParameterInfo.cs index 7bf0f89c..556d9421 100644 --- a/src/Kook.Net.Commands/Info/ParameterInfo.cs +++ b/src/Kook.Net.Commands/Info/ParameterInfo.cs @@ -5,7 +5,7 @@ namespace Kook.Commands; /// -/// Provides the information of a parameter. +/// 表示一个参数的信息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ParameterInfo @@ -13,52 +13,52 @@ public class ParameterInfo private readonly TypeReader _reader; /// - /// Gets the command that associates with this parameter. + /// 获取此参数所属的命令。 /// public CommandInfo Command { get; } /// - /// Gets the name of this parameter. + /// 获取此参数的名称。 /// public string Name { get; } /// - /// Gets the summary of this parameter. + /// 获取此参数的摘要。 /// public string? Summary { get; } /// - /// Gets a value that indicates whether this parameter is optional or not. + /// 获取此参数是否为可选参数。 /// public bool IsOptional { get; } /// - /// Gets a value that indicates whether this parameter is a remainder parameter or not. + /// 获取此参数是否接收全部剩余参数。 /// public bool IsRemainder { get; } /// - /// Gets a value that indicates whether this parameter is a multiple parameter or not. + /// 获取此参数是否为多值参数。 /// public bool IsMultiple { get; } /// - /// Gets the type of the parameter. + /// 获取此参数的类型。 /// public Type? Type { get; } /// - /// Gets the default value for this optional parameter if applicable. + /// 获取此参数的默认值。 /// public object? DefaultValue { get; } /// - /// Gets a read-only list of precondition that apply to this parameter. + /// 获取此参数的所有先决条件。 /// public IReadOnlyList Preconditions { get; } /// - /// Gets a read-only list of attributes that apply to this parameter. + /// 获取此参数的所有特性。 /// public IReadOnlyList Attributes { get; } @@ -82,12 +82,12 @@ internal ParameterInfo(ParameterBuilder builder, CommandInfo command, CommandSer } /// - /// Checks the preconditions of this parameter. + /// 检查此参数是否满足其先决条件。 /// - /// The context of the command. - /// The argument that is being parsed. - /// The service provider that is used to resolve services. - /// A that indicates whether the precondition is successful or not. + /// 命令的上下文。 + /// 参数的值。 + /// 用于解析服务的服务提供程序。 + /// 一个表示异步检查操作的任务。任务的结果包含先决条件的结果。 public async Task CheckPreconditionsAsync(ICommandContext context, object? arg, IServiceProvider? services = null) { @@ -103,12 +103,12 @@ public async Task CheckPreconditionsAsync(ICommandContext co } /// - /// Parses the input string into the desired type. + /// 解析字符串输入为此参数目标类型的值。 /// - /// The context of the command. - /// The input string. - /// The service provider that is used to resolve services. - /// A that contains the parsing result. + /// 命令的上下文。 + /// 要解析的字符串输入。 + /// 用于解析服务的服务提供程序。 + /// 一个表示异步解析操作的任务。任务的结果包含参数解析的结果。 public async Task ParseAsync(ICommandContext context, string input, IServiceProvider? services = null) { diff --git a/src/Kook.Net.Commands/ModuleBase.cs b/src/Kook.Net.Commands/ModuleBase.cs index ac0c27f1..2ed57dce 100644 --- a/src/Kook.Net.Commands/ModuleBase.cs +++ b/src/Kook.Net.Commands/ModuleBase.cs @@ -3,43 +3,34 @@ namespace Kook.Commands; /// -/// Provides a base class for a command module to inherit from. +/// 表示一个模块基类。 /// public abstract class ModuleBase : ModuleBase; /// -/// Provides a base class for a command module to inherit from. +/// 表示一个模块基类。 /// -/// A class that implements . +/// 模块的上下文类型。 public abstract class ModuleBase : IModuleBase where T : class, ICommandContext { #region ModuleBase /// - /// The underlying context of the command. + /// 获取此命令的上下文。 /// - /// - /// - public T Context { get; private set; } = null!; // Set by SetContext + public T Context { get; private set; } = null!; // 将由 SetContext 方法设置。 /// - /// Sends a file to the source channel. + /// 发送文件到此命令消息所在的频道。 /// - /// - /// The file path of the file. - /// - /// - /// The name of the file. - /// - /// The type of the attachment. - /// - /// true if the source message will be quoted in this message; otherwise, false. - /// - /// - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// - /// The request options for this async request. + /// 文件的路径。 + /// 文件名。 + /// 文件的媒体类型。 + /// 是否引用源消息。 + /// 是否以临时消息的形式发送给命令调用者。如果设置为 true,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 protected virtual async Task> ReplyFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, bool isQuote = true, bool isEphemeral = false, RequestOptions? options = null) => @@ -49,22 +40,15 @@ await Context.Channel.SendFileAsync(path, filename, type, .ConfigureAwait(false); /// - /// Sends a file to the source channel. + /// 发送文件到此命令消息所在的频道。 /// - /// - /// Stream of the file to be sent. - /// - /// - /// The name of the file. - /// - /// The type of the attachment. - /// - /// true if the source message will be quoted in this message; otherwise, false. - /// - /// - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// - /// The request options for this async request. + /// 文件的流。 + /// 文件名。 + /// 文件的媒体类型。 + /// 是否引用源消息。 + /// 是否以临时消息的形式发送给命令调用者。如果设置为 true,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 protected virtual async Task> ReplyFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, bool isQuote = true, bool isEphemeral = false, RequestOptions? options = null) => @@ -74,16 +58,13 @@ await Context.Channel.SendFileAsync(stream, filename, type, .ConfigureAwait(false); /// - /// Sends a file to the source channel. + /// 发送文件到此命令消息所在的频道。 /// - /// The attachment containing the file. - /// - /// true if the source message will be quoted in this message; otherwise, false. - /// - /// - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// - /// The request options for this async request. + /// 文件的附件信息。 + /// 是否引用源消息。 + /// 是否以临时消息的形式发送给命令调用者。如果设置为 true,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 protected virtual async Task> ReplyFileAsync(FileAttachment attachment, bool isQuote = true, bool isEphemeral = false, RequestOptions? options = null) => await Context.Channel.SendFileAsync(attachment, @@ -92,38 +73,28 @@ await Context.Channel.SendFileAsync(attachment, .ConfigureAwait(false); /// - /// Sends a text message to the source channel. + /// 发送文本消息到此命令消息所在的频道。 /// - /// - /// Contents of the message. - /// - /// - /// true if the source message will be quoted in this message; otherwise, false. - /// - /// - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// - /// The request options for this async request. - protected virtual async Task> ReplyTextAsync(string message, bool isQuote = true, + /// 要发送的文本。 + /// 是否引用源消息。 + /// 是否以临时消息的形式发送给命令调用者。如果设置为 true,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 + protected virtual async Task> ReplyTextAsync(string text, bool isQuote = true, bool isEphemeral = false, RequestOptions? options = null) => - await Context.Channel.SendTextAsync(message, + await Context.Channel.SendTextAsync(text, isQuote ? new MessageReference(Context.Message.Id) : null, isEphemeral ? Context.User : null, options) .ConfigureAwait(false); /// - /// Sends a card message to the source channel. + /// 发送卡片消息到此命令消息所在的频道。 /// - /// - /// The cards to be sent. - /// - /// - /// true if the source message will be quoted in this message; otherwise, false. - /// - /// - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// - /// The request options for this async request. + /// 要发送的卡片。 + /// 是否引用源消息。 + /// 是否以临时消息的形式发送给命令调用者。如果设置为 true,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 protected virtual async Task> ReplyCardsAsync(IEnumerable cards, bool isQuote = true, bool isEphemeral = false, RequestOptions? options = null) => await Context.Channel.SendCardsAsync(cards, @@ -132,18 +103,13 @@ await Context.Channel.SendCardsAsync(cards, .ConfigureAwait(false); /// - /// Sends a card message to the source channel. + /// 发送卡片消息到此命令消息所在的频道。 /// - /// - /// The card to be sent. - /// - /// - /// true if the source message will be quoted in this message; otherwise, false. - /// - /// - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// - /// The request options for this async request. + /// 要发送的卡片。 + /// 是否引用源消息。 + /// 是否以临时消息的形式发送给命令调用者。如果设置为 true,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 protected virtual async Task> ReplyCardAsync(ICard card, bool isQuote = true, bool isEphemeral = false, RequestOptions? options = null) => await Context.Channel.SendCardAsync(card, @@ -151,39 +117,23 @@ await Context.Channel.SendCardAsync(card, isEphemeral ? Context.User : null, options) .ConfigureAwait(false); - /// - /// The method to execute asynchronously before executing the command. - /// - /// The of the command to be executed. + /// protected virtual Task BeforeExecuteAsync(CommandInfo command) => Task.CompletedTask; - /// - /// The method to execute before executing the command. - /// - /// The of the command to be executed. + /// protected virtual void BeforeExecute(CommandInfo command) { } - /// - /// The method to execute asynchronously after executing the command. - /// - /// The of the command to be executed. + /// protected virtual Task AfterExecuteAsync(CommandInfo command) => Task.CompletedTask; - /// - /// The method to execute after executing the command. - /// - /// The of the command to be executed. + /// protected virtual void AfterExecute(CommandInfo command) { } - /// - /// The method to execute when building the module. - /// - /// The used to create the module. - /// The builder used to build the module. + /// protected virtual void OnModuleBuilding(CommandService commandService, ModuleBuilder builder) { } diff --git a/src/Kook.Net.Commands/MultiMatchHandling.cs b/src/Kook.Net.Commands/MultiMatchHandling.cs index 50393d1e..c9c8ea40 100644 --- a/src/Kook.Net.Commands/MultiMatchHandling.cs +++ b/src/Kook.Net.Commands/MultiMatchHandling.cs @@ -1,13 +1,17 @@ namespace Kook.Commands; /// -/// Specifies the behavior when multiple matches are found during the command parsing stage. +/// 表示在命令解析阶段匹配到多个结果时的行为。 /// public enum MultiMatchHandling { - /// Indicates that when multiple results are found, an exception should be thrown. + /// + /// 当匹配到多个结果时引发异常。 + /// Exception, - /// Indicates that when multiple results are found, the best result should be chosen. + /// + /// 当匹配到多个结果时选择最佳匹配。 + /// Best } diff --git a/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs b/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs index df5f2808..d7236b68 100644 --- a/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs @@ -3,15 +3,9 @@ namespace Kook.Commands; /// -/// A for parsing objects implementing . +/// 表示一个用于解析字符串到实现了 的对象的类型读取器。 /// -/// -/// This is shipped with Kook.Net and is used by default to parse any -/// implemented object within a command. The TypeReader will attempt to first parse the -/// input by mention, then the identifier, then by name; the highest candidate will be chosen as the -/// final output; otherwise, an erroneous is returned. -/// -/// The type to be checked; must implement . +/// 要解析为的频道类型。 public class ChannelTypeReader : TypeReader where T : class, IChannel { diff --git a/src/Kook.Net.Commands/Readers/MessageTypeReader.cs b/src/Kook.Net.Commands/Readers/MessageTypeReader.cs index b5a76870..5fa3a704 100644 --- a/src/Kook.Net.Commands/Readers/MessageTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/MessageTypeReader.cs @@ -1,9 +1,9 @@ namespace Kook.Commands; /// -/// A for parsing objects implementing . +/// 表示一个用于解析实现了 的对象的类型读取器。 /// -/// The type to be checked; must implement . +/// 要解析为的消息类型。 public class MessageTypeReader : TypeReader where T : class, IMessage { diff --git a/src/Kook.Net.Commands/Readers/RoleTypeReader.cs b/src/Kook.Net.Commands/Readers/RoleTypeReader.cs index 59068865..caabe7f9 100644 --- a/src/Kook.Net.Commands/Readers/RoleTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/RoleTypeReader.cs @@ -3,9 +3,9 @@ namespace Kook.Commands; /// -/// A for parsing objects implementing . +/// 表示一个用于解析实现了 的对象的类型读取器。 /// -/// The type to be checked; must implement . +/// 要解析为的角色类型。 public class RoleTypeReader : TypeReader where T : class, IRole { diff --git a/src/Kook.Net.Commands/Readers/TypeReader.cs b/src/Kook.Net.Commands/Readers/TypeReader.cs index f08363e1..f007b188 100644 --- a/src/Kook.Net.Commands/Readers/TypeReader.cs +++ b/src/Kook.Net.Commands/Readers/TypeReader.cs @@ -1,18 +1,16 @@ namespace Kook.Commands; /// -/// Defines a reader class that parses user input into a specified type. +/// 表示一个将用户的字符串输入解析为指定类型的类型读取器基类。 /// public abstract class TypeReader { /// - /// Attempts to parse the into the desired type. + /// 尝试将字符串输入解析为指定类型。 /// - /// The context of the command. - /// The raw input of the command. - /// The service collection used for dependency injection. - /// - /// A task that represents the asynchronous parsing operation. The task result contains the parsing result. - /// + /// 命令执行上下文。 + /// 要解析的字符串输入。 + /// 依赖注入服务容器。 + /// 一个表示异步解析操作的任务。任务的结果包含解析的结果。 public abstract Task ReadAsync(ICommandContext context, string input, IServiceProvider services); } diff --git a/src/Kook.Net.Commands/Readers/UserTypeReader.cs b/src/Kook.Net.Commands/Readers/UserTypeReader.cs index c6b38bd3..b4c499b5 100644 --- a/src/Kook.Net.Commands/Readers/UserTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/UserTypeReader.cs @@ -4,9 +4,9 @@ namespace Kook.Commands; /// -/// A for parsing objects implementing . +/// 表示一个用于解析实现了 的对象的类型读取器。 /// -/// The type to be checked; must implement . +/// 要解析为的用户类型。 public class UserTypeReader : TypeReader where T : class, IUser { diff --git a/src/Kook.Net.Commands/Results/ExecuteResult.cs b/src/Kook.Net.Commands/Results/ExecuteResult.cs index b16626d5..43f5a5cb 100644 --- a/src/Kook.Net.Commands/Results/ExecuteResult.cs +++ b/src/Kook.Net.Commands/Results/ExecuteResult.cs @@ -3,13 +3,13 @@ namespace Kook.Commands; /// -/// Contains information of the command's overall execution result. +/// 表示一个命令的整体执行结果的信息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct ExecuteResult : IResult { /// - /// Gets the exception that may have occurred during the command execution. + /// 获取在命令执行期间发生的异常,如果没有异常则为 null。 /// public Exception? Exception { get; } @@ -30,54 +30,38 @@ private ExecuteResult(Exception? exception, CommandError? error, string? errorRe } /// - /// Initializes a new with no error, indicating a successful execution. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的执行。 /// - /// - /// A that does not contain any errors. - /// + /// 一个表示执行成功的 public static ExecuteResult FromSuccess() => new(null, null, null); /// - /// Initializes a new with a specified and its - /// reason, indicating an unsuccessful execution. + /// 初始化一个包含指定错误类型和原因的 结构的新实例,表示一个失败的执行。 /// - /// The type of error. - /// The reason behind the error. - /// - /// A that contains a and reason. - /// + /// 错误类型。 + /// 错误原因。 + /// 一个表示执行失败的 public static ExecuteResult FromError(CommandError error, string reason) => new(null, error, reason); /// - /// Initializes a new with a specified exception, indicating an unsuccessful - /// execution. + /// 初始化一个包含指定异常的 结构的新实例,表示一个失败的执行。 /// - /// The exception that caused the command execution to fail. + /// 导致执行失败的异常。 /// - /// A that contains the exception that caused the unsuccessful execution, along - /// with a of type Exception as well as the exception message as the - /// reason. + /// 一个包含导致执行失败的异常的 ,其错误类型为 + /// ,原因为异常消息。 /// public static ExecuteResult FromError(Exception? ex) => new(ex, CommandError.Exception, ex?.Message); /// - /// Initializes a new with a specified result; this may or may not be an - /// successful execution depending on the and - /// specified. + /// 初始化一个包含指定结果的 结构的新实例,根据指定的 和 + /// ,这可能是一个成功的执行,也可能是一个失败的执行。 /// - /// The result to inherit from. - /// - /// A that inherits the error type and reason. - /// + /// 要包装的结果。 + /// 一个表示执行结果的 ,错误类型和原因与 相同。 public static ExecuteResult FromError(IResult result) => new(null, result.Error, result.ErrorReason); - /// - /// Gets a string that indicates the execution result. - /// - /// - /// Success if is true; otherwise ": - /// ". - /// + /// public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; diff --git a/src/Kook.Net.Commands/Results/IResult.cs b/src/Kook.Net.Commands/Results/IResult.cs index d35e1d85..5173722d 100644 --- a/src/Kook.Net.Commands/Results/IResult.cs +++ b/src/Kook.Net.Commands/Results/IResult.cs @@ -1,32 +1,22 @@ namespace Kook.Commands; /// -/// Contains information of the result related to a command. +/// 表示一个有关命令的结果的信息。 /// public interface IResult { /// - /// Describes the error type that may have occurred during the operation. + /// 获取在命令执行期间发生的异常信息,如果没有异常则为 null。 /// - /// - /// A indicating the type of error that may have occurred during the operation; - /// null if the operation was successful. - /// CommandError? Error { get; } /// - /// Describes the reason for the error. + /// 获取在命令执行期间发生的异常的原因,如果没有异常则为 null。 /// - /// - /// A string containing the error reason. - /// string? ErrorReason { get; } /// - /// Indicates whether the operation was successful or not. + /// 获取命令执行的结果是否为成功。 /// - /// - /// true if the result is positive; otherwise false. - /// bool IsSuccess { get; } } diff --git a/src/Kook.Net.Commands/Results/MatchResult.cs b/src/Kook.Net.Commands/Results/MatchResult.cs index f35b6ea1..7f6ea31b 100644 --- a/src/Kook.Net.Commands/Results/MatchResult.cs +++ b/src/Kook.Net.Commands/Results/MatchResult.cs @@ -3,18 +3,18 @@ namespace Kook.Commands; /// -/// Represents the match result of a command. +/// 表示一个命令的匹配结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class MatchResult : IResult { /// - /// Gets the command that may have matched during the command execution. + /// 获取在命令执行期间可能与输入文本匹配的命令。 /// public CommandMatch? Match { get; } /// - /// Gets on which pipeline stage the command may have matched or failed. + /// 获取命令在执行工作流中的阶段。 /// public IResult? Pipeline { get; } @@ -36,44 +36,44 @@ private MatchResult(CommandMatch? match, IResult? pipeline, CommandError? error, } /// - /// Creates a successful match result. + /// 初始化一个不包含任何错误的 类的新实例,表示一个成功的匹配。 /// - /// The command that matched. - /// The pipeline stage on which the command matched. - /// The match result. + /// 命令匹配信息。 + /// 命令执行工作流中的阶段。 + /// 一个表示匹配成功的 public static MatchResult FromSuccess(CommandMatch match, IResult pipeline) => new(match, pipeline, null, null); /// - /// Creates a failed match result. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的匹配。 /// - /// The error that occurred. - /// The reason for the error. - /// The match result. + /// 命令匹配失败的类型。 + /// 命令匹配失败的原因。 + /// 一个表示匹配失败的 public static MatchResult FromError(CommandError error, string reason) => new(null, null, error, reason); /// - /// Creates a failed match result. + /// 初始化一个包含指定异常的 类的新实例,表示一个失败的匹配。 /// - /// The exception that occurred. - /// The match result. + /// 导致匹配失败的异常。 + /// 一个表示匹配失败的 public static MatchResult FromError(Exception ex) => FromError(CommandError.Exception, ex.Message); /// - /// Creates a failed match result. + /// 初始化一个包含指定失败结果的 类的新实例,表示一个失败的匹配。 /// - /// The result that failed. - /// The match result. + /// 失败的结果。 + /// 一个表示匹配失败的 public static MatchResult FromError(IResult result) => new(null, null, result.Error, result.ErrorReason); /// - /// Creates a failed match result. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的匹配。 /// - /// The pipeline stage on which the command failed. - /// The error that occurred. - /// The reason for the error. - /// The match result. + /// 命令执行工作流中的阶段。 + /// 错误类型。 + /// 错误原因。 + /// 一个表示匹配失败的 public static MatchResult FromError(IResult pipeline, CommandError error, string reason) => new(null, pipeline, error, reason); diff --git a/src/Kook.Net.Commands/Results/ParseResult.cs b/src/Kook.Net.Commands/Results/ParseResult.cs index 1b3be29a..61041eb7 100644 --- a/src/Kook.Net.Commands/Results/ParseResult.cs +++ b/src/Kook.Net.Commands/Results/ParseResult.cs @@ -3,18 +3,18 @@ namespace Kook.Commands; /// -/// Contains information for the parsing result from the command service's parser. +/// 表示一个命令的解析结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct ParseResult : IResult { /// - /// Gets a read-only collection containing the parsed argument values. + /// 获取所有实参解析结果。 /// public IReadOnlyList ArgValues { get; } /// - /// Gets a read-only collection containing the parsed parameter values. + /// 获取所有形参解析结果。 /// public IReadOnlyList ParamValues { get; } @@ -25,12 +25,8 @@ public struct ParseResult : IResult public string? ErrorReason { get; } /// - /// Provides information about the parameter that caused the parsing error. + /// 获取在解析过程中导致解析错误的参数信息。 /// - /// - /// A indicating the parameter info of the error that may have occurred during parsing; - /// null if the parsing was successful or the parsing error is not specific to a single parameter. - /// public ParameterInfo? ErrorParameter { get; } /// @@ -47,11 +43,11 @@ private ParseResult(IReadOnlyList argValues, IReadOnlyList - /// Creates a successful parsing result. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的解析。 /// - /// The parsed argument values. - /// The parsed parameter values. - /// The parsing result. + /// 实参解析结果。 + /// 形参解析结果。 + /// 一个表示匹配成功的 public static ParseResult FromSuccess(IReadOnlyList argValues, IReadOnlyList paramValues) { if (argValues.Any(x => x.Values.Count > 1)) @@ -62,11 +58,11 @@ public static ParseResult FromSuccess(IReadOnlyList argValues, } /// - /// Creates a successful parsing result. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的解析。 /// - /// The parsed argument values. - /// The parsed parameter values. - /// The parsing result. + /// 实参解析结果。 + /// 形参解析结果。 + /// 一个表示匹配成功的 public static ParseResult FromSuccess(IReadOnlyList argValues, IReadOnlyList paramValues) { TypeReaderResult[] argList = [..argValues.Select(TypeReaderResult.FromSuccess)]; @@ -75,44 +71,44 @@ public static ParseResult FromSuccess(IReadOnlyList argValues, } /// - /// Creates a failed parsing result. + /// 初始化一个包含指定错误类型和原因的 结构的新实例,表示一个失败的匹配。 /// - /// The error that occurred. - /// The reason for the error. - /// The parsing result. + /// 命令匹配失败的类型。 + /// 参数解析失败的原因。 + /// 一个表示解析失败的 public static ParseResult FromError(CommandError error, string reason) => new([], [], error, reason, null); /// - /// Creates a failed parsing result. + /// 初始化一个包含指定错误类型和原因的 结构的新实例,表示一个失败的匹配。 /// - /// The error that occurred. - /// The reason for the error. - /// The parameter info of the error that may have occurred during parsing. - /// The parsing result. + /// 命令匹配失败的类型。 + /// 参数解析失败的原因。 + /// 导致解析失败的参数信息。 + /// 一个表示解析失败的 public static ParseResult FromError(CommandError error, string reason, ParameterInfo parameterInfo) => new([], [], error, reason, parameterInfo); /// - /// Creates a failed parsing result. + /// 初始化一个包含指定异常的 结构的新实例,表示一个失败的匹配。 /// - /// The exception that occurred. - /// The parsing result. + /// 导致匹配失败的异常。 + /// 一个表示匹配失败的 public static ParseResult FromError(Exception ex) => FromError(CommandError.Exception, ex.Message); /// - /// Creates a failed parsing result. + /// 初始化一个包含指定异常的 结构的新实例,表示一个失败的匹配。 /// - /// The result that contains the error. - /// The parsing result. + /// 失败的结果。 + /// 一个表示匹配失败的 public static ParseResult FromError(IResult result) => new([], [], result.Error, result.ErrorReason, null); /// - /// Creates a failed parsing result. + /// 初始化一个包含指定异常的 结构的新实例,表示一个失败的匹配。 /// - /// The result that contains the error. - /// The parameter info of the error that may have occurred during parsing. - /// The parsing result. + /// 失败的结果。 + /// 导致解析失败的参数信息。 + /// 一个表示匹配失败的 public static ParseResult FromError(IResult result, ParameterInfo parameterInfo) => new([], [], result.Error, result.ErrorReason, parameterInfo); diff --git a/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs b/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs index b50a8fd3..a4aa3148 100644 --- a/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs +++ b/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs @@ -3,22 +3,22 @@ namespace Kook.Commands; /// -/// Represents the result of a grouped precondition check. +/// 表示一个分组的先决条件检查结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PreconditionGroupResult : PreconditionResult { /// - /// Gets the results of the precondition checks. + /// 获取先决条件检查的结果。 /// public IReadOnlyCollection PreconditionResults { get; } /// - /// Creates a new with the specified error, reason, and precondition results. + /// 初始化一个包含指定错误、原因和先决条件检查结果的 类的新实例。 /// - /// The error that occurred. - /// The reason for the error. - /// The results of the precondition checks. + /// 错误类型。 + /// 错误原因。 + /// 先决条件检查结果。 protected PreconditionGroupResult(CommandError? error, string? errorReason, ICollection preconditions) : base(error, errorReason) { @@ -26,28 +26,32 @@ protected PreconditionGroupResult(CommandError? error, string? errorReason, ICol } /// - /// Returns a with no errors. + /// 初始化一个不包含任何错误的 类的新实例,表示一个成功的先决条件检查。 /// + /// 一个表示先决条件检查成功的 public static new PreconditionGroupResult FromSuccess() => new(null, null, []); /// - /// Returns a with the reason and precondition results. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的先决条件检查。 /// - /// The reason for the error. - /// The results of the precondition checks. + /// 错误原因。 + /// 先决条件检查结果。 + /// 一个表示先决条件检查失败的 public static PreconditionGroupResult FromError(string reason, ICollection preconditions) => new(CommandError.UnmetPrecondition, reason, preconditions); /// - /// Returns a with an exception. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的先决条件检查。 /// - /// The exception that occurred. + /// 导致先决条件检查失败的异常。 + /// 一个表示先决条件检查失败的 public static new PreconditionGroupResult FromError(Exception ex) => new(CommandError.Exception, ex.Message, []); /// - /// Returns a with the specified result. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的先决条件检查。 /// - /// The result of failure. + /// 包含错误类型和原因的结果。 + /// 一个表示先决条件检查失败的 public static new PreconditionGroupResult FromError(IResult result) => new(result.Error, result.ErrorReason, []); //needed? /// diff --git a/src/Kook.Net.Commands/Results/PreconditionResult.cs b/src/Kook.Net.Commands/Results/PreconditionResult.cs index 8cd72934..a8b6e66e 100644 --- a/src/Kook.Net.Commands/Results/PreconditionResult.cs +++ b/src/Kook.Net.Commands/Results/PreconditionResult.cs @@ -3,7 +3,7 @@ namespace Kook.Commands; /// -/// Represents a result type for command preconditions. +/// 表示一个命令的先决条件检查结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PreconditionResult : IResult @@ -18,11 +18,10 @@ public class PreconditionResult : IResult public bool IsSuccess => !Error.HasValue; /// - /// Initializes a new class with the command type - /// and reason. + /// 初始化一个包含指定错误类型和原因的 类的新实例。 /// - /// The type of failure. - /// The reason of failure. + /// 错误类型。 + /// 错误原因。 protected PreconditionResult(CommandError? error, string? errorReason) { Error = error; @@ -30,32 +29,33 @@ protected PreconditionResult(CommandError? error, string? errorReason) } /// - /// Returns a with no errors. + /// 初始化一个不包含任何错误的 类的新实例,表示一个成功的先决条件检查。 /// + /// 一个表示先决条件检查成功的 public static PreconditionResult FromSuccess() => new(null, null); /// - /// Returns a with and the - /// specified reason. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的先决条件检查。 /// - /// The reason of failure. + /// 错误原因。 + /// 一个表示先决条件检查失败的 public static PreconditionResult FromError(string reason) => new(CommandError.UnmetPrecondition, reason); /// - /// Returns a with an exception. + /// 初始化一个包含指定错误类型和原因的 类的新实例,表示一个失败的先决条件检查。 /// - /// The exception that occurred. + /// 导致先决条件检查失败的异常。 + /// 一个表示先决条件检查失败的 public static PreconditionResult FromError(Exception ex) => new(CommandError.Exception, ex.Message); /// - /// Returns a with the specified type. + /// 初始化一个包含指定结果的 类的新实例,表示一个失败的先决条件检查。 /// - /// The result of failure. + /// 要包装的结果。 + /// 一个表示先决条件检查失败的 public static PreconditionResult FromError(IResult result) => new(result.Error, result.ErrorReason); - /// - /// Returns a string indicating whether the is successful. - /// + /// public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; diff --git a/src/Kook.Net.Commands/Results/RuntimeResult.cs b/src/Kook.Net.Commands/Results/RuntimeResult.cs index 39b98069..e0c94405 100644 --- a/src/Kook.Net.Commands/Results/RuntimeResult.cs +++ b/src/Kook.Net.Commands/Results/RuntimeResult.cs @@ -3,16 +3,16 @@ namespace Kook.Commands; /// -/// Represents the runtime result of a command execution. +/// 表示命令执行的运行时结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public abstract class RuntimeResult : IResult { /// - /// Initializes a new class with the type of error and reason. + /// 初始化一个包含指定错误类型和原因的 类的新实例。 /// - /// The type of failure, or null if none. - /// The reason of failure. + /// 错误类型。 + /// 错误原因。 protected RuntimeResult(CommandError? error, string reason) { Error = error; @@ -22,7 +22,9 @@ protected RuntimeResult(CommandError? error, string reason) /// public CommandError? Error { get; } - /// Describes the execution reason or result. + /// + /// 获取错误原因。 + /// public string Reason { get; } /// diff --git a/src/Kook.Net.Commands/Results/SearchResult.cs b/src/Kook.Net.Commands/Results/SearchResult.cs index 8872d406..108078b1 100644 --- a/src/Kook.Net.Commands/Results/SearchResult.cs +++ b/src/Kook.Net.Commands/Results/SearchResult.cs @@ -3,18 +3,18 @@ namespace Kook.Commands; /// -/// Represents the result of a command search. +/// 表示一个命令搜索的结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct SearchResult : IResult { /// - /// Gets the text that was searched in. + /// 获取用于搜索的文本。 /// public string? Text { get; } /// - /// Gets the commands that were found. + /// 获取所有搜索到的命令。 /// public IReadOnlyList Commands { get; } @@ -36,31 +36,34 @@ private SearchResult(string? text, IReadOnlyList commands, Command } /// - /// Returns a with no errors. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的搜索。 /// - /// The text that was searched in. - /// The commands that were found. + /// 用于搜索的文本。 + /// 搜索到的命令。 + /// 一个表示搜索成功的 public static SearchResult FromSuccess(string text, IReadOnlyList commands) => new(text, commands, null, null); /// - /// Returns a with a . + /// 初始化一个包含指定错误类型和原因的 结构的新实例,表示一个失败的搜索。 /// - /// The type of failure. - /// The reason of failure. - /// + /// 搜索失败的类型。 + /// 搜索失败的原因。 + /// 一个表示搜索失败的 public static SearchResult FromError(CommandError error, string reason) => new(null, [], error, reason); /// - /// Returns a with an exception. + /// 初始化一个包含指定异常的 结构的新实例,表示一个失败的搜索。 /// - /// The exception that occurred. + /// 导致搜索失败的异常。 + /// 一个表示搜索失败的 public static SearchResult FromError(Exception ex) => FromError(CommandError.Exception, ex.Message); /// - /// Returns a with the specified type. + /// 初始化一个包含指定结果的 结构的新实例,表示一个失败的搜索。 /// - /// The result of failure. + /// 失败的结果。 + /// 一个表示搜索失败的 public static SearchResult FromError(IResult result) => new(null, [], result.Error, result.ErrorReason); /// diff --git a/src/Kook.Net.Commands/Results/TypeReaderResult.cs b/src/Kook.Net.Commands/Results/TypeReaderResult.cs index ec0854ca..4ebcccbb 100644 --- a/src/Kook.Net.Commands/Results/TypeReaderResult.cs +++ b/src/Kook.Net.Commands/Results/TypeReaderResult.cs @@ -4,26 +4,26 @@ namespace Kook.Commands; /// -/// Represents a parsing result of a type reader. +/// 表示一个类型读取器的解析值。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct TypeReaderValue { /// - /// Gets the parsed value. + /// 获取解析的值。 /// public object? Value { get; } /// - /// Gets the confidence score of the parsing. + /// 获取解析的置信度分数。 /// public float Score { get; } /// - /// Initializes a new instance of the struct. + /// 齿梳化一个包含解析值和置信度分数的 结构的新实例。 /// - /// The parsed value. - /// The confidence score of the parsing. + /// 解析的值。 + /// 解析的置信度分数。 public TypeReaderValue(object? value, float score) { Value = value; @@ -37,13 +37,13 @@ public TypeReaderValue(object? value, float score) } /// -/// Represents a parsing result of a type reader. +/// 表示一个类型读取器的解析结果。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct TypeReaderResult : IResult { /// - /// Gets the parsed values. + /// 获取解析的值。 /// public IReadOnlyCollection Values { get; } @@ -56,7 +56,10 @@ public struct TypeReaderResult : IResult /// public bool IsSuccess => !Error.HasValue; - /// TypeReaderResult was not successful. + /// + /// 获取最佳匹配的解析值。 + /// + /// 解析失败。 public object? BestMatch => IsSuccess ? Values?.MaxBy(v => v.Score).Value : throw new InvalidOperationException("TypeReaderResult was not successful."); @@ -69,42 +72,48 @@ private TypeReaderResult(IReadOnlyCollection values, CommandErr } /// - /// Returns a with no errors. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的解析。 /// - /// The parsed value. + /// 解析的值。 + /// 一个表示解析成功的 public static TypeReaderResult FromSuccess(object? value) => new(ImmutableArray.Create(new TypeReaderValue(value, 1.0f)), null, null); /// - /// Returns a with no errors. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的解析。 /// - /// The parsed value. + /// 解析的值。 + /// 一个表示解析成功的 public static TypeReaderResult FromSuccess(TypeReaderValue value) => new(ImmutableArray.Create(value), null, null); /// - /// Returns a with no errors. + /// 初始化一个不包含任何错误的 结构的新实例,表示一个成功的解析。 /// - /// The parsed values. + /// 解析的值。 + /// 一个表示解析成功的 public static TypeReaderResult FromSuccess(IReadOnlyCollection values) => new(values, null, null); /// - /// Returns a with a specified error. + /// 初始化一个包含指定错误类型和原因的 结构的新实例,表示一个失败的解析。 /// - /// The error. - /// The reason for the error. + /// 错误类型。 + /// 错误原因。 + /// 一个表示解析失败的 public static TypeReaderResult FromError(CommandError error, string reason) => new([], error, reason); /// - /// Returns a with an exception. + /// 初始化一个包含指定异常的 结构的新实例,表示一个失败的解析。 /// - /// The exception that occurred. + /// 导致解析失败的异常。 + /// 一个表示解析失败的 public static TypeReaderResult FromError(Exception ex) => FromError(CommandError.Exception, ex.Message); /// - /// Returns a with a specified result. + /// 初始化一个包含指定结果的 结构的新实例,表示一个失败的解析。 /// - /// The result. + /// 要包装的结果。 + /// 一个表示解析失败的 public static TypeReaderResult FromError(IResult result) => new([], result.Error, result.ErrorReason); /// diff --git a/src/Kook.Net.Commands/RunMode.cs b/src/Kook.Net.Commands/RunMode.cs index 7bb95f9b..c3f3ac4e 100644 --- a/src/Kook.Net.Commands/RunMode.cs +++ b/src/Kook.Net.Commands/RunMode.cs @@ -1,24 +1,22 @@ namespace Kook.Commands; /// -/// Specifies the behavior of the command execution workflow. +/// 表示命令执行工作流的行为。 /// -/// -/// public enum RunMode { /// - /// The default behavior set in . + /// 使用在 中设置的默认行为。 /// Default, /// - /// Executes the command on the same thread as gateway one. + /// 在与网关线程相同的线程上执行命令。 /// Sync, /// - /// Executes the command on a different thread from the gateway one. + /// 在与网关线程不同的线程上执行命令。 /// Async } diff --git a/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs b/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs index 5788f643..e3f962fc 100644 --- a/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs +++ b/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs @@ -1,16 +1,14 @@ namespace Kook.Commands; /// -/// Utility class which contains the default matching pairs of quotation marks for CommandServiceConfig +/// 包含默认的匹配引号对的帮助类,用于 。 /// internal static class QuotationAliasUtils { /// - /// A default map of open-close pairs of quotation marks. - /// Contains many regional and Unicode equivalents. - /// Used in the . + /// 一个默认的引号对的开闭映射,这可能包含了许多地区和 Unicode 符号中可视为开闭对的符号。 /// - /// + /// internal static Dictionary DefaultAliasMap => // Output of a gist provided by https://gist.github.com/ufcpp // https://gist.github.com/ufcpp/5b2cf9a9bf7d0b8743714a0b88f7edc5 @@ -34,8 +32,7 @@ internal static class QuotationAliasUtils { '"', '"' }, { ''', ''' }, { '「', '」' }, - // Changed from ( and ) because of the usage of keyword by Kook KMarkdown - { '(', ')' }, + // { '(', ')' }, // Removed ( and ) because of the usage of keyword by KOOK KMarkdown { '༺', '༻' }, { '༼', '༽' }, { '᚛', '᚜' }, @@ -79,6 +76,7 @@ internal static class QuotationAliasUtils { '⸤', '⸥' }, { '⸦', '⸧' }, { '⸨', '⸩' }, + { '(', ')' }, { '【', '】' }, { '〔', '〕' }, { '〖', '〗' }, diff --git a/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs b/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs index abd8cdc4..525b464d 100644 --- a/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs +++ b/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs @@ -22,7 +22,8 @@ internal static Func CreateBuilder(TypeInfo typeInfo, Co .ToArray(); T obj = InvokeConstructor(constructor, args, typeInfo); - foreach (PropertyInfo property in properties) property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo)); + foreach (PropertyInfo property in properties) + property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo)); return obj; }; } diff --git a/src/Kook.Net.Core/Audio/AudioApplication.cs b/src/Kook.Net.Core/Audio/AudioApplication.cs index 82a35137..3d1df74c 100644 --- a/src/Kook.Net.Core/Audio/AudioApplication.cs +++ b/src/Kook.Net.Core/Audio/AudioApplication.cs @@ -1,22 +1,22 @@ namespace Kook.Audio; /// -/// Represents the application type of the audio. +/// 表示音频应用程序的应用场景。 /// public enum AudioApplication { /// - /// The audio is intended for voice communication. + /// 用于语音。 /// Voice, /// - /// The audio is intended for music. + /// 用于音乐。 /// Music, /// - /// The audio is intended for mixed usage. + /// 同时用于语音和音乐。 /// Mixed } diff --git a/src/Kook.Net.Core/Audio/AudioInStream.cs b/src/Kook.Net.Core/Audio/AudioInStream.cs index 32538f76..8fb49344 100644 --- a/src/Kook.Net.Core/Audio/AudioInStream.cs +++ b/src/Kook.Net.Core/Audio/AudioInStream.cs @@ -1,12 +1,12 @@ namespace Kook.Audio; /// -/// Represents a generic incoming audio stream. +/// 表示一个通用的输入音频流。 /// public abstract class AudioInStream : AudioStream { /// - /// Gets how many frames are available. + /// 获取当前可用的帧数。 /// public abstract int AvailableFrames { get; } @@ -16,13 +16,18 @@ public abstract class AudioInStream : AudioStream public override bool CanWrite => true; /// - /// Read an RTP frame. + /// 读取一个 RTP 帧。 /// + /// 用于取消任务的取消令牌。 + /// 一个表示异步读取的任务。任务的结果为读取到的 RTP 帧。 public abstract Task ReadFrameAsync(CancellationToken cancellationToken); /// - /// Try reading an RTP frame. + /// 尝试读取一个 RTP 帧。 /// + /// 用于取消任务的取消令牌。 + /// 如果成功读取到 RTP 帧,则为读取到的 RTP 帧;否则为 。 + /// 是否成功读取到 RTP 帧。 public abstract bool TryReadFrame(CancellationToken cancellationToken, out RtpFrame frame); /// diff --git a/src/Kook.Net.Core/Audio/AudioOutStream.cs b/src/Kook.Net.Core/Audio/AudioOutStream.cs index 5e0ed6e5..c28b48ab 100644 --- a/src/Kook.Net.Core/Audio/AudioOutStream.cs +++ b/src/Kook.Net.Core/Audio/AudioOutStream.cs @@ -1,7 +1,7 @@ namespace Kook.Audio; /// -/// Represents a generic outgoing audio stream. +/// 表示一个通用的输出音频流。 /// public abstract class AudioOutStream : AudioStream { @@ -9,17 +9,14 @@ public abstract class AudioOutStream : AudioStream public override bool CanWrite => true; /// - /// Reading this stream is not supported. public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); /// - /// Setting the length to this stream is not supported. public override void SetLength(long value) => throw new NotSupportedException(); /// - /// Seeking this stream is not supported.. public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); } diff --git a/src/Kook.Net.Core/Audio/AudioStream.cs b/src/Kook.Net.Core/Audio/AudioStream.cs index 96bddd34..4efc858e 100644 --- a/src/Kook.Net.Core/Audio/AudioStream.cs +++ b/src/Kook.Net.Core/Audio/AudioStream.cs @@ -1,7 +1,7 @@ namespace Kook.Audio; /// -/// Represents a generic audio stream. +/// 表示一个通用的音频流。 /// public abstract class AudioStream : Stream { @@ -15,12 +15,12 @@ public abstract class AudioStream : Stream public override bool CanWrite => false; /// - /// Writes a header to the stream. + /// 向流中写入一个头部信息。 /// - /// The sequence number of the header. - /// The timestamp of the header. - /// Whether the header is for a missed packet. - // This stream does not accept headers. + /// 头部的序列号。 + /// 头部的时间戳。 + /// 头部是否用于标识丢失的数据包。 + /// 该流不接收头部信息。 public virtual void WriteHeader(ushort seq, uint timestamp, bool missed) => throw new InvalidOperationException("This stream does not accept headers."); @@ -35,26 +35,32 @@ public override void Flush() } /// - /// Clears the stream, causing all buffered data to be lost. + /// 清空该流. /// + /// + /// 此操作会导致丢失所有缓冲的数据。 + /// public void Clear() { } /// - /// Clears the stream, causing all buffered data to be lost. + /// 清空该流. /// - /// The cancellation token to be used. - /// A task that represents an asynchronous clear operation. + /// 用于取消该异步操作的取消令牌。 + /// 一个清空操作的异步任务。 + /// + /// 此操作会导致丢失所有缓冲的数据。 + /// public virtual Task ClearAsync(CancellationToken cancellationToken) => Task.CompletedTask; /// - /// Reading stream length is not supported. + /// 不支持获取此音频流的长度。 public override long Length => throw new NotSupportedException(); /// - /// Getting or setting this stream position is not supported. + /// 不支持获取或设置此音频流的位置。 public override long Position { get => throw new NotSupportedException(); @@ -62,17 +68,17 @@ public override long Position } /// - /// Reading this stream is not supported. + /// 不支持读取此音频流。 public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); /// - /// Setting the length to this stream is not supported. + /// 不支持为此音频流设置长度。 public override void SetLength(long value) => throw new NotSupportedException(); /// - /// Seeking this stream is not supported.. + /// 不支持在此音频流中进行定位操作。 public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); } diff --git a/src/Kook.Net.Core/Audio/IAudioClient.cs b/src/Kook.Net.Core/Audio/IAudioClient.cs index 41018356..641e49ba 100644 --- a/src/Kook.Net.Core/Audio/IAudioClient.cs +++ b/src/Kook.Net.Core/Audio/IAudioClient.cs @@ -1,102 +1,149 @@ namespace Kook.Audio; /// -/// Represents a generic audio client. +/// 表示一个通用的音频客户端。 /// public interface IAudioClient : IDisposable { /// - /// Occurs when a new incoming stream is created. - /// The first parameter is the RTP SSRC. - /// The second parameter is the audio stream. + /// 当客户端接收到一个新的语音输入流时引发。 /// + /// + /// + /// SSRC 为 RTP 实时传输协议中的同步信源标识符,RTP 会话中,每个媒体流应具有一个唯一的 SSRC 标识符。KOOK + /// 服务端未通过网关下发用户与 RTP 流 SSRC 的映射关系,因此无法通过 SSRC 直接获取其关联的用户。Kook.Net 遵循 RTP + /// 协议,以 SSRC 区分不同的信源,创建不同的 实例,并引发此事件。 + /// 一般地,每个 SSRC 值都可以分别表示一个用户在一个语音频道内在一次连接与断开之间的音频流的唯一标识符, + /// 同一用户切换语音频道或断开后重新连接到同一语音频道,KOOK 语音服务器都会为其分配新的 SSRC 标识符。 + /// + ///
+ /// + /// Bot 用户可以通过 API 指定要使用的 SSRC 标识符,这可能会导致 SSRC 碰撞。KOOK 开发者文档推荐 Bot + /// 用户使用 1111 为 SSRC 标识符,如果需要区分音频流是否由 Bot 创建,可以尝试判断 SSRC 标识符是否为 + /// 1111 作为参考。Kook.Net 不以固定的 1111 作为 SSRC + /// 标识符,而是使用随机值,如果音频由 Kook.Net 所构建的 Bot 推送,此方法可能无法区分该音频流是否由 Bot 创建。 + /// + ///
+ /// 事件参数: + /// + /// 参数是 RTP 流的 SSRC 同步信源标识符。 + /// 参数是所新创建的音频输入流。 + /// + ///
event Func StreamCreated; /// - /// Occurs when an incoming stream is destroyed. - /// The first parameter is the RTP SSRC. + /// 当音频输入流被销毁时引发。 /// + /// + /// 事件参数: + /// + /// 参数是 RTP 流的 SSRC 同步信源标识符。 + /// + /// event Func StreamDestroyed; /// - /// Occurs when the client has connected to the voice server. + /// 当客户端成功连接到语音服务器时引发。 /// event Func Connected; /// - /// Occurs when the client has disconnected from the voice server. - /// The first parameter is the exception that caused the disconnection. + /// 当客户端从语音服务器断开连接时引发。 /// + /// + /// 事件参数: + /// + /// 参数是导致连接断开的异常。 + /// + /// event Func Disconnected; // /// - // /// Occurs when the latency of the voice WebSocket server has been updated. + // /// 当语音 WebSocket 服务器的延迟更新时引发。 // /// // event Func LatencyUpdated; /// - /// Occurs when the latency of the voice UDP server has been updated. - /// The first parameter is the latency in milliseconds before the update. - /// The second parameter is the current updated latency in milliseconds. + /// 当语音 UDP 服务器的延迟已更新时引发。 /// + /// + /// 事件参数: + /// + /// 参数是更新前的延迟(毫秒)。 + /// 参数是更新后的延迟(毫秒)。 + /// + /// event Func UdpLatencyUpdated; /// - /// Gets the current connection state of this client. + /// 获取此客户端当前的连接状态。 /// ConnectionState ConnectionState { get; } // /// - // /// Gets the estimated round-trip latency, in milliseconds, to the voice WebSocket server. + // /// 获取到语音 WebSocket 服务器的往返时间估计值,单位为毫秒。 // /// // int Latency { get; } /// - /// Gets the estimated round-trip latency, in milliseconds, to the voice UDP server. + /// 获取到语音 UDP 服务器的往返时间估计值,单位为毫秒。 /// int UdpLatency { get; } /// - /// Gets the current audio streams. + /// 获取该语音客户端所接收的所有音频输入流。 /// - /// A dictionary of audio streams, where each stream is keyed by the RTP SSRC. + /// 一个只读字典,其中键是 RTP 流的 SSRC 同步信源标识符,值是对应的音频输入流。 IReadOnlyDictionary GetStreams(); /// - /// Stops the client from sending audio. + /// 停止该语音客户端发送音频。 /// - /// A task representing the asynchronous operation. + /// 一个停止操作的异步任务。 Task StopAsync(); /// - /// Creates a new audio stream from the Opus codec. + /// 使用 Opus 编解码器创建一个新的音频流。 /// - /// The buffer size, in milliseconds, of the audio stream. - /// A new Opus audio stream. + /// 音频流的缓冲区大小,单位为毫秒。 + /// 一个新的 Opus 音频流。 AudioOutStream CreateOpusStream(int bufferMillis = 1000); /// - /// Creates a new audio stream from the Opus codec without buffering. + /// 使用 Opus 编解码器创建一个新的音频流,不设置缓冲区。 /// - /// A new Opus audio stream. + /// 一个新的 Opus 音频流。 AudioOutStream CreateDirectOpusStream(); /// - /// Creates a new audio stream from the PCM codec. + /// 使用 PCM 编解码器创建一个新的音频流。 /// - /// The audio application to use. - /// The bitrate of the audio stream; leave null to use the bitrate requested from KOOK. - /// The buffer size, in milliseconds, of the audio stream. - /// The packet loss percentage of the audio stream. - /// A new PCM audio stream. + /// 音频应用程序的应用场景。 + /// 音频流的比特率,单位为比特每秒;留空则使用在请求建立音频通道时由 KOOK 返回的指定的比特率。 + /// 音频流的缓冲区大小,单位为毫秒。 + /// 音频流的丢包率,单位为百分比,默认值为 30%。 + /// 一个新的 PCM 音频流。 + /// + /// + /// 如果为 设置了比特率,但比特率过多地超过了由 + /// KOOK 返回的指定的比特率,语音连接可能会被 KOOK 语音服务断开。 + /// + /// AudioOutStream CreatePcmStream(AudioApplication application, int? bitrate = null, int bufferMillis = 1000, int packetLoss = 30); /// - /// Creates a new audio stream from the PCM codec without buffering. + /// 使用 PCM 编解码器创建一个新的音频流,不设置缓冲区。 /// - /// The audio application to use. - /// The bitrate of the audio stream; leave null to use the bitrate requested from KOOK. - /// The packet loss percentage of the audio stream. - /// A new PCM audio stream. + /// 音频应用程序的应用场景。 + /// 音频流的比特率,单位为比特每秒;留空则使用在请求建立音频通道时由 KOOK 返回的指定的比特率。 + /// 音频流的丢包率,单位为百分比,默认值为 30%。 + /// 一个新的 PCM 音频流。 + /// + /// + /// 如果为 设置了比特率,但比特率过多地超过了由 + /// KOOK 返回的指定的比特率,语音连接可能会被 KOOK 语音服务断开。 + /// + /// AudioOutStream CreateDirectPcmStream(AudioApplication application, int? bitrate = null, int packetLoss = 30); } diff --git a/src/Kook.Net.Core/Audio/RtpFrame.cs b/src/Kook.Net.Core/Audio/RtpFrame.cs index 61154cd5..555a84a2 100644 --- a/src/Kook.Net.Core/Audio/RtpFrame.cs +++ b/src/Kook.Net.Core/Audio/RtpFrame.cs @@ -1,33 +1,37 @@ namespace Kook.Audio; /// -/// Represents an RTP frame. +/// 表示一个 RTP 帧。 /// public readonly struct RtpFrame { /// - /// Gets the sequence number of this frame. + /// 获取此帧的序列号。 /// public ushort Sequence { get; init; } /// - /// Gets the timestamp of this frame. + /// 获取此帧的时间戳。 /// public uint Timestamp { get; init; } /// - /// Gets the payload of this frame. + /// 获取此帧的有效负载。 /// public byte[] Payload { get; init; } /// - /// Gets whether this frame was missed. + /// 获取此帧是否丢失。 /// public bool Missed { get; init; } /// - /// Initializes a new instance of . + /// 初始化 结构的新实例。 /// + /// 序列号。 + /// 时间戳。 + /// 有效负载。 + /// 是否丢失。 public RtpFrame(ushort sequence, uint timestamp, byte[] payload, bool missed) { Sequence = sequence; diff --git a/src/Kook.Net.Core/Commands/ICommandContext.cs b/src/Kook.Net.Core/Commands/ICommandContext.cs index 2fbe4380..7ce230de 100644 --- a/src/Kook.Net.Core/Commands/ICommandContext.cs +++ b/src/Kook.Net.Core/Commands/ICommandContext.cs @@ -1,32 +1,32 @@ namespace Kook.Commands; /// -/// Represents a context of a command. This may include the client, guild, channel, user, and message. +/// 表示命令的上下文。这可能包括客户端、公会、频道、用户和消息。 /// public interface ICommandContext { /// - /// Gets the that the command is executed with. + /// 获取命令执行时所使用的 。 /// IKookClient Client { get; } /// - /// Gets the that the command is executed in. + /// 获取命令执行所在的 。 /// IGuild? Guild { get; } /// - /// Gets the that the command is executed in. + /// 获取命令执行所在的 。 /// IMessageChannel Channel { get; } /// - /// Gets the who executed the command. + /// 获取执行命令的 。 /// IUser User { get; } /// - /// Gets the that the command is interpreted from. + /// 获取命令解析的源 。 /// IUserMessage Message { get; } } diff --git a/src/Kook.Net.Core/ConnectionState.cs b/src/Kook.Net.Core/ConnectionState.cs index e70a03f3..bccd561a 100644 --- a/src/Kook.Net.Core/ConnectionState.cs +++ b/src/Kook.Net.Core/ConnectionState.cs @@ -1,17 +1,27 @@ namespace Kook; -/// Specifies the connection state of a client. +/// +/// 指定客户端的连接状态。 +/// public enum ConnectionState : byte { - /// The client has disconnected from Kook. + /// + /// 客户端已断开与 KOOK 的连接。 + /// Disconnected, - /// The client is connecting to Kook. + /// + /// 客户端正在连接到 KOOK。 + /// Connecting, - /// The client has established a connection to Kook. + /// + /// 客户端已连接到 KOOK。 + /// Connected, - /// The client is disconnecting from Kook. + /// + /// 客户端正在断开与 KOOK 的连接。 + /// Disconnecting } diff --git a/src/Kook.Net.Core/Entities/Activities/ActivityType.cs b/src/Kook.Net.Core/Entities/Activities/ActivityType.cs index 0ab5b68f..212f61a6 100644 --- a/src/Kook.Net.Core/Entities/Activities/ActivityType.cs +++ b/src/Kook.Net.Core/Entities/Activities/ActivityType.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the type of activities. +/// 表示活动的类型。 /// public enum ActivityType { /// - /// Specifies that the activity is a game. + /// 游戏。 /// Game = 1, /// - /// Specifies that the activity is music. + /// 音乐。 /// Music = 2 } diff --git a/src/Kook.Net.Core/Entities/Activities/GameCreationSource.cs b/src/Kook.Net.Core/Entities/Activities/GameCreationSource.cs index 39ff532e..beb762e5 100644 --- a/src/Kook.Net.Core/Entities/Activities/GameCreationSource.cs +++ b/src/Kook.Net.Core/Entities/Activities/GameCreationSource.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Represents the creation source of a game. +/// 表示游戏信息的创建来源。 /// public enum GameCreationSource { /// - /// Represents that the game was created by the current user. + /// 由当前用户创建。 /// SelfUser = 1, /// - /// Represents that the game was created by the system by default. + /// 由系统默认创建。 /// System = 2 } diff --git a/src/Kook.Net.Core/Entities/Activities/GameProperties.cs b/src/Kook.Net.Core/Entities/Activities/GameProperties.cs index b9ee8711..c8837823 100644 --- a/src/Kook.Net.Core/Entities/Activities/GameProperties.cs +++ b/src/Kook.Net.Core/Entities/Activities/GameProperties.cs @@ -1,18 +1,18 @@ namespace Kook; /// -/// Properties that are used to modify an with the specified changes. +/// 提供用于修改 的属性。 /// -/// +/// public class GameProperties { /// - /// Gets or sets the name of the game. + /// 获取或设置游戏的名称。 /// public required string Name { get; set; } /// - /// Gets or sets the icon URL of the game. + /// 获取或设置游戏的图标 URL。 /// public string? IconUrl { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Activities/GameType.cs b/src/Kook.Net.Core/Entities/Activities/GameType.cs index 56fc4b22..fa2e09e1 100644 --- a/src/Kook.Net.Core/Entities/Activities/GameType.cs +++ b/src/Kook.Net.Core/Entities/Activities/GameType.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Specifies the type of games. +/// 表示游戏的类型。 /// public enum GameType { /// - /// Specifies that the game is just a game. + /// 仅仅是游戏。 /// Game = 0, /// - /// Specifies that the game is a virtual uploader. + /// 虚拟主播。 /// VirtualUploader = 1, /// - /// Specifies that the game is a process. + /// 进程。 /// Process = 2 } diff --git a/src/Kook.Net.Core/Entities/Activities/IActivity.cs b/src/Kook.Net.Core/Entities/Activities/IActivity.cs index aba71070..289d2cb2 100644 --- a/src/Kook.Net.Core/Entities/Activities/IActivity.cs +++ b/src/Kook.Net.Core/Entities/Activities/IActivity.cs @@ -1,6 +1,6 @@ namespace Kook; /// -/// A user's activity status. +/// 表示一个通用的用户活动。 /// public interface IActivity; diff --git a/src/Kook.Net.Core/Entities/Activities/IGame.cs b/src/Kook.Net.Core/Entities/Activities/IGame.cs index bb009625..157e6f36 100644 --- a/src/Kook.Net.Core/Entities/Activities/IGame.cs +++ b/src/Kook.Net.Core/Entities/Activities/IGame.cs @@ -1,77 +1,53 @@ namespace Kook; /// -/// Represents a generic game object. +/// 表示一个通用的游戏信息。 /// public interface IGame : IActivity, IEntity, IDeletable { /// - /// Gets the name of the game. + /// 获取游戏的名称。 /// - /// - /// A string containing the name of the game. - /// string Name { get; } /// - /// Gets the type of the game. + /// 获取游戏的类型。 /// - /// - /// The type of the game. - /// GameType GameType { get; } /// - /// Gets the additional information about the game. + /// 获取游戏的额外信息。 /// - /// - /// A string containing the additional information about the game. - /// string? Options { get; } /// - /// Gets whether the Kook client needs administrator privileges to detect the game. + /// 获取 KOOK 客户端是否需要管理员权限来检测游戏进程。 /// - /// - /// true if the Kook client needs administrator privileges to detect the game; otherwise, false. - /// bool RequireAdminPrivilege { get; } /// - /// Gets the process names of the game. + /// 获取游戏的进程名称。 /// - /// - /// An containing the process names of the game. - /// IReadOnlyCollection ProcessNames { get; } /// - /// Gets the product names of the game. + /// 获取游戏的产品名称。 /// - /// - /// An containing the product names of the game. - /// IReadOnlyCollection ProductNames { get; } /// - /// Gets the URL of the game's icon. + /// 获取游戏图标的 URL。 /// - /// - /// A string representing the URL of the game's icon. - /// string? Icon { get; } /// - /// Modifies this game. + /// 修改此游戏信息的属性。 /// /// - /// This method modifies this game with the specified properties. To see an example of this - /// method and what properties are available, please refer to . + /// 此方法使用指定的属性修改当前游戏信息。要查看可用的属性,请参考 。 /// - /// A delegate containing the properties to modify the game with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// + /// 一个包含修改游戏属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示信息属性修改操作的异步任务。 Task ModifyAsync(Action func, RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Activities/Music.cs b/src/Kook.Net.Core/Entities/Activities/Music.cs index 3404bbd3..ed15d473 100644 --- a/src/Kook.Net.Core/Entities/Activities/Music.cs +++ b/src/Kook.Net.Core/Entities/Activities/Music.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Represents a music activity. +/// 表示音乐的信息。 /// public class Music { /// - /// Gets or sets the music provider. + /// 获取或设置音乐的提供来源。 /// public MusicProvider Provider { get; set; } /// - /// Gets or sets the music ID. + /// 获取或设置音乐的名称。 /// public string? Name { get; set; } /// - /// Gets or sets the singer. + /// 获取或设置音乐的歌手名称。 /// public string? Singer { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs b/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs index 4ba897ce..84699027 100644 --- a/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs +++ b/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// Specifies the provider of music. +/// 表示音乐的提供来源。 /// public enum MusicProvider { /// - /// Specifies that the music provider is unspecified. + /// 未指定。 /// Unspecified = 0, /// - /// Specifies that the music provider is NetEase. + /// 网易云音乐。 /// NetEaseCloudMusic = 1, /// - /// Specifies that the music provider is Tencent QQ. + /// QQ 音乐。 /// TencentMusic = 2, /// - /// Specifies that the music provider is KuGou. + /// 酷狗音乐。 /// KuGouMusic = 3 } diff --git a/src/Kook.Net.Core/Entities/Audio/PeerPermissionInfo.cs b/src/Kook.Net.Core/Entities/Audio/PeerPermissionInfo.cs index c8822721..a30cc41d 100644 --- a/src/Kook.Net.Core/Entities/Audio/PeerPermissionInfo.cs +++ b/src/Kook.Net.Core/Entities/Audio/PeerPermissionInfo.cs @@ -1,37 +1,37 @@ namespace Kook.Audio; /// -/// Represents the information of a peer's permission in a voice channel. +/// 表示语音频道中其它语音客户端的权限信息。 /// public readonly struct PeerPermissionInfo { /// - /// Gets whether the peer is muted by the guild. + /// 获取是否被服务器闭麦。 /// public bool MutedByGuild { get; init; } /// - /// Gets whether the peer is deafened by the guild. + /// 获取是否被服务器静音。 /// public bool DeafenedByGuild { get; init; } /// - /// Gets whether the peer can use voice activity, i.e. the peer can speak without pressing a key. + /// 获取是否可以在当前语音频道使用语音活性检测,以自由麦的方式不按键即说话。 /// public bool CanUseVoiceActivity { get; init; } /// - /// Gets whether the peer can connect to the voice channel. + /// 获取是否可以连接到当前语音频道。 /// public bool CanConnect { get; init; } /// - /// Gets whether the peer can speak in the voice channel. + /// 获取是否可以在当前语音频道中说话。 /// public bool CanSpeak { get; init; } /// - /// Gets whether the peer can manage the voice channel. + /// 获取是否可以管理当前语音频道。 /// public bool CanManageVoice { get; init; } } diff --git a/src/Kook.Net.Core/Entities/Audio/SoundtrackInfo.cs b/src/Kook.Net.Core/Entities/Audio/SoundtrackInfo.cs index 2aa9de23..382efdde 100644 --- a/src/Kook.Net.Core/Entities/Audio/SoundtrackInfo.cs +++ b/src/Kook.Net.Core/Entities/Audio/SoundtrackInfo.cs @@ -1,22 +1,22 @@ namespace Kook.Audio; /// -/// Represents the information of a soundtrack. +/// 表示计算机音频共享信息。 /// public readonly struct SoundtrackInfo { /// - /// Gets the name of the software from which the soundtrack audio originates + /// 获取计算机音频来源的应用程序名称。 /// public string? Software { get; init; } /// - /// Gets the name of the music soundtrack + /// 获取计算机音频共享的音乐名称。 /// public string? Music { get; init; } /// - /// Gets the singer of the music soundtrack + /// 获取计算机音频共享的音乐的歌手名称。 /// public string? Singer { get; init; } } diff --git a/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs b/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs index 40b3bdac..4d1b6112 100644 --- a/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs +++ b/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Specifies the style of badges. +/// 表示徽章的样式。 /// public enum BadgeStyle { /// - /// The badge contains only the guild name. + /// 徽章展示服务器名称。 /// GuildName = 0, /// - /// The badge contains the number of online members in the guild. + /// 徽章展示服务器在线成员数量。 /// OnlineMemberCount = 1, /// - /// The badge contains the number of both online and all members in the guild. + /// 徽章展示服务器在线成员数量和总成员数量。 /// OnlineAndTotalMemberCount = 2 } diff --git a/src/Kook.Net.Core/Entities/CacheMode.cs b/src/Kook.Net.Core/Entities/CacheMode.cs index af4c3aab..c9432a80 100644 --- a/src/Kook.Net.Core/Entities/CacheMode.cs +++ b/src/Kook.Net.Core/Entities/CacheMode.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the cache mode that should be used. +/// 表示应该使用的缓存模式。 /// public enum CacheMode { /// - /// Allows the object to be downloaded if it does not exist in the current cache. + /// 允许在实体不存在于现有缓存中时下载对象。 /// AllowDownload, /// - /// Only allows the object to be pulled from the existing cache. + /// 仅允许从现有缓存中提取对象。 /// CacheOnly } diff --git a/src/Kook.Net.Core/Entities/Channels/ChannelType.cs b/src/Kook.Net.Core/Entities/Channels/ChannelType.cs index dbac7bac..18ff82b8 100644 --- a/src/Kook.Net.Core/Entities/Channels/ChannelType.cs +++ b/src/Kook.Net.Core/Entities/Channels/ChannelType.cs @@ -1,32 +1,32 @@ namespace Kook; /// -/// Specifies the type of a guild channel. +/// 表示服务器频道的类型。 /// public enum ChannelType { /// - /// Specifies that the type of the channel is unknown. + /// 频道类型未指定。 /// Unspecified = -1, /// - /// Specifies that the channel is a guild category channel. + /// 分组频道。 /// Category = 0, /// - /// Specifies that the channel is a guild text channel. + /// 文字频道。 /// Text = 1, /// - /// Specifies that the channel is a guild voice channel. + /// 语音频道。 /// Voice = 2, /// - /// Specifies that the channel is a direct message channel. + /// 私信频道。 /// DM = 3 } diff --git a/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs index 05f89b77..1c1e2339 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs @@ -1,7 +1,7 @@ namespace Kook; /// -/// Provides properties that are used to create an with the specified properties. +/// 提供用于创建 的属性。 /// -/// +/// public class CreateCategoryChannelProperties : CreateGuildChannelProperties; diff --git a/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs index 3f78d236..265d8697 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs @@ -1,6 +1,6 @@ namespace Kook; /// -/// Properties that are used to create an with the specified properties. +/// 提供用于创建 的属性。 /// public class CreateGuildChannelProperties; diff --git a/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs index 57cacf82..dfac1d33 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs @@ -1,18 +1,17 @@ namespace Kook; /// -/// Provides properties that are used to create an with the specified properties. +/// 提供用于创建 的属性。 /// -/// +/// public class CreateTextChannelProperties : CreateGuildChannelProperties { /// - /// Gets or sets the category ID for this channel. + /// 获取或设置要设置到此频道的所属分组频道的 ID。 /// /// - /// Setting this value to a category's identifier will set this channel's parent to the - /// specified channel; setting this value to null will leave this channel alone - /// from any parents. + /// 将此值设置为某分组频道的 ID 可以使新建频道位于该分组频道下;将此值设置为 null + /// 可以使新建频道位于服务器所有分组频道的上方,即不属于任何分组频道。 /// public ulong? CategoryId { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs index 326f1488..021d295e 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs @@ -1,18 +1,18 @@ namespace Kook; /// -/// Provides properties that are used to create an with the specified properties. +/// 提供用于创建 的属性。 /// -/// +/// public class CreateVoiceChannelProperties : CreateTextChannelProperties { /// - /// Gets or sets the voice quality that the clients in this voice channel are requested to use. + /// 获取或设置要求语音频道中的客户端使用的语音质量。 /// public VoiceQuality? VoiceQuality { get; set; } /// - /// Gets or sets the maximum number of users that can be present in a channel, or null if none. + /// 获取或设置允许同时连接到此频道的最大用户数;null 表示不限制。 /// public int? UserLimit { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Channels/Direction.cs b/src/Kook.Net.Core/Entities/Channels/Direction.cs index e734413e..bafafdc4 100644 --- a/src/Kook.Net.Core/Entities/Channels/Direction.cs +++ b/src/Kook.Net.Core/Entities/Channels/Direction.cs @@ -1,36 +1,27 @@ namespace Kook; /// -/// Specifies the direction of where message(s) should be retrieved from. +/// 表示获取消息的方向。 /// -/// -/// This enum is used to specify the direction for retrieving messages. -/// -/// At the time of writing, is not yet implemented into -/// . -/// Attempting to use the method with will throw -/// a . -/// -/// public enum Direction { /// - /// How the message(s) should be retrieved is unspecified. + /// 未指定消息的获取方向。 /// Unspecified, /// - /// The message(s) should be retrieved before a message. + /// 以指定的参考消息为基准,向前获取消息。 /// Before, /// - /// The message(s) should be retrieved around a message. + /// 以指定的参考消息为基准,获取周围的消息。 /// Around, /// - /// The message(s) should be retrieved after a message. + /// 以指定的参考消息为基准,向后获取消息。 /// After } diff --git a/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs b/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs index a7c8bbd0..aaf3ac5e 100644 --- a/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs @@ -3,53 +3,54 @@ namespace Kook; /// -/// Represents a generic audio channel. +/// 表示一个通用的音频频道。 /// public interface IAudioChannel : IChannel { /// - /// Gets whether the voice region of this audio channel is overwritten. + /// 获取在此音频频道上建立的语音客户端。 + /// + IAudioClient? AudioClient { get; } + + /// + /// 获取此音频频道的语音区域设置是否覆写了服务器的语音区域设置。 /// bool? IsVoiceRegionOverwritten { get; } /// - /// Gets the voice region for this audio channel. + /// 获取此音频频道所设置的语音服务器区域。 /// /// /// - /// This property may be empty if the voice channel is created before this feature was released. + /// 对于语音频道区域设置功能发布之前创建的语音频道,该属性可能为空。 /// /// + /// string? VoiceRegion { get; } /// - /// Gets the server url that clients should connect to to join this voice channel. + /// 获取语音客户端连接到此语音频道的语音服务器 URL。 /// - /// - /// A string representing the url that clients should connect to to join this voice channel. - /// string? ServerUrl { get; } - // /// Determines whether the client should deaf itself upon connection. - // /// Determines whether the client should mute itself upon connection. + // /// 指定连接到此语音客户端时是否应该对自身静音。 + // /// 指定连接到此语音客户端时是否应该对自身闭麦。 /// - /// Connects to this audio channel. + /// 连接到此音频频道。 /// - /// Determines whether the audio client is an external one or not. - /// Determines whether the client should send a disconnect call before connecting to a new voice channel. - /// The password to use when connecting to the audio channel. + /// 指定语音客户端是否是由外部管理的。当设置为 时,当前方法不会尝试连接到语音频道。 + /// 指定语音客户端在连接到新的语音频道之前是否应调用断开连接。 + /// 指定客户端连接到设置了密码的语音频道时所使用的密码。 /// - /// A task representing the asynchronous connection operation. The task result contains the - /// responsible for the connection. + /// 一个表示音频连接操作的异步任务。任务的结果是一个负责音频连接的 实例;如果 + /// ,则会返回 。 /// Task ConnectAsync( /*bool selfDeaf = false, bool selfMute = false, */ bool external = false, bool disconnect = true, string? password = null); /// - /// Disconnects from this audio channel. + /// 断开与此音频频道的连接。 /// - /// - /// A task representing the asynchronous operation for disconnecting from the audio channel. - /// + /// 一个表示音频断开连接操作的异步任务。 Task DisconnectAsync(); } diff --git a/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs b/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs index 4501dc8d..c86ca7a6 100644 --- a/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs @@ -1,6 +1,6 @@ namespace Kook; /// -/// Represents a generic category channel. +/// 表示一个通用的分组频道。 /// public interface ICategoryChannel : IGuildChannel; diff --git a/src/Kook.Net.Core/Entities/Channels/IChannel.cs b/src/Kook.Net.Core/Entities/Channels/IChannel.cs index a3d9d241..1b2d2abb 100644 --- a/src/Kook.Net.Core/Entities/Channels/IChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IChannel.cs @@ -1,18 +1,15 @@ namespace Kook; /// -/// Represents a generic channel. +/// 表示一个通用的频道。 /// public interface IChannel : IEntity { #region General /// - /// Gets the name of this channel. + /// 获取此频道的名称。 /// - /// - /// A string containing the name of this channel. - /// string Name { get; } #endregion @@ -20,37 +17,33 @@ public interface IChannel : IEntity #region Users /// - /// Gets a collection of users that are able to view the channel or are currently in this channel. + /// 获取能够查看频道或当前在该频道中的所有用户。 /// /// /// - /// The returned collection is an asynchronous enumerable object; one must call - /// to access the individual messages as a - /// collection. + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 /// - /// This method will attempt to fetch all users that is able to view this channel or is currently in this channel. - /// The library will attempt to split up the requests according to and . - /// In other words, if there are 3000 users, and the constant - /// is 50, the request will be split into 60 individual requests; thus returning 60 individual asynchronous - /// responses, hence the need of flattening. + ///
+ /// 此方法将尝试获取所有能够查看该频道或当前在该频道中的用户。此方法会根据 + /// 将请求拆分。换句话说,如果有 3000 名用户,而 的常量为 + /// 50,则请求将被拆分为 60 个单独请求,因此异步枚举器会异步枚举返回 60 个响应。 + /// + /// 方法可以展开这 60 个响应返回的集合,并将其合并为一个集合。 ///
- /// The that determines whether the object should be fetched from cache. - /// The options to be used when sending the request. - /// - /// Paged collection of users. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 分页的用户集合的异步可枚举对象。 IAsyncEnumerable> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a user in this channel. + /// 获取此频道中的用户。 /// - /// The identifier of the user (e.g. 168693960628371456). - /// 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 a user object that - /// represents the found user; null if none is found. - /// + /// 要获取的用户的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务结果包含表示找到的用户;如果没有找到,则返回 null Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs b/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs index df6a8637..c92c9a2b 100644 --- a/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs @@ -1,43 +1,38 @@ namespace Kook; /// -/// Represents a generic direct-message channel. +/// 表示一个通用的私聊频道。 /// public interface IDMChannel : IMessageChannel, IPrivateChannel, IEntity { #region General /// - /// Gets the unique identifier of this direct-message channel. + /// 获取此私聊频道的唯一标识符。 /// - /// - /// A that represents this direct-message channel's unique identifier. - /// + /// + /// 此属性的值与 相同。 + /// new Guid Id { get; } /// - /// Gets the chat code of the direct-message channel. + /// 获取此私聊频道的聊天代码。 /// - /// - /// A that represents the chat code of the direct-message channel. - /// + /// + /// 此属性的值与 相同。 + /// Guid ChatCode { get; } /// - /// Gets the recipient of all messages in this channel. + /// 获取参与到此私聊频道的另外一位用户。 /// - /// - /// A user object that represents the other user in this channel. - /// IUser Recipient { get; } /// - /// Closes this private channel, removing it from your channel list. + /// 关闭此私聊频道,将其从您的频道列表中移除。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous close operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步关闭操作的任务。 Task CloseAsync(RequestOptions? options = null); #endregion @@ -45,59 +40,63 @@ public interface IDMChannel : IMessageChannel, IPrivateChannel, IEntity #region Send Messages /// - /// Sends a file to this message channel. + /// 发送文件到此消息频道。 /// - /// - /// A task that represents an asynchronous send operation for delivering the message. The task result - /// contains the identifier and timestamp of the sent message. - /// + /// 文件的路径。 + /// 文件名。 + /// 文件的媒体类型。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null); /// - /// Sends a file to this message channel. + /// 发送文件到此消息频道。 /// - /// - /// A task that represents an asynchronous send operation for delivering the message. The task result - /// contains the identifier and timestamp of the sent message. - /// + /// 文件的流。 + /// 文件名。 + /// 文件的媒体类型。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null); /// - /// Sends a file to this message channel. + /// 发送文件到此消息频道。 /// - /// - /// A task that represents an asynchronous send operation for delivering the message. The task result - /// contains the identifier and timestamp of the sent message. - /// + /// 文件的附件信息。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendFileAsync(FileAttachment attachment, IQuote? quote = null, RequestOptions? options = null); /// - /// Sends a text message to this message channel. + /// 发送文本消息到此消息频道。 /// - /// - /// A task that represents an asynchronous send operation for delivering the message. The task result - /// contains the identifier and timestamp of the sent message. - /// + /// 要发送的文本。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendTextAsync(string text, IQuote? quote = null, RequestOptions? options = null); /// - /// Sends a card message to this message channel. + /// 发送卡片消息到此消息频道。 /// - /// - /// A task that represents an asynchronous send operation for delivering the message. The task result - /// contains the identifier and timestamp of the sent message. - /// + /// 要发送的卡片。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendCardAsync(ICard card, IQuote? quote = null, RequestOptions? options = null); /// - /// Sends a card message to this message channel. + /// 发送卡片消息到此消息频道。 /// - /// - /// A task that represents an asynchronous send operation for delivering the message. The task result - /// contains the identifier and timestamp of the sent message. - /// + /// 要发送的卡片。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendCardsAsync(IEnumerable cards, IQuote? quote = null, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs b/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs index a922312a..2c64cd62 100644 --- a/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs @@ -1,92 +1,65 @@ namespace Kook; /// -/// Represents a generic guild channel. +/// 表示一个通用的服务器频道。 /// public interface IGuildChannel : IChannel, IDeletable { #region General /// - /// Gets the guild associated with this channel. + /// 获取此频道所属的服务器。 /// - /// - /// A guild object that this channel belongs to. - /// IGuild Guild { get; } /// - /// Gets the guild ID associated with this channel. + /// 获取与此频道所属的服务器的 ID。 /// - /// - /// An ulong representing the guild identifier for the guild that this channel - /// belongs to. - /// ulong GuildId { get; } /// - /// Gets the position of this channel. + /// 获取此频道在服务器频道列表中的位置。 /// - /// - /// An int representing the position of this channel in the guild's channel list relative to - /// others of the same type. - /// + /// + /// 更小的数值表示更靠近列表顶部的位置。 + /// int? Position { get; } /// - /// Gets the type of this channel. + /// 获取此频道的类型。 /// - /// - /// A representing the type of this channel. - /// ChannelType Type { get; } /// - /// Gets the identifier of the user who created this channel. + /// 获取创建此频道的用户的 ID。 /// - /// - /// A ulong representing the identifier of the user who created this channel. - /// ulong? CreatorId { get; } /// - /// Gets a collection of permission overwrites for roles for this channel. + /// 获取此频道的角色的权限重写集合。 /// - /// - /// A collection of overwrites for roles associated with this channel. - /// IReadOnlyCollection RolePermissionOverwrites { get; } /// - /// Gets a collection of permission overwrites for users for this channel. + /// 获取此频道的用户的权限重写集合。 /// - /// - /// A collection of overwrites for users associated with this channel. - /// IReadOnlyCollection UserPermissionOverwrites { get; } /// - /// Modifies this guild channel. + /// 修改此服务器频道。 /// - /// - /// This method modifies the current guild channel with the specified properties. To see an example of this - /// method and what properties are available, please refer to . - /// - /// The delegate containing the properties to modify the channel with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// + /// 一个包含修改服务器频道属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示服务器频道属性修改操作的异步任务。 + /// Task ModifyAsync(Action func, RequestOptions? options = null); /// - /// Gets the creator of this channel. + /// 获取此频道的创建者。 /// - /// 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 creator of this channel. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果为此频道的创建者;如果没有找到则为 null Task GetCreatorAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion @@ -94,85 +67,67 @@ public interface IGuildChannel : IChannel, IDeletable #region Permissions /// - /// Gets the permission overwrite for a specific role. + /// 获取给定角色的权限重写配置。 /// - /// The role to get the overwrite from. - /// - /// An overwrite object for the targeted role; null if none is set. - /// + /// 要获取权限重写配置的角色。 + /// 一个表示目标角色的权限重写配置;如果没有设置则为 null OverwritePermissions? GetPermissionOverwrite(IRole role); /// - /// Gets the permission overwrite for a specific user. + /// 获取给定用户的权限重写配置。 /// - /// The user to get the overwrite from. - /// - /// An overwrite object for the targeted user; null if none is set. - /// + /// 要获取权限重写配置的用户。 + /// 一个表示目标用户的权限重写配置;如果没有设置则为 null OverwritePermissions? GetPermissionOverwrite(IUser user); /// - /// Removes the permission overwrite for the given role, if one exists. + /// 对于给定的角色,如果存在权限重写配置,则移除它。 /// - /// The role to remove the overwrite from. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// 要对其移除权限重写配置的角色。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除频道内角色权限重写配置操作的任务。 Task RemovePermissionOverwriteAsync(IRole role, RequestOptions? options = null); /// - /// Removes the permission overwrite for the given user, if one exists. + /// 对于给定的用户,如果存在权限重写配置,则移除它。 /// - /// The user to remove the overwrite from. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// 要对其移除权限重写配置的用户。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除频道内用户权限重写配置操作的任务。 Task RemovePermissionOverwriteAsync(IGuildUser user, RequestOptions? options = null); /// - /// Adds the permission overwrite for the given role. + /// 添加给定角色的权限重写配置。 /// - /// The role to add the overwrite to. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the - /// channel. - /// + /// 要添加权限重写配置的角色。 + /// 发送请求时要使用的选项。 + /// 一个表示异步添加频道内角色权限重写配置操作的任务。 Task AddPermissionOverwriteAsync(IRole role, RequestOptions? options = null); /// - /// Adds the permission overwrite for the given user. + /// 添加给定用户的权限重写配置。 /// - /// The user to add the overwrite to. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. - /// + /// 要添加权限重写配置的用户。 + /// 发送请求时要使用的选项。 + /// 一个表示异步添加频道内用户权限重写配置操作的任务。 Task AddPermissionOverwriteAsync(IGuildUser user, RequestOptions? options = null); /// - /// Updates the permission overwrite for the given role. + /// 更新给定角色的权限重写配置。 /// - /// The role to add the overwrite to. - /// A delegate containing the values to modify the permission overwrite with. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the - /// channel. - /// + /// 要更新权限重写配置的角色。 + /// 一个包含修改权限重写配置的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步更新频道内角色权限重写配置操作的任务。 Task ModifyPermissionOverwriteAsync(IRole role, Func func, RequestOptions? options = null); /// - /// Updates the permission overwrite for the given user. + /// 更新给定用户的权限重写配置。 /// - /// The user to add the overwrite to. - /// A delegate containing the values to modify the permission overwrite with. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. - /// + /// 要更新权限重写配置的用户。 + /// 一个包含修改权限重写配置的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步更新频道内用户权限重写配置操作的任务。 Task ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions? options = null); #endregion @@ -180,29 +135,33 @@ public interface IGuildChannel : IChannel, IDeletable #region Users /// - /// Gets a collection of users that are able to view the channel or are currently in this channel. + /// 获取能够查看频道或当前在此频道中的所有用户。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// 此方法将尝试获取所有能够查看该频道或当前在该频道中的用户。此方法会根据 + /// 将请求拆分。换句话说,如果有 3000 名用户,而 的常量为 + /// 50,则请求将被拆分为 60 个单独请求,因此异步枚举器会异步枚举返回 60 个响应。 + /// + /// 方法可以展开这 60 个响应返回的集合,并将其合并为一个集合。 ///
- /// The that determines whether the object should be fetched from cache. - /// The options to be used when sending the request. - /// - /// Paged collection of users. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 分页的服务器用户集合的异步可枚举对象。 new IAsyncEnumerable> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a user in this channel. + /// 获取此频道中的用户。 /// - /// The identifier of the user. - /// The that determines whether the object should be fetched from cache. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous get operation. The task result contains a guild user object that - /// represents the user; null if none is found. - /// + /// 要获取的用户的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果为此频道中的服务器用户;如果没有找到则为 null new Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs b/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs index 17d712ef..eec4b401 100644 --- a/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs @@ -1,221 +1,180 @@ namespace Kook; /// -/// Represents a channel that can send and receive messages. +/// 表示一个通用的消息频道,可以用来发送和接收消息。 /// public interface IMessageChannel : IChannel { #region Send Messages /// - /// Sends a file to this message channel. + /// 发送文件到此消息频道。 /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The file path of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// The user only who can see the message. Leave null to let everyone see the message. - /// 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 identifier and timestamp of the sent message. - /// + /// 文件的路径。 + /// 文件名。 + /// 文件的媒体类型。 + /// 消息引用,用于回复消息。 + /// 临时消息的接收者。如果设置为指定的用户,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null); /// - /// Sends a file to this message channel. + /// 发送文件到此消息频道。 /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The stream of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// The user only who can see the message. Leave null to let everyone see the message. - /// 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 identifier and timestamp of the sent message. - /// + /// 文件的流。 + /// 文件名。 + /// 文件的媒体类型。 + /// 消息引用,用于回复消息。 + /// 临时消息的接收者。如果设置为指定的用户,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null); /// - /// Sends a file to this message channel. + /// 发送文件到此消息频道。 /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The attachment containing the file. - /// The message quote to be included. Used to reply to specific messages. - /// The user only who can see the message. Leave null to let everyone see the message. - /// 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 identifier and timestamp of the sent message. - /// + /// 文件的附件信息。 + /// 消息引用,用于回复消息。 + /// 临时消息的接收者。如果设置为指定的用户,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendFileAsync(FileAttachment attachment, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null); /// - /// Sends a text message to this message channel. + /// 发送文本消息到此消息频道。 /// - /// The message to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// The user only who can see the message. Leave null to let everyone see the message. - /// 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 identifier and timestamp of the sent message. - /// + /// 要发送的文本。 + /// 消息引用,用于回复消息。 + /// 临时消息的接收者。如果设置为指定的用户,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendTextAsync(string text, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null); /// - /// Sends a card message to this message channel. + /// 发送卡片消息到此消息频道。 /// - /// The card to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// The user only who can see the message. Leave null to let everyone see the message. - /// 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 identifier and timestamp of the sent message. - /// + /// 要发送的卡片。 + /// 消息引用,用于回复消息。 + /// 临时消息的接收者。如果设置为指定的用户,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendCardAsync(ICard card, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null); /// - /// Sends a card message to this message channel. + /// 发送卡片消息到此消息频道。 /// - /// The cards to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// The user only who can see the message. Leave null to let everyone see the message. - /// 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 identifier and timestamp of the sent message. - /// + /// 要发送的卡片。 + /// 消息引用,用于回复消息。 + /// 临时消息的接收者。如果设置为指定的用户,则仅该用户可以看到此消息,否则所有人都可以看到此消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 Task> SendCardsAsync(IEnumerable cards, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null); - /// - /// Gets a message from this message channel. - /// - /// The identifier of the message. - /// The that determines whether the object should be fetched from cache. - /// The options to be used when sending the request. - /// - /// A task that represents an asynchronous get operation for retrieving the message. The task result contains - /// the retrieved message; null if no message is found with the specified identifier. - /// - Task GetMessageAsync(Guid id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); - #endregion #region Get Messages /// - /// Gets the last N messages from this message channel. + /// 从此消息频道获取一条消息。 + /// + /// 消息的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务结果包含检索到的消息;如果未找到具有指定 ID 的消息,则返回 null + Task GetMessageAsync(Guid id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); + + /// + /// 获取此消息频道中的最新的一些消息。 /// /// /// - /// The returned collection is an asynchronous enumerable object; one must call - /// to access the individual messages as a - /// collection. + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 /// + ///
/// - /// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual - /// rate limit, causing your bot to freeze! + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 /// - /// This method will attempt to fetch the number of messages specified under . The - /// library will attempt to split up the requests according to your and - /// . In other words, should the user request 500 messages, - /// and the constant is 100, the request will - /// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need - /// of flattening. + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The numbers of message to be gotten from. - /// The that determines whether the object should be fetched from - /// cache. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要获取的消息数量。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 IAsyncEnumerable> GetMessagesAsync(int limit = KookConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// /// - /// The returned collection is an asynchronous enumerable object; one must call - /// to access the individual messages as a - /// collection. + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 /// + ///
/// - /// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual - /// rate limit, causing your bot to freeze! + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 /// - /// This method will attempt to fetch the number of messages specified under around - /// the message depending on the . The library will - /// attempt to split up the requests according to your and - /// . In other words, should the user request 500 messages, - /// and the constant is 100, the request will - /// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need - /// of flattening. + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The ID of the starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The that determines whether the object should be fetched from - /// cache. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息的 ID。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// /// - /// The returned collection is an asynchronous enumerable object; one must call - /// to access the individual messages as a - /// collection. + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 /// + ///
/// - /// Do not fetch too many messages at once! This may cause unwanted preemptive rate limit or even actual - /// rate limit, causing your bot to freeze! + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 /// - /// This method will attempt to fetch the number of messages specified under around - /// the message depending on the . The library will - /// attempt to split up the requests according to your and - /// . In other words, should the user request 500 messages, - /// and the constant is 100, the request will - /// be split into 5 individual requests; thus returning 5 individual asynchronous responses, hence the need - /// of flattening. + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The that determines whether the object should be fetched from - /// cache. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); @@ -225,21 +184,17 @@ IAsyncEnumerable> GetMessagesAsync(IMessage refere #region Delete Messages /// - /// Deletes a message. + /// 删除一条消息。 /// - /// The identifier of the message that would be removed. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous removal operation. - /// + /// 要删除的消息的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步删除操作的任务。 Task DeleteMessageAsync(Guid messageId, RequestOptions? options = null); - /// Deletes a message based on the provided message in this channel. - /// The message that would be removed. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous removal operation. - /// + /// 删除一条消息. + /// 要删除的消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步删除操作的任务。 Task DeleteMessageAsync(IMessage message, RequestOptions? options = null); #endregion @@ -247,18 +202,13 @@ IAsyncEnumerable> GetMessagesAsync(IMessage refere #region Modify Messages /// - /// Modifies a message. + /// 修改一条消息。 /// - /// - /// This method modifies this message with the specified properties. To see an example of this - /// method and what properties are available, please refer to . - /// - /// The identifier of the message that would be changed. - /// A delegate containing the properties to modify the message with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// + /// 要修改的消息的 ID。 + /// 一个包含修改消息属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 + /// Task ModifyMessageAsync(Guid messageId, Action func, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs b/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs index 035efc53..b298669b 100644 --- a/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs @@ -1,47 +1,41 @@ namespace Kook; /// -/// Represents a type of guild channel that can be nested within a category. +/// 表示一个通用的嵌套频道,即可以嵌套在分组频道中的服务器频道。 /// public interface INestedChannel : IGuildChannel { #region General /// - /// Gets the parent (category) ID of this channel in the guild's channel list. + /// 获取此嵌套频道在服务器频道列表中所属的分组频道的 ID。 /// - /// - /// A ulong representing the identifier of the parent of this channel; - /// null if none is set. - /// + /// 如果当前频道不属于任何分组频道,则会返回 null ulong? CategoryId { get; } /// - /// Specifies whether the permissions of this channel is synchronized with its parent channel. + /// 指示此嵌套频道的权限是否与其所属分组频道同步。 /// - /// - /// A bool indicating whether the permissions of this channel is synchronized with its parent channel. - /// + /// + /// 如果权限同步,则此属性返回 true;如果权限不同步,则返回 false;如果无法确定权限是否同步,则返回 null。 + /// bool? IsPermissionSynced { get; } /// - /// Syncs the permissions of this nested channel with its parent's. + /// 同步此嵌套频道的权限配置与其所属分组频道一致,并保持同步。 /// - /// The options to be used when sending the request. + /// 发送请求时要使用的选项。 /// - /// A task that represents the asynchronous operation for syncing channel permissions with its parent's. + /// 一个表示异步频道权限同步操作的任务。 /// Task SyncPermissionsAsync(RequestOptions? options = null); /// - /// Gets the parent (category) channel of this channel. + /// 获取此频道的所属分组频道。 /// - /// 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 category channel - /// representing the parent of this channel; null if none is set. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此频道所属的分组频道,如果当前频道不属于任何分组频道,则为 null Task GetCategoryAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion @@ -49,39 +43,30 @@ public interface INestedChannel : IGuildChannel #region Invites /// - /// Gets a collection of all invites from this guild channel. + /// 获取此嵌套频道的所有邀请信息。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// invite, each representing information for an invite found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此频道中找到的所有邀请信息。 Task> GetInvitesAsync(RequestOptions? options = null); /// - /// Creates a new invite to this channel. + /// 创建一个到此频道新邀请。 /// - /// The time until the invite expires. Set to InviteMaxAge.NeverExpires to never expire. - /// The max amount of times this invite may be used. Set to InviteMaxUses.Unlimited to have unlimited uses. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous invite creation operation. The task result contains an invite - /// metadata object containing information for the created invite. - /// + /// 邀请链接的有效时长, 表示永不过期。 + /// 邀请链接的可用人次, 表示无限制。 + /// 发送请求时要使用的选项。 + /// 一个表示异步邀请创建操作的任务。任务的结果包含所创建的邀请链接的元数据,其中包含有关邀请链接的信息。 Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge._604800, InviteMaxUses maxUses = InviteMaxUses.Unlimited, RequestOptions? options = null); /// - /// Creates a new invite to this channel. + /// 创建一个到此频道新邀请。 /// - /// The time (in seconds) until the invite expires. Set to null to never expire. - /// The max amount of times this invite may be used. Set to null to have unlimited uses. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous invite creation operation. The task result contains an invite - /// metadata object containing information for the created invite. - /// + /// 邀请链接的有效时长,null 表示永不过期。 + /// 邀请链接的可用人次,null 表示无限制。 + /// 发送请求时要使用的选项。 + /// 一个表示异步邀请创建操作的任务。任务的结果包含所创建的邀请链接的元数据,其中包含有关邀请链接的信息。 Task CreateInviteAsync(int? maxAge = 604800, int? maxUses = null, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs b/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs index 79ead275..d9455be2 100644 --- a/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs @@ -1,15 +1,12 @@ namespace Kook; /// -/// Represents a generic channel that is private to selected recipients. +/// 表示一个通用的私有频道,只有特定的用户可以访问。 /// public interface IPrivateChannel : IChannel { /// - /// Gets the users that can access this channel. + /// 获取可以访问此频道的所有用户。 /// - /// - /// A read-only collection of users that can access this channel. - /// IReadOnlyCollection Recipients { get; } } diff --git a/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs b/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs index bca186ad..2c19eaf7 100644 --- a/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs @@ -1,48 +1,42 @@ namespace Kook; /// -/// Represents a generic channel in a guild that can send and receive messages. +/// 表示服务器中一个通用的具有文字聊天能力的频道,可以发送和接收消息。 /// public interface ITextChannel : INestedChannel, IMentionable, IMessageChannel { #region General /// - /// Gets the current topic for this text channel. + /// 获取此频道的说明。 /// - /// - /// A string representing the topic set in the channel; null if none is set. - /// string Topic { get; } /// - /// Gets the current slow-mode delay for this channel. + /// 获取此频道当前设置的慢速模式延迟。 /// - /// - /// An int representing the time in seconds required before the user can send another message; 0 if disabled. - /// + /// + /// 拥有 或 + /// 权限的用户不受慢速模式延迟的限制。 + /// + /// 一个 int,表示用户在可以发送另一条消息之前需要等待的时间(以秒为单位);如果未启用,则为 0 int SlowModeInterval { get; } /// - /// Modifies this text channel. + /// 修改此频道有关文字聊天能力的属性。 /// - /// The delegate containing the properties to modify the channel with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// - /// + /// 一个包含修改频道有关文字聊天能力的属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 + /// Task ModifyAsync(Action func, RequestOptions? options = null); #endregion /// - /// Gets a collection of pinned messages in this channel. + /// 获取此频道中的所有置顶消息。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation for retrieving pinned messages in this channel. - /// The task result contains a collection of messages found in the pinned messages. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此频道中找到的所有置顶消息。 Task> GetPinnedMessagesAsync(RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs b/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs index 2f26e122..90d9fbca 100644 --- a/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs @@ -1,55 +1,40 @@ namespace Kook; /// -/// Represents a generic voice channel in a guild. +/// 表示服务器中的一个通用的具有语音聊天能力的频道。 /// public interface IVoiceChannel : ITextChannel, IAudioChannel { /// - /// Gets the voice quality that the clients in this voice channel are requested to use. + /// 获取要求此频道中的客户端使用的语音质量。 /// - /// - /// A representing the voice quality that this voice channel defines and requests the - /// client(s) to use. - /// VoiceQuality? VoiceQuality { get; } /// - /// Gets the max number of users allowed to be connected to this channel at once. + /// 获取允许同时连接到此频道的最大用户数。 /// - /// - /// An int representing the maximum number of users that are allowed to be connected to this - /// channel at once; 0 if a limit is not set. - /// + /// 一个 int,表示允许同时连接到此频道的最大用户数;如果没有限制,则为 0 int UserLimit { get; } /// - /// Gets whether this voice channel is locked by a password. + /// 获取此频道是否已被密码锁定。 /// - /// - /// A bool representing whether this voice channel is locked by a password. - /// bool HasPassword { get; } /// - /// Modifies this voice channel. + /// 修改此频道有关语音聊天能力的属性。 /// - /// The properties to modify the channel with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// - /// + /// 一个包含修改有关语音聊天能力的属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 + /// Task ModifyAsync(Action func, RequestOptions? options = null); /// - /// Gets the users connected to this voice channel. + /// 获取连接到此频道的用户。 /// - /// 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 a collection of - /// s that are connected to this voice channel. - /// - Task> GetConnectedUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含连接到此频道的所有服务器用户。 + Task> GetConnectedUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Channels/MessageSource.cs b/src/Kook.Net.Core/Entities/Channels/MessageSource.cs index a848f03a..084d7622 100644 --- a/src/Kook.Net.Core/Entities/Channels/MessageSource.cs +++ b/src/Kook.Net.Core/Entities/Channels/MessageSource.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Specifies the source of the Kook message. +/// 表示消息的来源。 /// public enum MessageSource { /// - /// The message is sent by the system. + /// 系统消息。 /// System, /// - /// The message is sent by a user. + /// 消息由用户发送。 /// User, /// - /// The message is sent by a bot. + /// 消息由 Bot 发送。 /// Bot } diff --git a/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs index 051a39ab..ca0909bb 100644 --- a/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs @@ -1,35 +1,34 @@ namespace Kook; /// -/// Properties that are used to modify an with the specified properties. +/// 提供用于修改 的属性。 /// -/// +/// public class ModifyGuildChannelProperties { /// - /// Gets or sets the channel to this name to be modified. + /// 获取或设置要设置到此频道的新名称。 /// /// - /// This property defines the new name for this channel; - /// if this is null, the name will not be modified. + /// 如果此值为 null,则频道的名称不会被修改。 /// public string? Name { get; set; } /// - /// Moves the channel to the following position. This property is one-based. + /// 获取或设置要设置到此频道的新位置。 /// /// - /// If this is null, the position will not be modified. + /// 更小的数值表示更靠近列表顶部的位置。设置为与同分组下的其他频道相同的值,将会使当前频道排列于与该频道相邻更靠近列表顶部的位置。 + /// 如果此值为 null,则频道的位置不会被修改。 /// public int? Position { get; set; } /// - /// Gets or sets the category ID for this channel. + /// 获取或设置要设置到此频道的所属分组频道的 ID。 /// /// - /// Setting this value to a category's identifier will change this channel's parent to the - /// specified channel; setting this value to 0 will detach this channel from its parent if one - /// is set; if this is null, the parent of this channel will not be modified. + /// 设置此值为某分组频道的 ID 将会使当前频道移动至该分组频道下;设置此值为 0 将会使当前频道脱离其当前所属的分组频道, + /// 位于所有分组频道的上方;如果此值为 null,则当前频道的所属分组频道不会被修改。 /// public ulong? CategoryId { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs index f39f960e..088c4bd4 100644 --- a/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs @@ -1,30 +1,29 @@ namespace Kook; /// -/// Provides properties that are used to modify an with the specified properties. +/// 提供用于修改 的属性。 /// -/// +/// public class ModifyTextChannelProperties : ModifyGuildChannelProperties { /// - /// Gets or sets the topic of the channel. + /// 获取或设置要设置到此频道的说明。 /// /// - /// Setting this value to any string other than null or will set the - /// channel topic or description to the desired value. + /// 如果此值为 null,则频道的说明不会被修改;如果此值为 ,则频道的说明将被清空; + /// 设置为其他值将会修改频道的说明。 /// public string? Topic { get; set; } /// - /// Gets or sets the slow-mode ratelimit in seconds for this channel. + /// 获取或设置要设置到此频道的慢速模式延迟。 /// /// - /// Setting this value will require each user to wait before sending another message; setting this value to - /// will disable slow-mode for this channel; - /// if this value is set to null, the slow-mode interval will not be modified. + /// 设置此值将要求每个用户在发送另一条消息之前等待指定的时间间隔;设置为 + /// 将会为此频道禁用慢速模式;如果此值为 null,则慢速模式延迟不会被修改。 /// - /// Users with or - /// will be exempt from slow-mode. + /// 拥有 或 + /// 权限的用户不受慢速模式延迟的限制。 /// /// public SlowModeInterval? SlowModeInterval { get; set; } diff --git a/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs index abf737b4..e086abda 100644 --- a/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs @@ -1,44 +1,56 @@ namespace Kook; /// -/// Provides properties that are used to modify an with the specified properties. +/// 提供用于修改 的属性。 /// -/// +/// public class ModifyVoiceChannelProperties : ModifyTextChannelProperties { /// - /// Gets or sets the voice quality that the clients in this voice channel are requested to use; - /// null if not set. + /// 获取或设置要设置到此频道的要求语音频道中的客户端使用的语音质量。 /// /// /// - /// This property cannot be set to the quality equivalent or higher than - /// via Kook REST API - /// because of the server-side limitation despite of the fact that - /// the voice channel exists in a boosted guild. + /// 受限于 KOOK API,无法通过 KOOK API 设置语音频道的语音质量为 + /// 或更高的值,尽管语音频道所属的服务器已有相应的服务器助力。通过此属性设置为不低于 + /// 的语音质量的操作是无效的。 /// + ///
+ /// 如果此值为 null,则语音质量不会被修改。 ///
public VoiceQuality? VoiceQuality { get; set; } /// - /// Gets or sets the maximum number of users that can be present in a channel, or 0 if none; - /// null if not set. + /// 获取或设置要设置到此频道的允许同时连接到此频道的最大用户数;如果没有限制,则为 0。 /// + /// + /// 如果此值为 0,则用户限制将被清除;如果此值为 null,则用户限制不会被修改。 + /// public int? UserLimit { get; set; } /// - /// Gets or sets the password of the channel, or empty string to clear the password; null if not set. + /// 获取或设置要设置到此频道的密码。 /// + /// + /// 密码只支持 1 至 12 位的数字,设置密码后,用户连接到此频道时需要输入密码。如果此值为 + /// ,则密码将被清除;如果此值为 null,则密码不会被修改。 + /// public string? Password { get; set; } /// - /// Gets or sets a value that indicates whether the voice region of the channel is overwritten; - /// null if not set. + /// 获取或设置要设置到此频道的是否覆写了服务器默认设置的语音服务器区域。 /// + /// + /// 如果此值为 null,则不会修改是否覆写了服务器默认设置的语音服务器区域。 + /// public bool? OverwriteVoiceRegion { get; set; } /// - /// Gets or sets the voice region of the channel; null if not set. + /// 获取或设置要设置到此频道的语音服务器区域。 /// + /// + /// 如果此值为 null,则语音服务器区域不会被修改。 + /// + /// public string? VoiceRegion { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs b/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs index 52a43e28..7f6a9460 100644 --- a/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs +++ b/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs @@ -1,77 +1,77 @@ namespace Kook; /// -/// Specifies the slow-mode ratelimit in seconds for an . +/// 表示 的慢速模式延迟时间秒数。 /// public enum SlowModeInterval { /// - /// Slow-mode is disabled. + /// 禁用慢速模式。 /// None = 0, /// - /// Each user needs to wait for 5 seconds before sending another message. + /// 每个用户每 5 秒最多发送一条消息。 /// _5 = 5, /// - /// Each user needs to wait for 10 seconds before sending another message. + /// 每个用户每 10 秒最多发送一条消息。 /// _10 = 10, /// - /// Each user needs to wait for 15 seconds before sending another message. + /// 每个用户每 15 秒最多发送一条消息。 /// _15 = 15, /// - /// Each user needs to wait for 30 seconds before sending another message. + /// 每个用户每 30 秒最多发送一条消息。 /// _30 = 30, /// - /// Each user needs to wait for 1 minute (60 seconds) before sending another message. + /// 每个用户每 1 分钟(60 秒)最多发送一条消息。 /// _60 = 60, /// - /// Each user needs to wait for 2 minutes (120 seconds) before sending another message. + /// 每个用户每 2 分钟(120 秒)最多发送一条消息。 /// _120 = 120, /// - /// Each user needs to wait for 5 minutes (300 seconds) before sending another message. + /// 每个用户每 5 分钟(300 秒)最多发送一条消息。 /// _300 = 300, /// - /// Each user needs to wait for 10 minutes (600 seconds) before sending another message. + /// 每个用户每 10 分钟(600 秒)最多发送一条消息。 /// _600 = 600, /// - /// Each user needs to wait for 15 minutes (900 seconds) before sending another message. + /// 每个用户每 15 分钟(900 秒)最多发送一条消息。 /// _900 = 900, /// - /// Each user needs to wait for 30 minutes (1800 seconds) before sending another message. + /// 每个用户每 30 分钟(1800 秒)最多发送一条消息。 /// _1800 = 1800, /// - /// Each user needs to wait for 1 hour (3600 seconds) before sending another message. + /// 每个用户每 1 小时(3600 秒)最多发送一条消息。 /// _3600 = 3600, /// - /// Each user needs to wait for 2 hours (7200 seconds) before sending another message. + /// 每个用户每 2 小时(7200 秒)最多发送一条消息。 /// _7200 = 7200, /// - /// Each user needs to wait for 6 hours (21600 seconds) before sending another message. + /// 每个用户每 6 小时(21600 秒)最多发送一条消息。 /// _21600 = 21600 } diff --git a/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs b/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs index 2a10b968..2cac4f73 100644 --- a/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs +++ b/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs @@ -1,54 +1,54 @@ namespace Kook; /// -/// Specifies the voice quality of an . +/// 表示 的语音质量。 /// public enum VoiceQuality { /// - /// Equivalent to approximately 18 kbps. + /// 等效于约 18 kbps。 /// _18kbps = 1, /// - /// Equivalent to approximately is 48 kbps. + /// 等效于约 48 kbps。 /// _48kbps = 2, /// - /// Equivalent to approximately is 96 kbps. + /// 等效于约 96 kbps。 /// _96kbps = 3, /// - /// Equivalent to approximately 128 kbps. + /// 等效于约 128 kbps。 /// /// - /// This quality needs the boost level to reach LV1. + /// 此质量需要服务器助力等级达到 。 /// _128kbps = 4, /// - /// Equivalent to approximately 192 kbps. + /// 等效于约 192 kbps。 /// /// - /// This quality needs the boost level to reach LV2. + /// 此质量需要服务器助力等级达到 。 /// _192kbps = 5, /// - /// Equivalent to approximately 256 kbps. + /// 等效于约 256 kbps。 /// /// - /// This quality needs the boost level to reach LV3. + /// 此质量需要服务器助力等级达到 。 /// _256kbps = 6, /// - /// Equivalent to approximately 320 kbps. + /// 等效于约 320 kbps。 /// /// - /// This quality needs the boost level to reach LV5. + /// 此质量需要服务器助力等级达到 。 /// _320kbps = 7 } diff --git a/src/Kook.Net.Core/Entities/Emotes/Emoji.cs b/src/Kook.Net.Core/Entities/Emotes/Emoji.cs index 44567c25..e5e8297c 100644 --- a/src/Kook.Net.Core/Entities/Emotes/Emoji.cs +++ b/src/Kook.Net.Core/Entities/Emotes/Emoji.cs @@ -5,8 +5,11 @@ namespace Kook; /// -/// A Unicode emoji. +/// 一个 Unicode 表情符号。 /// +/// +/// 有关受支持的表情符号列表,请参阅 https://kooknet.dev/guides/emoji/emoji-list.html。 +/// public class Emoji : IEmote { /// @@ -16,26 +19,21 @@ public class Emoji : IEmote public string Id => Name; /// - /// Gets the Unicode representation of this emoji. + /// 获取此表情符号的 Unicode 表示。 /// - /// - /// A string that resolves to . - /// + /// 一个解析为 的字符串。 public override string ToString() => Name; /// - /// Initializes a new class with the provided Unicode. + /// 使用提供的 Unicode 初始化一个新的 类的实例。 /// - /// The pure UTF-8 encoding of an emoji. + /// 表情符号的 Unicode 表示。 public Emoji(string unicode) { - Name = TryParseAsUnicodePoint(unicode, out string? name) ? name : unicode; + Name = TryParseToName(unicode, out string? name) ? name : unicode; } - /// - /// Determines whether the specified emoji is equal to the current one. - /// - /// The object to compare with the current object. + /// public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) return false; @@ -43,49 +41,63 @@ public override bool Equals([NotNullWhen(true)] object? obj) return obj is Emoji otherEmoji && string.Equals(Name, otherEmoji.Name); } - /// Tries to parse an from its raw format. - /// The raw encoding of an emoji. For example: :heart: or ❤ - /// An emoji. + /// + /// 尝试从原始格式解析 类的新实例。 + /// + /// 要解析的字符串,例如::heart:。 + /// 如果解析成功,则包含解析的 ;否则为 null。 + /// 如果解析成功,则为 true;否则为 false public static bool TryParse([NotNullWhen(true)] string? text, [NotNullWhen(true)] out Emoji? result) { + if (TryParseToName(text, out string? name)) + { + result = new Emoji(name); + return true; + } + result = null; - if (text is null || string.IsNullOrWhiteSpace(text)) - return false; - if (NamesAndUnicodes.TryGetValue(text, out string? nameUnicode)) - result = new Emoji(nameUnicode); - if (Unicodes.Contains(text)) - result = new Emoji(text); - return result != null; + return false; } - /// Parse an from its raw format. - /// The raw encoding of an emoji. For example: :heart: or ❤ - /// String is not emoji or unicode! - public static Emoji Parse([NotNull] string? emojiStr) + /// + /// 从原始格式解析 类的新实例。 + /// + /// 要解析的字符串,例如::heart:。 + /// 解析的 + /// 不是表情符号名称或 Unicode。 + public static Emoji Parse([NotNull] string? text) { - if (!TryParse(emojiStr, out Emoji? emoji)) + if (!TryParse(text, out Emoji? emoji)) throw new FormatException("String is not emoji name or unicode."); return emoji; } /// - /// Try parsing an from its unicode point format. - /// For example: [#128187;] -> 💻 + /// 尝试从由方括号包围的 HTML 实体编码的十进制表示形式解析 的凝成。 /// - internal static bool TryParseAsUnicodePoint(string unicodePoint, [NotNullWhen(true)] out string? name) + /// 要解析的字符串,例如:[#128187;]:grinning:。 + /// 如果解析成功,则包含解析的名称;否则为 null。 + /// 如果解析成功,则为 true;否则为 false + private static bool TryParseToName(string? text, [NotNullWhen(true)] out string? name) { - name = null; - if (!unicodePoint.StartsWith("[#") || !unicodePoint.EndsWith(";]")) return false; - if (!int.TryParse(unicodePoint[2..^2], out int codePoint)) return false; - name = char.ConvertFromUtf32(codePoint); - return true; + if (text is null || string.IsNullOrWhiteSpace(text)) + name = null; + else if (text.StartsWith("[#") && text.EndsWith(";]") && int.TryParse(text[2..^2], out int codePoint)) + name = char.ConvertFromUtf32(codePoint); + else if (NamesAndUnicodes.TryGetValue(text, out string? nameUnicode)) + name = nameUnicode; + else if (Unicodes.Contains(text)) + name = text; + else + name = null; + return name != null; } /// public override int GetHashCode() => Name.GetHashCode(); - // Originally from https://img.kookapp.cn/assets/emoji.json + // 源于 https://img.kookapp.cn/assets/emoji.json private static IReadOnlyDictionary NamesAndUnicodes { get; } = new Dictionary { [":grinning:"] = "\ud83d\ude00", @@ -1833,12 +1845,6 @@ private static IReadOnlyDictionary> UnicodesA } } - /// - /// Parses the given string into an . - /// - /// The string to parse. - /// The parsed . - /// The provided string is not emoji name or unicode. - /// - public static implicit operator Emoji(string s) => Parse(s); + /// + public static implicit operator Emoji(string emojiStr) => Parse(emojiStr); } diff --git a/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs b/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs index 38ddf5a5..dfe9fd7f 100644 --- a/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs +++ b/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the type of an emoji. +/// 表示一个表情符号的类型。 /// public enum EmojiType { /// - /// The emoji is static. + /// 静态表情符号。 /// Static = 1, /// - /// The emoji is animated. + /// 动态表情符号。 /// Animated = 2 } diff --git a/src/Kook.Net.Core/Entities/Emotes/Emote.cs b/src/Kook.Net.Core/Entities/Emotes/Emote.cs index a014789d..f2a3f8be 100644 --- a/src/Kook.Net.Core/Entities/Emotes/Emote.cs +++ b/src/Kook.Net.Core/Entities/Emotes/Emote.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Represents a guild emote. +/// 表示一个表情符号。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Emote : IEmote @@ -17,22 +17,22 @@ public class Emote : IEmote RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); /// - /// Gets the identifier of this emote. + /// 获取此表情符号的唯一标识符。 /// public string Id { get; } /// - /// Gets the name of this emote. + /// 获取此表情符号的名称。 /// public string Name { get; } /// - /// Gets whether this emote is animated. + /// 获取此表情符号是否为动态表情。如果无法确定此表情符号是否为动态表情,则为 null。 /// public bool? Animated { get; } /// - /// Creates a new instance of . + /// 创建一个新的 实例。 /// public Emote(string id, string name, bool? animated = null) { @@ -50,14 +50,17 @@ public override bool Equals([NotNullWhen(true)] object? obj) return Id == otherEmote.Id; } - /// Tries to parse an from its raw format. + /// + /// 尝试从一个表情符号的原始格式中解析出一个 。 + /// /// - /// The raw encoding of an emote; for example, - /// [:emotename:1991895624896587/hbCFVWhu923k03k] when is TagMode.PlainText, - /// or (emj)emotename(emj)[1991895624896587/hbCFVWhu923k03k] when is TagMode.KMarkdown. + /// 表情符号的原始格式。例如: 时的 + /// [:emotename:1991895624896587/hbCFVWhu923k03k];为 时的 + /// (emj)emotename(emj)[1991895624896587/hbCFVWhu923k03k]。 /// - /// An emote. - /// + /// 如果解析成功,则为解析出的 ;否则为 null。 + /// 解析标签的语法模式。 + /// 如果解析成功,则为 true;否则为 false public static bool TryParse([NotNullWhen(true)] string? text, [NotNullWhen(true)] out Emote? result, TagMode tagMode) { @@ -76,42 +79,56 @@ public static bool TryParse([NotNullWhen(true)] string? text, return true; } - /// Parses an from its raw format. + /// + /// 从一个表情符号的原始格式中解析出一个 。 + /// /// - /// The raw encoding of an emote; for example, - /// [:emotename:1991895624896587/hbCFVWhu923k03k] when is TagMode.PlainText, - /// or (emj)emotename(emj)[1991895624896587/hbCFVWhu923k03k] when is TagMode.KMarkdown. + /// 表情符号的原始格式。例如: 时的 + /// [:emotename:1991895624896587/hbCFVWhu923k03k];为 时的 + /// (emj)emotename(emj)[1991895624896587/hbCFVWhu923k03k]。 /// - /// - /// An emote. - /// Invalid emote format. + /// 解析标签的语法模式。 + /// 解析出的 + /// + /// 无法以 的语法模式解析 为一个有效的表情符号。 + /// public static Emote Parse([NotNull] string? text, TagMode tagMode) { if (TryParse(text, out Emote? result, tagMode)) return result; - throw new ArgumentException("Invalid emote format.", nameof(text)); + throw new FormatException("Invalid emote format."); } /// public override int GetHashCode() => Id.GetHashCode(); /// - /// Gets a string representation of the emote in KMarkdown format. + /// 获取此表情的 KMarkdown 格式字符串。 /// + /// 此表情的 KMarkdown 格式字符串。 public string ToKMarkdownString() => $"(emj){Name}(emj)[{Id}]"; /// - /// Gets a string representation of the emote in plain text format. + /// 获取此表情的纯文本格式字符串。 /// + /// 此表情的纯文本格式字符串。 public string ToPlainTextString() => $"[:{Name}:{Id}]"; private string DebuggerDisplay => $"{Name} ({Id})"; + /// + public override string ToString() => ToString(TagMode.KMarkdown); + /// - /// Returns the raw representation of the emote. + /// 获取此表情的字符串表示形式。 /// - /// - /// A string representing the raw presentation of the emote (e.g. [:thonkang:282745590985523200]). - /// - public override string ToString() => $"[:{Name}:{Id}]"; + /// 标签的语法模式。 + /// 此表情的字符串表示形式。 + /// 不是有效的标签语法模式。 + public string ToString(TagMode tagMode) => tagMode switch + { + TagMode.PlainText => ToPlainTextString(), + TagMode.KMarkdown => ToKMarkdownString(), + _ => throw new ArgumentOutOfRangeException(nameof(tagMode), tagMode, null) + }; } diff --git a/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs b/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs index c69e42b1..350e8885 100644 --- a/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs +++ b/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs @@ -3,7 +3,7 @@ namespace Kook; /// -/// An image-based emote that is attached to a guild. +/// 表示一个附属于服务器的基于图片的表情符号。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class GuildEmote : Emote @@ -16,31 +16,19 @@ internal GuildEmote(string id, string name, bool? animated, ulong guildId, ulong } /// - /// The ID of the guild this emote is attached to. + /// 获取此表情符号所属的服务器的 ID。 /// - /// - /// A ulong that identifies the guild this emote is attached to. - /// public ulong GuildId { get; } /// - /// Gets the user who created this emote. + /// 获取创建此表情符号的用户的 ID /// - /// - /// An representing the user who created this emote; - /// null if unknown. - /// + /// + /// 如果无法确定创建此表情符号的用户的 ID,则为 null。 + /// public ulong? CreatorId { get; } private string DebuggerDisplay => $"{Name} ({Id}{(Animated == true ? ", Animated" : "")})"; - /// - /// Gets the raw representation of the emote. - /// - /// - /// A string representing the raw presentation of the emote. - /// - public override string ToString() => $"(emj){Name}(emj)[{Id}]"; - internal GuildEmote Clone() => (GuildEmote) MemberwiseClone(); } diff --git a/src/Kook.Net.Core/Entities/Emotes/IEmote.cs b/src/Kook.Net.Core/Entities/Emotes/IEmote.cs index 1cbd1d3a..70b23769 100644 --- a/src/Kook.Net.Core/Entities/Emotes/IEmote.cs +++ b/src/Kook.Net.Core/Entities/Emotes/IEmote.cs @@ -1,15 +1,12 @@ namespace Kook; /// -/// Represents a general container for any type of emote in a message. +/// 表示一个通用的表情符号。 /// public interface IEmote : IEntity { /// - /// Gets the display name or Unicode representation of this emote. + /// 获取此表情符号的显示名称或 Unicode 表示。 /// - /// - /// A string representing the display name or the Unicode representation (e.g. 🤔) of this emote. - /// string Name { get; } } diff --git a/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs b/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs index d3998c37..dfccc9d9 100644 --- a/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs +++ b/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs @@ -1,42 +1,42 @@ namespace Kook; /// -/// Specifies the boost level of a guild. +/// 表示一个服务器助力等级。 /// public enum BoostLevel { /// - /// No boost. + /// 服务器助力等级 0。 /// None = 0, /// - /// Boost level 1. + /// 服务器助力等级 1。 /// Level1 = 1, /// - /// Boost level 2. + /// 服务器助力等级 2。 /// Level2 = 2, /// - /// Boost level 3. + /// 服务器助力等级 3。 /// Level3 = 3, /// - /// Boost level 4. + /// 服务器助力等级 4。 /// Level4 = 4, /// - /// Boost level 5. + /// 服务器助力等级 5。 /// Level5 = 5, /// - /// Boost level 6. + /// 服务器助力等级 6。 /// Level6 = 6 } diff --git a/src/Kook.Net.Core/Entities/Guilds/GuildCertification.cs b/src/Kook.Net.Core/Entities/Guilds/GuildCertification.cs index d78f1c13..055ecceb 100644 --- a/src/Kook.Net.Core/Entities/Guilds/GuildCertification.cs +++ b/src/Kook.Net.Core/Entities/Guilds/GuildCertification.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// Represents a guild certification. +/// 表示一个服务器认证信息。 /// public class GuildCertification { /// - /// Gets the type of the certification. + /// 获取认证的类型。 /// public GuildCertificationType Type { get; } /// - /// Gets the title of the certification. + /// 获取认证的名称。 /// public string Title { get; private set; } = string.Empty; /// - /// Gets the picture URL of the certification. + /// 获取认证的图片 URL。 /// public string? Picture { get; private set; } /// - /// Gets the description of the certification. + /// 获取认证的描述。 /// public string? Description { get; private set; } diff --git a/src/Kook.Net.Core/Entities/Guilds/GuildCertificationType.cs b/src/Kook.Net.Core/Entities/Guilds/GuildCertificationType.cs index 8d469dde..70944946 100644 --- a/src/Kook.Net.Core/Entities/Guilds/GuildCertificationType.cs +++ b/src/Kook.Net.Core/Entities/Guilds/GuildCertificationType.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// Represents a guild certification type. +/// 表示一个服务器认证的类型。 /// public enum GuildCertificationType { /// - /// Represents an official certification. + /// 官方认证。 /// Official = 1, /// - /// Represents a partner certification. + /// 合作伙伴认证。 /// Partner = 2, /// - /// Represents a recommended certification. + /// 推荐认证。 /// Recommended = 4, /// - /// Represents a personal certification. + /// 个人认证。 /// Personal = 6 diff --git a/src/Kook.Net.Core/Entities/Guilds/GuildFeature.cs b/src/Kook.Net.Core/Entities/Guilds/GuildFeature.cs index a23e3f59..c0207614 100644 --- a/src/Kook.Net.Core/Entities/Guilds/GuildFeature.cs +++ b/src/Kook.Net.Core/Entities/Guilds/GuildFeature.cs @@ -1,28 +1,28 @@ namespace Kook; /// -/// Represents a feature of a guild. +/// 表示一个服务器特性。 /// [Flags] public enum GuildFeature : uint { /// - /// The guild has no features. + /// 无特性。 /// None = 0, /// - /// The guild is an official KOOK guild. + /// 服务器是官方服务器。 /// Official = 1 << 0, /// - /// The guild is a partner guild. + /// 服务器是合作伙伴服务器。 /// Partner = 1 << 1, /// - /// The guild is a key account guild. + /// 服务器是重点客户服务器。 /// KeyAccount = 1 << 2, } diff --git a/src/Kook.Net.Core/Entities/Guilds/GuildFeatures.cs b/src/Kook.Net.Core/Entities/Guilds/GuildFeatures.cs index 07792028..ca1688ef 100644 --- a/src/Kook.Net.Core/Entities/Guilds/GuildFeatures.cs +++ b/src/Kook.Net.Core/Entities/Guilds/GuildFeatures.cs @@ -3,38 +3,35 @@ namespace Kook; /// -/// Represents a collection of features of a guild. +/// 表示一个服务器的所有特性。 /// public readonly struct GuildFeatures { - /// Gets a blank that grants no permissions. - public static readonly GuildPermissions None = new(); - /// - /// Gets the flags of recognized features for this guild. + /// 获取此服务器的已识别特性。 /// public GuildFeature Value { get; } /// - /// Gets a collection of strings representing the raw values of the features. + /// 获取此服务器的所有特性的原始值。 /// /// - /// Features that are not contained in can be found here. + /// 若特性未包含在 中,则可以在此找到。 /// public IReadOnlyCollection RawValues { get; } /// - /// Gets whether the guild is an official KOOK guild. + /// 获取此服务器是否为官方服务器。 /// public bool IsOfficial => HasFeature(GuildFeature.Official); /// - /// Gets whether the guild is a partner guild. + /// 获取此服务器是否为合作伙伴服务器。 /// public bool IsPartner => HasFeature(GuildFeature.Partner); /// - /// Gets whether the guild is a key account guild. + /// 获取此服务器是否为重点客户服务器。 /// public bool IsKeyAccount => HasFeature(GuildFeature.KeyAccount); @@ -45,18 +42,18 @@ internal GuildFeatures(GuildFeature value, IEnumerable rawValues) } /// - /// Returns whether or not this guild has a feature. + /// 获取此服务器是否具有指定的特性。 /// - /// The feature(s) to check for. - /// true if this guild has the provided feature(s), otherwise false. + /// 要进行检查的服务器特性。 + /// 如果此服务器具有指定的特性,则为 true,否则为 false public bool HasFeature(GuildFeature feature) => Value.HasFlag(feature); /// - /// Returns whether or not this guild has a feature. + /// 获取此服务器是否具有指定的特性。 /// - /// The feature to check for. - /// true if this guild has the provided feature, otherwise false. + /// 要进行检查的服务器特性。 + /// 如果此服务器具有指定的特性,则为 true,否则为 false public bool HasFeature(string feature) => RawValues.Contains(feature); diff --git a/src/Kook.Net.Core/Entities/Guilds/IBan.cs b/src/Kook.Net.Core/Entities/Guilds/IBan.cs index a5b8b01c..cb6c1972 100644 --- a/src/Kook.Net.Core/Entities/Guilds/IBan.cs +++ b/src/Kook.Net.Core/Entities/Guilds/IBan.cs @@ -1,31 +1,22 @@ namespace Kook; /// -/// Represents a generic ban object. +/// 表示一个通用的封禁对象。 /// public interface IBan { /// - /// Gets the banned user. + /// 获取被封禁的用户。 /// - /// - /// A user that was banned. - /// IUser User { get; } /// - /// Gets the time when the ban was issued. + /// 获取封禁的时间。 /// - /// - /// A DateTime object that represents the time when the ban was issued. - /// DateTimeOffset CreatedAt { get; } /// - /// Gets the reason why the user is banned if specified. + /// 获取封禁的原因。 /// - /// - /// A string containing the reason behind the ban; null if none is specified. - /// string Reason { get; } } diff --git a/src/Kook.Net.Core/Entities/Guilds/IGuild.cs b/src/Kook.Net.Core/Entities/Guilds/IGuild.cs index 72fac505..688ed909 100644 --- a/src/Kook.Net.Core/Entities/Guilds/IGuild.cs +++ b/src/Kook.Net.Core/Entities/Guilds/IGuild.cs @@ -4,206 +4,185 @@ namespace Kook; /// -/// Represents a generic guild/server. +/// 表示一个通用的服务器。 /// public interface IGuild : IEntity { #region General /// - /// Gets the name of this guild. + /// 获取此服务器的名称。 /// - /// - /// A string containing the name of this guild. - /// string Name { get; } /// - /// Gets the topic for the guild. + /// 获取此服务器的介绍。 /// - /// - /// The description for the guild; null if none is set. - /// string Topic { get; } /// - /// Gets the ID of the user that owns this guild. + /// 获取此服务器所有者的用户 ID。 /// - /// - /// A ulong representing the identifier of the user that owns this guild. - /// ulong OwnerId { get; } /// - /// Gets the URL of this guild's icon. + /// 获取此服务器图标的 URL。 /// - /// - /// A URL pointing to the guild's icon; null if none is set. - /// string Icon { get; } /// - /// Gets the URL of this guild's banner image. + /// 获取此服务器横幅图像的 URL。 /// - /// - /// A URL pointing to the guild's banner image; null if none is set. - /// string Banner { get; } /// - /// Gets the default notification type for this guild. + /// 获取此服务器的默认通知类型。 /// - /// - /// A representing the default notification type for this guild. - /// NotifyType NotifyType { get; } /// - /// Gets the default voice region for this guild. + /// 获取此服务器的默认语音服务器区域。 /// - /// - /// A string representing the default voice region for this guild. - /// + /// + /// 语音服务器区域是指语音服务器所在的地理位置,各个语音服务器区域由一个唯一的字符串表示。
+ /// 可用语音服务器区域参考列表: + /// + /// + /// 区域 ID + /// 区域名称 + /// + /// + /// chengdu + /// 西南(成都) + /// + /// + /// beijing + /// 华北(北京) + /// + /// + /// shanghai + /// 华东(上海) + /// + /// + /// shenzhen + /// 华南(深圳) + /// + /// + /// hk + /// 亚太(香港) + /// + /// + /// vnga + /// 国际专线(助力专享) + /// + /// + /// 此列表仅供参考。 + ///
string Region { get; } /// - /// Gets the currently associated with this guild. + /// 获取在此服务内的语音频道上建立的语音客户端。 /// - /// - /// An currently associated with this guild. - /// + /// [Obsolete("Use AudioClients instead.")] IAudioClient? AudioClient { get; } /// - /// Gets a collection of all audio clients associated with this guild. + /// 获取在此服务内的语音频道上建立的所有语音客户端。 /// + /// IReadOnlyDictionary AudioClients { get; } /// - /// Gets whether this guild is public. + /// 获取此服务器是否为公开服务器。 /// - /// - /// true if this guild is public; false otherwise. - /// bool IsOpenEnabled { get; } /// - /// Gets the open ID for this guild. + /// 获取此服务器的公开 ID。 /// - /// - /// A uint representing the open ID for this guild; - /// this property should be null if is false. - /// + /// + /// 当 true 时,此属性应该返回一个有效的公开服务器 ID; + /// 如果 false,则此属性应该返回 null。 + /// uint? OpenId { get; } /// - /// Gets the default channel ID for this guild. + /// 获取默认文字频道的 ID。 /// - /// - /// A ulong representing the default channel ID for this guild. - /// ulong? DefaultChannelId { get; } /// - /// Gets the welcome channel ID for this guild. + /// 获取欢迎通知频道的 ID。 /// - /// - /// A ulong representing the welcome channel ID for this guild. - /// ulong? WelcomeChannelId { get; } /// - /// Determines if this guild is currently connected and ready to be used. + /// 确定此服务器实体是否已准备就绪以供用户代码访问。 /// /// /// - /// This property only applies to a WebSocket-based client. + /// 此属性仅对基于网关连接的客户端有意义。 /// - /// This boolean is used to determine if the guild is currently connected to the WebSocket and is ready to be used/accessed. + /// 此属性为 true 表示,此服务器实体已完整缓存基础数据,并与网关同步。
+ /// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 ///
- /// - /// true if this guild is currently connected and ready to be used; otherwise false. - /// - bool Available { get; } + bool IsAvailable { get; } /// - /// Gets the built-in role containing all users in this guild. + /// 获取此服务器中的 @全体成员 全体成员角色。 /// - /// - /// A role object that represents an @everyone role in this guild. - /// IRole EveryoneRole { get; } /// - /// Gets the features of this guild. + /// 获取此服务器的所有特性。 /// - /// - /// An array of string representing the features of this guild. - /// GuildFeatures Features { get; } /// - /// Gets the number of boost subscribers of this guild. + /// 获取此服务器的服务器助力包的数量。 /// - /// - /// The number of boost subscribers of this guild. - /// int BoostSubscriptionCount { get; } /// - /// Gets the number of boost subscribers who activates buffer of this guild. + /// 获取此服务器来自拥有 BUFF 会员的用的服务器助力包的数量。 /// - /// - /// The number of boost subscribers who activates buffer of this guild. - /// int BufferBoostSubscriptionCount { get; } /// - /// Gets the max bitrate for voice channels in this guild. + /// 获取此服务器中语音频道的最高比特率。 /// - /// - /// A representing the maximum bitrate value allowed by Kook in this guild. - /// + /// + /// 此限制取决于服务器的助力状态。 + /// int MaxBitrate { get; } /// - /// Gets the upload limit in bytes for this guild. This number is dependent on the guild's boost status. + /// 获取此服务器的文件上传限制,以字节为单位。 /// + /// + /// 此限制取决于服务器的助力状态。 + /// ulong MaxUploadLimit { get; } /// - /// Gets the level of guild boosting in this guild. + /// 获取此服务器的服务器助力等级。 /// - /// - /// The level of guild boosting in this guild. - /// BoostLevel BoostLevel { get; } /// - /// Gets a collection of all custom emotes for this guild. + /// 获取此服务器的所有自定义表情。 /// - /// - /// A read-only collection of all custom emotes for this guild. - /// - /// IReadOnlyCollection Emotes { get; } /// - /// Gets a collection of all roles in this guild. + /// 获取此服务器的所有角色。 /// - /// - /// A read-only collection of roles found within this guild. - /// IReadOnlyCollection Roles { get; } /// - /// Gets the recommendation information for this guild. + /// 获取此服务器的推荐信息。 /// - /// - /// A recommendation object that represents the recommendation information for this guild; - /// null if the guild does not have a recommendation. - /// IRecommendInfo? RecommendInfo { get; } #endregion @@ -211,39 +190,24 @@ public interface IGuild : IEntity #region Guilds /// - /// Leaves this guild. + /// 退出此服务器。 /// - /// - /// This method will make the currently logged-in user leave the guild. - /// - /// If the user is the owner of this guild, use instead. - /// - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous leave operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步退出操作的任务。 Task LeaveAsync(RequestOptions? options = null); /// - /// Gets all subscriptions for this guild. + /// 所有此服务器的所有服务器助力包。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous retrieval operation. The task result contains - /// a collection of , each representing the subscriptions information. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有为此服务器助力的用户及所应用的服务器助力包。 Task>> GetBoostSubscriptionsAsync(RequestOptions? options = null); /// - /// Gets subscriptions which are not expired for this guild. + /// 获取此服务器所有生效中的服务器助力包。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous retrieval operation. The task result contains - /// a collection of which are not expired, - /// each representing the subscriptions information. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有为此服务器助力的用户及所应用的生效中的服务器助力包。 Task>> GetActiveBoostSubscriptionsAsync(RequestOptions? options = null); #endregion @@ -251,82 +215,64 @@ public interface IGuild : IEntity #region Guild Bans /// - /// Gets a collection of all users banned in this guild. + /// 获取此服务器的所有封禁信息。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// ban objects that this guild currently possesses, with each object containing the user banned and reason - /// behind the ban. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有封禁信息。 Task> GetBansAsync(RequestOptions? options = null); /// - /// Gets a ban object for a banned user. + /// 获取指定用户在此服务器内当前的封禁信息。 /// - /// The banned user. - /// 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. - /// + /// 要获取封禁信息的用户。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含该用户在此服务器内的封禁信息;如果该用户当前未被此服务器封禁,则返回 null Task GetBanAsync(IUser user, RequestOptions? options = null); /// - /// Gets a ban object for a banned user. + /// 获取指定用户在此服务器内的封禁信息。 /// - /// The identifier for the banned user. - /// 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. - /// + /// 要获取封禁信息的用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含该用户在此服务器内的封禁信息;如果该用户未被此服务器封禁,或封禁已过期或解除,则返回 null Task GetBanAsync(ulong userId, RequestOptions? options = null); /// - /// Bans the user from this guild and optionally prunes their recent messages. + /// 封禁服务器内的用户。 /// - /// The user to ban. - /// The number of days to remove messages from this user for, and this number must be between [0, 7]. - /// The reason of the ban to be written in the audit log. - /// The options to be used when sending the request. - /// is not between 0 to 7. - /// - /// A task that represents the asynchronous add operation for the ban. - /// + /// 要封禁的用户。 + /// 要删除此服务器中来自此用户的最近几天的消息,范围为 070 表示不删除。 + /// 封禁原因。 + /// 发送请求时要使用的选项。 + /// 超出了 0 至 7 的范围。 + /// 一个表示异步封禁操作的任务。 Task AddBanAsync(IUser user, int pruneDays = 0, string? reason = null, RequestOptions? options = null); /// - /// Bans the user from this guild and optionally prunes their recent messages. + /// 封禁服务器内的用户。 /// - /// The identifier of the user to ban. - /// The number of days to remove messages from this user for, and this number must be between [0, 7]. - /// The reason of the ban to be written in the audit log. - /// The options to be used when sending the request. - /// is not between 0 to 7. - /// - /// A task that represents the asynchronous add operation for the ban. - /// + /// 要封禁的用户的 ID。 + /// 要删除此服务器中来自此用户的最近几天的消息,范围为 070 表示不删除。 + /// 封禁原因。 + /// 发送请求时要使用的选项。 + /// 超出了 0 至 7 的范围。 + /// 一个表示异步封禁操作的任务。 Task AddBanAsync(ulong userId, int pruneDays = 0, string? reason = null, RequestOptions? options = null); /// - /// Unbans the user if they are currently banned. + /// 解除服务器对用户的封禁。 /// - /// The user to be unbanned. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous removal operation for the ban. - /// + /// 要解除封禁的用户。 + /// 发送请求时要使用的选项。 + /// 一个表示异步封禁解除操作的任务。 Task RemoveBanAsync(IUser user, RequestOptions? options = null); /// - /// Unbans the user if they are currently banned. + /// 解除服务器对用户的封禁。 /// - /// The identifier of the user to be unbanned. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous removal operation for the ban. - /// + /// 要解除封禁的用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步封禁解除操作的任务。 Task RemoveBanAsync(ulong userId, RequestOptions? options = null); #endregion @@ -334,145 +280,113 @@ public interface IGuild : IEntity #region Channels /// - /// Gets a collection of all channels 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 a read-only collection of - /// generic channels found within this guild. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有频道。 Task> GetChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a channel in this guild. + /// 获取此服务器内的频道。 /// - /// The identifier for the channel. - /// 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 generic channel - /// associated with the specified ; null if none is found. - /// - Task GetChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, - RequestOptions? options = null); + /// 要获取的频道的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null + Task GetChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of all text channels 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 a read-only collection of - /// message channels found within this guild. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有具有文字聊天能力的频道。 + /// + /// 语音频道也是一种文字频道,此方法本意用于获取所有具有文字聊天能力的频道,通过此方法获取到的文字频道列表中也包含了语音频道。 + /// 如需获取频道的实际类型,请参考 。 + /// Task> GetTextChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a text channel in this guild. + /// 获取此服务器内指定具有文字聊天能力的频道。 /// - /// The identifier for the text channel. - /// 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 - /// associated with the specified ; null if none is found. - /// - Task GetTextChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, - RequestOptions? options = null); + /// 要获取的频道的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null + /// + /// 语音频道也是一种文字频道,此方法本意用于获取具有文字聊天能力的频道。如果通过此方法传入的 ID 对应的频道是语音频道,那么也会返回对应的语音频道实体。 + /// 如需获取频道的实际类型,请参考 。 + /// + Task GetTextChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of all voice channels 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 a read-only collection of - /// voice channels found within this guild. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有具有语音聊天能力的频道。 Task> GetVoiceChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a voice channel in this guild. + /// 获取此服务器内指定具有语音聊天能力的频道。 /// - /// The identifier for the voice channel. - /// 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 voice channel associated - /// with the specified ; null if none is found. - /// - Task GetVoiceChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, - RequestOptions? options = null); + /// 要获取的频道的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null + Task GetVoiceChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of all category channels 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 a read-only collection of - /// category channels found within this guild. - /// - Task> GetCategoryChannelsAsync(CacheMode mode = CacheMode.AllowDownload, - RequestOptions? options = null); + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有分组频道。 + Task> GetCategoryChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets the default text channel for 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 default text channel for this guild; - /// null if none is found. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的默认文字频道;如果未找到,则返回 null Task GetDefaultChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets the welcome text channel for 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 welcome text channel for this guild; - /// null if none is found. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的欢迎通知频道;如果未找到,则返回 null Task GetWelcomeChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Creates a new text channel in this guild. + /// 在此服务器内创建一个新的文字频道。 /// - /// The new name for the text channel. - /// The delegate containing the properties to be applied to the channel upon its creation. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// text channel. - /// + /// 频道的名称。 + /// 一个包含要应用到新创建频道的配置的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的文字频道。 Task CreateTextChannelAsync(string name, Action? func = null, RequestOptions? options = null); /// - /// Creates a new voice channel in this guild. + /// 在此服务器内创建一个新的语音频道。 /// - /// 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. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// voice channel. - /// + /// 频道的名称。 + /// 一个包含要应用到新创建频道的配置的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的语音频道。 Task CreateVoiceChannelAsync(string name, Action? func = null, RequestOptions? options = null); /// - /// Creates a new channel category in this guild. + /// 在此服务器内创建一个新的分组频道。 /// - /// 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. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// category channel. - /// + /// 频道的名称。 + /// 一个包含要应用到新创建频道的配置的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的分组频道。 Task CreateCategoryChannelAsync(string name, Action? func = null, RequestOptions? options = null); #endregion @@ -480,37 +394,28 @@ Task> GetCategoryChannelsAsync(CacheMode m #region Invites /// - /// Gets a collection of all invites in this guild. + /// 获取此服务器内的所有邀请信息。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// invite, each representing information for an invite found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器内的所有邀请信息。 Task> GetInvitesAsync(RequestOptions? options = null); /// - /// Creates a new invite to this channel. + /// 创建一个到此服务器的新邀请。 /// - /// The time until the invite expires. Set to InviteMaxAge.NeverExpires to never expire. - /// The max amount of times this invite may be used. Set to InviteMaxUses.Unlimited to have unlimited uses. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous invite creation operation. The task result contains an invite - /// metadata object containing information for the created invite. - /// + /// 邀请链接的有效时长, 表示永不过期。 + /// 邀请链接的可用人次, 表示无限制。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的邀请链接的元数据,其中包含有关邀请链接的信息。 Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge._604800, InviteMaxUses maxUses = InviteMaxUses.Unlimited, RequestOptions? options = null); /// - /// Creates a new invite to this channel. + /// 创建一个到此服务器的新邀请。 /// - /// The time (in seconds) until the invite expires. Set to null to never expire. - /// The max amount of times this invite may be used. Set to null to have unlimited uses. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous invite creation operation. The task result contains an invite - /// metadata object containing information for the created invite. - /// + /// 邀请链接的有效时长,null 表示永不过期。 + /// 邀请链接的可用人次,null 表示无限制。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的邀请链接的元数据,其中包含有关邀请链接的信息。 Task CreateInviteAsync(int? maxAge = 604800, int? maxUses = null, RequestOptions? options = null); #endregion @@ -518,22 +423,18 @@ Task> GetCategoryChannelsAsync(CacheMode m #region Roles /// - /// Gets a role in this guild. + /// 获取此服务器内的角色。 /// - /// The identifier for the role. - /// - /// A role that is associated with the specified ; null if none is found. - /// + /// 要获取的角色的 ID。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的角色;如果未找到,则返回 null IRole? GetRole(uint id); /// - /// Creates a new role with the provided name. + /// 在此服务器内创建一个新角色。 /// - /// The new name for the role. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created role. - /// + /// 角色的名称。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的角色。 Task CreateRoleAsync(string name, RequestOptions? options = null); #endregion @@ -541,112 +442,86 @@ Task> GetCategoryChannelsAsync(CacheMode m #region Users /// - /// Gets a collection of all users in this guild. + /// 获取此服务器内的所有用户。 /// - /// - /// This method retrieves all users found within 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 a collection of guild - /// users found within this guild. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器内的所有用户。 Task> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a user from this guild. + /// 获取此服务器内的用户。 /// /// - /// This method retrieves a user found within this guild. + /// 此方法获取加入到此服务器内的用户。 /// - /// This may return null in the WebSocket implementation due to incomplete user collection in - /// large guilds. + /// 此方法在网关的实现中可能返回 null,因为在大型服务器中,用户列表的缓存可能不完整。 /// /// - /// The identifier of the user. - /// 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 guild user - /// associated with the specified ; null if none is found. - /// + /// 要获取的用户的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的用户;如果未找到,则返回 null Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets the current user for 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 currently logged-in - /// user within this guild. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器内当前登录的用户。 Task GetCurrentUserAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets the owner of 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 owner of this guild. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有者。 Task GetOwnerAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Downloads all users for this guild if the current list is incomplete. + /// 下载此服务器内的所有用户。 /// /// - /// This method downloads all users found within this guild through the Gateway and caches them. + /// 此方法会下载所有加入到此服务器内的用户,并缓存它们。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous download operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步下载操作的任务。 Task DownloadUsersAsync(RequestOptions? options = null); /// - /// Downloads all voice states for this guild. + /// 下载此服务器内的所有语音状态。 /// /// - /// This method downloads all voice states for this guild through the Gateway and caches them. + /// 此方法会下载此服务器内的所有语音状态,并缓存它们。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous download operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步下载操作的任务。 Task DownloadVoiceStatesAsync(RequestOptions? options = null); /// - /// Downloads all boost subscriptions for this guild. + /// 下载此服务器内的所有服务器助力信息。 /// /// - /// This method downloads all boost subscriptions for this guild through the Gateway and caches them. - /// To download all boost subscriptions, the current user must has the - /// permission. + /// 此方法会通过网关下载此服务器内的所有服务器助力信息,并缓存它们。 + /// 要下载所有服务器助力信息,当前用户必须具有 权限。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous download operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步下载操作的任务。 Task DownloadBoostSubscriptionsAsync(RequestOptions? options = null); /// - /// Gets a collection of users in this guild that the name or nickname contains the - /// provided string at . + /// 搜索加入到此服务器内匹配指定搜索条件的所有用户。 /// /// - /// The can not be higher than . + /// 此方法使用指定的属性搜索服务器用户。要查看可用的属性,请参考 。 /// - /// A delegate containing the properties to search users with. - /// The maximum number of users to be gotten. - /// 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 a collection of guild - /// users that matches the properties with the provided at . - /// + /// 一个包含要搜索的用户属性及排序条件的委托。 + /// 搜索结果的最大数量。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与提供的 中指定的属性匹配的服务器用户集合。 IAsyncEnumerable> SearchUsersAsync(Action func, int limit = KookConfig.MaxUsersPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); @@ -655,57 +530,44 @@ IAsyncEnumerable> SearchUsersAsync(Action - /// Gets a collection of emotes from this guild. + /// 获取此服务器的所有自定义表情。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection - /// of emotes found within the guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有自定义表情。 Task> GetEmotesAsync(RequestOptions? options = null); /// - /// Gets a specific emote from this guild. + /// 获取此服务器的指定自定义表情。 /// - /// The identifier for the guild emote. - /// 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. - /// + /// 要获取的自定义表情的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的自定义表情;如果未找到,则返回 null Task GetEmoteAsync(string id, RequestOptions? options = null); /// - /// Creates a new in this guild. + /// 在此服务器内创建一个新的自定义表情。 /// - /// The name of the guild emote. - /// The image of the new emote. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the created emote. - /// + /// 新自定义表情的名称。 + /// 新自定义表情的图像信息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果包含新创建的自定义表情。 Task CreateEmoteAsync(string name, Image image, RequestOptions? options = null); /// - /// Modifies an existing in this guild. + /// 修改此服务器内的现有自定义表情。 /// - /// The emote to be modified. - /// The new name of the emote. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. The task result contains the modified - /// emote. - /// + /// 要修改的自定义表情。 + /// 新的自定义表情名称。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。任务的结果包含修改后的自定义表情。 Task ModifyEmoteNameAsync(GuildEmote emote, string name, RequestOptions? options = null); /// - /// Deletes an existing from this guild. + /// 删除此服务器内的现有自定义表情。 /// - /// The emote to delete. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous removal operation. - /// + /// 要删除的自定义表情。 + /// 发送请求时要使用的选项。 + /// 一个表示异步删除操作的任务。 Task DeleteEmoteAsync(GuildEmote emote, RequestOptions? options = null); #endregion @@ -713,12 +575,12 @@ IAsyncEnumerable> SearchUsersAsync(Action - /// Moves the user to the voice channel. + /// 移动用户到语音频道。 /// - /// The users to move. - /// the channel where the user gets moved to. - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for moving a user. + /// 要移动的用户。 + /// 要移动用户到的语音频道。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移动操作的任务。 Task MoveUsersAsync(IEnumerable users, IVoiceChannel targetChannel, RequestOptions? options = null); #endregion @@ -726,14 +588,11 @@ IAsyncEnumerable> SearchUsersAsync(Action - /// Gets a badge which is associated with this guild. + /// 获取与此服务器关联的徽章。 /// - /// The that specifies the style of the badge. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the stream of the badge - /// associated with this guild. - /// + /// 要获取的徽章的样式。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与此服务器关联的徽章的流。 Task GetBadgeAsync(BadgeStyle style = BadgeStyle.GuildName, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs b/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs index 9799f736..09d65af3 100644 --- a/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs +++ b/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs @@ -1,95 +1,68 @@ namespace Kook; /// -/// Represents a generic recommendation information. +/// 获取一个通用的推荐信息。 /// public interface IRecommendInfo { /// - /// Gets the ID of the recommended guild. + /// 获取推荐服务器的 ID。 /// - /// - /// A ulong representing the ID of the recommended guild. - /// ulong GuildId { get; } /// - /// Gets the open ID for the recommended guild. + /// 获取推荐服务器的公开 ID。 /// uint? OpenId { get; } /// - /// Gets the default channel ID of the recommended guild. + /// 获取推荐服务器的默认文字频道 ID。 /// - /// - /// A ulong representing the default channel ID of the recommended guild. - /// ulong DefaultChannelId { get; } /// - /// Gets the name of the recommended guild. + /// 获取推荐服务器的名称。 /// - /// - /// A string representing the name of the recommended guild. - /// string Name { get; } /// - /// Gets the icon URL of the recommended guild. + /// 获取推荐服务器的图标 URL。 /// - /// - /// A string representing the icon URL of the recommended guild. - /// string Icon { get; } /// - /// Gets the banner URL of the recommended guild. + /// 获取推荐服务器的横幅图像的 URL。 /// - /// - /// A string representing the banner URL of the recommended guild. - /// string Banner { get; } /// - /// Gets the description of the recommended guild. + /// 获取推荐服务器的介绍。 /// - /// - /// A string representing the description of the recommended guild. - /// string Description { get; } /// - /// Gets the status of the recommended guild. + /// 获取推荐服务器的状态。 /// - /// - /// A int representing the status of the recommended guild. - /// int Status { get; } /// - /// Gets the tag of the recommended guild. + /// 获取推荐服务器的标签。 /// - /// - /// A string representing the tag of the recommended guild. - /// string Tag { get; } /// - /// Gets the features of the recommended guild. + /// 获取推荐服务器的特性。 /// GuildFeatures Features { get; } /// - /// Gets the certifications of the recommended guild. + /// 获取推荐服务器的所有认证。 /// IReadOnlyCollection? Certifications { get; } /// - /// Gets the boost level of the recommended guild. + /// 获取推荐服务器的服务器助力等级。 /// - /// - /// A representing the boost level of the recommended guild. - /// BoostLevel BoostLevel { get; } /// @@ -98,11 +71,8 @@ public interface IRecommendInfo string CustomId { get; } /// - /// Gets whether the recommended guild is an official partner. + /// 获取推荐服务器是否是官方合作伙伴。 /// - /// - /// A bool representing whether the recommended guild is an official partner. - /// bool IsOfficialPartner { get; } /// @@ -116,10 +86,7 @@ public interface IRecommendInfo int AuditStatus { get; } /// - /// Gets the number of days need to be waited before the recommendation information can be modified again. + /// 获取推荐服务器要等待多少天才能再次修改推荐信息。 /// - /// - /// An representing the number of days need to be waited before the recommendation information can be modified again. - /// int DaysBeforeModify { get; } } diff --git a/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs b/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs index 76e77800..261dd127 100644 --- a/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs +++ b/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// Specifies that how the guild should notify the user. +/// 表示服务器应如何通知用户。 /// public enum NotifyType { /// - /// Notifies the user as the default behavior of the guild. + /// 以服务器的默认行为通知用户。 /// Default = 0, /// - /// Notifies the user of all messages. + /// 通知用户所有消息。 /// AcceptAll = 1, /// - /// Notifies the user of the messages which mention the user. + /// 通知提及用户的消息。 /// OnlyMentioned = 2, /// - /// ]Never notifies the user. + /// 从不通知用户。 /// Muted = 3 } diff --git a/src/Kook.Net.Core/Entities/IDeletable.cs b/src/Kook.Net.Core/Entities/IDeletable.cs index 7ba19a94..33ca2d64 100644 --- a/src/Kook.Net.Core/Entities/IDeletable.cs +++ b/src/Kook.Net.Core/Entities/IDeletable.cs @@ -1,13 +1,13 @@ namespace Kook; /// -/// Determines whether the object is deletable or not. +/// 表示实体对象可以被删除。 /// public interface IDeletable { /// - /// Deletes this object and all its children. + /// 删除此对实体象及其所有子实体对象。 /// - /// The options to be used when sending the request. + /// 发送请求时要使用的选项。 Task DeleteAsync(RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/IEntity.cs b/src/Kook.Net.Core/Entities/IEntity.cs index d5cbd3de..4ffa698e 100644 --- a/src/Kook.Net.Core/Entities/IEntity.cs +++ b/src/Kook.Net.Core/Entities/IEntity.cs @@ -1,14 +1,14 @@ namespace Kook; /// -/// Represents a generic entity that has a unique identifier. +/// 表示一个通用的具有唯一标识符的实体。 /// -/// The type of the unique identifier. +/// 唯一标识符的类型。 public interface IEntity where TId : IEquatable { /// - /// Gets the unique identifier for this object. + /// 获取此实体的唯一标识符。 /// TId Id { get; } } diff --git a/src/Kook.Net.Core/Entities/IMentionable.cs b/src/Kook.Net.Core/Entities/IMentionable.cs index 760ff007..70b2c0ce 100644 --- a/src/Kook.Net.Core/Entities/IMentionable.cs +++ b/src/Kook.Net.Core/Entities/IMentionable.cs @@ -1,23 +1,17 @@ namespace Kook; /// -/// Determines whether the object is mentionable or not. +/// 表示一个可以被提及的实体对象。 /// public interface IMentionable { /// - /// Returns a special string used to mention this object in plain text formatted text. + /// 获取一个用于在纯文本格式文本中提及此对象的格式化字符串。 /// - /// - /// A string that is recognized by Kook as a mention in plain text formatted text. - /// string PlainTextMention { get; } /// - /// Returns a special string used to mention this object in KMarkdown formatted text. + /// 返回一个用于在 KMarkdown 格式文本中提及此对象的格式化字符串。 /// - /// - /// A string that is recognized by Kook as a mention in KMarkdown formatted text. - /// string KMarkdownMention { get; } } diff --git a/src/Kook.Net.Core/Entities/IUpdateable.cs b/src/Kook.Net.Core/Entities/IUpdateable.cs index a204b9e7..c23d2288 100644 --- a/src/Kook.Net.Core/Entities/IUpdateable.cs +++ b/src/Kook.Net.Core/Entities/IUpdateable.cs @@ -1,21 +1,21 @@ namespace Kook; /// -/// Defines whether the object is updateable or not. +/// 表示一个可以被更新的实体对象。 /// +/// +/// 更新操作表示的是从 KOOK REST API 获取最新数据并替换当前对象的属性,而非修改 KOOK 服务端的数据。 +/// public interface IUpdateable { /// - /// Updates this object's properties with its current state. + /// 通过 REST API 获取此实体对象的最新状态,并替换当前对象的属性。 /// - /// The options to be used when sending the request. - /// - /// A task that represents an asynchronous reloading operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步更新操作的任务。 /// /// - /// This method will fetch the latest data from REST API, - /// and replace the current object's properties with the new data. + /// 此方法将从 KOOK REST API 获取最新数据,并替换当前对象的属性,而非使用指定的属性修改 KOOK 服务端的数据。 /// /// Task UpdateAsync(RequestOptions? options = null); diff --git a/src/Kook.Net.Core/Entities/Image.cs b/src/Kook.Net.Core/Entities/Image.cs index 0793c7bc..9533aeb7 100644 --- a/src/Kook.Net.Core/Entities/Image.cs +++ b/src/Kook.Net.Core/Entities/Image.cs @@ -1,29 +1,23 @@ namespace Kook; /// -/// An image that will be uploaded to Kook. +/// 表一个要上传到 KOOK 的图像。 /// public struct Image : IDisposable { private bool _isDisposed; /// - /// Gets the stream to be uploaded to Kook. + /// 获取此图像的流。 /// public Stream Stream { get; } - /// - /// Gets the file extension of the image if possible. - /// internal string? FileExtension { get; } /// - /// Create the image with a . + /// 使用指定的流初始化一个 解构的新实例。 /// - /// - /// The to create the image with. Note that this must be some type of stream - /// with the contents of a file in it. - /// + /// 图像的流。 public Image(Stream stream) { _isDisposed = false; @@ -40,33 +34,15 @@ internal Image(Stream stream, string fileExtension) } /// - /// Create the image from a file path. + /// 通过文件路径创建图像。 /// + /// 文件的路径。 /// - /// This file path is NOT validated and is passed directly into a - /// . + /// 此构造函数会使用 获取文件的扩展名,然后将其直接传递给 + /// 方法。 /// - /// The path to the file. - /// - /// is a zero-length string, contains only white space, or contains one or more invalid - /// characters as defined by . - /// - /// is null. - /// - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on - /// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 - /// characters. - /// - /// is in an invalid format. - /// - /// The specified is invalid, (for example, it is on an unmapped drive). - /// - /// - /// specified a directory.-or- The caller does not have the required permission. - /// - /// The file specified in was not found. - /// - /// An I/O error occurred while opening the file. + /// + /// public Image(string path) { _isDisposed = false; diff --git a/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs b/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs index 3d8b9a67..e97233c8 100644 --- a/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs +++ b/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs @@ -1,63 +1,57 @@ namespace Kook; /// -/// Represents a generic intimacy. +/// 表示一个通用的亲密度。 /// +/// +/// 由于亲密度的使用率较低,官方已隐藏亲密度的管理入口。如要管理亲密度,请访问 +/// https://developer.kookapp.cn/bot/cohesion,在左上角切换至要管理其亲密度的应用。 +/// public interface IIntimacy : IEntity { /// - /// Gets the user associated with this intimacy. + /// 获取与此亲密度相关的用户。 /// - /// - /// An representing the user associated with this intimacy. - /// IUser User { get; } /// - /// Gets the social information associated with this intimacy. + /// 获取与此亲密度关联的社交信息。 /// - /// - /// A string representing the social information associated with this intimacy. - /// string SocialInfo { get; } /// - /// Gets the time at which the user read the message. + /// 获取用户最近一次查看此亲密度的时间。 /// - /// - /// A time at which the user read the message. - /// DateTimeOffset LastReadAt { get; } /// - /// Gets the time at which this intimacy was modified last time. + /// 获取此亲密度最近一次修改的时间。 /// - /// - /// A time at which this intimacy was modified last time. - /// DateTimeOffset? LastModifyAt { get; } /// - /// Gets the score associated with this intimacy. + /// 获取此亲密度的分数。 /// - /// - /// A int representing the score associated with this intimacy. - /// + /// + /// 亲密度的分数是一个整数,表示用户与此亲密度的亲密程度,最小值为 0,最大值为 2200。
+ /// 亲密度以 10 颗颜色与样式不同的心形图案组成。
+ /// 当亲密度分数不小于 1000 时,亲密度将显示为红色,其中,实心图案的数量为 (Score - 1000) / 100 的四舍五入值,最大值为 10,其余为空心图案。
+ /// 当亲密度分数小于 1000 时,亲密度将显示为灰色,其中,心碎图案的数量为 10 - Score / 100 的四舍五入值,其余为空心图案。 + ///
int Score { get; } /// - /// Gets the images associated with this intimacy. + /// 获取此亲密度的所有形象图像。 /// - /// - /// An containing the images associated with this intimacy. - /// IReadOnlyCollection Images { get; } /// - /// Updates the intimacy information with this user. + /// 修改此用户的亲密度信息。 /// - /// A delegate containing the properties to modify the with. - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for updating the intimacy information. + /// 一个包含修改此亲密度信息的委托。 + /// 发送请求时要使用的选项。 + /// + /// 一个表示异步修改操作的任务。 + /// Task UpdateAsync(Action func, RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs b/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs index daee6bee..fe23179c 100644 --- a/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs +++ b/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs @@ -1,15 +1,10 @@ namespace Kook; /// -/// Represents a single image of an intimacy. +/// 表示一个亲密度的形象图像。 /// public class IntimacyImage { - /// - /// Initializes a new instance of the class. - /// - /// The ID of the image of an intimacy. - /// The URL of the image of an intimacy. internal IntimacyImage(uint id, string url) { Id = id; @@ -17,18 +12,12 @@ internal IntimacyImage(uint id, string url) } /// - /// Gets the ID of the image of an intimacy. + /// 获取此亲密度的形象图像的唯一标识符。 /// - /// - /// An int representing the ID of the image of an intimacy. - /// public uint Id { get; } /// - /// Gets the URL of the image of an intimacy. + /// 获取此亲密度的形象图像的 URL。 /// - /// - /// A string representing the URL of the image of an intimacy. - /// public string Url { get; } } diff --git a/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs b/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs index 2e3f215a..b4774653 100644 --- a/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs +++ b/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs @@ -1,9 +1,9 @@ namespace Kook; /// -/// Properties that are used to modify an with the specified changes. +/// 提供用于修改 的属性。 /// -/// +/// public class IntimacyProperties { internal IntimacyProperties(string socialInfo, int score) @@ -13,17 +13,28 @@ internal IntimacyProperties(string socialInfo, int score) } /// - /// The social information to be set on the . + /// 获取或设置要设置到此亲密度的社交信息。 /// - public string SocialInfo { get; set; } + /// + /// 社交信息是展示给用户的文本块。
+ /// 如果此值为 null,则不会修改此亲密度的社交信息。 + ///
+ public string? SocialInfo { get; set; } /// - /// The score to be set on the . + /// 获取或设置要设置到此亲密度的分数。 /// - public int Score { get; set; } + /// + /// 如果此值为 null,则不会修改此亲密度的分数。 + /// + /// + public int? Score { get; set; } /// - /// The ID of the image to be updated on the . + /// 获取或设置要设置到此亲密度的形象图像的 ID。 /// + /// + /// 如果此值为 null,则不会修改此亲密度的形象图像。 + /// public uint? ImageId { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Invites/IInvite.cs b/src/Kook.Net.Core/Entities/Invites/IInvite.cs index ffe016a6..32dd594c 100644 --- a/src/Kook.Net.Core/Entities/Invites/IInvite.cs +++ b/src/Kook.Net.Core/Entities/Invites/IInvite.cs @@ -1,143 +1,104 @@ namespace Kook; /// -/// Represents a generic invite. +/// 表示一个通用的邀请。 /// public interface IInvite : IEntity, IDeletable { /// - /// Gets the unique identifier for this invite. + /// 获取此邀请的唯一代码。 /// - /// - /// A string containing the invite code (e.g. wEAF5t). - /// string Code { get; } /// - /// Gets the URL used to accept this invite using . + /// 获取用于接受此邀请的 URL,URL 的路径中包含 属性的值。 /// - /// - /// A string containing the full invite URL (e.g. https://kaihei.co/wEAF5t). - /// 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. + /// 获取此邀请链接指向的频道。 /// - /// - /// A generic channel that the invite points to. - /// IChannel Channel { get; } /// - /// Gets the type of the channel this invite is linked to. + /// 获取此邀请链接指向的频道的类型。 /// ChannelType ChannelType { get; } /// - /// Gets the ID of the channel this invite is linked to. + /// 获取此邀请链接指向的频道的 ID。 /// - /// - /// A ulong representing the channel identifier that the invite points to. - /// ulong? ChannelId { get; } /// - /// Gets the name of the channel this invite is linked to. + /// 获取此邀请链接指向的频道的名称。 /// - /// - /// A string containing the name of the channel that the invite points to. - /// string? ChannelName { get; } /// - /// Gets the guild this invite is linked to. + /// 获取此邀请链接指向的服务器。 /// - /// - /// A guild object representing the guild that the invite points to. - /// IGuild Guild { get; } /// - /// Gets the ID of the guild this invite is linked to. + /// 获取此邀请链接指向的服务器的 ID。 /// - /// - /// A ulong representing the guild identifier that the invite points to. - /// ulong? GuildId { get; } /// - /// Gets the name of the guild this invite is linked to. + /// 获取此邀请链接指向的服务器的名称。 /// - /// - /// A string containing the name of the guild that the invite points to. - /// string GuildName { get; } /// - /// Gets the time at which this invite was created. + /// 获取此邀请的创建时间。 /// - /// - /// A representing the time at which this invite was created. - /// DateTimeOffset CreatedAt { get; } /// - /// Gets the time at which this invite will expire. + /// 获取此邀请的过期时间。 /// - /// - /// A representing the time until this invite expires; null if this - /// invite never expires. - /// + /// + /// 如果此邀请永不过期,则此属性的值为 null。 + /// DateTimeOffset? ExpiresAt { get; } /// - /// Gets the time span until the invite expires. + /// 获取此邀请的有效时长。 /// - /// - /// A representing the time span until this invite expires; null if this - /// invite never expires. - /// + /// + /// 如果此邀请永不过期,则此属性的值为 null。 + /// TimeSpan? MaxAge { get; } /// - /// Gets the max number of uses this invite may have. + /// 获取此邀请的可用人次。 /// - /// - /// An int representing the number of uses this invite may be accepted until it is removed - /// from the guild; null if none is set. - /// + /// + /// 如果此邀请不限制可用人次,则此属性的值为 null。 + /// int? MaxUses { get; } /// - /// Gets the number of times this invite has been used. + /// 获取此邀请已被使用的次数。 /// - /// - /// An int representing the number of times this invite has been used; null if none is set. - /// int? Uses { get; } /// - /// Gets the number of times this invite still remains. + /// 获取此邀请剩余可用次数。 /// - /// - /// An int representing the number of times this invite still remains; null if none is set. - /// + /// + /// 如果此邀请不限制可用人次,则此属性的值为 null。 + /// int? RemainingUses { get; } /// - /// Gets the number of users that have accepted this invite. + /// 获取已接受此邀请的用户数量。 /// - /// - /// An int representing the number of users that have accepted this invite. - /// int InvitedUsersCount { get; } } diff --git a/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs b/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs index f27bd6c2..c6458159 100644 --- a/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs +++ b/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs @@ -1,42 +1,42 @@ namespace Kook; /// -/// Specifies the time in second after which an will be expired. +/// 表示一个邀请的最大有效时长。 /// public enum InviteMaxAge { /// - /// The invite will never expire. + /// 永不过期。 /// NeverExpires = 0, /// - /// The invite will expire after half an hour (1800 seconds). + /// 此邀请在创建后半小时(1800 秒)后过期。 /// _1800 = 1800, /// - /// The invite will expire after one hour (3600 seconds). + /// 此邀请在创建后一小时(3600 秒)后过期。 /// _3600 = 3600, /// - /// The invite will expire after 6 hours (21600 seconds). + /// 此邀请在创建后 6 小时(21600 秒)后过期。 /// _21600 = 21600, /// - /// The invite will expire after half a day (43200 seconds). + /// 此邀请在创建后半天(43200 秒)后过期。 /// _43200 = 43200, /// - /// The invite will expire after one day (86400 seconds). + /// 此邀请在创建后一天(86400 秒)后过期。 /// _86400 = 86400, /// - /// The invite will expire after one week (604800 seconds). + /// 此邀请在创建后一周(604800 秒)后过期。 /// _604800 = 604800 } diff --git a/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs b/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs index 668ae800..afed6853 100644 --- a/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs +++ b/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs @@ -1,42 +1,42 @@ namespace Kook; /// -/// Specifies the number of uses after which an will be expired. +/// 表示一个邀请的可用人次。 /// public enum InviteMaxUses { /// - /// This can be used for unlimited times. + /// 此邀请不限制可用人次。 /// Unlimited = -1, /// - /// This can be used only once. + /// 此邀请最多只能使用一次。 /// _1 = 1, /// - /// This can be used for 5 times. + /// 此邀请最多只能使用 5 次。 /// _5 = 5, /// - /// This can be used for 10 times. + /// 此邀请最多只能使用 10 次。 /// _10 = 10, /// - /// This can be used for 25 times. + /// 此邀请最多只能使用 25 次。 /// _25 = 25, /// - /// This can be used for 50 times. + /// 此邀请最多只能使用 50 次。 /// _50 = 50, /// - /// This can be used for 100 times. + /// 此邀请最多只能使用 100 次。 /// _100 = 100 } diff --git a/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs b/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs index 00689234..ef3ef8e7 100644 --- a/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs +++ b/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// Specifies the type of the attachment. +/// 表示附件的类型。 /// public enum AttachmentType { /// - /// The attachment is a file. + /// 附件是一份文件。 /// File, /// - /// The attachment is an image. + /// 附件是一张图片。 /// Image, /// - /// The attachment is a video. + /// 附件是一段视频。 /// Video, /// - /// The attachment is an audio. + /// 附件是一段音频。 /// Audio } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs index 4f57f86b..165e1dda 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Represents a card object seen in an . +/// 表示一个卡片对象,可用于卡片消息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Card : ICard, IEquatable, IEquatable @@ -25,63 +25,46 @@ internal Card(CardTheme theme, CardSize size, Color? color, ImmutableArray Modules.Length; /// - /// Gets the theme of this card. + /// 获取卡片的主题。 /// - /// - /// A value that represents the theme of this card. - /// public CardTheme Theme { get; } /// - /// Gets the color of this embed. + /// 获取卡片侧边的颜色。 /// - /// - /// A represents a color present on the side of the card, or null if none is set. - /// public Color? Color { get; } /// - /// Gets the size of this card. + /// 获取卡片的大小。 /// - /// - /// A value that represents the size of this card. - /// public CardSize Size { get; } /// - /// Gets the modules in this card. + /// 获取卡片的模块。 /// - /// - /// An array of the modules of the card. - /// public ImmutableArray Modules { get; } private string DebuggerDisplay => $"{Type} ({Modules.Length} Modules)"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(Card left, Card right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(Card left, Card right) => !(left == right); - /// Determines whether the specified object is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is Card card && Equals(card); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] Card? card) => GetHashCode() == card?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs index a53781cf..b4514aeb 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs @@ -3,18 +3,19 @@ namespace Kook; /// -/// Represents a builder class for creating a . +/// 用来构建 卡片的构建器。 /// public class CardBuilder : ICardBuilder, IEquatable, IEquatable { /// - /// Initializes a new instance of the class with the specified parameters. + /// 初始化一个 类的新实例。 /// - /// The theme of the card. - /// The color displayed along the left side of the card. - /// The size of the card. - /// The modules in the card. - public CardBuilder(CardTheme theme = CardTheme.Primary, Color? color = null, CardSize size = CardSize.Large, IList? modules = null) + /// 卡片的主题。 + /// 卡片侧边的颜色。 + /// 卡片的大小。 + /// 卡片的模块。 + public CardBuilder(CardTheme theme = CardTheme.Primary, Color? color = null, CardSize size = CardSize.Large, + IList? modules = null) { Theme = theme; Color = color; @@ -22,55 +23,43 @@ public CardBuilder(CardTheme theme = CardTheme.Primary, Color? color = null, Car Modules = modules ?? []; } - /// - /// Gets the type of the card. - /// - /// - /// A value that represents the type of the card. - /// + /// public CardType Type => CardType.Card; /// - /// Gets or sets the theme of the card. + /// 获取或设置卡片的主题。 /// - /// - /// A value that represents the theme of the card. - /// + /// + /// 属性的优先级高于此属性。 + /// public CardTheme Theme { get; set; } /// - /// Gets or sets the color displayed along the left side of the card. + /// 获取或设置卡片侧边的颜色。 /// - /// - /// A value that represents the color displayed along the left side of the card. - /// + /// + /// 此属性的优先级高于 属性。 + /// public Color? Color { get; set; } /// - /// Gets or sets the size of the card. + /// 获取或设置卡片的大小。 /// - /// - /// A value that represents the size of the card. - /// - public CardSize Size { get; set; } = CardSize.Large; + public CardSize Size { get; set; } /// - /// Gets or sets the modules in the card. + /// 获取或设置卡片的模块。 /// - /// - /// An containing the modules in the card. - /// public IList Modules { get; set; } /// - /// Sets the theme of the card. + /// 设置卡片的主题。 /// - /// - /// A value that represents the theme of the card to be set. - /// - /// - /// The current builder. - /// + /// 卡片的主题。 + /// 当前构建器。 + /// + /// 属性的优先级高于 属性。 + /// public CardBuilder WithTheme(CardTheme theme) { Theme = theme; @@ -78,14 +67,13 @@ public CardBuilder WithTheme(CardTheme theme) } /// - /// Sets the color displayed along the left side of the card. + /// 设置卡片侧边的颜色。 /// - /// - /// A value that represents the color displayed along the left side of the card to be set. - /// - /// - /// The current builder. - /// + /// 卡片侧边的颜色。 + /// 当前构建器。 + /// + /// 属性的优先级高于 属性。 + /// public CardBuilder WithColor(Color? color) { Color = color; @@ -93,14 +81,10 @@ public CardBuilder WithColor(Color? color) } /// - /// Sets the size of the card. + /// 设置卡片的大小。 /// - /// - /// A value that represents the size of the card to be set. - /// - /// - /// The current builder. - /// + /// 卡片的大小。 + /// 当前构建器。 public CardBuilder WithSize(CardSize size) { Size = size; @@ -108,14 +92,10 @@ public CardBuilder WithSize(CardSize size) } /// - /// Adds a module to the card. + /// 添加一个模块到卡片。 /// - /// - /// An that represents the module to be added to the card. - /// - /// - /// The current builder. - /// + /// 要添加的模块。 + /// 当前构建器。 public CardBuilder AddModule(IModuleBuilder module) { Modules.Add(module); @@ -123,14 +103,10 @@ public CardBuilder AddModule(IModuleBuilder module) } /// - /// Adds a module to the card. + /// 添加一个模块到卡片。 /// - /// - /// The action to adds a module to the card. - /// - /// - /// The current builder. - /// + /// 一个包含对要添加的新创建的模块进行配置的操作的委托。 + /// 当前构建器。 public CardBuilder AddModule(Action? action = null) where T : IModuleBuilder, new() { @@ -141,13 +117,11 @@ public CardBuilder AddModule(Action? action = null) } /// - /// Builds the into a . + /// 构建当前构建器为一个 。 /// - /// - /// A represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The theme of the card cannot be invisible, which is reserved for text graphics mixed messages. + /// 卡片的主题不能为 ,该值保留用于图文混排消息,暂不支持手动构建。 /// public Card Build() { @@ -161,34 +135,24 @@ public Card Build() ICard ICardBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; otherwise, false. - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(CardBuilder? left, CardBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; otherwise, false. - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(CardBuilder? left, CardBuilder? right) => !(left == right); - /// - /// Determines whether the specified is equal to the current . - /// - /// The object to compare with the current . - /// true if the specified object is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is CardBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] CardBuilder? cardBuilder) { if (cardBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs index 3c8431d9..b9d7f8f1 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs @@ -1,17 +1,23 @@ namespace Kook; /// -/// Specifies the size of a card. +/// 表示卡片的大小。 /// public enum CardSize { /// - /// The card is a small card. + /// 卡片的尺寸较小。 /// + /// + /// 卡片的宽度为 276px。 + /// Small, /// - /// The card is a large card. + /// 卡片的尺寸较大。 /// + /// + /// 卡片的最大宽度为 436px。 + /// Large } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs index e1b96fdd..f832fd42 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs @@ -1,47 +1,81 @@ namespace Kook; /// -/// Specifies the theme of the card. +/// 表示卡片的主题。 /// +/// +/// 卡片的主题主要用于控制卡片左侧边的颜色。 +/// public enum CardTheme : uint { /// - /// The card shows like a regular message. + /// 外观表现为主要卡片。 /// + /// + /// 此主题与 主题相同。
+ /// 卡片侧边的颜色大体为天蓝色,浅色模式下为 #0096FF(http://www.color-hex.com/color/0096ff),深色模式下为 + /// #33AAFF(http://www.color-hex.com/color/33aaff)。 + ///
Primary, /// - /// The card shows like a success message. + /// 外观表现为成功。 /// + /// + /// 卡片侧边的颜色大体为薄荷绿色 #00D287(http://www.color-hex.com/color/00d287)。 + /// Success, /// - /// The card shows like a warning message. + /// 外观表现为警告。 /// + /// + /// 卡片侧边的颜色大体为橙色,浅色模式下为 #FF8200(http://www.color-hex.com/color/ff8200),深色模式下为 + /// #FF8F19(http://www.color-hex.com/color/ff8f19)。 + /// Warning, /// - /// The card shows like an error message. + /// 外观表现为危险。 /// + /// + /// 卡片侧边的颜色大体为鲜红色,浅色模式下为 #FF3200(http://www.color-hex.com/color/ff3200),深色模式下为 + /// #FF4D42(http://www.color-hex.com/color/ff4d42)。 + /// Danger, /// - /// The card shows like an info message. + /// 外观表现为信息。 /// + /// + /// 此主题与 主题相同。
+ /// 卡片侧边的颜色大体为天蓝色,浅色模式下为 #0096FF(http://www.color-hex.com/color/0096ff),深色模式下为 + /// #33AAFF(http://www.color-hex.com/color/33aaff)。 + ///
Info, /// - /// The card shows like a light message. + /// 外观表现为次要卡片。 /// + /// + /// 卡片侧边的颜色大体为灰色,浅色模式下为 #666666(http://www.color-hex.com/color/666666),深色模式下为 + /// #AAAAAA(http://www.color-hex.com/color/aaaaaa)。 + /// Secondary, /// - /// The card shows like a dark message. + /// 外观表现为无侧边。 /// + /// + /// 卡片无侧边。 + /// None, /// - /// The card is a text graphic mixed message. + /// 外观表现为图文混排消息。 /// + /// + /// 卡片无侧边,无底色,无边框。此主题用于图文混排消息的展示。 + /// Invisible } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs index c0b28d1a..0762e03c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs @@ -1,12 +1,12 @@ namespace Kook; /// -/// Specifies the type of the card. +/// 表示一个 的类型。 /// public enum CardType { /// - /// The card is a normal card. + /// 常规卡片。 /// Card } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ButtonElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ButtonElementBuilder.cs index 7062b7a3..aea7099e 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ButtonElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ButtonElementBuilder.cs @@ -4,29 +4,35 @@ namespace Kook; /// -/// An element builder to build a . +/// 用来构建 元素的构建器。 /// public class ButtonElementBuilder : IElementBuilder, IEquatable, IEquatable { /// - /// Gets the maximum button text length allowed by Kook. + /// 按钮文本的最大长度。 /// public const int MaxButtonTextLength = 40; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public ButtonElementBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The text of the button. - /// The theme of the button. - /// The value of the button. - /// The type of the click event. + /// 按钮的文本。 + /// 按钮的主题。 + /// 按钮的值。 + /// 按钮的点击事件类型。 + /// + /// 如果 设置为 , + /// 则在用户点击按钮时,KOOK 会通过网关下发按钮点击事件,并携带 的值。
+ /// 如果 设置为 , + /// 则在用户点击按钮时,KOOK 会将用户重定向到 指定的 URL。 + ///
public ButtonElementBuilder(string text, ButtonTheme theme = ButtonTheme.Primary, string? value = null, ButtonClickEventType click = ButtonClickEventType.None) { @@ -36,60 +42,49 @@ public ButtonElementBuilder(string text, ButtonTheme theme = ButtonTheme.Primary Click = click; } - /// - /// Gets the type of the element that this builder builds. - /// - /// - /// An that represents the type of element that this builder builds. - /// + /// public ElementType Type => ElementType.Button; /// - /// Gets or sets the theme of the button. + /// 获取或设置按钮的主题。 /// - /// - /// A that represents the theme of the button. - /// public ButtonTheme Theme { get; set; } /// - /// Gets or sets the value of the button. + /// 获取或设置按钮的值。 /// - /// - /// A string that represents the value of the button. - /// /// - /// If the is set to , - /// the value of the property will be returned when the button is clicked. + /// 如果 设置为 , + /// 则在用户点击按钮时,KOOK 会通过网关下发按钮点击事件,并携带此属性的值。
+ /// 如果 设置为 , + /// 则在用户点击按钮时,KOOK 会将用户重定向到此属性指定的 URL。 ///
public string? Value { get; set; } /// - /// Gets or sets the type of the click event. + /// 获取或设置按钮被点击时触发的事件类型。 /// - /// - /// A that represents the type of the click event. - /// + /// + /// 如果此属性设置为 , + /// 则在用户点击按钮时,KOOK 会通过网关下发按钮点击事件,并携带 的值。
+ /// 如果此属性设置为 , + /// 则在用户点击按钮时,KOOK 会将用户重定向到 指定的 URL。 + ///
public ButtonClickEventType Click { get; set; } /// - /// Gets or sets the text element of the button. + /// 获取或设置按钮的文本元素。 /// - /// - /// An that represents the text of the button. - /// /// - /// This property only takes a or a . + /// 此属性只接受 。 /// public IElementBuilder? Text { get; set; } /// - /// Sets the theme of a . + /// 设置按钮的主题,值将被设置到 属性上。 /// - /// The theme to be set. - /// - /// The current builder. - /// + /// 按钮的主题。 + /// 当前构建器。 public ButtonElementBuilder WithTheme(ButtonTheme theme) { Theme = theme; @@ -97,12 +92,10 @@ public ButtonElementBuilder WithTheme(ButtonTheme theme) } /// - /// Sets the value of a . + /// 设置按钮的值,值将被设置到 属性上。 /// - /// The value to be set. - /// - /// The current builder. - /// + /// 按钮的值。 + /// 当前构建器。 public ButtonElementBuilder WithValue(string? value) { Value = value; @@ -110,14 +103,10 @@ public ButtonElementBuilder WithValue(string? value) } /// - /// Sets the type of the event to be fired when the button is clicked in a . + /// 设置按钮被点击时触发的事件类型,值将被设置到 属性上。 /// - /// - /// The type of the event to be fired when the button is clicked. - /// - /// - /// The current builder. - /// + /// 按钮的点击事件类型。 + /// 当前构建器。 public ButtonElementBuilder WithClick(ButtonClickEventType click) { Click = click; @@ -125,14 +114,10 @@ public ButtonElementBuilder WithClick(ButtonClickEventType click) } /// - /// Sets the text of a . + /// 设置按钮的文本。 /// - /// - /// The builder of a , which will be set as the text of the button. - /// - /// - /// The current builder. - /// + /// 按钮的文本。 + /// 当前构建器。 public ButtonElementBuilder WithText(PlainTextElementBuilder text) { Text = text; @@ -140,14 +125,10 @@ public ButtonElementBuilder WithText(PlainTextElementBuilder text) } /// - /// Sets the text of a . + /// 设置按钮的文本。 /// - /// - /// The builder of a , which will be set as the text of the button. - /// - /// - /// The current builder. - /// + /// 按钮的文本。 + /// 当前构建器。 public ButtonElementBuilder WithText(KMarkdownElementBuilder text) { Text = text; @@ -155,16 +136,13 @@ public ButtonElementBuilder WithText(KMarkdownElementBuilder text) } /// - /// Sets the text of a . + /// 设置按钮的文本。 /// /// - /// The action to create a builder of an , - /// which will be set as the text of the button. - /// The action must return a or a . + /// 一个包含对新创建的文本元素构建器进行配置的操作的委托,委托的入参类型必须是 + /// 或 。 /// - /// - /// The current builder. - /// + /// 当前构建器。 public ButtonElementBuilder WithText(Action action) where T : IElementBuilder, new() { @@ -175,19 +153,16 @@ public ButtonElementBuilder WithText(Action action) } /// - /// Sets the text of a . + /// 设置按钮的文本。 /// /// - /// A string to be set as the text of the button. + /// 按钮的文本。 /// /// - /// A bool indicating whether the text is in KMarkdown format; - /// if true, the text will be set as a ; - /// if false, the text will be set as a . + /// 文本是否为 KMarkdown 格式;如果为 true,则文本将被设置为 ;如果为 + /// false,则文本将被设置为 。 /// - /// - /// The current builder. - /// + /// 当前构建器。 public ButtonElementBuilder WithText(string text, bool isKMarkdown = false) { Text = isKMarkdown switch @@ -199,25 +174,26 @@ public ButtonElementBuilder WithText(string text, bool isKMarkdown = false) } /// - /// Builds the into a . + /// 构建当前构建器为一个 。 /// - /// - /// A represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is neither a nor a . + /// 既不是 也不是 。 /// /// - /// The is null. + /// null。 /// /// - /// The is empty. + /// 为空字符串。 /// /// - /// The length of is greater than . + /// 文本的长度超过了 。 /// /// - /// The of a button with a link event type is null or empty. + /// null 或空。 + /// + /// + /// 不是有效的 URL。 /// [MemberNotNull(nameof(Text))] public ButtonElement Build() @@ -247,7 +223,8 @@ public ButtonElement Build() if (Click == ButtonClickEventType.Link) { if (Value is null || string.IsNullOrEmpty(Value)) - throw new ArgumentException("The value of a button with a link event type cannot be null or empty.", nameof(Value)); + throw new ArgumentException("The value of a button with a link event type cannot be null or empty.", + nameof(Value)); UrlValidation.Validate(Value); } @@ -259,30 +236,24 @@ public ButtonElement Build() IElement IElementBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ButtonElementBuilder? left, ButtonElementBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ButtonElementBuilder? left, ButtonElementBuilder? right) => !(left == right); - /// - /// Determines whether the specified is equal to the current . - /// - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ButtonElementBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ButtonElementBuilder? buttonElementBuilder) { if (buttonElementBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/IElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/IElementBuilder.cs index 2841fe74..786c2ed2 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/IElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/IElementBuilder.cs @@ -1,23 +1,18 @@ namespace Kook; /// -/// A generic builder for creating an . +/// 表示一个通用的元素构建器,用于构建一个 。 /// public interface IElementBuilder { /// - /// Specifies the type of the element to be created. + /// 获取此构建器构建的元素的类型。 /// - /// - /// An that specifies the type of the element to be created. - /// ElementType Type { get; } /// - /// Builds the into an . + /// 构建当前构建器为一个 。 /// - /// - /// An represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 IElement Build(); } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ImageElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ImageElementBuilder.cs index 7e5697c8..9d47aac7 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ImageElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ImageElementBuilder.cs @@ -4,31 +4,33 @@ namespace Kook; /// -/// An element builder to build an . +/// 用来构建 元素的构建器。 /// public class ImageElementBuilder : IElementBuilder, IEquatable, IEquatable { /// - /// Gets the maximum image alternative text length allowed by Kook. + /// 图片替代文本的最大长度。 /// public const int MaxAlternativeLength = 20; /// - /// Initialized a new instance of the class. + /// 初始化一个 类的新实例。 /// public ImageElementBuilder() { } /// - /// Initialized a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The source of the image. - /// The alternative text of the image. - /// The size of the image. - /// Whether the image should be rendered as a circle. - public ImageElementBuilder(string source, string? alternative = null, ImageSize size = ImageSize.Small, - bool circle = false) + /// 图片的源。 + /// 图片的替代文本。 + /// 图片的大小。 + /// 图片是否应渲染为圆形。 + /// + /// 仅在 中生效, 中不生效。 + /// + public ImageElementBuilder(string source, string? alternative = null, ImageSize? size = null, bool circle = false) { Source = source; Alternative = alternative; @@ -36,57 +38,43 @@ public ImageElementBuilder(string source, string? alternative = null, ImageSize Circle = circle; } - /// - /// Gets the type of the element that this builder builds. - /// - /// - /// An that represents the type of element that this builder builds. - /// + /// public ElementType Type => ElementType.Image; /// - /// Gets or sets the source of an . + /// 获取或设置图片的源。 /// - /// - /// A string that represents the source of the . - /// + /// + /// 图片的媒体类型仅支持 image/jpegimage/gifimage/png。 + /// public string? Source { get; set; } /// - /// Gets or sets the alternative text of an . + /// 获取或设置图片的替代文本。 /// - /// - /// A string that represents the alternative text of the . - /// public string? Alternative { get; set; } /// - /// Gets or sets the size of the image of an . + /// 获取或设置 的图片大小。 /// - /// - /// An that represents the size of the image of the ; - /// null if the size is not specified. - /// + /// + /// 当前属性仅在 中生效, 中不生效。 + /// public ImageSize? Size { get; set; } /// - /// Gets or sets whether the image should be rendered as a circle. + /// 获取或设置图片是否应渲染为圆形。 /// - /// - /// true if the image should be rendered as a circle; otherwise, false; - /// or null if whether the image should be rendered as a circle is not specified. - /// public bool? Circle { get; set; } /// - /// Sets the source of an . + /// 设置图片的源,值将被设置到 属性上。 /// - /// - /// The source to be set. - /// - /// - /// The current builder. - /// + /// 图片的源。 + /// 当前构建器。 + /// + /// 图片的媒体类型仅支持 image/jpegimage/gifimage/png。 + /// public ImageElementBuilder WithSource(string? source) { Source = source; @@ -94,14 +82,10 @@ public ImageElementBuilder WithSource(string? source) } /// - /// Sets the alternative text of an . + /// 设置图片的替代文本,值将被设置到 属性上。 /// - /// - /// The alternative text to be set. - /// - /// - /// The current builder. - /// + /// 图片的替代文本。 + /// 当前构建器。 public ImageElementBuilder WithAlternative(string? alternative) { Alternative = alternative; @@ -109,14 +93,10 @@ public ImageElementBuilder WithAlternative(string? alternative) } /// - /// Sets the size of the image of an . + /// 设置图片的大小,值将被设置到 属性上。 /// - /// - /// The size to be set. - /// - /// - /// The current builder. - /// + /// 图片的大小。 + /// 当前构建器。 public ImageElementBuilder WithSize(ImageSize? size) { Size = size; @@ -124,14 +104,10 @@ public ImageElementBuilder WithSize(ImageSize? size) } /// - /// Sets whether the image should be rendered as a circle. + /// 设置图片是否应渲染为圆形,值将被设置到 属性上。 /// - /// - /// true if the image should be rendered as a circle; otherwise, false. - /// - /// - /// The current builder. - /// + /// 图片是否应渲染为圆形。 + /// 当前构建器。 public ImageElementBuilder WithCircle(bool? circle) { Circle = circle; @@ -139,22 +115,20 @@ public ImageElementBuilder WithCircle(bool? circle) } /// - /// Builds the into an . + /// 构建当前构建器为一个 。 /// - /// - /// An represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The url is null. + /// null。 /// /// - /// The url is empty. + /// 为空字符串。 /// - /// - /// The url does not include a protocol (either HTTP or HTTPS). + /// + /// 不是有效的 URL。 /// /// - /// The length of is greater than . + /// 的长度超过了 。 /// [MemberNotNull(nameof(Source))] public ImageElement Build() @@ -177,15 +151,10 @@ public ImageElement Build() } /// - /// Initialized a new instance of the class - /// with the specified content. + /// 使用指定的图片源初始化一个新的 类的实例。 /// - /// - /// The content of the . - /// - /// - /// An object that is initialized with the specified image source. - /// + /// 图片的源。 + /// 一个使用指定的图片源初始化的 类的实例。 public static implicit operator ImageElementBuilder(string source) => new(source); /// @@ -193,30 +162,24 @@ public ImageElement Build() IElement IElementBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ImageElementBuilder? left, ImageElementBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ImageElementBuilder? left, ImageElementBuilder? right) => !(left == right); - /// - /// Determines whether the specified is equal to the current . - /// - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ImageElementBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ImageElementBuilder? imageElementBuilder) { if (imageElementBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/KMarkdownElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/KMarkdownElementBuilder.cs index cc3700fb..d2420c1c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/KMarkdownElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/KMarkdownElementBuilder.cs @@ -3,54 +3,44 @@ namespace Kook; /// -/// An element builder to build a . +/// 用来构建 元素的构建器。 /// public class KMarkdownElementBuilder : IElementBuilder, IEquatable, IEquatable { /// - /// Gets the maximum KMarkdown length allowed by Kook. + /// KMarkdown 文本的最大长度。 /// public const int MaxKMarkdownLength = 5000; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public KMarkdownElementBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// + /// KMarkdown 文本内容。 public KMarkdownElementBuilder(string? content) { Content = content; } - /// - /// Gets the type of the element that this builder builds. - /// - /// - /// An that represents the type of element that this builder builds. - /// + /// public ElementType Type => ElementType.KMarkdown; /// - /// Gets or sets the content of a . + /// 获取或设置 KMarkdown 的文本内容。 /// - /// - /// The content of the . - /// public string? Content { get; set; } /// - /// Sets the content of a . + /// 设置 KMarkdown 的文本内容,值将被设置到 属性上。 /// - /// The text to be set as the content. - /// - /// The current builder. - /// + /// KMarkdown 的文本内容。 + /// 当前构建器。 public KMarkdownElementBuilder WithContent(string content) { Content = content; @@ -58,16 +48,14 @@ public KMarkdownElementBuilder WithContent(string content) } /// - /// Builds the into a . + /// 构建当前构建器为一个 。 /// - /// - /// A represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is null. + /// null。 /// /// - /// The length of is greater than . + /// 的长度超过了 。 /// [MemberNotNull(nameof(Content))] public KMarkdownElement Build() @@ -84,15 +72,10 @@ public KMarkdownElement Build() } /// - /// Initialized a new instance of the class - /// with the specified content. + /// 使用指定的 KMarkdown 文本内容初始化一个新的 类的实例。 /// - /// - /// The content of the . - /// - /// - /// A object that is initialized with the specified content. - /// + /// KMarkdown 文本内容。 + /// 一个使用指定的 KMarkdown 文本内容初始化的 类的实例。 public static implicit operator KMarkdownElementBuilder(string content) => new(content); /// @@ -100,30 +83,24 @@ public KMarkdownElement Build() IElement IElementBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(KMarkdownElementBuilder? left, KMarkdownElementBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(KMarkdownElementBuilder? left, KMarkdownElementBuilder? right) => !(left == right); - /// - /// Determines whether the specified is equal to the current . - /// - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is KMarkdownElementBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] KMarkdownElementBuilder? kMarkdownElementBuilder) { if (kMarkdownElementBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ParagraphStructBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ParagraphStructBuilder.cs index 280f0af0..0d480761 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ParagraphStructBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/ParagraphStructBuilder.cs @@ -3,27 +3,27 @@ namespace Kook; /// -/// An element builder to build a . +/// 用来构建 元素的构建器。 /// public class ParagraphStructBuilder : IElementBuilder, IEquatable, IEquatable { /// - /// Returns the maximum number of fields allowed by Kook. + /// 区域文本内文本块的最大数量。 /// public const int MaxFieldCount = 50; /// - /// Returns the minimum number of columns allowed by Kook. + /// 区域文本的最小列数。 /// public const int MinColumnCount = 1; /// - /// Returns the maximum number of columns allowed by Kook. + /// 区域文本的最大列数。 /// public const int MaxColumnCount = 3; /// - /// Initializes a new class. + /// 初始化一个 类的新实例。 /// public ParagraphStructBuilder() { @@ -31,47 +31,37 @@ public ParagraphStructBuilder() } /// - /// Initializes a new class. + /// 初始化一个 类的新实例。 /// + /// 区域文本的列数。 + /// 区域文本的文本块。 public ParagraphStructBuilder(int columnCount, IList? fields = null) { ColumnCount = columnCount; Fields = fields ?? []; } - /// - /// Gets the type of the element that this builder builds. - /// - /// - /// An that represents the type of element that this builder builds. - /// + /// public ElementType Type => ElementType.Paragraph; /// - /// Gets or sets the number of columns of the paragraph. + /// 获取或设置区域文本的列数。 /// - /// - /// An int that represents the number of columns of the paragraph. - /// + /// + /// 默认值为 。 + /// public int ColumnCount { get; set; } = MinColumnCount; /// - /// Gets or sets the fields of the paragraph. + /// 获取或设置区域文本的文本块。 /// - /// - /// An that represents the fields of the paragraph. - /// public IList Fields { get; set; } /// - /// Sets the number of columns of the paragraph. + /// 设置区域文本的列数。 /// - /// - /// An int that represents the number of columns of the paragraph. - /// - /// - /// The current builder. - /// + /// 区域文本的列数。 + /// 当前构建器。 public ParagraphStructBuilder WithColumnCount(int count) { ColumnCount = count; @@ -79,14 +69,10 @@ public ParagraphStructBuilder WithColumnCount(int count) } /// - /// Adds a field to the paragraph. + /// 添加一个纯文本文本块到区域文本。 /// - /// - /// A that represents the field to add. - /// - /// - /// The current builder. - /// + /// 要添加的纯文本文本块。 + /// 当前构建器。 public ParagraphStructBuilder AddField(PlainTextElementBuilder field) { Fields.Add(field); @@ -94,14 +80,10 @@ public ParagraphStructBuilder AddField(PlainTextElementBuilder field) } /// - /// Adds a field to the paragraph. + /// 添加一个 KMarkdown 文本块到区域文本。 /// - /// - /// A that represents the field to add. - /// - /// - /// The current builder. - /// + /// 要添加的 KMarkdown 文本块。 + /// 当前构建器。 public ParagraphStructBuilder AddField(KMarkdownElementBuilder field) { Fields.Add(field); @@ -109,14 +91,12 @@ public ParagraphStructBuilder AddField(KMarkdownElementBuilder field) } /// - /// Adds a field to the paragraph. + /// 添加一个文本块到区域文本。 /// /// - /// The action to create a builder of a , which will be added to the paragraph. + /// 用于创建一个 的构建器的操作,该构建器将被添加到区域文本。 /// - /// - /// The current builder. - /// + /// 当前构建器。 public ParagraphStructBuilder AddField(Action? action = null) where T : IElementBuilder, new() { @@ -127,26 +107,23 @@ public ParagraphStructBuilder AddField(Action? action = null) } /// - /// Builds the into a . + /// 构建当前构建器为一个 。 /// - /// - /// A represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is less than . + /// 不足 。 /// /// - /// The is greater than . + /// 超出了 。 /// /// - /// The is null. + /// null。 /// /// - /// The number of is greater than . + /// 的数量超出了 。 /// /// - /// The contain an element that is not a - /// or . + /// 包含了既不是 也不是 的元素。 /// public ParagraphStruct Build() { @@ -190,30 +167,24 @@ public ParagraphStruct Build() IElement IElementBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ParagraphStructBuilder? left, ParagraphStructBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ParagraphStructBuilder? left, ParagraphStructBuilder? right) => !(left == right); - /// - /// Determines whether the specified is equal to the current . - /// - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ParagraphStructBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ParagraphStructBuilder? paragraphStructBuilder) { if (paragraphStructBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/PlainTextElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/PlainTextElementBuilder.cs index d4f198b2..db2a2a2a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/PlainTextElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/Builders/PlainTextElementBuilder.cs @@ -3,20 +3,17 @@ namespace Kook; /// -/// An element builder to build a . +/// 用来构建 元素的构建器。 /// public class PlainTextElementBuilder : IElementBuilder, IEquatable, IEquatable { /// - /// Gets the maximum plain text length allowed by Kook. + /// 纯文本的最大长度。 /// - /// - /// An int that represents the maximum plain text length allowed by Kook. - /// public const int MaxPlainTextLength = 2000; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public PlainTextElementBuilder() { @@ -24,49 +21,36 @@ public PlainTextElementBuilder() } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The content of the . - /// A boolean value that indicates whether the shortcuts should be translated into emojis. + /// 纯文本的内容。 + /// 是否将 Emoji 表情符号的短代码解析为表情符号。 + /// public PlainTextElementBuilder(string? content, bool emoji = true) { Content = content; Emoji = emoji; } - /// - /// Gets the type of the element that this builder builds. - /// - /// - /// An that represents the type of element that this builder builds. - /// + /// public ElementType Type => ElementType.PlainText; /// - /// Gets or sets the content of a . + /// 获取或设置纯文本的文本内容。 /// - /// - /// The content of the . - /// public string? Content { get; set; } /// - /// Gets whether the shortcuts should be translated into emojis. + /// 获取或设置 Emoji 表情符号的短代码是否应被解析为表情符号。 /// - /// - /// A boolean value that indicates whether the shortcuts should be translated into emojis. - /// true if the shortcuts should be translated into emojis; - /// false if the text should be displayed as is. - /// + /// public bool Emoji { get; set; } = true; /// - /// Sets the content of a . + /// 设置纯文本的文本内容。 /// - /// The text to be set as the content. - /// - /// The current builder. - /// + /// 纯文本的文本内容。 + /// 当前构建器。 public PlainTextElementBuilder WithContent(string content) { Content = content; @@ -74,16 +58,11 @@ public PlainTextElementBuilder WithContent(string content) } /// - /// Sets whether the shortcuts should be translated into emojis. + /// 设置 Emoji 表情符号的短代码是否应被解析为表情符号。 /// - /// - /// A boolean value that indicates whether the shortcuts should be translated into emojis. - /// true if the shortcuts should be translated into emojis; - /// false if the text should be displayed as is. - /// - /// - /// The current builder. - /// + /// Emoji 表情符号的短代码是否应被解析为表情符号。 + /// 当前构建器。 + /// public PlainTextElementBuilder WithEmoji(bool emoji) { Emoji = emoji; @@ -91,16 +70,14 @@ public PlainTextElementBuilder WithEmoji(bool emoji) } /// - /// Builds the into a . + /// 构建当前构建器为一个 。 /// - /// - /// A represents the built element object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is null. + /// null。 /// /// - /// The length of the is greater than . + /// 的长度超过了 。 /// [MemberNotNull(nameof(Content))] public PlainTextElement Build() @@ -117,15 +94,10 @@ public PlainTextElement Build() } /// - /// Initialized a new instance of the class - /// with the specified content. + /// 使用指定的纯文本内容初始化一个新的 类的实例。 /// - /// - /// The content of the . - /// - /// - /// A object that is initialized with the specified content. - /// + /// 纯文本内容。 + /// 一个使用指定的纯文本内容初始化的 类的实例。 public static implicit operator PlainTextElementBuilder(string content) => new(content); /// @@ -133,30 +105,24 @@ public PlainTextElement Build() IElement IElementBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(PlainTextElementBuilder? left, PlainTextElementBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(PlainTextElementBuilder? left, PlainTextElementBuilder? right) => !(left == right); - /// - /// Determines whether the specified is equal to the current . - /// - /// The to compare with the current . - /// + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is PlainTextElementBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] PlainTextElementBuilder? plainTextElementBuilder) { if (plainTextElementBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs index 0b88ffd6..4e5b5cd3 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Specifies the event type fired when a is clicked. +/// 表示 被点击时触发的事件类型。 /// public enum ButtonClickEventType { /// - /// Nothing will happen when the button is clicked. + /// 用户点击按钮时不会触发任何事件。 /// None, /// - /// The user will be redirected to the specified URL when the button is clicked. + /// 用户点击按钮时将会被重定向到指定的 URL。 /// Link, /// - /// The value of the button's property will be submitted. + /// 用户点击按钮时将会提交按钮的 属性的值,KOOK 将会通过网关携带此值下发事件。 /// ReturnValue } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs index b37e5c18..085fa363 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// A button element that can be used in an . +/// 按钮元素,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ButtonElement : IElement, IEquatable, IEquatable @@ -17,76 +17,50 @@ internal ButtonElement(ButtonTheme? theme, string? value, ButtonClickEventType? Text = text; } - /// - /// Gets the theme of the button. - /// - /// - /// An value that represents the theme of the button. - /// + /// public ElementType Type => ElementType.Button; /// - /// Gets the theme of the button. + /// 获取按钮的主题。 /// - /// - /// A value that represents the theme of the button. - /// public ButtonTheme? Theme { get; } /// - /// Gets the value of the button. + /// 获取按钮的值。 /// - /// - /// A string value that represents the value of the button. - /// public string? Value { get; } /// - /// Gets the event type fired when the button is clicked. + /// 获取按钮被点击时触发的事件类型。 /// - /// - /// A value that represents the event type fired when the button is clicked. - /// public ButtonClickEventType? Click { get; } /// - /// Gets the text element of the button. + /// 获取按钮的文本元素。 /// - /// - /// An value that represents the text element of the button. - /// public IElement Text { get; } private string DebuggerDisplay => $"{Type}: {Text} ({Click}, {Value}, {Theme})"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; otherwise, false. - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ButtonElement? left, ButtonElement? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; otherwise, false. - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ButtonElement? left, ButtonElement? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ButtonElement buttonElement && Equals(buttonElement); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ButtonElement? buttonElement) => GetHashCode() == buttonElement?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs index a4ba52a2..05abcff4 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs @@ -1,37 +1,59 @@ namespace Kook; /// -/// Specifies the theme of a . +/// 表示 的主题。 /// public enum ButtonTheme { /// - /// The button is a primary button. + /// 外观表现为主要操作。 /// + /// + /// 按钮的背景色大体为草绿色,浅色模式下为 #7ACC35(http://www.color-hex.com/color/7acc35),深色模式下为 + /// #6CBF00(http://www.color-hex.com/color/6cbf00)。 + /// Primary, /// - /// The button is a success button. + /// 外观表现为成功。 /// + /// + /// 按钮的背景色大体为薄荷绿色 #00D287(http://www.color-hex.com/color/00d287)。 + /// Success, /// - /// The button is a warning button. + /// 外观表现为警告。 /// + /// + /// 按钮的背景色大体为橙色,浅色模式下为 #FF8200(http://www.color-hex.com/color/ff8200),深色模式下为 + /// #FF8F19(http://www.color-hex.com/color/ff8f19)。 + /// Warning, /// - /// The button is a danger button. + /// 外观表现为危险。 /// + /// + /// 按钮的背景色大体为鲜红色,浅色模式下为 #FF3200(http://www.color-hex.com/color/ff3200),深色模式下为 + /// #FF4D42(http://www.color-hex.com/color/ff4d42)。 + /// Danger, /// - /// The button is an info button. + /// 外观表现为信息。 /// + /// + /// 按钮的背景色大体为天蓝色,浅色模式下为 #0096FF(http://www.color-hex.com/color/0096ff),深色模式下为 + /// #33AAFF(http://www.color-hex.com/color/33aaff)。 + /// Info, /// - /// The button is a secondary button. + /// 外观表现为次要操作。 /// + /// + /// 按钮的背景色大体为灰色 #BBBEC4(http://www.color-hex.com/color/bbbec4),不透明度为 0.3。 + /// Secondary } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs index 0e4547b6..4ab2948f 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs @@ -1,32 +1,32 @@ namespace Kook; /// -/// Specifies the type of an . +/// 表示一个 的类型。 /// public enum ElementType { /// - /// The element is a plain text element. + /// 纯文本元素。 /// PlainText, /// - /// The element is a KMarkdown element. + /// KMarkdown 文本元素。 /// KMarkdown, /// - /// The element is an image element. + /// 图片元素。 /// Image, /// - /// The element is a button element. + /// 按钮元素。 /// Button, /// - /// The element is a paragraph struct. + /// 区域文本结构。 /// Paragraph } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs index fe0fe1d1..ac796549 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs @@ -1,12 +1,12 @@ namespace Kook; /// -/// A generic element used in modules. +/// 表示一个通用的用于模块内的元素。 /// public interface IElement { /// - /// Gets the type of this element. + /// 获取元素的类型。 /// ElementType Type { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs index 274add2f..9cf60f06 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// An image element that can be used in an . +/// 图片元素,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ImageElement : IElement, IEquatable, IEquatable @@ -17,74 +17,50 @@ internal ImageElement(string source, string? alternative = null, ImageSize? size Circle = circle; } - /// - /// Gets the type of the element. - /// - /// - /// An value that represents the theme of the button. - /// + /// public ElementType Type => ElementType.Image; /// - /// Gets the source of the image. + /// 获取图像的源。 /// - /// - /// A string that represents the source of the image. - /// public string Source { get; } /// - /// Gets the alternative text of the image. + /// 获取图像的替代文本。 /// - /// - /// A string that represents the alternative text of the image. - /// public string? Alternative { get; } /// - /// Gets the size of the image. + /// 获取图像的大小。 /// - /// - /// An that represents the size of the image; - /// or null if the size is not specified. - /// public ImageSize? Size { get; } /// - /// Gets a value indicating whether the image should be rendered as a circle. + /// 获取图片是否渲染为圆形。 /// - /// - /// true if the image should be rendered as a circle; otherwise, false; - /// or null if whether the image should be rendered as a circle is not specified. - /// public bool? Circle { get; } private string DebuggerDisplay => $"{Type}: {Source}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ImageElement? left, ImageElement? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ImageElement? left, ImageElement? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ImageElement imageElement && Equals(imageElement); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ImageElement? imageElement) => GetHashCode() == imageElement?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs index fa238193..55142932 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the size of the image in . +/// 表示 中的图像大小。 /// public enum ImageSize { /// - /// The image is displayed at small size. + /// 图像以小尺寸显示。 /// Small, /// - /// The image is displayed at large size. + /// 图像以大尺寸显示。 /// Large } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs index 0265d5f2..50c3aec9 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// A KMarkdown element that can be used in an . +/// KMarkdown 文本元素,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class KMarkdownElement : IElement, IEquatable, IEquatable @@ -14,20 +14,12 @@ internal KMarkdownElement(string content) Content = content; } - /// - /// Gets the type of the element. - /// - /// - /// An value that represents the theme of the button. - /// + /// public ElementType Type => ElementType.KMarkdown; /// - /// Gets the KMarkdown content of the element. + /// 获取 KMarkdown 文本的内容。 /// - /// - /// A string that represents the KMarkdown content of the element. - /// public string Content { get; } /// @@ -36,29 +28,24 @@ internal KMarkdownElement(string content) private string DebuggerDisplay => $"{Type}: {Content}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(KMarkdownElement? left, KMarkdownElement? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(KMarkdownElement? left, KMarkdownElement? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is KMarkdownElement kMarkdownElement && Equals(kMarkdownElement); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] KMarkdownElement? kMarkdownElement) => GetHashCode() == kMarkdownElement?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs index b0b5094a..a16c8f37 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// A paragraph struct that can be used in modules. +/// 区域文本结构,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ParagraphStruct : IElement, IEquatable, IEquatable @@ -16,56 +16,40 @@ internal ParagraphStruct(int? columnCount, ImmutableArray fields) Fields = fields; } - /// - /// Gets the type of the element. - /// - /// - /// An value that represents the theme of the button. - /// + /// public ElementType Type => ElementType.Paragraph; /// - /// Gets the number of columns in the paragraph. + /// 获取区域文本的列数。 /// - /// - /// An int value that represents the number of columns in the paragraph. - /// public int? ColumnCount { get; } /// - /// Gets the fields in the paragraph. + /// 获取区域文本的文本块。 /// - /// - /// An array that contains the fields in the paragraph. - /// public ImmutableArray Fields { get; } private string DebuggerDisplay => $"{Type} ({ColumnCount} Columns, {Fields.Length} Fields)"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ParagraphStruct? left, ParagraphStruct? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ParagraphStruct? left, ParagraphStruct? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ParagraphStruct paragraphStruct && Equals(paragraphStruct); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ParagraphStruct? paragraphStruct) => GetHashCode() == paragraphStruct?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs index ba0f1efe..26064769 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// A plain text element that can be used in an . +/// 纯文本元素,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PlainTextElement : IElement, IEquatable, IEquatable @@ -15,30 +15,17 @@ internal PlainTextElement(string content, bool? emoji) Emoji = emoji; } - /// - /// Gets the type of the element. - /// - /// - /// An value that represents the theme of the button. - /// + /// public ElementType Type => ElementType.PlainText; /// - /// Gets the KMarkdown content of the element. + /// 获取纯文本的内容。 /// - /// - /// A string that represents the KMarkdown content of the element. - /// public string Content { get; } /// - /// Gets whether the shortcuts should be translated into emojis. + /// 获取 Emoji 表情符号的短代码是否被解析为表情符号。 /// - /// - /// A boolean value that indicates whether the shortcuts should be translated into emojis. - /// true if the shortcuts should be translated into emojis; - /// false if the text should be displayed as is. - /// public bool? Emoji { get; } /// @@ -47,29 +34,24 @@ internal PlainTextElement(string content, bool? emoji) private string DebuggerDisplay => $"{Type}: {Content}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(PlainTextElement? left, PlainTextElement? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(PlainTextElement? left, PlainTextElement? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is PlainTextElement plainTextElement && Equals(plainTextElement); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] PlainTextElement? plainTextElement) => GetHashCode() == plainTextElement?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs index d9d595b5..83c10c62 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs @@ -1,68 +1,107 @@ namespace Kook; /// -/// Represents text themes used in . +/// 表示卡片内 KMarkdown 文本的颜色。 /// /// /// -/// The text themes of KMarkdown are currently only supported in card messages. -/// KMarkdown messages theming is not supported yet. +/// 彩色 KMarkdown 文本目前仅支持在卡片消息中使用,KMarkdown 文本消息暂不支持彩色。 /// +///
/// -/// The color of the text themes vary on different platforms. It is recommended to -/// test your card messages on different platforms to ensure that the text themes -/// are displayed correctly. +/// 彩色文本的颜色在不同的平台上可能会有所不同。建议您在不同的平台上测试您的卡片消息,以确保文本颜色符合您的预期。 /// ///
+/// 。 public enum TextTheme : ushort { /// - /// Represents a primary theme. + /// 外观表现为主要文本。 /// + /// + /// 文本的前景色大体为草绿色,浅色模式下为 #7ACC35(http://www.color-hex.com/color/7acc35),深色模式下为 + /// #6CBF00(http://www.color-hex.com/color/6cbf00)。 + /// Primary, /// - /// Represents a success theme. + /// 外观表现为成功。 /// + /// + /// 文本的前景色大体为薄荷绿色 #00D287(http://www.color-hex.com/color/00d287)。 + /// Success, /// - /// Represents a danger theme. + /// 外观表现为危险。 /// + /// + /// 文本的前景色大体为鲜红色,浅色模式下为 #FF3200(http://www.color-hex.com/color/ff3200),深色模式下为 + /// #FF4D42(http://www.color-hex.com/color/ff4d42)。 + /// Danger, /// - /// Represents a warning theme. + /// 外观表现为警告。 /// + /// + /// 文本的前景色大体为橙色,浅色模式下为 #FF8200(http://www.color-hex.com/color/ff8200),深色模式下为 + /// #FF8F19(http://www.color-hex.com/color/ff8f19)。 + /// Warning, /// - /// Represents an info theme. + /// 外观表现为信息。 /// + /// + /// 此颜色主题可能不生效。 + /// Info, /// - /// Represents a secondary theme. + /// 外观表现为次要文本。 /// + /// + /// 文本的前景色大体为灰色,浅色模式下为 #666666(http://www.color-hex.com/color/666666),深色模式下为 + /// #AAAAAA(http://www.color-hex.com/color/aaaaaa)。 + /// Secondary, /// - /// Represents a body theme. + /// 外观表现为正文。 /// + /// + /// 文本的前景色大体为黑色或白色,浅色模式下为 #222222(http://www.color-hex.com/color/222222),深色模式下为 + /// #FFFFFF(http://www.color-hex.com/color/ffffff)。 + /// Body, /// - /// Represents a tips theme. + /// 外观表现为提示。 /// + /// + /// 文本的前景色大体为与背景色差别较小的灰色,浅色模式下为 #999999(http://www.color-hex.com/color/999999),深色模式下为 + /// #777777(http://www.color-hex.com/color/777777)。 + /// Tips, /// - /// Represents a pink theme. + /// 外观表现为粉色。 /// + /// + /// 文本的前景色大体为粉色,浅色模式下为 #F65299(http://www.color-hex.com/color/f65299),深色模式下为 + /// #F765A5(http://www.color-hex.com/color/F765A5)。 + /// Pink, /// - /// Represents a purple theme. + /// 外观表现为紫色。 /// + /// + /// 文本的前景色大体为紫色,浅色模式下为 #853EFD(http://www.color-hex.com/color/853efd),深色模式下为 + /// #9557FE(http://www.color-hex.com/color/9557fe)。 + /// Purple } + + diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs b/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs index 385f9f1b..9e2a71a1 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs @@ -1,23 +1,17 @@ namespace Kook; /// -/// Represents a generic card. +/// 表示一个通用的卡片。 /// public interface ICard { /// - /// Gets the type of the card. + /// 获取卡片的类型。 /// - /// - /// A value that represents the type of the card. - /// CardType Type { get; } /// - /// Gets the number of the modules in this card. + /// 获取卡片中模块的数量。 /// - /// - /// An int value that represents how many modules are in this card. - /// int ModuleCount { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs index 942f3d9a..23c80d48 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs @@ -1,20 +1,18 @@ namespace Kook; /// -/// Represents a generic card builder for creating a . +/// 表示一个通用的卡片构建器,用于构建一个 。 /// public interface ICardBuilder { /// - /// Gets the type of the this builder creates. + /// 获取此构建器构建的卡片的类型。 /// CardType Type { get; } /// - /// Builds the into an . + /// 构建当前构建器为一个 。 /// - /// - /// An represents the built card object. - /// + /// 由当前构建器表示的属性构建的 对象。 ICard Build(); } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs index 4298c30f..bcb80ea8 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Represents an action group module that can be used in an . +/// 按钮组模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ActionGroupModule : IModule, IEquatable, IEquatable @@ -19,39 +19,31 @@ internal ActionGroupModule(ImmutableArray elements) public ModuleType Type => ModuleType.ActionGroup; /// - /// Gets the elements of this module. + /// 获取模块的元素。 /// - /// - /// An containing the elements of this module. - /// public ImmutableArray Elements { get; } private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ActionGroupModule left, ActionGroupModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ActionGroupModule left, ActionGroupModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ActionGroupModule actionGroupModule && Equals(actionGroupModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ActionGroupModule? actionGroupModule) => GetHashCode() == actionGroupModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs index 3e771c45..b85776f6 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents an audio module that can be used in an . +/// 音频模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class AudioModule : IMediaModule, IEquatable, IEquatable @@ -19,46 +19,42 @@ internal AudioModule(string source, string? title, string? cover) /// public ModuleType Type => ModuleType.Audio; - /// + /// + /// 获取音频的 URL。 + /// public string Source { get; } - /// + /// + /// 获取音频的标题。 + /// public string? Title { get; } /// - /// Gets the cover of the audio associated with this module. + /// 获取音频的封面的 URL。 /// - /// - /// A string representing the cover of the audio associated with this module. - /// public string? Cover { get; } private string DebuggerDisplay => $"{Type}: {Title}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(AudioModule left, AudioModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(AudioModule left, AudioModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is AudioModule audioModule && Equals(audioModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] AudioModule? audioModule) => GetHashCode() == audioModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ActionGroupModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ActionGroupModuleBuilder.cs index 6bd6f677..1a61aeb0 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ActionGroupModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ActionGroupModuleBuilder.cs @@ -3,17 +3,17 @@ namespace Kook; /// -/// Represents a action group module builder for creating an . +/// 用来构建 模块的构建器。 /// public class ActionGroupModuleBuilder : IModuleBuilder, IEquatable, IEquatable { /// - /// Returns the maximum number of elements allowed by Kook. + /// 元素的最大数量。 /// public const int MaxElementCount = 4; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public ActionGroupModuleBuilder() { @@ -21,8 +21,9 @@ public ActionGroupModuleBuilder() } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// + /// 按钮组模块要包含的按钮元素。 public ActionGroupModuleBuilder(IList elements) { Elements = elements; @@ -32,22 +33,15 @@ public ActionGroupModuleBuilder(IList elements) public ModuleType Type => ModuleType.ActionGroup; /// - /// Gets or sets the button elements of the action group module. + /// 获取或设置按钮组模块的按钮元素。 /// - /// - /// An containing the button elements of the action group module. - /// public IList Elements { get; set; } /// - /// Adds a button element to the action group module. + /// 添加一个按钮元素到按钮组模块。 /// - /// - /// The button element to add. - /// - /// - /// The current builder. - /// + /// 要添加的按钮元素。 + /// 当前构建器。 public ActionGroupModuleBuilder AddElement(ButtonElementBuilder field) { Elements.Add(field); @@ -55,17 +49,10 @@ public ActionGroupModuleBuilder AddElement(ButtonElementBuilder field) } /// - /// Adds a button element to the action group module. + /// 添加一个按钮元素到按钮组模块。 /// - /// - /// The action to add a button element to the action group module. - /// - /// - /// The current builder. - /// - /// - /// The addition operation would cause the number of elements to exceed . - /// + /// 一个包含对要添加的新创建的按钮元素进行配置的操作的委托。 + /// 当前构建器。 public ActionGroupModuleBuilder AddElement(Action? action = null) { ButtonElementBuilder field = new(); @@ -75,19 +62,17 @@ public ActionGroupModuleBuilder AddElement(Action? action } /// - /// Builds this builder into an . + /// 构建当前构建器为一个 对象。 /// - /// - /// An representing the built action group module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// is null. + /// null。 /// /// - /// is an empty list. + /// 是一个空列表。 /// /// - /// The number of elements of is greater than . + /// 的元素数量超过了 。 /// public ActionGroupModule Build() { @@ -107,29 +92,24 @@ public ActionGroupModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ActionGroupModuleBuilder? left, ActionGroupModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ActionGroupModuleBuilder? left, ActionGroupModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ActionGroupModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ActionGroupModuleBuilder? actionGroupModuleBuilder) { if (actionGroupModuleBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/AudioModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/AudioModuleBuilder.cs index 8fd7a79a..a7afc791 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/AudioModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/AudioModuleBuilder.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents an audio module builder for creating an . +/// 用来构建 模块的构建器。 /// public class AudioModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -12,18 +12,18 @@ public class AudioModuleBuilder : IModuleBuilder, IEquatable public ModuleType Type => ModuleType.Audio; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public AudioModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The source URL of the video. - /// The cover URL of the video. - /// The title of the video. + /// 音频的 URL。 + /// 音频的封面的 URL。 + /// 音频的标题。 public AudioModuleBuilder(string source, string? cover = null, string? title = null) { Source = source; @@ -32,38 +32,25 @@ public AudioModuleBuilder(string source, string? cover = null, string? title = n } /// - /// Gets or sets the source URL of the video. + /// 获取或设置音频的 URL。 /// - /// - /// The source URL of the video. - /// public string? Source { get; set; } /// - /// Gets or sets the cover URL of the video. + /// 获取或设置音频的封面的 URL。 /// - /// - /// The cover URL of the video. - /// public string? Cover { get; set; } /// - /// Gets or sets the title of the video. + /// 获取或设置音频的标题。 /// - /// - /// The title of the video. - /// public string? Title { get; set; } /// - /// Sets the source URL of the video. + /// 设置音频的 URL。 /// - /// - /// The source URL of the video to be set. - /// - /// - /// The current builder. - /// + /// 音频的 URL。 + /// 当前构建器。 public AudioModuleBuilder WithSource(string? source) { Source = source; @@ -71,14 +58,10 @@ public AudioModuleBuilder WithSource(string? source) } /// - /// Sets the cover URL of the video. + /// 设置音频的封面的 URL。 /// - /// - /// The cover URL of the video to be set. - /// - /// - /// The current builder. - /// + /// 音频的封面的 URL。 + /// 当前构建器。 public AudioModuleBuilder WithCover(string? cover) { Cover = cover; @@ -86,14 +69,10 @@ public AudioModuleBuilder WithCover(string? cover) } /// - /// Sets the title of the video. + /// 设置音频的标题。 /// - /// - /// The title of the video to be set. - /// - /// - /// The current builder. - /// + /// 音频的标题。 + /// 当前构建器。 public AudioModuleBuilder WithTitle(string? title) { Title = title; @@ -101,22 +80,17 @@ public AudioModuleBuilder WithTitle(string? title) } /// - /// Builds this builder into an . + /// 构建当前构建器为一个 对象。 /// - /// - /// An representing the built audio module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// cannot be null + /// null。 /// /// - /// cannot be empty + /// 为空字符串。 /// /// - /// is not a valid URL - /// - /// - /// is not a valid URL + /// 不是有效的 URL。 /// [MemberNotNull(nameof(Source))] public AudioModule Build() @@ -136,29 +110,24 @@ public AudioModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(AudioModuleBuilder? left, AudioModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(AudioModuleBuilder? left, AudioModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is AudioModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] AudioModuleBuilder? audioModuleBuilder) { if (audioModuleBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContainerModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContainerModuleBuilder.cs index 0741d648..f2a5e2f4 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContainerModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContainerModuleBuilder.cs @@ -3,17 +3,17 @@ namespace Kook; /// -/// Represents a container module builder for creating a . +/// 用来构建 模块的构建器。 /// public class ContainerModuleBuilder : IModuleBuilder, IEquatable, IEquatable { /// - /// Returns the maximum number of elements allowed by Kook. + /// 元素的最大数量。 /// public const int MaxElementCount = 9; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public ContainerModuleBuilder() { @@ -21,8 +21,9 @@ public ContainerModuleBuilder() } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// + /// 图片组模块要包含的图片元素。 public ContainerModuleBuilder(IList elements) { Elements = elements; @@ -32,22 +33,15 @@ public ContainerModuleBuilder(IList elements) public ModuleType Type => ModuleType.Container; /// - /// Gets or sets the image elements in the container module. + /// 获取或设置图片组模块的图片元素。 /// - /// - /// An containing the image elements in this image container module. - /// public IList Elements { get; set; } /// - /// Adds an image element to the container module. + /// 添加一个图片元素到图片组模块。 /// - /// - /// The image element to add. - /// - /// - /// The current builder. - /// + /// 要添加的图片元素。 + /// 当前构建器。 public ContainerModuleBuilder AddElement(ImageElementBuilder field) { Elements.Add(field); @@ -55,14 +49,10 @@ public ContainerModuleBuilder AddElement(ImageElementBuilder field) } /// - /// Adds an image element to the container module. + /// 添加一个图片元素到图片组模块。 /// - /// - /// The action to add an image element to the container module. - /// - /// - /// The current builder. - /// + /// 一个包含对要添加的新创建的图片元素进行配置的操作的委托。 + /// 当前构建器。 public ContainerModuleBuilder AddElement(Action? action = null) { ImageElementBuilder field = new(); @@ -72,19 +62,17 @@ public ContainerModuleBuilder AddElement(Action? action = n } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built container module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// cannot be null. + /// null。 /// /// - /// cannot be an empty list. + /// 为空列表。 /// /// - /// count must be less than or equal to . + /// 的元素数量超过了 。 /// public ContainerModule Build() { @@ -106,29 +94,24 @@ public ContainerModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ContainerModuleBuilder? left, ContainerModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ContainerModuleBuilder? left, ContainerModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ContainerModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ContainerModuleBuilder? containerModuleBuilder) { if (containerModuleBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContextModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContextModuleBuilder.cs index cc4dcba5..daef0434 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContextModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ContextModuleBuilder.cs @@ -3,17 +3,17 @@ namespace Kook; /// -/// Represents a context module builder for creating a . +/// 用来构建 模块的构建器。 /// public class ContextModuleBuilder : IModuleBuilder, IEquatable, IEquatable { /// - /// Returns the maximum number of elements allowed by Kook. + /// 元素的最大数量。 /// public const int MaxElementCount = 10; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public ContextModuleBuilder() { @@ -21,8 +21,9 @@ public ContextModuleBuilder() } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// + /// 备注模块要包含的元素。 public ContextModuleBuilder(IList elements) { Elements = elements; @@ -32,22 +33,15 @@ public ContextModuleBuilder(IList elements) public ModuleType Type => ModuleType.Context; /// - /// Gets or sets the elements of the context module. + /// 获取或设置备注模块的元素。 /// public IList Elements { get; set; } /// - /// Adds a PlainText element to the context module. + /// 添加一个纯文本元素到备注模块。 /// - /// - /// The PlainText element to add. - /// - /// - /// The current builder. - /// - /// - /// The addition operation would cause the number of elements to exceed . - /// + /// 要添加的纯文本元素。 + /// 当前构建器。 public ContextModuleBuilder AddElement(PlainTextElementBuilder field) { Elements.Add(field); @@ -55,14 +49,10 @@ public ContextModuleBuilder AddElement(PlainTextElementBuilder field) } /// - /// Adds a KMarkdown element to the context module. + /// 添加一个 KMarkdown 元素到备注模块。 /// - /// - /// The KMarkdown element to add. - /// - /// - /// The current builder. - /// + /// 要添加的 KMarkdown 元素。 + /// 当前构建器。 public ContextModuleBuilder AddElement(KMarkdownElementBuilder field) { Elements.Add(field); @@ -70,17 +60,10 @@ public ContextModuleBuilder AddElement(KMarkdownElementBuilder field) } /// - /// Adds an image element to the context module. + /// 添加一个图片元素到备注模块。 /// - /// - /// The image element to add. - /// - /// - /// The current builder. - /// - /// - /// The addition operation would cause the number of elements to exceed . - /// + /// 要添加的图片元素。 + /// 当前构建器。 public ContextModuleBuilder AddElement(ImageElementBuilder field) { Elements.Add(field); @@ -88,14 +71,11 @@ public ContextModuleBuilder AddElement(ImageElementBuilder field) } /// - /// Adds an element to the context module. + /// 添加一个元素到备注模块。 /// - /// - /// The action to add an element to the context module. - /// - /// - /// The current builder. - /// + /// 一个包含对要添加的新创建的元素进行配置的操作的委托。 + /// 要添加的元素的类型。 + /// 当前构建器。 public ContextModuleBuilder AddElement(Action? action = null) where T : IElementBuilder, new() { @@ -106,20 +86,18 @@ public ContextModuleBuilder AddElement(Action? action = null) } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built context module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is null. + /// null。 /// /// - /// The count is greater than . + /// 的元素数量超过了 。 /// /// - /// The contain an element that is not a , - /// , or . + /// 包含一个既不是 , + /// 也不是 的元素。 /// public ContextModule Build() { @@ -145,29 +123,24 @@ public ContextModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ContextModuleBuilder? left, ContextModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ContextModuleBuilder? left, ContextModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ContextModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ContextModuleBuilder? contextModuleBuilder) { if (contextModuleBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/CountdownModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/CountdownModuleBuilder.cs index 6af0380c..176cbe38 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/CountdownModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/CountdownModuleBuilder.cs @@ -3,7 +3,7 @@ namespace Kook; /// -/// Represents a countdown module builder for creating a . +/// 用来构建 模块的构建器。 /// public class CountdownModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -11,15 +11,18 @@ public class CountdownModuleBuilder : IModuleBuilder, IEquatable ModuleType.Countdown; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public CountdownModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// + /// 倒计时的显示模式。 + /// 倒计时结束的时间。 + /// 倒计时开始的时间。 public CountdownModuleBuilder(CountdownMode mode, DateTimeOffset endTime, DateTimeOffset? startTime = null) { Mode = mode; @@ -28,38 +31,28 @@ public CountdownModuleBuilder(CountdownMode mode, DateTimeOffset endTime, DateTi } /// - /// Gets or sets the ending time of the countdown. + /// 获取或设置倒计时结束的时间。 /// - /// - /// The time at which the countdown ends. - /// public DateTimeOffset EndTime { get; set; } /// - /// Gets or sets the beginning time of the countdown. + /// 获取或设置倒计时开始的时间。 /// - /// - /// The time at which the countdown begins. - /// + /// + /// 仅当 时,才允许设置 。 + /// public DateTimeOffset? StartTime { get; set; } /// - /// Gets or sets how the countdown should be displayed. + /// 获取或设置倒计时的显示模式。 /// - /// - /// A representing how the countdown should be displayed. - /// public CountdownMode Mode { get; set; } /// - /// Sets how the countdown should be displayed. + /// 设置倒计时的显示模式。 /// - /// - /// A representing how the countdown should be displayed. - /// - /// - /// The current builder. - /// + /// 倒计时的显示模式。 + /// 当前构建器。 public CountdownModuleBuilder WithMode(CountdownMode mode) { Mode = mode; @@ -67,14 +60,10 @@ public CountdownModuleBuilder WithMode(CountdownMode mode) } /// - /// Sets the beginning time of the countdown. + /// 设置倒计时结束的时间。 /// - /// - /// The time at which the countdown ends. - /// - /// - /// The current builder. - /// + /// 倒计时结束的时间。 + /// 当前构建器。 public CountdownModuleBuilder WithEndTime(DateTimeOffset endTime) { EndTime = endTime; @@ -82,14 +71,13 @@ public CountdownModuleBuilder WithEndTime(DateTimeOffset endTime) } /// - /// Sets the beginning time of the countdown. + /// 设置倒计时开始的时间。 /// - /// - /// The time at which the countdown begins. - /// - /// - /// The current builder. - /// + /// 倒计时开始的时间。 + /// 当前构建器。 + /// + /// 仅当 时,才允许设置 。 + /// public CountdownModuleBuilder WithStartTime(DateTimeOffset? startTime) { StartTime = startTime; @@ -97,22 +85,20 @@ public CountdownModuleBuilder WithStartTime(DateTimeOffset? startTime) } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built countdown module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// is not but is set. + /// 不为 时,不允许设置 。 /// /// - /// is before the current time. + /// 早于当前时间。 /// /// - /// is before the Unix epoch. + /// 早于 Unix 纪元时间。 /// /// - /// is equal or before + /// 应晚于 。 /// public CountdownModule Build() { @@ -142,29 +128,24 @@ public CountdownModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(CountdownModuleBuilder? left, CountdownModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(CountdownModuleBuilder? left, CountdownModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is CountdownModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] CountdownModuleBuilder? countdownModuleBuilder) { if (countdownModuleBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/DividerModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/DividerModuleBuilder.cs index a3bafead..8ae3ff37 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/DividerModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/DividerModuleBuilder.cs @@ -3,7 +3,7 @@ namespace Kook; /// -/// Represents a divider module builder for creating a . +/// 用来构建 模块的构建器。 /// public class DividerModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -11,40 +11,40 @@ public class DividerModuleBuilder : IModuleBuilder, IEquatable ModuleType.Divider; /// - /// Builds this builder into a . + /// 初始化一个 类的新实例。 /// - /// - /// A representing the built divider module object. - /// + public DividerModuleBuilder() + { + } + + /// + /// 构建当前构建器为一个 对象。 + /// + /// 由当前构建器表示的属性构建的 对象。 public DividerModule Build() => new(); /// IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(DividerModuleBuilder? left, DividerModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(DividerModuleBuilder? left, DividerModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is DividerModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] DividerModuleBuilder? dividerModuleBuilder) { if (dividerModuleBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/FileModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/FileModuleBuilder.cs index 71b1578c..dc33fba9 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/FileModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/FileModuleBuilder.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents a file module builder for creating a . +/// 用来构建 模块的构建器。 /// public class FileModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -12,17 +12,17 @@ public class FileModuleBuilder : IModuleBuilder, IEquatable, public ModuleType Type => ModuleType.File; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public FileModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The source URL of the file. - /// The title of the file. + /// 文件的 URL。 + /// 文件名。 public FileModuleBuilder(string source, string? title = null) { Source = source; @@ -30,30 +30,20 @@ public FileModuleBuilder(string source, string? title = null) } /// - /// Gets or sets the source URL of the file. + /// 获取或设置文件的 URL。 /// - /// - /// The source URL of the file. - /// public string? Source { get; set; } /// - /// Gets or sets the title of the file. + /// 获取或设置文件名。 /// - /// - /// The title of the file. - /// public string? Title { get; set; } /// - /// Sets the source URL of the file. + /// 设置文件的 URL。 /// - /// - /// The source URL of the file to be set. - /// - /// - /// The current builder. - /// + /// 文件的 URL。 + /// 当前构建器。 public FileModuleBuilder WithSource(string? source) { Source = source; @@ -61,14 +51,10 @@ public FileModuleBuilder WithSource(string? source) } /// - /// Sets the title of the file. + /// 设置文件名。 /// - /// - /// The title of the file to be set. - /// - /// - /// The current builder. - /// + /// 文件名。 + /// 当前构建器。 public FileModuleBuilder WithTitle(string title) { Title = title; @@ -76,19 +62,17 @@ public FileModuleBuilder WithTitle(string title) } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built file module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The url is null. + /// null。 /// /// - /// The url is empty. + /// 为空字符串。 /// - /// - /// The url does not include a protocol (either HTTP or HTTPS). + /// + /// 不是有效的 URL。 /// [MemberNotNull(nameof(Source))] public FileModule Build() @@ -108,29 +92,24 @@ public FileModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(FileModuleBuilder? left, FileModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(FileModuleBuilder? left, FileModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is FileModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] FileModuleBuilder? fileModuleBuilder) { if (fileModuleBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/HeaderModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/HeaderModuleBuilder.cs index 4a556f28..9a5a5328 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/HeaderModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/HeaderModuleBuilder.cs @@ -3,60 +3,53 @@ namespace Kook; /// -/// Represents a header module builder for creating a . +/// 用来构建 模块的构建器。 /// public class HeaderModuleBuilder : IModuleBuilder, IEquatable, IEquatable { /// - /// Gets the maximum content length for header allowed by Kook. + /// 标题内容文本的最大长度。 /// - public const int MaxTitleContentLength = 100; + public const int MaxHeaderContentLength = 100; /// public ModuleType Type => ModuleType.Header; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public HeaderModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The text to be set for the header. + /// 标题文本。 public HeaderModuleBuilder(PlainTextElementBuilder text) { Text = text; } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The text to be set for the header. + /// 标题文本。 public HeaderModuleBuilder(string text) { Text = new PlainTextElementBuilder(text); } /// - /// Gets or sets the text of the header. + /// 获取或设置标题文本。 /// - /// - /// A representing the text of the header. - /// public PlainTextElementBuilder? Text { get; set; } /// - /// Sets the text of the header. + /// 设置标题文本。 /// - /// - /// The text to be set for the header. - /// - /// - /// The current builder. - /// + /// 要设置的标题文本。 + /// 当前构建器。 public HeaderModuleBuilder WithText(PlainTextElementBuilder text) { Text = text; @@ -64,10 +57,10 @@ public HeaderModuleBuilder WithText(PlainTextElementBuilder text) } /// - /// Sets the text of the header. + /// 设置标题文本。 /// - /// The text to be set for the header. - /// The current builder. + /// 要设置的标题文本。 + /// 当前构建器。 public HeaderModuleBuilder WithText(string text) { Text = new PlainTextElementBuilder(text); @@ -75,14 +68,10 @@ public HeaderModuleBuilder WithText(string text) } /// - /// Sets the text of the header. + /// 设置标题文本。 /// - /// - /// The action to set the text of the header. - /// - /// - /// The current builder. - /// + /// 一个包含对要设置的标题文本进行配置的操作的委托。 + /// 当前构建器。 public HeaderModuleBuilder WithText(Action? action = null) { PlainTextElementBuilder text = new(); @@ -92,19 +81,17 @@ public HeaderModuleBuilder WithText(Action? action = nu } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built header module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is null. + /// null。 /// /// - /// The is null. + /// 的内容为 null。 /// /// - /// The content is longer than . + /// 的内容长度超过了 。 /// [MemberNotNull(nameof(Text))] public HeaderModule Build() @@ -115,24 +102,15 @@ public HeaderModule Build() if (Text.Content is null) throw new ArgumentException("The content of the header text cannot be null.", nameof(Text)); - if (Text.Content.Length > MaxTitleContentLength) + if (Text.Content.Length > MaxHeaderContentLength) throw new ArgumentException( - $"Header content length must be less than or equal to {MaxTitleContentLength}.", + $"Header content length must be less than or equal to {MaxHeaderContentLength}.", nameof(Text)); return new HeaderModule(Text.Build()); } - /// - /// Initialized a new instance of the class - /// with the specified . - /// - /// - /// The text to be set for the header. - /// - /// - /// An object that is initialized with the specified . - /// + /// public static implicit operator HeaderModuleBuilder(string text) => new(text); /// @@ -140,29 +118,24 @@ public HeaderModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(HeaderModuleBuilder? left, HeaderModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(HeaderModuleBuilder? left, HeaderModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is HeaderModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] HeaderModuleBuilder? headerModuleBuilder) { if (headerModuleBuilder == null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/IModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/IModuleBuilder.cs index ec61480d..07e4bb8c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/IModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/IModuleBuilder.cs @@ -1,23 +1,18 @@ namespace Kook; /// -/// A generic module builder for creating an . +/// 表示一个通用的模块构建器,用于构建一个 。 /// public interface IModuleBuilder { /// - /// Specifies the module type of the this builder creates. + /// 获取此构建器构建的模块的类型。 /// - /// - /// A representing the module type of the this builder creates. - /// ModuleType Type { get; } /// - /// Builds the into an . + /// 构建当前构建器为一个 。 /// - /// - /// An representing the built module object. - /// + /// 由当前构建器表示的属性构建的 对象。 IModule Build(); } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ImageGroupModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ImageGroupModuleBuilder.cs index 8ccc4469..bcea4b75 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ImageGroupModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/ImageGroupModuleBuilder.cs @@ -3,17 +3,17 @@ namespace Kook; /// -/// Representing an image group module builder for create an . +/// 用来构建 模块的构建器。 /// public class ImageGroupModuleBuilder : IModuleBuilder, IEquatable, IEquatable { /// - /// Returns the maximum number of elements allowed by Kook. + /// 元素的最大数量。 /// public const int MaxElementCount = 9; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public ImageGroupModuleBuilder() { @@ -21,8 +21,9 @@ public ImageGroupModuleBuilder() } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// + /// 图片组模块要包含的图片元素。 public ImageGroupModuleBuilder(IList elements) { Elements = elements; @@ -32,28 +33,15 @@ public ImageGroupModuleBuilder(IList elements) public ModuleType Type => ModuleType.ImageGroup; /// - /// Gets or sets the elements of the image group. + /// 获取或设置图片组模块的图片元素。 /// - /// - /// The addition operation would cause the number of elements to exceed . - /// - /// - /// An containing the elements of the image group. - /// public IList Elements { get; set; } /// - /// Adds an image element to the image group. + /// 添加一个图片元素到图片组模块。 /// - /// - /// The image element to add. - /// - /// - /// The current builder. - /// - /// - /// The addition operation would cause the number of elements to exceed . - /// + /// 要添加的图片元素。 + /// 当前构建器。 public ImageGroupModuleBuilder AddElement(ImageElementBuilder field) { if (Elements.Count >= MaxElementCount) @@ -66,17 +54,10 @@ public ImageGroupModuleBuilder AddElement(ImageElementBuilder field) } /// - /// Adds an image element to the image group. + /// 添加一个图片元素到图片组模块。 /// - /// - /// The action to add an image element to the image group. - /// - /// - /// The current builder. - /// - /// - /// The addition operation would cause the number of elements to exceed . - /// + /// 一个包含对要添加的新创建的图片元素进行配置的操作的委托。 + /// 当前构建器。 public ImageGroupModuleBuilder AddElement(Action action) { ImageElementBuilder field = new(); @@ -86,19 +67,17 @@ public ImageGroupModuleBuilder AddElement(Action action) } /// - /// Builds this builder into an . + /// 构建当前构建器为一个 对象。 /// - /// - /// An representing the built image group module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is null. + /// null。 /// /// - /// The is an empty list. + /// 为空列表。 /// /// - /// Element count is greater than . + /// 的元素数量超过了 。 /// public ImageGroupModule Build() { @@ -120,29 +99,24 @@ public ImageGroupModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ImageGroupModuleBuilder? left, ImageGroupModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ImageGroupModuleBuilder? left, ImageGroupModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ImageGroupModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ImageGroupModuleBuilder? imageGroupModuleBuilder) { if (imageGroupModuleBuilder is null) diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/InviteModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/InviteModuleBuilder.cs index 88c9ad63..0b36514c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/InviteModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/InviteModuleBuilder.cs @@ -3,7 +3,7 @@ namespace Kook; /// -/// Represents a invite module builder for creating an . +/// 用来构建 模块的构建器。 /// public class InviteModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -11,38 +11,31 @@ public class InviteModuleBuilder : IModuleBuilder, IEquatable ModuleType.Invite; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public InviteModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// + /// 邀请代码。 public InviteModuleBuilder(string code) { Code = code; } /// - /// Gets or sets the code of the invite. + /// 获取或设置邀请代码。 /// - /// - /// A string representing the code of the invite. - /// public string? Code { get; set; } /// - /// Sets the code of the invite. + /// 设置邀请代码。 /// - /// - /// The code of the invite to be set. - /// - /// - /// The current builder. - /// + /// 邀请代码。 + /// 当前构建器。 public InviteModuleBuilder WithCode(string code) { Code = code; @@ -50,16 +43,14 @@ public InviteModuleBuilder WithCode(string code) } /// - /// Builds this builder into an . + /// 构建当前构建器为一个 对象。 /// - /// - /// An representing the built invite module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is null. + /// null。 /// /// - /// The is empty or whitespace. + /// 为空或空白字符串。 /// [MemberNotNull(nameof(Code))] public InviteModule Build() @@ -71,16 +62,7 @@ public InviteModule Build() return new InviteModule(Code); } - /// - /// Initialized a new instance of the class - /// with the specified . - /// - /// - /// The code representing the invite. - /// - /// - /// An object that is initialized with the specified . - /// + /// public static implicit operator InviteModuleBuilder(string code) => new(code); /// @@ -88,29 +70,24 @@ public InviteModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(InviteModuleBuilder? left, InviteModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(InviteModuleBuilder? left, InviteModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is InviteModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] InviteModuleBuilder? inviteModuleBuilder) { if (inviteModuleBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/SectionModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/SectionModuleBuilder.cs index 447feebd..2a975ba3 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/SectionModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/SectionModuleBuilder.cs @@ -3,7 +3,7 @@ namespace Kook; /// -/// Represents a section module builder for creating a . +/// 用来构建 模块的构建器。 /// public class SectionModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -11,21 +11,18 @@ public class SectionModuleBuilder : IModuleBuilder, IEquatable ModuleType.Section; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public SectionModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// - /// The is not any form of text element, - /// including , , - /// and ; or the is neither - /// an nor . - /// + /// 文本元素。 + /// 附加内容的显示模式。 + /// 附加内容元素。 public SectionModuleBuilder(IElementBuilder? text, SectionAccessoryMode? mode = null, IElementBuilder? accessory = null) { @@ -35,14 +32,12 @@ public SectionModuleBuilder(IElementBuilder? text, } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// - /// The is not any form of text element, - /// including , , - /// and ; or the is neither - /// an nor . - /// + /// 文本元素。 + /// 是否为 KMarkdown 格式。 + /// 附加内容的显示模式。 + /// 附加内容元素。 public SectionModuleBuilder(string? text, bool isKMarkdown = false, SectionAccessoryMode? mode = null, IElementBuilder? accessory = null) { @@ -52,47 +47,25 @@ public SectionModuleBuilder(string? text, bool isKMarkdown = false, } /// - /// Gets or sets how the is positioned relative to the . + /// 获取或设置附加内容的显示模式。 /// - /// - /// A representing - /// how the is positioned relative to the . - /// public SectionAccessoryMode? Mode { get; set; } /// - /// Gets or sets the text of the section. + /// 获取或设置模块的文本。 /// - /// - /// An representing the text of the section. - /// - /// - /// The is not any form of text element, - /// including , , and . - /// public IElementBuilder? Text { get; set; } /// - /// Gets or sets the accessory of the section. + /// 获取或设置模块的附加内容。 /// - /// - /// An representing the accessory of the section. - /// - /// - /// The is neither an - /// nor . - /// public IElementBuilder? Accessory { get; set; } /// - /// Sets the text of the section. + /// 设置模块的文本。 /// - /// - /// The text to be set for the section. - /// - /// - /// The current builder. - /// + /// 要设置的文本。 + /// 当前构建器。 public SectionModuleBuilder WithText(PlainTextElementBuilder text) { Text = text; @@ -100,14 +73,10 @@ public SectionModuleBuilder WithText(PlainTextElementBuilder text) } /// - /// Sets the text of the section. + /// 设置模块的文本。 /// - /// - /// The text to be set for the section. - /// - /// - /// The current builder. - /// + /// 要设置的文本。 + /// 当前构建器。 public SectionModuleBuilder WithText(KMarkdownElementBuilder text) { Text = text; @@ -115,17 +84,11 @@ public SectionModuleBuilder WithText(KMarkdownElementBuilder text) } /// - /// Sets the text of the section. + /// 设置模块的文本。 /// - /// The text to be set for the section. - /// - /// A bool indicating whether the text is in KMarkdown format; - /// if true, the text will be set as a ; - /// if false, the text will be set as a . - /// - /// - /// The current builder. - /// + /// 要设置的文本。 + /// 是否为 KMarkdown 格式。 + /// 当前构建器。 public SectionModuleBuilder WithText(string? text, bool isKMarkdown = false) { Text = isKMarkdown switch @@ -137,14 +100,10 @@ public SectionModuleBuilder WithText(string? text, bool isKMarkdown = false) } /// - /// Sets the text of the section. + /// 设置模块的文本。 /// - /// - /// The text to be set for the section. - /// - /// - /// The current builder. - /// + /// 要设置的文本。 + /// 当前构建器。 public SectionModuleBuilder WithText(ParagraphStructBuilder text) { Text = text; @@ -152,14 +111,11 @@ public SectionModuleBuilder WithText(ParagraphStructBuilder text) } /// - /// Sets the text of the section. + /// 设置模块的文本。 /// - /// - /// The action to set the text of the section. - /// - /// - /// The current builder. - /// + /// 一个包含对要设置的文本进行配置的操作的委托。 + /// 要设置的文本的类型。 + /// 当前构建器。 public SectionModuleBuilder WithText(Action? action = null) where T : IElementBuilder, new() { @@ -170,14 +126,10 @@ public SectionModuleBuilder WithText(Action? action = null) } /// - /// Sets the accessory of the section. + /// 设置模块的附加内容。 /// - /// - /// The accessory to be set for the section. - /// - /// - /// The current builder. - /// + /// 要设置的附加内容。 + /// 当前构建器。 public SectionModuleBuilder WithAccessory(ImageElementBuilder accessory) { Accessory = accessory; @@ -185,14 +137,10 @@ public SectionModuleBuilder WithAccessory(ImageElementBuilder accessory) } /// - /// Sets the accessory of the section. + /// 设置模块的附加内容。 /// - /// - /// The accessory to be set for the section. - /// - /// - /// The current builder. - /// + /// 要设置的附加内容。 + /// 当前构建器。 public SectionModuleBuilder WithAccessory(ButtonElementBuilder accessory) { Accessory = accessory; @@ -200,14 +148,10 @@ public SectionModuleBuilder WithAccessory(ButtonElementBuilder accessory) } /// - /// Sets the accessory of the section. + /// 设置模块的附加内容。 /// - /// - /// The action to set the accessory of the section. - /// - /// - /// The current builder. - /// + /// 一个包含对要设置的附加内容进行配置的操作的委托。 + /// 当前构建器。 public SectionModuleBuilder WithAccessory(Action? action = null) where T : IElementBuilder, new() { @@ -218,14 +162,10 @@ public SectionModuleBuilder WithAccessory(Action? action = null) } /// - /// Sets how the is positioned relative to the . + /// 设置附加内容的显示模式。 /// - /// - /// How the is positioned relative to the . - /// - /// - /// The current builder. - /// + /// 要设置的附加内容的显示模式。 + /// 当前构建器。 public SectionModuleBuilder WithMode(SectionAccessoryMode mode) { Mode = mode; @@ -233,23 +173,18 @@ public SectionModuleBuilder WithMode(SectionAccessoryMode mode) } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built section module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The is not any form of text element, - /// including , , - /// and . + /// 不是任何形式的文本元素,包括 、 + /// 。 /// /// - /// The is neither an - /// nor . + /// 既不是 也不是 。 /// /// - /// The was not positioned to the left of the , - /// which is not allowed. + /// 不应位于 的左侧。 /// public SectionModule Build() { @@ -273,29 +208,24 @@ public SectionModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(SectionModuleBuilder? left, SectionModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(SectionModuleBuilder? left, SectionModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is SectionModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] SectionModuleBuilder? sectionModuleBuilder) { if (sectionModuleBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/VideoModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/VideoModuleBuilder.cs index 026bb873..3026479c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/VideoModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/Builders/VideoModuleBuilder.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents a video module builder for creating a . +/// 用来构建 模块的构建器。 /// public class VideoModuleBuilder : IModuleBuilder, IEquatable, IEquatable { @@ -12,17 +12,17 @@ public class VideoModuleBuilder : IModuleBuilder, IEquatable public ModuleType Type => ModuleType.Video; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public VideoModuleBuilder() { } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The source URL of the video. - /// The title of the video. + /// 视频的 URL。 + /// 视频标题。 public VideoModuleBuilder(string source, string? title = null) { Source = source; @@ -30,30 +30,20 @@ public VideoModuleBuilder(string source, string? title = null) } /// - /// Gets or sets the source URL of the video. + /// 获取或设置视频的 URL。 /// - /// - /// The source URL of the video. - /// public string? Source { get; set; } /// - /// Gets or sets the title of the video. + /// 获取或设置视频标题。 /// - /// - /// The title of the video. - /// public string? Title { get; set; } /// - /// Sets the source URL of the video. + /// 设置视频的 URL。 /// - /// - /// The source URL of the video to be set. - /// - /// - /// The current builder. - /// + /// 视频的 URL。 + /// 当前构建器。 public VideoModuleBuilder WithSource(string? source) { Source = source; @@ -61,14 +51,10 @@ public VideoModuleBuilder WithSource(string? source) } /// - /// Sets the title of the video. + /// 设置视频标题。 /// - /// - /// The title of the video to be set. - /// - /// - /// The current builder. - /// + /// 视频标题。 + /// 当前构建器。 public VideoModuleBuilder WithTitle(string title) { Title = title; @@ -76,19 +62,17 @@ public VideoModuleBuilder WithTitle(string title) } /// - /// Builds this builder into a . + /// 构建当前构建器为一个 对象。 /// - /// - /// A representing the built video module object. - /// + /// 由当前构建器表示的属性构建的 对象。 /// - /// The url is null. + /// null。 /// /// - /// The url is empty. + /// 为空字符串。 /// - /// - /// The url does not include a protocol (either HTTP or HTTPS). + /// + /// 不是有效的 URL。 /// [MemberNotNull(nameof(Source))] public VideoModule Build() @@ -108,29 +92,24 @@ public VideoModule Build() IModule IModuleBuilder.Build() => Build(); /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(VideoModuleBuilder? left, VideoModuleBuilder? right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(VideoModuleBuilder? left, VideoModuleBuilder? right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is VideoModuleBuilder builder && Equals(builder); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] VideoModuleBuilder? videoModuleBuilder) { if (videoModuleBuilder is null) return false; diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs index 3c92798a..6625f3ad 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Represents a container module that can be used in an . +/// 容器模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ContainerModule : IModule, IEquatable, IEquatable @@ -19,39 +19,31 @@ internal ContainerModule(ImmutableArray elements) public ModuleType Type => ModuleType.Container; /// - /// Gets the elements in this container module. + /// 获取模块的元素。 /// - /// - /// An representing the elements in this container module. - /// public ImmutableArray Elements { get; } private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ContainerModule left, ContainerModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ContainerModule left, ContainerModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ContainerModule containerModule && Equals(containerModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ContainerModule? containerModule) => GetHashCode() == containerModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs index 27b8ec1c..814f7b41 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Represents a context module that can be used in an . +/// 备注模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ContextModule : IModule, IEquatable, IEquatable @@ -19,39 +19,31 @@ internal ContextModule(ImmutableArray elements) public ModuleType Type => ModuleType.Context; /// - /// Gets the elements in this context module. + /// 获取模块的元素。 /// - /// - /// An representing the elements in this context module. - /// public ImmutableArray Elements { get; } private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ContextModule left, ContextModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ContextModule left, ContextModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ContextModule contextModule && Equals(contextModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ContextModule? contextModule) => GetHashCode() == contextModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs index a713f51f..c2e3f8ab 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Specifies the display mode for the countdown timer. +/// 表示一个 的倒计时显示模式。 /// public enum CountdownMode { /// - /// The timer will display the time in days, hours, minutes and seconds. + /// 倒计时器将以天、小时、分钟和秒的形式显示时间。 /// Day, /// - /// The timer will display the time in hours, minutes and seconds. + /// 倒计时器将以小时、分钟和秒的形式显示时间。 /// Hour, /// - /// The timer will display the time in seconds. + /// 倒计时器将以秒的形式显示时间。 /// Second } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs index 953a59c4..4fee1d6c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents a countdown module that can be used in an . +/// 倒计时模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class CountdownModule : IModule, IEquatable, IEquatable @@ -20,60 +20,42 @@ internal CountdownModule(CountdownMode mode, DateTimeOffset endTime, DateTimeOff public ModuleType Type => ModuleType.Countdown; /// - /// Gets the end time of the countdown. + /// 获取倒计时的结束时间。 /// - /// - /// The end time of the countdown. - /// public DateTimeOffset EndTime { get; } /// - /// Gets the start time of the countdown. + /// 获取倒计时的开始时间。 /// - /// - /// The start time of the countdown. - /// public DateTimeOffset? StartTime { get; } /// - /// Gets the mode of the countdown. + /// 获取倒计时的显示模式。 /// - /// - /// A value that represents the mode of the countdown. - /// public CountdownMode Mode { get; } private string DebuggerDisplay => $"{Type}: To {EndTime:yyyy'/'M'/'d HH:mm:ss z} ({Mode} Mode{(StartTime is null ? string.Empty : $", From {EndTime:yyyy'/'M'/'d HH:mm:ss z}")})"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; otherwise, false. - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(CountdownModule left, CountdownModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; otherwise, false. - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(CountdownModule left, CountdownModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is CountdownModule countdownModule && Equals(countdownModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] CountdownModule? countdownModule) => GetHashCode() == countdownModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs index f4cfc7b5..5f25a6a3 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// A divider module that can be used in an . +/// 分割线模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class DividerModule : IModule, IEquatable, IEquatable @@ -19,29 +19,24 @@ internal DividerModule() private string DebuggerDisplay => $"{Type}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(DividerModule left, DividerModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(DividerModule left, DividerModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is DividerModule dividerModule && Equals(dividerModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] DividerModule? dividerModule) => GetHashCode() == dividerModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs index 8e948edb..7a636ab1 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// A file module that can be used in an . +/// 文件模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class FileModule : IMediaModule, IEquatable, IEquatable @@ -19,47 +19,42 @@ internal FileModule(string source, string? title, int? size = null) /// public ModuleType Type => ModuleType.File; - /// + /// + /// 获取文件的 URL。 + /// public string Source { get; } - /// + /// + /// 获取文件的标题。 + /// public string? Title { get; } /// - /// The size of the file in bytes. + /// 获取文件的大小(单位:字节)。 /// public int? Size { get; } private string DebuggerDisplay => $"{Type}: {Title}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; otherwise, false. - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(FileModule left, FileModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; otherwise, false. - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(FileModule left, FileModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is FileModule fileModule && Equals(fileModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] FileModule? fileModule) => GetHashCode() == fileModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs index 70790e55..6ac39b98 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents a header module in an . +/// 标题模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class HeaderModule : IModule, IEquatable, IEquatable @@ -18,11 +18,8 @@ internal HeaderModule(PlainTextElement? text) public ModuleType Type => ModuleType.Header; /// - /// Gets the text element of the header. + /// 获取模块的标题内容。 /// - /// - /// A representing the text of the header. - /// public PlainTextElement? Text { get; } /// @@ -31,29 +28,24 @@ internal HeaderModule(PlainTextElement? text) private string DebuggerDisplay => $"{Type}: {Text}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// true if the specified is equal to the current ; otherwise, false. + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(HeaderModule left, HeaderModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to the current ; otherwise, false. + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(HeaderModule left, HeaderModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is HeaderModule headerModule && Equals(headerModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] HeaderModule? headerModule) => GetHashCode() == headerModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs index d1b6482b..3dbfacb6 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs @@ -1,23 +1,17 @@ namespace Kook; /// -/// A generic media module that can be used in an . +/// 表示一个通用的媒体模块,可用于 中。 /// public interface IMediaModule : IModule { /// - /// Gets the source of the media associated with this module. + /// 获取与此模块关联的媒体的源。 /// - /// - /// A string representing the source of the audio associated with this module. - /// string Source { get; } /// - /// Gets the title of the media associated with this module. + /// 获取与此模块关联的媒体的标题。 /// - /// - /// A string representing the title of the media associated with this module. - /// string? Title { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs index 87b7e05f..86cd25b9 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs @@ -1,15 +1,12 @@ namespace Kook; /// -/// Represents a generic module that can be used in an . +/// 表示一个通用的模块,可用于 中。 /// public interface IModule { /// - /// Gets the type of the module. + /// 获取模块的类型。 /// - /// - /// A value that represents the type of the module. - /// ModuleType Type { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs index 80340c0d..1313f65d 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Represents an image group module that can be used in an . +/// 图片组模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ImageGroupModule : IModule, IEquatable, IEquatable @@ -19,43 +19,31 @@ internal ImageGroupModule(ImmutableArray elements) public ModuleType Type => ModuleType.ImageGroup; /// - /// Gets the image elements in this image group module. + /// 获取模块的元素。 /// - /// - /// An representing the images in this image group module. - /// public ImmutableArray Elements { get; } private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(ImageGroupModule left, ImageGroupModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(ImageGroupModule left, ImageGroupModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is ImageGroupModule imageGroupModule && Equals(imageGroupModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] ImageGroupModule? imageGroupModule) => GetHashCode() == imageGroupModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs index 6381a2c7..ce6225bd 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs @@ -3,8 +3,8 @@ namespace Kook; -/// -/// An invite module that can be used in an . +/// 3 +/// 邀请模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class InviteModule : IModule, IEquatable, IEquatable @@ -18,40 +18,31 @@ internal InviteModule(string? code) public ModuleType Type => ModuleType.Invite; /// - /// Gets the invite code. + /// 获取邀请代码。 /// public string? Code { get; } private string DebuggerDisplay => $"{Type}: {Code}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(InviteModule left, InviteModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(InviteModule left, InviteModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is InviteModule inviteModule && Equals(inviteModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] InviteModule? inviteModule) => GetHashCode() == inviteModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs index 5bfc3077..89a1d5fb 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs @@ -1,67 +1,67 @@ namespace Kook; /// -/// Specifies the type of an . +/// 表示一个 的类型。 /// public enum ModuleType { /// - /// A . + /// 标题模块。 /// Header, /// - /// A . + /// 内容模块。 /// Section, /// - /// An . + /// 图片组模块。 /// ImageGroup, /// - /// A . + /// 容器模块。 /// Container, /// - /// An . + /// 按钮组模块。 /// ActionGroup, /// - /// A . + /// 备注模块。 /// Context, /// - /// A . + /// 分割线模块。 /// Divider, /// - /// A . + /// 文件模块。 /// File, /// - /// An . + /// 音频模块。 /// Audio, /// - /// A . + /// 视频模块。 /// Video, /// - /// A . + /// 倒计时模块。 /// Countdown, /// - /// An . + /// 邀请模块。 /// Invite } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs index 9d2de74b..bfb28cb8 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the accessory position relative to the text element. +/// 表示 中的附加内容的位置。 /// public enum SectionAccessoryMode { /// - /// The accessory is positioned to the left of the text element. + /// 附加内容位于文本元素的左侧。 /// Left, /// - /// The accessory is positioned to the right of the text element. + /// 附加内容位于文本元素的右侧。 /// Right } diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs index a91077be..d3b689b5 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents a section module in card. +/// 内容模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SectionModule : IModule, IEquatable, IEquatable @@ -20,60 +20,41 @@ internal SectionModule(SectionAccessoryMode? mode, IElement? text = null, IEleme public ModuleType Type => ModuleType.Section; /// - /// Specifies that the is to the left or right of . + /// 获取模块的附加内容的位置。 /// - /// - /// if the is to the left of , - /// if the is to the right of , - /// public SectionAccessoryMode? Mode { get; } /// - /// Gets the text of the section. + /// 获取模块的文本内容。 /// - /// - /// An representing the text of the section. - /// public IElement? Text { get; } /// - /// Gets the accessory of the section. + /// 获取模块的附加内容。 /// - /// - /// An representing the accessory of the section. - /// public IElement? Accessory { get; } private string DebuggerDisplay => $"{Type}: {Text}{(Accessory is null ? string.Empty : $"{Mode} Accessory")}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; otherwise, false. - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(SectionModule left, SectionModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; otherwise, false. - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(SectionModule left, SectionModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public override bool Equals([NotNullWhen(true)] object? obj) => obj is SectionModule sectionModule && Equals(sectionModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)] SectionModule? sectionModule) => GetHashCode() == sectionModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs index 636e1652..8d442d9f 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs @@ -4,7 +4,7 @@ namespace Kook; /// -/// Represents a video module in an . +/// 视频模块,可用于 中。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class VideoModule : IMediaModule, IEquatable, IEquatable @@ -18,42 +18,37 @@ internal VideoModule(string source, string? title) /// public ModuleType Type => ModuleType.Video; - /// + /// + /// 获取视频的 URL。 + /// public string Source { get; } - /// + /// + /// 获取视频的标题。 + /// public string? Title { get; } private string DebuggerDisplay => $"{Type}: {Title}"; /// - /// Determines whether the specified is equal to the current . + /// 判定两个 是否相等。 /// - /// - /// true if the specified is equal to the current ; otherwise, false. - /// + /// 如果两个 相等,则为 true;否则为 false public static bool operator ==(VideoModule left, VideoModule right) => left?.Equals(right) ?? right is null; /// - /// Determines whether the specified is not equal to the current . + /// 判定两个 是否不相等。 /// - /// - /// true if the specified is not equal to the current ; otherwise, false. - /// + /// 如果两个 不相等,则为 true;否则为 false public static bool operator !=(VideoModule left, VideoModule right) => !(left == right); - /// Determines whether the specified is equal to the current . - /// If the object passes is an , will be called to compare the 2 instances. - /// The object to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. - public override bool Equals([NotNullWhen(true)]object? obj) => + /// + public override bool Equals([NotNullWhen(true)] object? obj) => obj is VideoModule videoModule && Equals(videoModule); - /// Determines whether the specified is equal to the current . - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. + /// public bool Equals([NotNullWhen(true)]VideoModule? videoModule) => GetHashCode() == videoModule?.GetHashCode(); diff --git a/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs b/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs index a7a862b3..6b97ace6 100644 --- a/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs @@ -1,23 +1,22 @@ namespace Kook; /// -/// Indicates that how the will be operated to attache files. +/// 指示 如何创建附件。 /// public enum CreateAttachmentMode { /// - /// The will be created via a local file path. + /// 通过本地文件路径创建附件。 /// FilePath, /// - /// The will be created via a . + /// 通过 流的实例创建附件。 /// Stream, /// - /// The will be created via a - /// pointing to a file on KOOK asset OSS. + /// 通过指向 KOOK 对象存储服务器上的文件的 创建附件。 /// AssetUri } diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs index fdf380d3..bc1bffb6 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs @@ -1,7 +1,7 @@ namespace Kook; /// -/// Represents an embed in a message that links to a Bilibili video. +/// 表示一个消息中解析出的哔哩哔哩视频嵌入式内容。 /// public struct BilibiliVideoEmbed : IEmbed { @@ -20,40 +20,37 @@ internal BilibiliVideoEmbed(string url, string originUrl, string bvNumber, strin public EmbedType Type => EmbedType.BilibiliVideo; /// - /// Gets the URL of this embed. + /// 获取视频所在页面的 URL。 /// - /// - /// A string that represents the URL of this embed. - /// - public string Url { get; internal set; } + public string Url { get; } /// - /// A string that represents the origin URL of the Bilibili video. + /// 获取嵌入式内容所解析的原始 URL。 /// - public string OriginUrl { get; internal set; } + public string OriginUrl { get; } /// - /// A string that represents the Bilibili video number in BV format. + /// 获取视频的 BV 号。 /// - public string BvNumber { get; internal set; } + public string BvNumber { get; } /// - /// A string that represents the path of the iframe. + /// 获取视频的 iframe 路径。 /// - public string IframePath { get; internal set; } + public string IframePath { get; } /// - /// A that represents the duration of the Bilibili video. + /// 获取视频的时长。 /// - public TimeSpan Duration { get; internal set; } + public TimeSpan Duration { get; } /// - /// A string that represents the title of the Bilibili video. + /// 获取视频的标题。 /// - public string Title { get; internal set; } + public string Title { get; } /// - /// A string that represents the cover of the Bilibili video. + /// 获取图像封面图像的 URL。 /// - public string Cover { get; internal set; } + public string Cover { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/CardEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/CardEmbed.cs index ffad295e..c23a4ed7 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/CardEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/CardEmbed.cs @@ -1,7 +1,7 @@ namespace Kook; /// -/// Represents an embed in a message that +/// 表示一个消息中解析出的卡片嵌入式内容。 /// public struct CardEmbed : IEmbed { @@ -11,9 +11,9 @@ internal CardEmbed(ICard card) } /// - /// Gets the cards in this embed. + /// 获取卡片。 /// - public ICard Card { get; internal set; } + public ICard Card { get; } /// public EmbedType Type => EmbedType.Card; diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs index 6c8ab362..2223dfd1 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs @@ -1,32 +1,32 @@ namespace Kook; /// -/// Represents the type of an embed. +/// 表示嵌入式内容的类型。 /// public enum EmbedType { /// - /// Represents an embed that is not implemented. + /// 嵌入式内容的类型未解析到已知的强类型。 /// NotImplemented, /// - /// Represents an embed that is a link. + /// 嵌入式内容是一个网址链接。 /// Link, /// - /// Represents an embed that is an image. + /// 嵌入式内容是一个图片。 /// Image, /// - /// Represents an embed that is a Bilibili video. + /// 嵌入式内容是一个哔哩哔哩视频。 /// BilibiliVideo, /// - /// Represents an embed that is a card. + /// 嵌入式内容是一个卡片。 /// Card, diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs index 9b1b94d7..1f6b43c4 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs @@ -1,16 +1,13 @@ namespace Kook; /// -/// Represents a generic embed. +/// 表示一个消息内解析出的通用的嵌入式内容。 /// -/// +/// public interface IEmbed { /// - /// Gets the type of this embed. + /// 获取此嵌入式内容的类型。 /// - /// - /// A that represents the type of this embed. - /// EmbedType Type { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs index 4c5e145f..08d247f5 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs @@ -1,7 +1,7 @@ namespace Kook; /// -/// Represents an image embed. +/// 表示一个消息中解析出的图片嵌入式内容。 /// public struct ImageEmbed : IEmbed { @@ -15,18 +15,12 @@ internal ImageEmbed(string url, string originUrl) public EmbedType Type => EmbedType.Image; /// - /// Gets the URL of this embed. + /// 获取图像的 URL。 /// - /// - /// A string that represents the URL of this embed. - /// - public string Url { get; internal set; } + public string Url { get; } /// - /// Gets the original URL of the image. + /// 获取嵌入式内容所解析的原始 URL。 /// - /// - /// A string representing the original URL of the image. - /// - public string OriginUrl { get; internal set; } + public string OriginUrl { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs index 91dc9b90..7c38a244 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs @@ -1,7 +1,7 @@ namespace Kook; /// -/// Represents a link embed. +/// 表示一个消息中解析出的网址链接嵌入式内容。 /// public struct LinkEmbed : IEmbed { @@ -19,50 +19,32 @@ internal LinkEmbed(string url, string title, string description, string siteName public EmbedType Type => EmbedType.Link; /// - /// Gets the URL of this embed. + /// 获取网址链接的 URL。 /// - /// - /// A string that represents the URL of this embed. - /// public string Url { get; internal set; } /// - /// Gets the title of the website the link directs to. + /// 获取链接指向的网站的页面标题。 /// - /// - /// A string representing the title of the website the link directs to. - /// public string Title { get; internal set; } /// - /// Gets the description of the website the link directs to. + /// 获取链接指向的网站的页面描述。 /// - /// - /// A string representing the description of the website the link directs to. - /// public string Description { get; internal set; } /// - /// Gets the name of the website the link directs to. + /// 获取链接指向的网站的名称。 /// - /// - /// A string representing the name of the website the link directs to. - /// public string SiteName { get; internal set; } /// - /// Gets the color displayed along the left side of the card. + /// 获取卡片左侧边的颜色。 /// - /// - /// A string representing the color displayed along the left side of the card. - /// public Color Color { get; internal set; } /// - /// Gets the URL of the image related to the website the link directs to. + /// 获取预览图像的 URL。 /// - /// - /// A string representing the URL of the image related to the website the link directs to. - /// public string Image { get; internal set; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs index 9b1ae1ff..b5893aee 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs @@ -6,7 +6,7 @@ namespace Kook; /// -/// Represents a unimplemented embed. +/// 表示一个消息中未能被解析为已知的强类型的嵌入式内容。 /// public struct NotImplementedEmbed : IEmbed { @@ -20,36 +20,21 @@ internal NotImplementedEmbed(string rawType, JsonNode jsonNode) public EmbedType Type => EmbedType.NotImplemented; /// - /// Gets the type of the embed. + /// 获取嵌入式内容的类型的原始值。 /// - /// - /// A string representing the type of the embed. - /// - /// - /// This value originally came from the type field of the . - /// - public string RawType { get; internal set; } + public string RawType { get; } /// - /// Gets the raw JSON of the embed. + /// 获取嵌入式内容的原始 JSON。 /// - /// - /// A JsonNode representing the raw JSON of the embed. - /// - public JsonNode JsonNode { get; internal set; } + public JsonNode JsonNode { get; } /// - /// Resolves the embed to a concrete type via JSON deserialization. + /// 通过 JSON 反序列化将嵌入式内容解析为具体类型。 /// - /// - /// The options to use when deserializing the embed. - /// - /// - /// The concrete type to deserialize the embed to. - /// - /// - /// A representing the resolved embed. - /// + /// 用于反序列化操作的选项。 + /// 要解析为的具体类型。 + /// 解析后的嵌入式内容。 public T? Resolve(JsonSerializerOptions? options = null) where T : IEmbed { @@ -63,17 +48,11 @@ internal NotImplementedEmbed(string rawType, JsonNode jsonNode) } /// - /// Resolves the embed to a concrete type via delegate. + /// 通过指定的解析函数将嵌入式内容解析为具体类型。 /// - /// - /// The resolving function to use when resolves the embed. - /// - /// - /// The concrete type to deserialize the embed to. - /// - /// - /// A representing the resolved embed. - /// + /// 用于解析的函数。 + /// 要解析为的具体类型。 + /// 解析后的嵌入式内容。 public T Resolve(Func resolvingFunc) where T : IEmbed { diff --git a/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs b/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs index b0a448a0..f7232785 100644 --- a/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs +++ b/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs @@ -1,45 +1,43 @@ -using Kook.Utils; - namespace Kook; /// -/// Represents a file attachment. +/// 表示一个文件附件。 /// public struct FileAttachment : IDisposable { private bool _isDisposed; /// - /// Gets how this attachment will be operated. + /// 获取创建此文件附件的方式。 /// - public CreateAttachmentMode Mode { get; private set; } + public CreateAttachmentMode Mode { get; } /// - /// Gets the type of this attachment. + /// 获取此附件的类型。 /// - public AttachmentType Type { get; private set; } + public AttachmentType Type { get; } /// - /// Gets the filename. + /// 获取此附件的文件名。 /// - public string FileName { get; private set; } + public string FileName { get; } /// - /// Gets the stream containing the file content. + /// 获取包含文件内容的流。 /// public Stream? Stream { get; } /// - /// Gets the URI of the file. + /// 获取指向文件的 URL。 /// public Uri? Uri { get; internal set; } /// - /// Creates a file attachment from a stream. + /// 通过流创建附件。 /// - /// The stream to create the attachment from. - /// The name of the attachment. - /// The type of the attachment. + /// 创建附件所使用的流。 + /// 文件名。 + /// 附件的类型。 public FileAttachment(Stream stream, string filename, AttachmentType type = AttachmentType.File) { _isDisposed = false; @@ -60,42 +58,16 @@ public FileAttachment(Stream stream, string filename, AttachmentType type = Atta } /// - /// Create the file attachment from a file path. + /// 通过文件路径创建附件。 /// + /// 文件的路径。 + /// 文件名。 + /// 附件的类型。 /// - /// This file path is NOT validated and is passed directly into a - /// . + /// 此构造函数不会校验文件路径的格式, 的值将会直接传递给 + /// 方法。 /// - /// The path to the file. - /// The name of the attachment. - /// The type of the attachment. - /// - /// is a zero-length string, contains only white space, or contains one or - /// more invalid characters as defined by . - /// - /// - /// is null. - /// - /// - /// The specified path, file name, or both exceed the system-defined maximum length. For example, on - /// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 - /// characters. - /// - /// - /// is in an invalid format. - /// - /// - /// The specified is invalid, (for example, it is on an unmapped drive). - /// - /// - /// specified a directory. -or- The caller does not have the required permission. - /// - /// - /// The file specified in was not found. - /// - /// - /// An I/O error occurred while opening the file. - /// + /// public FileAttachment(string path, string? filename = null, AttachmentType type = AttachmentType.File) { _isDisposed = false; @@ -107,19 +79,16 @@ public FileAttachment(string path, string? filename = null, AttachmentType type } /// - /// Create the file attachment from a URI. + /// 通过 URL 创建附件。 /// /// - /// This URI path will be validated before being passed into REST API. - /// If the resource the URI points to is not stored on KOOK OSS, this constructor will throw an exception. - /// Under this circumstance, please create asset in advance. + /// URL 应该是指向 KOOK 对象存储服务器上的资源的 URL。如果传入的网络地址不是指向 KOOK 对象存储服务器上的资源的 URL, + /// 虽然此构造函数不会引发异常,但在发送消息时可能会引发异常。此时,网络资源应先通过转存至 KOOK 对象存储服务器上,再使用此构造函数。 /// - /// The URI of the file. - /// The name of the attachment. - /// The type of the attachment. - /// The URI provided is not an asset on the KOOK OSS. - /// The URI provided is blank. - /// + /// 文件的 URL。 + /// 文件名。 + /// 附件的类型。 + /// public FileAttachment(Uri uri, string filename, AttachmentType type = AttachmentType.File) { _isDisposed = false; diff --git a/src/Kook.Net.Core/Entities/Messages/IAttachment.cs b/src/Kook.Net.Core/Entities/Messages/IAttachment.cs index a640c9d6..8e83821c 100644 --- a/src/Kook.Net.Core/Entities/Messages/IAttachment.cs +++ b/src/Kook.Net.Core/Entities/Messages/IAttachment.cs @@ -1,76 +1,47 @@ namespace Kook; /// -/// Represents a message attachment found in a . +/// 表示一个消息内通用的附件。 /// public interface IAttachment { /// - /// Gets the type of the attachment. + /// 获取此附件的类型。 /// - /// - /// An representing the type of the attachment. - /// AttachmentType Type { get; } /// - /// Gets the URL of the attachment. + /// 获取此附件的 URL。 /// - /// - /// A string representing the URL of the attachment. - /// string Url { get; } /// - /// Gets the filename of this attachment. + /// 获取此附件的文件名。 /// - /// - /// A string containing the full filename of this attachment. - /// string? Filename { get; } /// - /// Gets the file size of the attachment. + /// 获取此附件的文件大小。 /// - /// - /// An int representing the file size of the attachment; - /// null if the file size is unknown or not applicable. - /// int? Size { get; } /// - /// Gets the file type of the attachment. + /// 获取此附件的文件类型。 /// - /// - /// A string representing the file type of the attachment; - /// null if the file type is unknown or not applicable. - /// string? FileType { get; } /// - /// Gets the duration of the attachment. + /// 如果此附件表示可播放的内容,则获取其持续时间。 /// - /// - /// A timespan representing the duration of the attachment; - /// null if the duration is unknown or not applicable. - /// TimeSpan? Duration { get; } /// - /// Gets the width of the attachment. + /// 如果此附件表示的内容包含画面,则获取其宽度。 /// - /// - /// An int representing the width of the attachment; - /// null if the width is unknown or not applicable. - /// int? Width { get; } /// - /// Gets the height of the attachment. + /// 如果此附件表示的内容包含画面,则获取其高度。 /// - /// - /// An int representing the height of the attachment; - /// null if the height is unknown or not applicable. - /// int? Height { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/IMessage.cs b/src/Kook.Net.Core/Entities/Messages/IMessage.cs index 6b597a65..a4569411 100644 --- a/src/Kook.Net.Core/Entities/Messages/IMessage.cs +++ b/src/Kook.Net.Core/Entities/Messages/IMessage.cs @@ -1,142 +1,117 @@ namespace Kook; /// -/// Represents a message object. +/// 表示一个通用的消息。 /// public interface IMessage : IEntity, IDeletable { #region General /// - /// Gets the type of this message. + /// 获取此消息的类型。 /// MessageType Type { get; } /// - /// Gets the source type of this message. + /// 获取此消息的来源。 /// MessageSource Source { get; } /// - /// Gets the value that indicates whether this message is pinned. + /// 获取此消息是否被置顶。 /// - /// - /// true if this message was added to its channel's pinned messages; otherwise false. - /// bool? IsPinned { get; } /// - /// Gets the source channel of the message. + /// 获取此消息的来源频道。 /// IMessageChannel Channel { get; } /// - /// Gets the author of this message. + /// 获取此消息的作者。 /// IUser Author { get; } /// - /// Gets the content for this message. + /// 获取此消息的内容。 /// - /// - /// A string that contains the body of the message; - /// note that this field may be empty or the original code if the message is not a text based message. - /// + /// + /// 如果消息不是文本消息,则此属性可能为空或包含原始代码。 + /// string Content { get; } /// - /// Gets the clean content for this message. + /// 获取此消息的纯净内容。 /// /// - /// A string that contains the body of the message stripped of mentions, markdown, emojis and pings; - /// note that this field may be empty or the original code if the message is not a text based message. + /// 此属性会对 的内容进行两步操作:
+ /// 1. 使用 + /// 方法解析所有标签的完整名称;
+ /// 2. 使用 清理所有 KMarkdown 格式字符。 ///
+ /// + /// string CleanContent { get; } /// - /// Gets the time this message was sent. + /// 获取此消息的发送时间。 /// - /// - /// Time of when the message was sent. - /// DateTimeOffset Timestamp { get; } /// - /// Gets the time of this message's last edit. + /// 获取此消息最后一次编辑的时间。 /// - /// - /// Time of when the message was last edited; - /// null if the message is never edited. - /// + /// + /// 如果此消息从未被编辑过,则此属性的值为 。 + /// DateTimeOffset? EditedTimestamp { get; } /// - /// Gets the IDs of users mentioned in this message. + /// 获取此消息中提及的所有用户的 ID。 /// - /// - /// A read-only collection of user IDs. - /// IReadOnlyCollection MentionedUserIds { get; } /// - /// Gets the IDs of roles mentioned in this message. + /// 获取此消息中提及的所有角色的 ID。 /// - /// - /// A read-only collection of role IDs. - /// IReadOnlyCollection MentionedRoleIds { get; } /// - /// Gets the value that indicates whether this message mentioned everyone. + /// 获取此消息是否提及了全体成员。 /// - /// - /// true if this message mentioned everyone; otherwise false. - /// bool MentionedEveryone { get; } /// - /// Gets the value that indicates whether this message mentioned online users. + /// 获取此消息是否提及了在线成员。 /// - /// - /// true if this message mentioned online users; otherwise false. - /// bool MentionedHere { get; } /// - /// Gets all tags included in this message's content. + /// 获取此消息中解析出的所有标签。 /// IReadOnlyCollection Tags { get; } /// - /// Gets the attachment included in this message. + /// 获取此消息中包含的所有附件。 /// - /// - /// The attachment included in this message; - /// + /// + /// 此属性也会包含从卡片中解析出来的附件信息。 + /// IReadOnlyCollection Attachments { get; } /// - /// Gets all cards included in this message. + /// 获取此消息中包含的所有卡片。 /// - /// - /// A read-only collection of card objects. - /// IReadOnlyCollection Cards { get; } /// - /// Gets all embeds included in this message. + /// 获取此消息中包含的所有嵌入式内容。 /// - /// - /// A read-only collection of embed objects. - /// IReadOnlyCollection Embeds { get; } /// - /// Gets all poke actions included in this message. + /// 获取此消息中包含的所有 POKE。 /// - /// - /// A read-only collection of poke actions objects. - /// IReadOnlyCollection Pokes { get; } #endregion @@ -144,53 +119,42 @@ public interface IMessage : IEntity, IDeletable #region Reactions /// - /// Gets all reactions included in this message. + /// 获取此消息中包含的所有回应。 /// IReadOnlyDictionary Reactions { get; } /// - /// Adds a reaction to this message. + /// 向此消息添加一个回应。 /// - /// The emoji used to react to this message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for adding a reaction to this message. - /// - /// + /// 要用于向此消息添加回应的表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示添加添加异步操作的任务。 Task AddReactionAsync(IEmote emote, RequestOptions? options = null); /// - /// Removes a reaction from message. + /// 从此消息中移除一个回应。 /// - /// The emoji used to react to this message. - /// The user that added the emoji. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for removing a reaction to this message. - /// - /// + /// 要从此消息移除的回应的表情符号。 + /// 要移除其回应的用户。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除操作的任务。 Task RemoveReactionAsync(IEmote emote, IUser user, RequestOptions? options = null); /// - /// Removes a reaction from message. + /// 从此消息中移除一个回应。 /// - /// The emoji used to react to this message. - /// The ID of the user that added the emoji. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for removing a reaction to this message. - /// - /// + /// 要从此消息移除的回应的表情符号。 + /// 要移除其回应的用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除操作的任务。 Task RemoveReactionAsync(IEmote emote, ulong userId, RequestOptions? options = null); /// - /// Gets all users that reacted to a message with a given emote. + /// 获取所有对消息使用给定表情符号进行回应的用户。 /// - /// The emoji that represents the reaction that you wish to get. - /// The options to be used when sending the request. - /// - /// Collection of users. - /// + /// 要获取其回应用户的表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含对消息使用给定表情符号进行回应的所有用户。 Task> GetReactionUsersAsync(IEmote emote, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Messages/IQuote.cs b/src/Kook.Net.Core/Entities/Messages/IQuote.cs index 16487868..ed35c002 100644 --- a/src/Kook.Net.Core/Entities/Messages/IQuote.cs +++ b/src/Kook.Net.Core/Entities/Messages/IQuote.cs @@ -1,12 +1,12 @@ namespace Kook; /// -/// Represents a generic message quote. +/// 表示一个通用的消息引用。 /// public interface IQuote { /// - /// Gets the identifier of the message this quote refers to. + /// 获取此引用所指向的消息的 ID。 /// Guid QuotedMessageId { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/IReaction.cs b/src/Kook.Net.Core/Entities/Messages/IReaction.cs index d6aebff2..c8ab35cf 100644 --- a/src/Kook.Net.Core/Entities/Messages/IReaction.cs +++ b/src/Kook.Net.Core/Entities/Messages/IReaction.cs @@ -1,12 +1,12 @@ namespace Kook; /// -/// Represents a generic reaction object. +/// 表示一个通用的回应。 /// public interface IReaction { /// - /// The used in the reaction. + /// 获取此回应所使用的表情符号。 /// IEmote Emote { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs b/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs index b4fc15bb..09dcd9c1 100644 --- a/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs +++ b/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs @@ -1,19 +1,17 @@ namespace Kook; /// -/// Represents a generic message sent by the system. +/// 表示一个通用的系统消息。 /// +/// +/// +/// KOOK 未统一规范系统消息类型,此接口并未在 之上封装更多的实用功能。 +/// +/// public interface ISystemMessage : IMessage { /// - /// Gets the type of the system message. + /// 获取此系统消息的类型。 /// - /// - /// - /// Because the data from Kook does not describe the type - /// of the message in detail, this property is not implemented yet. - /// Accessing this property will always result in an exception at present. - /// - /// SystemMessageType SystemMessageType { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/ITag.cs b/src/Kook.Net.Core/Entities/Messages/ITag.cs index e563779a..1a213bd7 100644 --- a/src/Kook.Net.Core/Entities/Messages/ITag.cs +++ b/src/Kook.Net.Core/Entities/Messages/ITag.cs @@ -1,33 +1,36 @@ namespace Kook; /// -/// Gets a generic tag found in messages. +/// 表示一个消息中通用的标签。 /// -/// public interface ITag { /// - /// Gets position of the tag in the message. + /// 获取消息中标签的位置。 /// int Index { get; } /// - /// Gets the length of the tag. + /// 获取标签的长度。 /// int Length { get; } /// - /// Gets the type of the tag. + /// 获取标签的类型。 /// TagType Type { get; } /// - /// Gets the key of the tag. + /// 获取标签的键。 /// - dynamic Key { get; } + object Key { get; } /// - /// Gets the value of the tag. + /// 获取标签的值。 /// + /// + /// 当 ,此属性应返回表示提及在线成员的实体,但这样的实体不存在。 + /// 为了便利,此属性返回与 相同的实体,但并不表示此标签提及的是所有人,而仍表示提及的是在线成员。 + /// object? Value { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs b/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs index 78493815..30ab8473 100644 --- a/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs +++ b/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs @@ -1,40 +1,33 @@ namespace Kook; /// -/// Represents a generic message sent by a user. +/// 表示一个通用的用户消息。 /// public interface IUserMessage : IMessage { /// - /// Gets the message quote. + /// 获取消息的引用。 /// - /// - /// The message quote. - /// IQuote? Quote { get; } /// - /// Modifies this message. + /// 修改此消息。 /// - /// - /// This method modifies this message with the specified properties. To see an example of this - /// method and what properties are available, please refer to . - /// - /// A delegate containing the properties to modify the message with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// + /// 一个包含修改消息属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 + /// Task ModifyAsync(Action func, RequestOptions? options = null); /// - /// Transforms this message's text into a human-readable form by resolving its tags. + /// 转换消息文本中的提及与表情符号为可读形式。 /// - /// Determines how the user tag should be handled. - /// Determines how the channel tag should be handled. - /// Determines how the role tag should be handled. - /// Determines how the @everyone tag should be handled. - /// Determines how the emoji tag should be handled. + /// 指定用户提及标签的处理方式。 + /// 指定频道提及标签的处理方式。 + /// 指定角色提及标签的处理方式。 + /// 指定全体成员与在线成员提及标签的处理方式。 + /// 指定表情符号标签的处理方式。 + /// 转换后的消息文本。 string Resolve( TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, diff --git a/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs b/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs index 8480e221..83181282 100644 --- a/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs +++ b/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs @@ -1,31 +1,44 @@ namespace Kook; /// -/// Properties that are used to modify an with the specified changes. +/// 提供用于修改 的属性。 /// -/// +/// public class MessageProperties { /// - /// Gets or sets the content of the message. + /// 获取或设置要设置到此消息的消息内容。 /// /// - /// This must be less than the constant defined by . + /// 修改此值为非空字符串可以修改消息的内容;不修改此值或将其设置为 null 可以保持消息的原内容。 /// public string? Content { get; set; } /// - /// Gets or sets the cards of the message. + /// 获取或设置要设置到此消息的卡片。 + /// 修改此值,或修改此 中的成员,可以修改消息中卡片的内容。 /// - public IEnumerable? Cards { get; set; } + public IList? Cards { get; set; } /// - /// Gets or sets the quote of the message. + /// 获取或设置要设置到此消息的消息引用。 /// + /// + /// 仅支持通过将此属性设置为 MessageReference.Empty 来清除消息引用,不支持更改现有消息引用。 + /// + /// public IQuote? Quote { get; set; } /// - /// Gets or sets the only user that can see this message. + /// 获取或设置要临时更新到此消息的用户。 /// + /// + /// 设置此属性会使此用户在本次登录会话中看到的消息内容为本次临时修改的内容, + /// 该用户在下次登录会话中看到的消息内容仍为原内容。
+ /// + /// 仅支持通过设置此属性为指定用户的 ID 来为该用户临时更新消息。
+ /// 设置此属性无法将非临时消息更改为仅指定用户可见的临时消息,也无法为过去发送的临时消息更改可见用户。 + ///
+ ///
public IUser? EphemeralUser { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Messages/MessageReference.cs b/src/Kook.Net.Core/Entities/Messages/MessageReference.cs index 343e345e..c7771d91 100644 --- a/src/Kook.Net.Core/Entities/Messages/MessageReference.cs +++ b/src/Kook.Net.Core/Entities/Messages/MessageReference.cs @@ -3,26 +3,24 @@ namespace Kook; /// -/// Represents a message reference. +/// 表示一个消息引用。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class MessageReference : IQuote { /// - /// Gets an empty quote whose quoted message is null. + /// 获取一个引用的消息为空的引用。 /// /// - /// Used to delete a quote when modifying a message. + /// 此属性用于在修改消息时删除引用。 /// + /// public static MessageReference Empty => new(Guid.Empty); /// - /// Creates a new instance of with the specified quoted message identifier. + /// 使用指定的消息 ID 创建一个新的 实例。 /// - /// - /// The identifier of the message that will be quoted. - /// If , the quote will be empty. - /// + /// 要引用的消息的 ID。 public MessageReference(Guid quotedMessageId) { QuotedMessageId = quotedMessageId; diff --git a/src/Kook.Net.Core/Entities/Messages/MessageType.cs b/src/Kook.Net.Core/Entities/Messages/MessageType.cs index 2b980f09..b087a469 100644 --- a/src/Kook.Net.Core/Entities/Messages/MessageType.cs +++ b/src/Kook.Net.Core/Entities/Messages/MessageType.cs @@ -1,52 +1,52 @@ namespace Kook; /// -/// Represents the type of a message. +/// 表示一个消息的类型。 /// public enum MessageType { /// - /// Represents that the type of the message contains plain text. + /// 纯文本消息。 /// Text = 1, /// - /// Represents that the type of the message contains an image. + /// 图片消息。 /// Image = 2, /// - /// Represents that the type of the message contains a video. + /// 视频消息。 /// Video = 3, /// - /// Represents that the type of the message contains a file. + /// 文件消息。 /// File = 4, /// - /// Represents that the type of the message contains a voice message. + /// 音频消息。 /// Audio = 8, /// - /// Represents that the type of the message contains a KMarkdown message. + /// KMarkdown 文本消息。 /// KMarkdown = 9, /// - /// Represents that the type of the message contains cards. + /// 卡片消息。 /// Card = 10, /// - /// Represents that the type of the message contains a poke action. + /// POKE 消息。 /// Poke = 12, /// - /// Represents that the type of the message originates from KOOK system. + /// 系统消息。 /// System = 255 } diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs index c81731c7..3342bf4c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs @@ -1,52 +1,52 @@ namespace Kook; /// -/// Represents a generic poke. +/// 表示一个通用的 POKE。 /// public interface IPoke : IEntity { /// - /// Gets the name of the poke. + /// 获取 POKE 的名称。 /// string Name { get; } /// - /// Gets the description of the poke. + /// 获取 POKE 的描述。 /// string Description { get; } /// - /// Gets how long a user needs to wait before they can use the poke again. + /// 获取用户使用此 POKE 后的冷却时间。 /// TimeSpan Cooldown { get; } /// - /// Gets the categories of the poke. + /// 获取此 POKE 的分类。 /// IReadOnlyCollection Categories { get; } /// - /// Gets the label of the poke. + /// 获取此 POKE 的标签。 /// PokeLabel Label { get; } /// - /// Gets the icon resources of the poke. + /// 获取此 POKE 的图标资源。 /// PokeIcon Icon { get; } /// - /// Gets the quality of the poke. + /// 获取此 POKE 的品质。 /// PokeQuality Quality { get; } /// - /// Gets the resource of the poke. + /// 获取此 POKE 的资源。 /// IPokeResource Resource { get; } /// - /// Gets how the poke can be used and displayed in message contexts. + /// 获取此 POKE 如何在消息上下文中使用和显示。 /// IReadOnlyDictionary MessageScenarios { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs index 2adb71eb..e7b4f43f 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Represents a single generic poke action. +/// 表示一个通用的 POKE 动作。 /// public interface IPokeAction { /// - /// Gets the user who performed the action. + /// 获取执行此动作的用户。 /// IUser Operator { get; } /// - /// Gets the users who were poked by the action. + /// 获取此动作的目标用户。 /// IReadOnlyCollection Targets { get; } /// - /// Gets the poke this action is associated with. + /// 获取此动作关联的 POKE。 /// IPoke Poke { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs index e4233289..ed1d7794 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs @@ -1,19 +1,19 @@ namespace Kook; /// -/// Represents an icon of an . +/// 表示一个 POKE 的图标。 /// public struct PokeIcon { /// - /// Gets the resource uri of the icon. + /// 获取图标资源的 URL。 /// - public string Resource { get; internal set; } + public string Resource { get; } /// - /// Gets the resource uri of the icon when the is expired. + /// 获取当此图标所关联的 POKE 过期后的图标资源的 URL。 /// - public string ResourceExpired { get; internal set; } + public string ResourceExpired { get; } internal PokeIcon(string resource, string resourceExpired) { diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs index 3c6b10c9..d73a59ff 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs @@ -1,19 +1,19 @@ namespace Kook; /// -/// Represents the label of a . +/// 表示一个 POKE 的标签。 /// public struct PokeLabel : IEntity { /// - /// Gets the ID of the poke action label. + /// 获取 POKE 的标签的唯一标识符。 /// - public uint Id { get; internal set; } + public uint Id { get; } /// - /// Gets the name of the poke action label. + /// 获取 POKE 的标签的名称。 /// - public string Name { get; internal set; } + public string Name { get; } internal PokeLabel(uint id, string name) { diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs index 0f136424..1c84da90 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs @@ -1,24 +1,24 @@ namespace Kook; /// -/// Represents the quality of a . +/// 表示一个 POKE 的品质。 /// public struct PokeQuality : IEntity { /// - /// Gets the identifier of the . + /// 获取 POKE 品质的唯一标识符。 /// - public uint Id { get; internal set; } + public uint Id { get; } /// - /// Gets the color of the . + /// 获取 POKE 品质的颜色。 /// - public Color Color { get; internal set; } + public Color Color { get; } /// - /// Gets the resources of the . + /// 获取 POKE 品质的资源。 /// - public IReadOnlyDictionary Resources { get; internal set; } + public IReadOnlyDictionary Resources { get; } internal PokeQuality(uint id, Color color, IReadOnlyDictionary resources) { diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs index c39bb8f4..20cf865a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs @@ -1,12 +1,12 @@ namespace Kook; /// -/// Represents a generic poke resource. +/// 表示一个通用的 POKE 资源。 /// public interface IPokeResource { /// - /// Gets the type of the poke resource. + /// 获取此 POKE 资源的类型。 /// PokeResourceType Type { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs index ebeb4ada..98be8eb2 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs @@ -1,7 +1,7 @@ namespace Kook; /// -/// Represents an image animation poke resource. +/// 表示一个 POKE 的图像与动画的资源。 /// public struct ImageAnimationPokeResource : IPokeResource { @@ -19,27 +19,27 @@ internal ImageAnimationPokeResource(IReadOnlyDictionary resource public PokeResourceType Type => PokeResourceType.ImageAnimation; /// - /// Gets the resources of the image animation. + /// 获取图像动画的资源。 /// - public IReadOnlyDictionary Resources { get; internal set; } + public IReadOnlyDictionary Resources { get; } /// - /// Gets how long this animation should last filling the full screen. + /// 获取此动画以全屏的形式播放的持续时间。 /// - public TimeSpan Duration { get; internal set; } + public TimeSpan Duration { get; } /// - /// Gets the width of the image animation. + /// 获取图像动画的宽度。 /// - public int Width { get; internal set; } + public int Width { get; } /// - /// Gets the height of the image animation. + /// 获取图像动画的高度。 /// - public int Height { get; internal set; } + public int Height { get; } /// /// // TODO: To be documented. /// - public decimal Percent { get; internal set; } + public decimal Percent { get; } } diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs index 861e8ed1..649db085 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs @@ -6,7 +6,7 @@ namespace Kook; /// -/// Represents a poke resource that is not implemented to be resolved yet. +/// 表示一个未能被解析为已知的强类型的 POKE 资源。 /// public struct NotImplementedPokeResource : IPokeResource { @@ -20,36 +20,21 @@ internal NotImplementedPokeResource(string rawType, JsonNode jsonNode) public PokeResourceType Type => PokeResourceType.NotImplemented; /// - /// Gets the type of the poke resource. + /// 获取此 POKE 资源的类型的原始值。 /// - /// - /// A string representing the type of the poke resource. - /// - /// - /// This value originally came from the type field of the . - /// - public string RawType { get; internal set; } + public string RawType { get; } /// - /// Gets the raw JSON of the embed. + /// 获取此 POKE 资源的原始 JSON。 /// - /// - /// A JsonNode representing the raw JSON of the embed. - /// - public JsonNode JsonNode { get; internal set; } + public JsonNode JsonNode { get; } /// - /// Resolves the embed to a concrete type via JSON deserialization. + /// 通过 JSON 反序列化将 POKE 资源解析为具体类型。 /// - /// - /// The options to use when deserializing the embed. - /// - /// - /// The concrete type to deserialize the embed to. - /// - /// - /// A representing the resolved embed. - /// + /// 用于反序列化操作的选项。 + /// 要解析为的具体类型。 + /// 解析后的 POKE 资源。 public T? Resolve(JsonSerializerOptions? options = null) where T : IPokeResource { @@ -63,17 +48,11 @@ internal NotImplementedPokeResource(string rawType, JsonNode jsonNode) } /// - /// Resolves the embed to a concrete type via delegate. + /// 通过指定的解析函数将 POKE 资源 解析为具体类型。 /// - /// - /// The resolving function to use when resolves the embed. - /// - /// - /// The concrete type to deserialize the embed to. - /// - /// - /// A representing the resolved embed. - /// + /// 用于解析的函数。 + /// 要解析为的具体类型。 + /// 解析后的 POKE 资源 。 public T Resolve(Func resolvingFunc) where T : IPokeResource { diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs index 4fd26958..d2742f5a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Represents the type of a . +/// 表示一个 POKE 资源的类型。 /// public enum PokeResourceType { /// - /// Represents a resource that is not implemented. + /// POKE 资源的类型未解析到已知的强类型。 /// NotImplemented, /// - /// Represents a resource that is an image. + /// POKE 资源是一个图像动画 /// ImageAnimation } diff --git a/src/Kook.Net.Core/Entities/Messages/Quote.cs b/src/Kook.Net.Core/Entities/Messages/Quote.cs index 8809b830..05f965d2 100644 --- a/src/Kook.Net.Core/Entities/Messages/Quote.cs +++ b/src/Kook.Net.Core/Entities/Messages/Quote.cs @@ -3,7 +3,7 @@ namespace Kook; /// -/// Represents a quoted message. +/// 表示一个引用的消息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Quote : IQuote @@ -12,48 +12,38 @@ public class Quote : IQuote public Guid QuotedMessageId { get; } /// - /// Gets the type of the message this quote refers to. + /// 获取此引用的消息的类型。 /// public MessageType Type { get; } /// - /// Gets the content of the message this quote refers to. + /// 获取此引用的消息的内容。 /// - /// - /// A string that contains the body of the message; - /// note that this field may be empty or the original code if the message is not a text based message. - /// + /// + /// 如果此引用的消息不是文本消息,则此属性可能为空或包含原始代码。 + /// public string Content { get; } /// - /// Gets the time this message was sent. + /// 获取此引用的消息的发送时间。 /// - /// - /// Time of when the message was sent. - /// public DateTimeOffset CreateAt { get; } /// - /// Gets the author of this message. + /// 获取此引用的消息的作者。 /// public IUser Author { get; } - /// - /// Gets an empty quote whose quoted message is null. - /// - /// - /// Used to delete a quote when modifying a message. - /// + /// [Obsolete("Use MessageReference.Empty instead.")] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static MessageReference Empty => new(Guid.Empty); /// - /// Initializes a new instance of the class. + /// 使用指定的消息 ID 创建一个新的 实例。 /// - /// - /// The quoted message identifier. - /// + /// 要引用的消息的 ID。 + /// [Obsolete("Use MessageReference instead.")] public Quote(Guid quotedMessageId) { diff --git a/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs b/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs index bfadc982..a2c29f10 100644 --- a/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs +++ b/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs @@ -1,23 +1,17 @@ namespace Kook; /// -/// A metadata containing reaction information. +/// 表示一个关于消息回应的元数据。 /// public struct ReactionMetadata { /// - /// Gets the number of reactions. + /// 获取此消息中已添加此回应的人数。 /// - /// - /// An int representing the number of this reactions that has been added to this message. - /// public int ReactionCount { get; internal set; } /// - /// Gets a value that indicates whether the current user has reacted to this. + /// 获取当前用户是否已对此消息做出回应。 /// - /// - /// true if the user has reacted to the message; otherwise false. - /// public bool IsMe { get; internal set; } } diff --git a/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs b/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs index 350c6598..2169ca30 100644 --- a/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs +++ b/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs @@ -1,8 +1,12 @@ namespace Kook; /// -/// Gets the type of a +/// 表示一个系统消息的类型。 /// public enum SystemMessageType { + /// + /// 表示一个未知的系统消息类型。 + /// + Unknown = -1 } diff --git a/src/Kook.Net.Core/Entities/Messages/Tag.cs b/src/Kook.Net.Core/Entities/Messages/Tag.cs index b2d5459f..7fbd7784 100644 --- a/src/Kook.Net.Core/Entities/Messages/Tag.cs +++ b/src/Kook.Net.Core/Entities/Messages/Tag.cs @@ -2,11 +2,11 @@ namespace Kook; -/// -/// Represents a tag found in . -/// +/// [DebuggerDisplay("{DebuggerDisplay,nq}")] -public class Tag : ITag +public class Tag : ITag + where TKey : IEquatable + where TValue : IEntity { /// public TagType Type { get; } @@ -17,20 +17,13 @@ public class Tag : ITag /// public int Length { get; } - /// - public dynamic Key { get; } - - /// - /// Gets the value of the tag. - /// - /// - /// When is , - /// this property returns the same entity as for convenience. - /// because there is no actual entities representing a group of online users. - /// - public T? Value { get; } - - internal Tag(TagType type, int index, int length, dynamic key, T? value) + /// + public TKey Key { get; } + + /// + public TValue? Value { get; } + + internal Tag(TagType type, int index, int length, TKey key, TValue? value) { Type = type; Index = index; @@ -44,6 +37,9 @@ internal Tag(TagType type, int index, int length, dynamic key, T? value) /// public override string ToString() => DebuggerDisplay; + /// + object ITag.Key => Key; + /// object? ITag.Value => Value; } diff --git a/src/Kook.Net.Core/Entities/Messages/TagHandling.cs b/src/Kook.Net.Core/Entities/Messages/TagHandling.cs index cd27536f..03e29bd6 100644 --- a/src/Kook.Net.Core/Entities/Messages/TagHandling.cs +++ b/src/Kook.Net.Core/Entities/Messages/TagHandling.cs @@ -1,44 +1,128 @@ namespace Kook; /// -/// Specifies the handling type the tag should use. +/// 表示在转换标签时应进行的操作类型。 /// -/// -/// +/// public enum TagHandling { /// - /// Tag handling is ignored. (e.g. (met)2810246202(met) -> (met)2810246202(met)) + /// 不进行任何处理。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) (met)2810246202(met) + /// (chn)5017360261312802(chn) (chn)5017360261312802(chn) + /// (rol)6790760(rol) (rol)6790760(rol) + /// (met)all(met) (met)all(met) + /// (met)here(met) (met)here(met) + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] + /// + /// Ignore = 0, /// - /// Removes the tag entirely. + /// 移除标签。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) + /// (chn)5017360261312802(chn) + /// (rol)6790760(rol) + /// (met)all(met) + /// (met)here(met) + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] + /// + /// Remove, /// - /// Resolves to username (e.g. (met)2810246202(met) -> @Someone). + /// 转换为名称,包含提及前缀。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) @用户名 + /// (chn)5017360261312802(chn) #频道名称 + /// (rol)6790760(rol) @角色名称 + /// (met)all(met) @全体成员 + /// (met)here(met) @在线成员 + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] :kooknet-logo: + /// + /// Name, /// - /// Resolves to username without mention prefix (e.g. (met)2810246202(met) -> Someone). + /// 转换为名称,但不包含提及前缀。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) 用户名 + /// (chn)5017360261312802(chn) 频道名称 + /// (rol)6790760(rol) 角色名称 + /// (met)all(met) 全体成员 + /// (met)here(met) 在线成员 + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] kooknet-logo + /// + /// NameNoPrefix, /// - /// Resolves to username with identify number value (e.g. (met)2810246202(met) -> @Someone#1234). + /// 转换为名称,包含提及前缀。如果提及标签为用户提及,则还会包含用户的识别号。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) @用户名#0001 + /// (chn)5017360261312802(chn) #频道名称 + /// (rol)6790760(rol) @角色名称 + /// (met)all(met) @全体成员 + /// (met)here(met) @在线成员 + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] :kooknet-logo: + /// + /// FullName, /// - /// Resolves to username with identify number value without mention prefix (e.g. (met)2810246202(met) -> Someone#1234). + /// 转换为名称,但不包含提及前缀。如果提及标签为用户提及,则还会包含用户的识别号。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) 用户名#0001 + /// (chn)5017360261312802(chn) 频道名称 + /// (rol)6790760(rol) 角色名称 + /// (met)all(met) 全体成员 + /// (met)here(met) 在线成员 + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] kooknet-logo + /// + /// FullNameNoPrefix, /// - /// Sanitizes the tag. (e.g. (met)2810246202(met) -> (met)2810246202(met) (an nbsp is inserted before the key)). + /// 使用 U+200B 零宽空格字符转义标签。 /// + /// + /// 例如: + /// + /// 原始值 转换结果 + /// (met)2810246202(met) (met)[ZWSP]2810246202(met) + /// (chn)5017360261312802(chn) (chn)[ZWSP]5017360261312802(chn) + /// (rol)6790760(rol) (rol)[ZWSP]6790760(rol) + /// (met)all(met) (met)[ZWSP]all(met) + /// (met)here(met) (met)[ZWSP]here(met) + /// (emj)kooknet-logo(emj)[1591057729615250/E8fy7hpRFU1jk1jk] (emj)[ZWSP]kooknet-logo(emj)[[ZWSP]1591057729615250/E8fy7hpRFU1jk1jk] + /// + /// 其中,[ZWSP] 代表 U+200B 零宽空格字符。 + /// Sanitize } diff --git a/src/Kook.Net.Core/Entities/Messages/TagMode.cs b/src/Kook.Net.Core/Entities/Messages/TagMode.cs index 1c31c98e..5d63a461 100644 --- a/src/Kook.Net.Core/Entities/Messages/TagMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/TagMode.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Represents the mode to parse tags. +/// 表示标签的语法模式。 /// public enum TagMode { /// - /// Parse tags as plain text. + /// 纯文本形式。 /// PlainText, /// - /// Parse tags as KMarkdown. + /// KMarkdown 格式。 /// KMarkdown } diff --git a/src/Kook.Net.Core/Entities/Messages/TagType.cs b/src/Kook.Net.Core/Entities/Messages/TagType.cs index 356b3f7d..d6b42253 100644 --- a/src/Kook.Net.Core/Entities/Messages/TagType.cs +++ b/src/Kook.Net.Core/Entities/Messages/TagType.cs @@ -1,23 +1,37 @@ namespace Kook; -/// Specifies the type of Kook tag. +/// +/// 表示标签的类型。 +/// public enum TagType { - /// The object is an user mention. + /// + /// 用户提及标签。 + /// UserMention, - /// The object is a channel mention. + /// + /// 频道提及标签。 + /// ChannelMention, - /// The object is a role mention. + /// + /// 角色提及标签。 + /// RoleMention, - /// The object is an everyone mention. + /// + /// 全体成员提及标签。 + /// EveryoneMention, - /// The object is a here mention. + /// + /// 在线成员提及标签。 + /// HereMention, - /// The object is an emoji. + /// + /// 表情符号标签。 + /// Emoji } diff --git a/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs b/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs index c6b88c2b..e198d555 100644 --- a/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs +++ b/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs @@ -1,102 +1,62 @@ namespace Kook; /// -/// Represents a permission can be granted to a channel. +/// 表示可以为角色或用户设置的频道级别的权限。 /// [Flags] public enum ChannelPermission : uint { - /// - /// Allows creation of invites. - /// + /// CreateInvites = 1 << 3, - /// - /// Allows management and editing of channels. - /// + /// ManageChannels = 1 << 5, - /// - /// Allows management and editing of roles. - /// + /// ManageRoles = 1 << 10, - /// - /// Allows guild members to view a channel, which includes reading messages in text channels. - /// + /// ViewChannel = 1 << 11, - /// - /// Allows for sending messages in a channel - /// + /// SendMessages = 1 << 12, - /// - /// Allows for deletion of other users messages. - /// + /// ManageMessages = 1 << 13, - /// - /// Allows for uploading images and files. - /// + /// AttachFiles = 1 << 14, - /// - /// Allows for joining of a voice channel. - /// + /// Connect = 1 << 15, - /// - /// Allows for disconnection of members, and moving of members between voice channels. - /// - /// - /// Such movements are allowed to channels that both the user to be moved and the operator have permissions to. - /// + /// ManageVoice = 1 << 16, - /// - /// Allows for using the everyone mention tag to notify all users in a channel, - /// and the online mention tag to notify all online users in a channel. - /// + /// MentionEveryone = 1 << 17, - /// - /// Allows for the addition of reactions to messages. - /// + /// AddReactions = 1 << 18, - /// - /// Limits the user to connecting to a voice channel only when the user is invited or moved by others. - /// + /// PassiveConnect = 1 << 20, - /// - /// Allows for speaking in voice a channel without having to press the speaking key. - /// + /// UseVoiceActivity = 1 << 22, - /// - /// Allows for speaking in a voice channel. - /// + /// Speak = 1 << 23, - /// - /// Allows for deafening of members in a voice channel. - /// + /// DeafenMembers = 1 << 24, - /// - /// Allows for muting members in a voice channel. - /// + /// MuteMembers = 1 << 25, - /// - /// Allows for playing soundtracks in a voice channel. - /// + /// PlaySoundtrack = 1 << 27, - /// - /// Allows for screen share. - /// + /// ShareScreen = 1 << 28 } diff --git a/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs b/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs index a1719dc9..c8942cc0 100644 --- a/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs +++ b/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs @@ -3,28 +3,42 @@ namespace Kook; /// -/// Represents a set of permissions for a channel. +/// 表示一个频道的权限集。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct ChannelPermissions { - /// Gets a blank that grants no permissions. + /// + /// 获取一个空的 ,不包含任何权限。 + /// public static readonly ChannelPermissions None = new(); - /// Gets a that grants all permissions for text channels. + /// + /// 获取一个包含所有可以为文字频道设置的权限的 。 + /// public static readonly ChannelPermissions Text = new(0b0_0000_0000_0110_0111_1100_0010_1000); - /// Gets a that grants all permissions for voice channels. + /// + /// 获取一个包含所有可以为语音频道设置的权限的 。 + /// public static readonly ChannelPermissions Voice = new(0b1_1011_1101_0111_1111_1100_0010_1000); - /// Gets a that grants all permissions for category channels. + /// + /// 获取一个包含所有可以为分组频道设置的权限的 。 + /// public static readonly ChannelPermissions Category = new(0b1_1011_1101_0111_1111_1100_0010_1000); - /// Gets a that grants all permissions for direct message channels. + /// + /// 获取一个包含所有可以为私聊频道设置的权限的 。 + /// public static readonly ChannelPermissions DM = new(0b0_0000_0000_0100_0101_1000_0000_0000); - /// Gets a that grants all permissions for a given channel type. - /// Unknown channel type. + /// + /// 为指定的频道根据其类型获取一个包含所有权限的 。 + /// + /// 要获取其包含所有权限的频道。 + /// 一个包含所有该频道可以拥有的权限的 + /// 未知的频道类型。 public static ChannelPermissions All(IChannel channel) => channel switch { @@ -35,64 +49,69 @@ public static ChannelPermissions All(IChannel channel) => _ => throw new ArgumentException("Unknown channel type.", nameof(channel)) }; - /// Gets a packed value representing all the permissions in this . + /// + /// 获取此权限集的原始值。 + /// public ulong RawValue { get; } - /// If true, a user may create invites. + /// public bool CreateInvites => Permissions.GetValue(RawValue, ChannelPermission.CreateInvites); - /// If true, a user may view and revoke invites. + /// public bool ManageChannels => Permissions.GetValue(RawValue, ChannelPermission.ManageChannels); - /// If true, a user may adjust roles. + /// public bool ManageRoles => Permissions.GetValue(RawValue, ChannelPermission.ManageRoles); - /// If true, a user may view channels. + /// public bool ViewChannel => Permissions.GetValue(RawValue, ChannelPermission.ViewChannel); - /// If true, a user may send messages. + /// public bool SendMessages => Permissions.GetValue(RawValue, ChannelPermission.SendMessages); - /// If true, a user may delete messages. + /// public bool ManageMessages => Permissions.GetValue(RawValue, ChannelPermission.ManageMessages); - /// If true, a user may send files. + /// public bool AttachFiles => Permissions.GetValue(RawValue, ChannelPermission.AttachFiles); - /// If true, a user may connect to a voice channel. + /// public bool Connect => Permissions.GetValue(RawValue, ChannelPermission.Connect); - /// If true, a user may kick other users from voice channels, and move other users between voice channels. + /// public bool ManageVoice => Permissions.GetValue(RawValue, ChannelPermission.ManageVoice); - /// If true, a user may mention all users. + /// public bool MentionEveryone => Permissions.GetValue(RawValue, ChannelPermission.MentionEveryone); - /// If true, a user may add reactions. + /// public bool AddReactions => Permissions.GetValue(RawValue, ChannelPermission.AddReactions); - /// If true, a user may connect to a voice channel only when the user is invited or moved by other users. + /// public bool PassiveConnect => Permissions.GetValue(RawValue, ChannelPermission.PassiveConnect); - /// If true, a user may use voice activation. + /// public bool UseVoiceActivity => Permissions.GetValue(RawValue, ChannelPermission.UseVoiceActivity); - /// If true, a user may speak in a voice channel. + /// public bool Speak => Permissions.GetValue(RawValue, ChannelPermission.Speak); - /// If true, a user may deafen users. + /// public bool DeafenMembers => Permissions.GetValue(RawValue, ChannelPermission.DeafenMembers); - /// If true, a user may mute users. + /// public bool MuteMembers => Permissions.GetValue(RawValue, ChannelPermission.MuteMembers); - /// If true, a user may play soundtracks in a voice channel. + /// public bool PlaySoundtrack => Permissions.GetValue(RawValue, ChannelPermission.PlaySoundtrack); - /// If true, a user may share screen in a voice channel. + /// public bool ShareScreen => Permissions.GetValue(RawValue, ChannelPermission.ShareScreen); - /// Creates a new with the provided packed value. + /// + /// 使用指定的权限原始值创建一个 结构的新实例。 + /// + /// 权限原始值。 public ChannelPermissions(ulong rawValue) { RawValue = rawValue; @@ -142,7 +161,27 @@ private ChannelPermissions(ulong initialValue, RawValue = value; } - /// Creates a new with the provided permissions. + /// + /// 使用指定的权限位信息创建一个 结构的新实例。 + /// + /// 创建邀请。 + /// 频道管理。 + /// 管理角色权限。 + /// 查看文字与语音频道。 + /// 发送文字消息。 + /// 消息管理。 + /// 上传文件。 + /// 语音连接。 + /// 语音管理。 + /// 提及全体成员、在线成员和所有角色。 + /// 添加回应。 + /// 被动连接语音频道。 + /// 使用自由麦。 + /// 发言。 + /// 服务器静音。 + /// 服务器闭麦。 + /// 共享计算机音频。 + /// 屏幕分享。 public ChannelPermissions( bool? createInvites = false, bool? manageChannels = false, @@ -168,7 +207,28 @@ public ChannelPermissions( { } - /// Creates a new from this one, changing the provided non-null permissions. + /// + /// 以当前权限集为基础,更改指定的权限,返回一个 结构的新实例。 + /// + /// 创建邀请。 + /// 频道管理。 + /// 管理角色权限。 + /// 查看文字与语音频道。 + /// 发送文字消息。 + /// 消息管理。 + /// 上传文件。 + /// 语音连接。 + /// 语音管理。 + /// 提及全体成员、在线成员和所有角色。 + /// 添加回应。 + /// 被动连接语音频道。 + /// 使用自由麦。 + /// 发言。 + /// 服务器静音。 + /// 服务器闭麦。 + /// 共享计算机音频。 + /// 屏幕分享。 + /// 更改了指定权限的新的权限集。 public ChannelPermissions Modify( bool? createInvites = null, bool? manageChannels = null, @@ -209,18 +269,16 @@ public ChannelPermissions Modify( shareScreen); /// - /// Returns a value that indicates if a specific is enabled - /// in these permissions. + /// 获取当前权限集是否包含指定的权限。 /// - /// The permission value to check for. - /// true if the permission is enabled, false otherwise. + /// 要检查的权限。 + /// 如果当前权限集包含了所有指定的权限信息,则为 true;否则为 false public bool Has(ChannelPermission permission) => Permissions.GetValue(RawValue, permission); /// - /// Returns a containing all of the - /// flags that are enabled. + /// 获取一个包含当前权限集所包含的所有已设置的 独立位标志枚举值的集合。 /// - /// A containing flags. Empty if none are enabled. + /// 一个包含当前权限集所包含的所有已设置的 独立位标志枚举值的集合;如果当前权限集未包含任何已设置的权限位,则会返回一个空集合。 public List ToList() { List perms = []; @@ -238,8 +296,9 @@ public List ToList() } /// - /// Gets the raw value of the permissions. + /// 获取此权限集原始值的字符串表示。 /// + /// 此权限集原始值的字符串表示。 public override string ToString() => RawValue.ToString(); private string DebuggerDisplay => $"{string.Join(", ", ToList())}"; diff --git a/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs b/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs index ab9c08c6..c9e2e80e 100644 --- a/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs +++ b/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs @@ -1,157 +1,240 @@ namespace Kook; /// -/// Represents a permission can be granted to a guild. +/// 表示可以为角色或用户设置的频道级别的服务器权限。 /// [Flags] public enum GuildPermission : uint { /// - /// Allows all permissions and bypasses channel permission overwrites. + /// 管理员。 /// + /// + /// 拥有此权限会获得完整的管理权,不受所有其他权限的限制。 + /// Administrator = 1 << 0, /// - /// Allows management and editing of guild. + /// 管理服务器。 /// + /// + /// 拥有此权限的成员可以修改服务器名称、头像和区域等设置项,以及未明确的概况设置项,并对服务器安全进行设置。 + /// ManageGuild = 1 << 1, /// - /// Allows for viewing of audit logs. + /// 查看管理日志。 /// + /// + /// 拥有此权限的成员可以查看服务器的管理日志。 + /// ViewAuditLog = 1 << 2, /// - /// Allows creation of invites. + /// 创建邀请。 /// + /// + /// 拥有此权限的成员可以创建邀请链接。 + /// CreateInvites = 1 << 3, /// - /// Allows for management of invites. + /// 管理邀请。 /// + /// + /// 拥有此权限的成员可以管理服务器邀请。 + /// ManageInvites = 1 << 4, /// - /// Allows management and editing of channels. + /// 频道管理。 /// + /// + /// 拥有此权限的成员可以创建新的频道以及编辑或删除已存在的频道。 + /// ManageChannels = 1 << 5, /// - /// Allows kicking members. + /// 踢出成员。 /// + /// + /// 拥有此权限的成员可以踢出其他成员。 + /// KickMembers = 1 << 6, /// - /// Allows banning members. + /// 加入服务器黑名单。 /// + /// + /// 拥有此权限的成员可以将其他成员加入服务器黑名单、查看服务器黑名单。 + /// BanMembers = 1 << 7, /// - /// Allows management and editing of emojis and stickers. + /// 管理自定义表情。 /// + /// + /// 拥有此权限的成员可以管理自定义表情。 + /// ManageEmojis = 1 << 8, /// - /// Allows for modification of own nickname. + /// 修改昵称。 /// + /// + /// 拥有此权限的用户可以更改自己的昵称。 + /// ChangeNickname = 1 << 9, /// - /// Allows management and editing of roles. + /// 管理角色权限。 /// + /// + /// 拥有此权限的成员可以创建新的角色,编辑或删除位次低于该角色的角色。 + /// ManageRoles = 1 << 10, /// - /// Allows guild members to view a channel, which includes reading messages in text channels. + /// 查看文字与语音频道。 /// + /// + /// 拥有此权限的成员可以查看文字、语音频道。 + /// ViewChannel = 1 << 11, /// - /// Allows for sending messages in a channel + /// 发送文字消息。 /// + /// + /// 拥有此权限的成员可以在文字频道中发送消息。 + /// SendMessages = 1 << 12, /// - /// Allows for deletion of other users messages. + /// 消息管理。 /// + /// + /// 拥有此权限的成员可以删除其他成员发出的消息和置顶消息。 + /// ManageMessages = 1 << 13, /// - /// Allows for uploading images and files. + /// 上传文件。 /// + /// + /// 拥有此权限的成员可以上传文件(包括图片)。 + /// AttachFiles = 1 << 14, /// - /// Allows for joining of a voice channel. + /// 语音连接。 /// + /// + /// 拥有此权限的成员可以连接到语音频道。 + /// Connect = 1 << 15, /// - /// Allows for disconnection of members, and moving of members between voice channels. + /// 语音管理。 /// /// - /// Such movements are allowed to channels that both the user to be moved and the operator have permissions to. + /// 拥有此权限的成员可修改频道发言模式,管理频道成员上麦,将频道成员转移至其他频道和踢出频道。 /// ManageVoice = 1 << 16, /// - /// Allows for using the everyone mention tag to notify all users in a channel, - /// and the online mention tag to notify all online users in a channel. + /// 提及全体成员、在线成员和所有角色。 /// + /// + /// 拥有此权限的成员可以使用@全体成员,@在线成员提及该频道中的所有成员,该权限可以绕开"允许任何人@提及此角色"的限制。 + /// MentionEveryone = 1 << 17, /// - /// Allows for the addition of reactions to messages. + /// 添加回应。 /// + /// + /// 拥有此权限的成员可以对消息添加新的回应。 + /// AddReactions = 1 << 18, /// - /// Allows for following of added reactions to messages. + /// 跟随添加回应。 /// + /// + /// 拥有此权限的成员可以跟随使用已经添加的回应。 + /// FollowReactions = 1 << 19, /// - /// Limits the user to connecting to a voice channel only when the user is invited or moved by others. + /// 被动连接语音频道。 /// + /// + /// 拥有此权限的成员在没有语音连接权限时,可以被动邀请或被人移动进入语音频道。 + /// PassiveConnect = 1 << 20, /// - /// Limits the user to speaking in a voice channel only when pressing the speaking key. + /// 仅使用按键说话。 /// + /// + /// 拥有此限制的成员加入语音频道后,只能使用按键说话。 + /// OnlyPushToTalk = 1 << 21, /// - /// Allows for speaking in voice a channel without having to press the speaking key. + /// 使用自由麦。 /// + /// + /// 没有此权限的成员,必须在频道内使用按键说话。 + /// UseVoiceActivity = 1 << 22, /// - /// Allows for speaking in a voice channel. + /// 发言。 /// + /// + /// 拥有此权限的成员可以在语音频道中发言。 + /// Speak = 1 << 23, /// - /// Allows for deafening of members in a voice channel. + /// 服务器静音。 /// + /// + /// 拥有此权限的成员可以限制其他成员在服务器中的语音接收。 + /// DeafenMembers = 1 << 24, /// - /// Allows for muting members in a voice channel. + /// 服务器闭麦。 /// + /// + /// 拥有此权限的成员可以限制其他成员在语音频道中发言和共享计算机音频。 + /// MuteMembers = 1 << 25, /// - /// Allows for modification of other users nicknames. + /// 修改他人昵称。 /// + /// + /// 拥有此权限的用户可以更改他人的昵称。 + /// ManageNicknames = 1 << 26, /// - /// Allows for playing soundtracks in a voice channel. + /// 共享计算机音频。 /// + /// + /// 拥有此权限的成员可在语音频道中共享计算机音频。 + /// PlaySoundtrack = 1 << 27, /// - /// Allows for screen share. + /// 屏幕分享。 /// + /// + /// 拥有此权限的成员可在语音频道中共享计算机画面。 + /// ShareScreen = 1 << 28 } diff --git a/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs b/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs index a61e51c2..b0aeabc1 100644 --- a/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs +++ b/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs @@ -3,119 +3,180 @@ namespace Kook; /// -/// Represents a set of permissions for a guild. +/// 表示一个服务器的权限集。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct GuildPermissions { - /// Gets a blank that grants no permissions. + /// + /// 获取一个空的 ,不包含任何权限。 + /// public static readonly GuildPermissions None = new(); - /// Gets a that grants all guild permissions. + /// + /// 获取一个包含所有可以为服务器设置的权限的 。 + /// public static readonly GuildPermissions All = new(0b1_1111_1111_1111_1111_1111_1111_1111); - /// Gets a packed value representing all the permissions in this . + /// + /// 获取此权限集的原始值。 + /// public ulong RawValue { get; } - /// If true, a user is granted all permissions, and cannot have them revoked via channel permissions. + /// + /// 获取此权限集的相关用户是否为服务器管理员。 + /// public bool Administrator => Permissions.GetValue(RawValue, GuildPermission.Administrator); - /// If true, a user may adjust guild properties. + /// + /// 获取此权限集是否允许相关用户管理服务器。 + /// public bool ManageGuild => Permissions.GetValue(RawValue, GuildPermission.ManageGuild); - /// If true, a user may view the audit log. + /// + /// 获取此权限集是否允许相关用户查看管理日志。 + /// public bool ViewAuditLog => Permissions.GetValue(RawValue, GuildPermission.ViewAuditLog); - /// If true, a user may create invites. + /// + /// 获取此权限集是否允许相关用户创建邀请。 + /// public bool CreateInvites => Permissions.GetValue(RawValue, GuildPermission.CreateInvites); - /// If true, a user may view and revoke invites. + /// + /// 获取此权限集是否允许相关用户管理邀请。 + /// public bool ManageInvites => Permissions.GetValue(RawValue, GuildPermission.ManageInvites); - /// If true, a user may create, delete and modify channels. + /// + /// 获取此权限集是否允许相关用户管理频道。 + /// public bool ManageChannels => Permissions.GetValue(RawValue, GuildPermission.ManageChannels); - /// If true, a user may kick users from the guild. + /// + /// 获取此权限集是否允许相关用户踢出其他用户。 + /// public bool KickMembers => Permissions.GetValue(RawValue, GuildPermission.KickMembers); - /// If true, a user may ban users from the guild. + /// + /// 获取此权限集是否允许相关用户封禁其他用户。 + /// public bool BanMembers => Permissions.GetValue(RawValue, GuildPermission.BanMembers); - /// If true, a user may edit the emojis for this guild. + /// + /// 获取此权限集是否允许相关用户管理自定义表情。 + /// public bool ManageEmojis => Permissions.GetValue(RawValue, GuildPermission.ManageEmojis); - /// If true, a user may change their own nickname. + /// + /// 获取此权限集是否允许相关用户修改昵称。 + /// public bool ChangeNickname => Permissions.GetValue(RawValue, GuildPermission.ChangeNickname); - /// If true, a user may adjust roles. + /// + /// 获取此权限集是否允许相关用户管理角色。 + /// public bool ManageRoles => Permissions.GetValue(RawValue, GuildPermission.ManageRoles); - /// If true, a user may view channels. + /// + /// 获取此权限集是否允许相关用户查看文字与语音频道。 + /// public bool ViewChannel => Permissions.GetValue(RawValue, GuildPermission.ViewChannel); - /// If true, a user may send messages. + /// + /// 获取此权限集是否允许相关用户发送文字消息。 + /// public bool SendMessages => Permissions.GetValue(RawValue, GuildPermission.SendMessages); - /// If true, a user may delete messages. + /// + /// 获取此权限集是否允许相关用户管理消息。 + /// public bool ManageMessages => Permissions.GetValue(RawValue, GuildPermission.ManageMessages); - /// If true, a user may send files. + /// + /// 获取此权限集是否允许相关用户上传文件。 + /// public bool AttachFiles => Permissions.GetValue(RawValue, GuildPermission.AttachFiles); - /// If true, a user may connect to a voice channel. + /// + /// 获取此权限集是否允许相关用户连接语音。 + /// public bool Connect => Permissions.GetValue(RawValue, GuildPermission.Connect); - /// If true, a user may kick other users from voice channels, and move other users between voice channels. + /// + /// 获取此权限集是否允许相关用户管理语音频道。 + /// public bool ManageVoice => Permissions.GetValue(RawValue, GuildPermission.ManageVoice); - /// If true, a user may mention all users. + /// + /// 获取此权限集是否允许相关用户提及全体成员、在线成员和所有角色。 + /// public bool MentionEveryone => Permissions.GetValue(RawValue, GuildPermission.MentionEveryone); - /// If true, a user may add reactions. + /// + /// 获取此权限集是否允许相关用户添加回应。 + /// public bool AddReactions => Permissions.GetValue(RawValue, GuildPermission.AddReactions); - /// If true, a user may follow added reactions. + /// + /// 获取此权限集是否允许相关用户跟随添加回应。 + /// public bool FollowReactions => Permissions.GetValue(RawValue, GuildPermission.FollowReactions); - /// If true, a user may connect to a voice channel only when the user is invited or moved by other users. + /// + /// 获取此权限集是否允许相关用户被动连接到语音频道。 + /// public bool PassiveConnect => Permissions.GetValue(RawValue, GuildPermission.PassiveConnect); - /// If true, a user may speak only via push-to-talk. + /// + /// 获取此权限集是否要求相关用户仅可使用按键说话。 + /// public bool OnlyPushToTalk => Permissions.GetValue(RawValue, GuildPermission.OnlyPushToTalk); - /// If true, a user may use voice activation. + /// + /// 获取此权限集是否允许相关用户使用自由麦。 + /// public bool UseVoiceActivity => Permissions.GetValue(RawValue, GuildPermission.UseVoiceActivity); - /// If true, a user may speak in a voice channel. + /// + /// 获取此权限集是否允许相关用户在语音频道中发言。 + /// public bool Speak => Permissions.GetValue(RawValue, GuildPermission.Speak); - /// If true, a user may deafen users. + /// + /// 获取此权限集是否允许相关用户使其他用户被服务器静音。 + /// public bool DeafenMembers => Permissions.GetValue(RawValue, GuildPermission.DeafenMembers); - /// If true, a user may mute users. + /// + /// 获取此权限集是否允许相关用户使其他用户被服务器闭麦。 + /// public bool MuteMembers => Permissions.GetValue(RawValue, GuildPermission.MuteMembers); - /// If true, a user may change the nickname of other users. + /// + /// 获取此权限集是否允许相关用户修改他人昵称。 + /// public bool ManageNicknames => Permissions.GetValue(RawValue, GuildPermission.ManageNicknames); - /// If true, a user may play soundtracks in a voice channel. + /// + /// 获取此权限集是否允许相关用户共享计算机音频。 + /// public bool PlaySoundtrack => Permissions.GetValue(RawValue, GuildPermission.PlaySoundtrack); - /// If true, a user may share screen in a voice channel. + /// + /// 获取此权限集是否允许相关用户共享计算机画面。 + /// public bool ShareScreen => Permissions.GetValue(RawValue, GuildPermission.ShareScreen); - /// Creates a new with the provided packed value. + /// + /// 使用指定的权限原始值创建一个 结构的新实例。 + /// + /// 权限原始值。 public GuildPermissions(ulong rawValue) { RawValue = rawValue; } - /// Creates a new with the provided packed value after converting to ulong. - public GuildPermissions(string rawValue) - { - RawValue = ulong.Parse(rawValue); - } - private GuildPermissions(ulong initialValue, bool? administrator = null, bool? manageGuild = null, @@ -183,7 +244,38 @@ private GuildPermissions(ulong initialValue, RawValue = value; } - /// Creates a new structure with the provided permissions. + /// + /// 使用指定的权限位信息创建一个 结构的新实例。 + /// + /// 管理员。 + /// 管理服务器。 + /// 查看管理日志。 + /// 创建邀请。 + /// 管理邀请。 + /// 频道管理。 + /// 踢出成员。 + /// 加入服务器黑名单。 + /// 管理自定义表情。 + /// 修改昵称。 + /// 管理角色权限。 + /// 查看文字与语音频道。 + /// 发送文字消息。 + /// 消息管理。 + /// 上传文件。 + /// 语音连接。 + /// 语音管理。 + /// 提及全体成员、在线成员和所有角色。 + /// 添加回应。 + /// 跟随添加回应。 + /// 被动连接语音频道。 + /// 仅使用按键说话。 + /// 使用自由麦。 + /// 发言。 + /// 服务器静音。 + /// 服务器闭麦。 + /// 修改他人昵称。 + /// 共享计算机音频。 + /// 屏幕分享。 public GuildPermissions( bool administrator = false, bool manageGuild = false, @@ -221,7 +313,39 @@ public GuildPermissions( { } - /// Creates a new from this one, changing the provided non-null permissions. + /// + /// 以当前权限集为基础,更改指定的权限,返回一个 结构的新实例。 + /// + /// 管理员。 + /// 管理服务器。 + /// 查看管理日志。 + /// 创建邀请。 + /// 管理邀请。 + /// 频道管理。 + /// 踢出成员。 + /// 加入服务器黑名单。 + /// 管理自定义表情。 + /// 修改昵称。 + /// 管理角色权限。 + /// 查看文字与语音频道。 + /// 发送文字消息。 + /// 消息管理。 + /// 上传文件。 + /// 语音连接。 + /// 语音管理。 + /// 提及全体成员、在线成员和所有角色。 + /// 添加回应。 + /// 跟随添加回应。 + /// 被动连接语音频道。 + /// 仅使用按键说话。 + /// 使用自由麦。 + /// 发言。 + /// 服务器静音。 + /// 服务器闭麦。 + /// 修改他人昵称。 + /// 共享计算机音频。 + /// 屏幕分享。 + /// 更改了指定权限的新的权限集。 public GuildPermissions Modify( bool? administrator = null, bool? manageGuild = null, @@ -259,18 +383,16 @@ public GuildPermissions Modify( manageNicknames, playSoundtrack, shareScreen); /// - /// Returns a value that indicates if a specific is enabled - /// in these permissions. + /// 获取当前权限集是否包含指定的权限。 /// - /// The permission value to check for. - /// true if the permission is enabled, false otherwise. + /// 要检查的权限。 + /// 如果当前权限集包含了所有指定的权限信息,则为 true;否则为 false public bool Has(GuildPermission permission) => Permissions.GetValue(RawValue, permission); /// - /// Returns a containing all of the - /// flags that are enabled. + /// 获取一个包含当前权限集所包含的所有已设置的 独立位标志枚举值的集合。 /// - /// A containing flags. Empty if none are enabled. + /// 一个包含当前权限集所包含的所有已设置的 独立位标志枚举值的集合;如果当前权限集未包含任何已设置的权限位,则会返回一个空集合。 public List ToList() { List perms = []; @@ -305,8 +427,9 @@ internal void Ensure(GuildPermission permissions) } /// - /// Gets the raw value of the permissions. + /// 获取此权限集原始值的字符串表示。 /// + /// 此权限集原始值的字符串表示。 public override string ToString() => RawValue.ToString(); private string DebuggerDisplay => $"{string.Join(", ", ToList())}"; diff --git a/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs b/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs index 8357ff5a..759d4d0c 100644 --- a/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs +++ b/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs @@ -1,20 +1,18 @@ namespace Kook; /// -/// Represents a generic permission overwrite. +/// 表示一个通用的频道权限重写设置。 /// -/// -/// The type of the target. -/// +/// 权限重写设置所应用的目标的实体类型。 public interface IPermissionOverwrite { /// - /// Gets the target of this overwrite. + /// 获取此重写所应用的目标。 /// TTarget Target { get; } /// - /// Gets the overwritten permission. + /// 获取此重写的权限重写配置。 /// OverwritePermissions Permissions { get; } } diff --git a/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs b/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs index 1468d4e3..2d24c75f 100644 --- a/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs +++ b/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs @@ -3,108 +3,141 @@ namespace Kook; /// -/// Represents a container for a series of overwrite permissions. +/// 表示一组权限重写配置。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct OverwritePermissions { /// - /// Gets a blank that inherits all permissions. + /// 获取一个空的 ,继承所有权限。 /// public static OverwritePermissions InheritAll { get; } = new(); /// - /// Gets a that grants all permissions for the given channel. + /// 获取一个在权限重写配置中为指定频道重写允许所有权限的 。 /// - /// Unknown channel type. + /// 未知的频道类型。 public static OverwritePermissions AllowAll(IChannel channel) => new(ChannelPermissions.All(channel).RawValue, 0); /// - /// Gets a that denies all permissions for the given channel. + /// 获取一个在权限重写配置中为指定频道重写禁止所有权限的 。 /// - /// Unknown channel type. + /// 未知的频道类型。 public static OverwritePermissions DenyAll(IChannel channel) => new(0, ChannelPermissions.All(channel).RawValue); /// - /// Gets a packed value representing all the allowed permissions in this . + /// 获取一个表示此重写中所有允许的权限的原始值。 /// public ulong AllowValue { get; } /// - /// Gets a packed value representing all the denied permissions in this . + /// 获取一个表示此重写中所有禁止的权限的原始值。 /// public ulong DenyValue { get; } - /// If Allowed, a user may create invites. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue CreateInvites => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.CreateInvites); - /// If Allowed, a user may create, delete and modify channels. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue ManageChannels => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageChannels); - /// If Allowed, a user may adjust roles. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue ManageRoles => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageRoles); - /// If Allowed, a user may view channels. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue ViewChannel => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ViewChannel); - /// If Allowed, a user may send messages. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue SendMessages => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.SendMessages); - /// If Allowed, a user may delete messages. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue ManageMessages => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageMessages); - /// If Allowed, a user may send files. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue AttachFiles => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.AttachFiles); - /// If Allowed, a user may connect to a voice channel. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue Connect => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.Connect); - /// If Allowed, a user may kick other users from voice channels, and move other users between voice channels. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue ManageVoice => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ManageVoice); - /// If Allowed, a user may mention all users. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue MentionEveryone => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.MentionEveryone); - /// If Allowed, a user may add reactions. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue AddReactions => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.AddReactions); - /// If Allowed, a user may connect to a voice channel only when the user is invited or moved by other users. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue PassiveConnect => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.PassiveConnect); - /// If Allowed, a user may use voice activation. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue UseVoiceActivity => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.UseVoiceActivity); - /// If Allowed, a user may speak in a voice channel. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue Speak => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.Speak); - /// If Allowed, a user may deafen users. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue DeafenMembers => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.DeafenMembers); - /// If Allowed, a user may mute users. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue MuteMembers => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.MuteMembers); - /// If Allowed, a user may play soundtracks in a voice channel. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue PlaySoundtrack => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.PlaySoundtrack); - /// If Allowed, a user may share screen in a voice channel. + /// + /// 获取此权限重写配置对频道权限位 的重写配置。 + /// public PermValue ShareScreen => Permissions.GetValue(AllowValue, DenyValue, ChannelPermission.ShareScreen); - /// Creates a new OverwritePermissions with the provided allow and deny packed values. + /// + /// 使用指定的原始值初始化一个 结构的新实例。 + /// + /// 重写允许的权限的原始值。 + /// 重写禁止的权限的原始值。 public OverwritePermissions(ulong allowValue, ulong denyValue) { AllowValue = allowValue; DenyValue = denyValue; } - /// Creates a new OverwritePermissions with the provided allow and deny packed values after converting to ulong. - public OverwritePermissions(string allowValue, string denyValue) - { - AllowValue = uint.Parse(allowValue); - DenyValue = uint.Parse(denyValue); - } - private OverwritePermissions(ulong allowValue, ulong denyValue, PermValue? createInvites = null, PermValue? manageChannels = null, @@ -149,8 +182,26 @@ private OverwritePermissions(ulong allowValue, ulong denyValue, } /// - /// Initializes a new struct with the provided permissions. + /// 使用指定的权限重写信息创建一个 结构的新实例。 /// + /// 创建邀请。 + /// 频道管理。 + /// 管理角色权限。 + /// 查看文字与语音频道。 + /// 发送文字消息。 + /// 消息管理。 + /// 上传文件。 + /// 语音连接。 + /// 语音管理。 + /// 提及全体成员、在线成员和所有角色。 + /// 添加回应。 + /// 被动连接语音频道。 + /// 使用自由麦。 + /// 发言。 + /// 服务器静音。 + /// 服务器闭麦。 + /// 共享计算机音频。 + /// 屏幕分享。 public OverwritePermissions( PermValue createInvites = PermValue.Inherit, PermValue manageChannels = PermValue.Inherit, @@ -177,9 +228,27 @@ public OverwritePermissions( } /// - /// Initializes a new from the current one, changing the provided - /// non-null permissions. + /// 以当前权限重写配置为基础,更改指定的重写,返回一个 结构的新实例。 /// + /// 创建邀请。 + /// 频道管理。 + /// 管理角色权限。 + /// 查看文字与语音频道。 + /// 发送文字消息。 + /// 消息管理。 + /// 上传文件。 + /// 语音连接。 + /// 语音管理。 + /// 提及全体成员、在线成员和所有角色。 + /// 添加回应。 + /// 被动连接语音频道。 + /// 使用自由麦。 + /// 发言。 + /// 服务器静音。 + /// 服务器闭麦。 + /// 共享计算机音频。 + /// 屏幕分享。 + /// 更改了指定权限的新的权限集。 public OverwritePermissions Modify( PermValue? createInvites = null, PermValue? manageChannels = null, @@ -204,9 +273,9 @@ public OverwritePermissions Modify( passiveConnect, useVoiceActivity, speak, deafenMembers, muteMembers, playSoundtrack, shareScreen); /// - /// Creates a of all the values that are allowed. + /// 获取一个包含当前权限重写配置所包含的所有重写允许的 独立位标志枚举值的集合。 /// - /// A of all allowed flags. If none, the list will be empty. + /// 一个包含当前权限重写配置所包含的所有重写允许的 独立位标志枚举值的集合;如果当前权限重写配置未包含任何重写允许的权限位,则会返回一个空集合。 public List ToAllowList() { List perms = []; @@ -222,9 +291,9 @@ public List ToAllowList() } /// - /// Creates a of all the values that are denied. + /// 获取一个包含当前权限重写配置所包含的所有重写禁止的 独立位标志枚举值的集合。 /// - /// A of all denied flags. If none, the list will be empty. + /// 一个包含当前权限重写配置所包含的所有重写禁止的 独立位标志枚举值的集合;如果当前权限重写配置未包含任何重写禁止的权限位,则会返回一个空集合。 public List ToDenyList() { List perms = new(); @@ -238,7 +307,10 @@ public List ToDenyList() return perms; } - /// + /// + /// 获取此权限重写配置所重写允许与重写禁止的权限的原始值的字符串表示。 + /// + /// 此权限重写配置所重写允许与重写禁止的权限的原始值的字符串表示。 public override string ToString() => $"Allow {AllowValue}, Deny {DenyValue}"; private string DebuggerDisplay => diff --git a/src/Kook.Net.Core/Entities/Permissions/PermValue.cs b/src/Kook.Net.Core/Entities/Permissions/PermValue.cs index c8ec0f1f..c959d5ee 100644 --- a/src/Kook.Net.Core/Entities/Permissions/PermValue.cs +++ b/src/Kook.Net.Core/Entities/Permissions/PermValue.cs @@ -1,14 +1,22 @@ namespace Kook; -/// Specifies the permission value. +/// +/// 表示一个权限的重写配置的值。 +/// public enum PermValue { - /// Allows this permission. + /// + /// 允许此权限。 + /// Allow, - /// Denies this permission. + /// + /// 禁止此权限。 + /// Deny, - /// Inherits the permission settings. + /// + /// 继承此权限。 + /// Inherit } diff --git a/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs b/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs index d1caa11e..9af43462 100644 --- a/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs +++ b/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs @@ -1,23 +1,23 @@ namespace Kook; /// -/// Represent a permission object for a role. +/// 表示一个为角色设置的频道权限重写设置。 /// public class RolePermissionOverwrite : IPermissionOverwrite { /// - /// Gets the identifier for the role this overwrite is targeting. + /// 获取此重写所应用的角色的 ID。 /// public uint Target { get; } - /// - /// Gets the permissions associated with this overwrite entry for a role. - /// + /// public OverwritePermissions Permissions { get; } /// - /// Initializes a new with provided ID of the role and modified permissions. + /// 初始化一个 类的新实例。 /// + /// 角色的 ID。 + /// 角色的权限重写配置。 public RolePermissionOverwrite(uint targetId, OverwritePermissions permissions) { Target = targetId; diff --git a/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs b/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs index 34737966..550ecee5 100644 --- a/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs +++ b/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs @@ -1,23 +1,23 @@ namespace Kook; /// -/// Represent a permission object for a user. +/// 表示一个为用户设置的频道权限重写设置。 /// public class UserPermissionOverwrite : IPermissionOverwrite { /// - /// Gets the user this overwrite is targeting. + /// 获取此重写所应用的用户。 /// public IUser Target { get; } - /// - /// Gets the permissions associated with this overwrite entry for a user. - /// + /// public OverwritePermissions Permissions { get; } /// - /// Initializes a new with provided user information and modified permissions. + /// 初始化一个 类的新实例。 /// + /// 用户。 + /// 用户的权限重写配置。 public UserPermissionOverwrite(IUser target, OverwritePermissions permissions) { Target = target; diff --git a/src/Kook.Net.Core/Entities/Roles/AlphaColor.cs b/src/Kook.Net.Core/Entities/Roles/AlphaColor.cs index 4db51c31..9b47107d 100644 --- a/src/Kook.Net.Core/Entities/Roles/AlphaColor.cs +++ b/src/Kook.Net.Core/Entities/Roles/AlphaColor.cs @@ -5,111 +5,126 @@ namespace Kook; /// -/// Represents a with an alpha channel. +/// 表示 KOOK 中使用的带有不透明度通道的颜色。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public readonly struct AlphaColor { - /// Gets the max decimal value of an color with an alpha channel. - public const ulong MaxDecimalValue = 0xFFFFFFFF; + /// + /// 获取一个 KOOK 中带有不透明度通道的颜色的最大值的原始值。 + /// + public const uint MaxDecimalValue = 0xFFFFFFFF; - /// Gets the default user color value. + /// + /// 获取默认颜色。 + /// public static readonly AlphaColor Default = new(Color.Default, 0xFF); /// - /// Gets the raw value for this color. + /// 获取此颜色的原始值。 /// - public ulong RawValue { get; } + /// + /// 颜色以 32 位无符号整型值 RGBA 格式进行编码,由高至低的每 8 位分别表示红色、绿色、蓝色和不透明度通道的强度。 + /// + public uint RawValue { get; } - /// Gets the red component for this color. + /// + /// 获取此颜色的红色通道的强度。 + /// public byte R => (byte)(RawValue >> 24); - /// Gets the green component for this color. + /// + /// 获取此颜色的绿色通道的强度。 + /// public byte G => (byte)(RawValue >> 16); - /// Gets the blue component for this color. + /// + /// 获取此颜色的蓝色通道的强度。 + /// public byte B => (byte)(RawValue >> 8); - /// Gets the alpha component for this color. + /// + /// 获取此颜色的不透明度通道的强度。 + /// public byte A => (byte)RawValue; /// - /// Gets the base color for this color without the alpha channel. + /// 获取此颜色不带有不透明度通道的基础颜色。 /// - public Color BaseColor => new((uint)RawValue >> 8); + public Color BaseColor => new(RawValue >> 8); /// - /// Initializes a new instance of the struct with the specified raw value. + /// 使用指定的 32 位无符号整型值初始化一个 结构的新实例。 /// - /// The raw value to use. - public AlphaColor(ulong rawValue) + /// + /// 创建 #607D8BFF(http://www.color-hex.com/color/607d8b)所表示的颜色,且其完全不透明: + /// + /// AlphaColor darkGrey = new AlphaColor(0x607D8BFF); + /// + /// + /// 颜色的 32 位无符号整型原始值。 + public AlphaColor(uint rawValue) { - if (rawValue > MaxDecimalValue) - throw new ArgumentException($"{nameof(RawValue)} of color cannot be greater than {MaxDecimalValue}!", nameof(rawValue)); - RawValue = rawValue; } /// - /// Initializes a struct with the given base color and alpha channel. + /// 使用指定的 及不透明度初始化一个 结构的新实例。 /// - /// The base color to use. - /// The byte that represents the alpha channel. - /// Value exceeds . + /// + /// 创建 #607D8BFF(http://www.color-hex.com/color/607d8b)所表示的颜色,且其完全不透明: + /// + /// AlphaColor darkGrey = new AlphaColor(new Color(0x607D8B), (byte)0xFF); + /// + /// + /// 基础颜色。 + /// 不透明度。 public AlphaColor(Color baseColor, byte alpha) { - ulong value = ((ulong)baseColor.R << 24) - | ((ulong)baseColor.G << 16) - | ((ulong)baseColor.B << 8) - | (ulong)alpha; - - if (value > MaxDecimalValue) - throw new ArgumentException($"{nameof(RawValue)} of color cannot be greater than {MaxDecimalValue}!"); + uint value = ((uint)baseColor.R << 24) + | ((uint)baseColor.G << 16) + | ((uint)baseColor.B << 8) + | (uint)alpha; RawValue = value; } /// - /// Initializes a struct with the given RGBA bytes. + /// 使用指定的 RGBA 通道值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a value of #607D8BFF. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色,且其完全不透明: /// - /// AlphaColor darkGrey = new AlphaColor((byte)0b_01100000, (byte)0b_01111101, (byte)0b_10001011, (byte)0b_11111111); + /// AlphaColor darkGrey = new AlphaColor((byte)0x60, (byte)0x7D, (byte)0x8B, (byte)0xFF); /// /// - /// The byte that represents the red color. - /// The byte that represents the green color. - /// The byte that represents the blue color. - /// The byte that represents the alpha channel. - /// Value exceeds . + /// 红色通道的强度。 + /// 绿色通道的强度。 + /// 蓝色通道的强度。 + /// 不透明度通道的强度。 public AlphaColor(byte r, byte g, byte b, byte a) { - ulong value = ((ulong)r << 24) - | ((ulong)g << 16) - | ((ulong)b << 8) - | (ulong)a; - - if (value > MaxDecimalValue) - throw new ArgumentException($"{nameof(RawValue)} of color cannot be greater than {MaxDecimalValue}!"); + uint value = ((uint)r << 24) + | ((uint)g << 16) + | ((uint)b << 8) + | (uint)a; RawValue = value; } /// - /// Initializes a struct with the given RGBA value. + /// 使用指定的 RGBA 通道值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a value of #607D8BFF. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色,且其完全不透明: /// - /// AlphaColor darkGrey = new AlphaColor(96, 125, 139, 255); + /// AlphaColor darkGrey = new AlphaColor(96, 125, 139, 255); /// /// - /// The value that represents the red color. Must be within 0~255. - /// The value that represents the green color. Must be within 0~255. - /// The value that represents the blue color. Must be within 0~255. - /// The value that represents the alpha channel. Must be within 0~255. - /// The argument value is not between 0 to 255. + /// 红色通道的强度。 + /// 绿色通道的强度。 + /// 蓝色通道的强度。 + /// 不透明度通道的强度。 public AlphaColor(int r, int g, int b, int a) { if (r is < 0 or > 255) @@ -124,27 +139,25 @@ public AlphaColor(int r, int g, int b, int a) if (a is < 0 or > 255) throw new ArgumentOutOfRangeException(nameof(a), "Value must be within [0,255]."); - RawValue = ((ulong)(uint)r << 24) - | ((ulong)(uint)g << 16) - | ((ulong)(uint)b << 8) - | (ulong)(uint)a; + RawValue = ((uint)r << 24) + | ((uint)g << 16) + | ((uint)b << 8) + | (uint)a; } - /// - /// Initializes a struct with the given RGBA float value. + /// 使用指定的 RGBA 通道值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a value of #607C8CFF. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色,且其完全不透明: /// - /// AlphaColor darkGrey = new AlphaColor(0.38f, 0.49f, 0.55f, 1.00f); + /// AlphaColor darkGrey = new AlphaColor(0.38f, 0.49f, 0.55f, 1.00f); /// /// - /// The value that represents the red color. Must be within 0~1. - /// The value that represents the green color. Must be within 0~1. - /// The value that represents the blue color. Must be within 0~1. - /// The value that represents the alpha channel. Must be within 0~1. - /// The argument value is not between 0 to 1. + /// 红色通道的强度。 + /// 绿色通道的强度。 + /// 蓝色通道的强度。 + /// 不透明度通道的强度。 public AlphaColor(float r, float g, float b, float a) { if (r is < 0.0f or > 1.0f) @@ -166,34 +179,31 @@ public AlphaColor(float r, float g, float b, float a) } /// - /// Determines whether the specified is equal to this instance. + /// 判定两个 是否相等。 /// - /// true if the specified is equal to this instance; otherwise, false . - public static bool operator ==(AlphaColor lhs, AlphaColor rhs) => - lhs.RawValue == rhs.RawValue; + /// 如果两个 相等,则为 true;否则为 false + public static bool operator ==(AlphaColor lhs, AlphaColor rhs) => lhs.RawValue == rhs.RawValue; /// - /// Determines whether the specified is not equal to this instance. + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to this instance; otherwise, false . - public static bool operator !=(AlphaColor lhs, AlphaColor rhs) => - lhs.RawValue != rhs.RawValue; + /// 如果两个 不相等,则为 true;否则为 false + public static bool operator !=(AlphaColor lhs, AlphaColor rhs) => lhs.RawValue != rhs.RawValue; /// - /// Converts the given raw value of to a . + /// 使用指定的 32 位无符号整型值初始化一个 结构的新实例。 /// - /// The raw value of the color. - /// The that represents the given raw value. - public static implicit operator AlphaColor(ulong rawValue) => - new(rawValue); + /// + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色,且其完全不透明: + /// + /// AlphaColor darkGrey = 0x607D8BFF; + /// + /// + /// 颜色的 32 位无符号整型原始值。 + public static implicit operator AlphaColor(uint rawValue) => new(rawValue); - /// - /// Converts the given to its raw value of . - /// - /// The to convert. - /// The raw value of the given . - public static implicit operator ulong(AlphaColor color) => - color.RawValue; + /// + public static implicit operator uint(AlphaColor color) => color.RawValue; /// public override bool Equals([NotNullWhen(true)] object? obj) => @@ -203,47 +213,41 @@ public override bool Equals([NotNullWhen(true)] object? obj) => public override int GetHashCode() => RawValue.GetHashCode(); /// - /// Converts the given Kook.Net-defined to a Kook.Net-defined . + /// 将由 Kook.Net 定义的 颜色转换为 Kook.Net 定义的 颜色。 /// - /// The Kook.Net-defined to convert. - /// The Kook.Net-defined that represents the given Kook.Net-defined . + /// 要进行转换的 Kook.Net 定义的 颜色。 + /// 与该 Kook.Net 定义的 颜色具有相同色值的 颜色。 public static implicit operator AlphaColor(Color color) => - new(((ulong)color.RawValue << 8) | 0xFF); + new((color.RawValue << 8) | 0xFF); - /// - /// Converts the given Kook.Net-defined to a Kook.Net-defined . - /// - /// The Kook.Net-defined to convert. - /// The Kook.Net-defined that represents the given Kook.Net-defined . + /// /// /// - /// This conversion will drop the alpha channel of the given . + /// 此转换会丢失不透明度通道的信息。 /// /// public static explicit operator Color(AlphaColor color) => color.BaseColor; /// - /// Converts the given Kook.Net-defined to a .NET standard . + /// 将由 Kook.Net 定义的 颜色转换为由 .NET 定义的 颜色。 /// - /// The Kook.Net-defined to convert. - /// The .NET standard that represents the given Kook.Net-defined . + /// 要进行转换的 颜色。 + /// 与该 颜色具有相同色值的 .NET 颜色。 public static implicit operator StandardColor(AlphaColor color) => StandardColor.FromArgb(color.A, color.R, color.G, color.B); /// - /// Converts the given .NET standard to a Kook.Net-defined . + /// 将由 .NET 定义的 颜色转换为由 Kook.Net 定义的 颜色。 /// - /// The .NET standard to convert. - /// The Kook.Net-defined that represents the given .NET standard . + /// 要进行转换的 .NET 颜色。 + /// 与该 .NET 颜色具有相同色值的 颜色。 public static explicit operator AlphaColor(StandardColor color) => new(color.R, color.G, color.B, color.A); /// - /// Gets the hexadecimal representation of the color (e.g. #000cccff). + /// 获取此颜色带有 # 前缀的 RGBA 十六进制字符串表示形式(例如 #000CCCFF)。 /// - /// - /// A hexadecimal string of the color. - /// + /// 此颜色带有 # 前缀的 RGBA 十六进制字符串表示形式(例如 #000CCCFF)。 public override string ToString() => $"#{RawValue:X8}"; private string DebuggerDisplay => $"#{RawValue:X8} ({RawValue})"; diff --git a/src/Kook.Net.Core/Entities/Roles/Color.cs b/src/Kook.Net.Core/Entities/Roles/Color.cs index 1ee5de01..8168aa55 100644 --- a/src/Kook.Net.Core/Entities/Roles/Color.cs +++ b/src/Kook.Net.Core/Entities/Roles/Color.cs @@ -5,147 +5,237 @@ namespace Kook; /// -/// Represents a color used in Kook. +/// 表示 KOOK 中使用的颜色。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public readonly struct Color { - /// Gets the max decimal value of color. + /// + /// 获取一个 KOOK 颜色的最大值的原始值。 + /// public const uint MaxDecimalValue = 0xFFFFFF; - /// Gets the default user color value. + /// + /// 获取默认颜色。 + /// public static readonly Color Default = new(0); - /// Gets the teal color value. - /// A color struct with the hex value of 1ABC9C. See http://www.color-hex.com/color/1ABC9C + /// + /// 获取青绿色。 + /// + /// + /// 青绿色 #1ABC9C(http://www.color-hex.com/color/1abc9c)。 + /// public static readonly Color Teal = new(0x1ABC9C); - /// Gets the dark teal color value. - /// A color struct with the hex value of 11806A. See http://www.color-hex.com/color/11806A + /// + /// 获取深青绿色。 + /// + /// + /// 深青绿色 #11806A(http://www.color-hex.com/color/11806a)。 + /// public static readonly Color DarkTeal = new(0x11806A); - /// Gets the green color value. - /// A color struct with the hex value of 2ECC71. See http://www.color-hex.com/color/2ECC71 + /// + /// 获取绿色。 + /// + /// + /// 绿色 #2ECC71(http://www.color-hex.com/color/2ecc71)。 + /// public static readonly Color Green = new(0x2ECC71); - /// Gets the dark green color value. - /// A color struct with the hex value of 1F8B4C. See http://www.color-hex.com/color/1F8B4C + /// + /// 获取深绿色。 + /// + /// + /// 深绿色 #1F8B4C(http://www.color-hex.com/color/1f8b4c)。 + /// public static readonly Color DarkGreen = new(0x1F8B4C); - /// Gets the blue color value. - /// A color struct with the hex value of 3498DB. See http://www.color-hex.com/color/3498DB + /// + /// 获取天蓝色。 + /// + /// + /// 天蓝色 #3498DB(http://www.color-hex.com/color/3498db)。 + /// public static readonly Color Blue = new(0x3498DB); - /// Gets the dark blue color value. - /// A color struct with the hex value of 206694. See http://www.color-hex.com/color/206694 + /// + /// 获取深蓝色。 + /// + /// + /// 深蓝色 #206694(http://www.color-hex.com/color/206694)。 + /// public static readonly Color DarkBlue = new(0x206694); - /// Gets the purple color value. - /// A color struct with the hex value of 9B59B6. See http://www.color-hex.com/color/9B59B6 + /// + /// 获取紫色。 + /// + /// + /// 紫色 #9B59B6(http://www.color-hex.com/color/9b59b6)。 + /// public static readonly Color Purple = new(0x9B59B6); - /// Gets the dark purple color value. - /// A color struct with the hex value of 71368A. See http://www.color-hex.com/color/71368A + /// + /// 获取深紫色。 + /// + /// + /// 深紫色 #71368A(http://www.color-hex.com/color/71368a)。 + /// public static readonly Color DarkPurple = new(0x71368A); - /// Gets the magenta color value. - /// A color struct with the hex value of E91E63. See http://www.color-hex.com/color/E91E63 + /// + /// 获取玫瑰红。 + /// + /// + /// 玫瑰红 #E91E63(http://www.color-hex.com/color/e91e63)。 + /// public static readonly Color Magenta = new(0xE91E63); - /// Gets the dark magenta color value. - /// A color struct with the hex value of AD1457. See http://www.color-hex.com/color/AD1457 + /// + /// 获取深粉色。 + /// + /// + /// 深粉色 #AD1457(http://www.color-hex.com/color/ad1457)。 + /// public static readonly Color DarkMagenta = new(0xAD1457); - /// Gets the gold color value. - /// A color struct with the hex value of F1C40F. See http://www.color-hex.com/color/F1C40F + /// + /// 获取金黄色。 + /// + /// + /// 金黄色 #F1C40F(http://www.color-hex.com/color/f1c40f)。 + /// public static readonly Color Gold = new(0xF1C40F); - /// Gets the light orange color value. - /// A color struct with the hex value of C27C0E. See http://www.color-hex.com/color/C27C0E + /// + /// 获取褐橙色。 + /// + /// + /// 褐橙色 #C27C0E(http://www.color-hex.com/color/c27c0e)。 + /// public static readonly Color LightOrange = new(0xC27C0E); - /// Gets the orange color value. - /// A color struct with the hex value of E67E22. See http://www.color-hex.com/color/E67E22 + /// + /// 获取橙色。 + /// + /// + /// 橙色 #E67E22(http://www.color-hex.com/color/e67e22)。 + /// public static readonly Color Orange = new(0xE67E22); - /// Gets the dark orange color value. - /// A color struct with the hex value of A84300. See http://www.color-hex.com/color/A84300 + /// + /// 获取深橙色。 + /// + /// + /// 深橙色 #A84300(http://www.color-hex.com/color/a84300)。 + /// public static readonly Color DarkOrange = new(0xA84300); - /// Gets the red color value. - /// A color struct with the hex value of E74C3C. See http://www.color-hex.com/color/E74C3C + /// + /// 获取猩红色。 + /// + /// + /// 猩红色 #E74C3C(http://www.color-hex.com/color/e74c3c)。 + /// public static readonly Color Red = new(0xE74C3C); - /// Gets the dark red color value. - /// A color struct with the hex value of 992D22. See http://www.color-hex.com/color/992D22 + /// + /// 获取深红色。 + /// + /// + /// 深红色 #992D22(http://www.color-hex.com/color/992d22)。 + /// public static readonly Color DarkRed = new(0x992D22); - /// Gets the light grey color value. - /// A color struct with the hex value of 95A5A6. See http://www.color-hex.com/color/95A5A6 + /// + /// 获取浅灰色。 + /// + /// + /// 浅灰色 #95A5A6(http://www.color-hex.com/color/95a5a6)。 + /// public static readonly Color LightGrey = new(0x95A5A6); - /// Gets the grey color value. - /// A color struct with the hex value of 666D71. See http://www.color-hex.com/color/666D71 + /// + /// 获取暗灰色。 + /// + /// + /// 暗灰色 #666D71(http://www.color-hex.com/color/666d71)。 + /// public static readonly Color Grey = new(0x666D71); - /// Gets the dark grey color value. - /// A color struct with the hex value of 607D8B. See http://www.color-hex.com/color/607D8B + /// + /// 获取钢蓝色。 + /// + /// + /// 钢蓝色 #607D8B(http://www.color-hex.com/color/607d8b)。 + /// public static readonly Color DarkGrey = new(0x607D8B); - /// Gets the darker grey color value. - /// A color struct with the hex value of 3A4B53. See http://www.color-hex.com/color/3A4B53 + /// + /// 获取深青色。 + /// + /// + /// 深青色 #3A4B53(http://www.color-hex.com/color/3a4b53)。 + /// public static readonly Color DarkerGrey = new(0x3A4B53); - /// Gets the encoded value for this color. + /// + /// 获取此颜色的原始值。 + /// /// - /// This value is encoded as an unsigned integer value. The most-significant 8 bits contain the red value, - /// the middle 8 bits contain the green value, and the least-significant 8 bits contain the blue value. + /// 颜色以 24 位无符号整型值 RGB 格式进行编码,由高至低的每 8 位分别表示红色、绿色和蓝色通道的强度。 /// public uint RawValue { get; } - /// Gets the red component for this color. + /// + /// 获取此颜色的红色通道的强度。 + /// public byte R => (byte)(RawValue >> 16); - /// Gets the green component for this color. + /// + /// 获取此颜色的绿色通道的强度。 + /// public byte G => (byte)(RawValue >> 8); - /// Gets the blue component for this color. + /// + /// 获取此颜色的蓝色通道的强度。 + /// public byte B => (byte)RawValue; /// - /// Initializes a struct with the given raw value. + /// 使用指定的 24 位无符号整型值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a hex value of - /// #607D8B. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色: /// - /// Color darkGrey = new Color(0x607D8B); + /// Color darkGrey = new Color(0x607D8B); /// /// - /// The raw value of the color (e.g. 0x607D8B). - /// Value exceeds . + /// 颜色的 24 位无符号整型原始值。 + /// 颜色原始值超过了 public Color(uint rawValue) { if (rawValue > MaxDecimalValue) - throw new ArgumentException($"{nameof(RawValue)} of color cannot be greater than {MaxDecimalValue}!", nameof(rawValue)); + throw new ArgumentException($"{nameof(RawValue)} of color cannot be greater than {MaxDecimalValue}!", + nameof(rawValue)); RawValue = rawValue; } /// - /// Initializes a struct with the given RGB bytes. + /// 使用指定的 RGB 通道值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a value of - /// #607D8B. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色: /// - /// Color darkGrey = new Color((byte)0b_01100000, (byte)0b_01111101, (byte)0b_10001011); + /// Color darkGrey = new Color((byte)0x60, (byte)0x7D, (byte)0x8B); /// /// - /// The byte that represents the red color. - /// The byte that represents the green color. - /// The byte that represents the blue color. - /// Value exceeds . + /// 红色通道的强度。 + /// 绿色通道的强度。 + /// 蓝色通道的强度。 + /// 所提供的三个通道的强度值所组成的颜色的原始值超过了 public Color(byte r, byte g, byte b) { uint value = ((uint)r << 16) @@ -159,19 +249,18 @@ public Color(byte r, byte g, byte b) } /// - /// Initializes a struct with the given RGB value. + /// 使用指定的 RGB 通道值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a value of - /// #607D8B. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色: /// - /// Color darkGrey = new Color(96, 125, 139); + /// Color darkGrey = new Color(96, 125, 139); /// /// - /// The value that represents the red color. Must be within 0~255. - /// The value that represents the green color. Must be within 0~255. - /// The value that represents the blue color. Must be within 0~255. - /// The argument value is not between 0 to 255. + /// 红色通道的强度。 + /// 绿色通道的强度。 + /// 蓝色通道的强度。 + /// 所提供的三个通道的强度值所组成的颜色的原始值超过了 public Color(int r, int g, int b) { if (r is < 0 or > 255) @@ -189,19 +278,18 @@ public Color(int r, int g, int b) } /// - /// Initializes a struct with the given RGB float value. + /// 使用指定的 RGB 通道值初始化一个 结构的新实例。 /// /// - /// The following will create a color that has a value of - /// #607C8C. + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色: /// - /// Color darkGrey = new Color(0.38f, 0.49f, 0.55f); + /// Color darkGrey = new Color(0.38f, 0.49f, 0.55f); /// /// - /// The value that represents the red color. Must be within 0~1. - /// The value that represents the green color. Must be within 0~1. - /// The value that represents the blue color. Must be within 0~1. - /// The argument value is not between 0 to 1. + /// 红色通道的强度。 + /// 绿色通道的强度。 + /// 蓝色通道的强度。 + /// 所提供的三个通道的强度值所组成的颜色的原始值超过了 public Color(float r, float g, float b) { if (r is < 0.0f or > 1.0f) @@ -219,34 +307,32 @@ public Color(float r, float g, float b) } /// - /// Determines whether the specified is equal to this instance. + /// 判定两个 是否相等。 /// - /// true if the specified is equal to this instance; otherwise, false . - public static bool operator ==(Color lhs, Color rhs) => - lhs.RawValue == rhs.RawValue; + /// 如果两个 相等,则为 true;否则为 false + public static bool operator ==(Color lhs, Color rhs) => lhs.RawValue == rhs.RawValue; /// - /// Determines whether the specified is not equal to this instance. + /// 判定两个 是否不相等。 /// - /// true if the specified is not equal to this instance; otherwise, false . - public static bool operator !=(Color lhs, Color rhs) => - lhs.RawValue != rhs.RawValue; + /// 如果两个 不相等,则为 true;否则为 false + public static bool operator !=(Color lhs, Color rhs) => lhs.RawValue != rhs.RawValue; /// - /// Converts the given raw value of to a . + /// 使用指定的 24 位无符号整型值初始化一个 结构的新实例。 /// - /// The raw value of the color. - /// The that represents the given raw value. - public static implicit operator Color(uint rawValue) => - new(rawValue); + /// + /// 创建 #607D8B(http://www.color-hex.com/color/607d8b)所表示的颜色: + /// + /// Color darkGrey = 0x607D8B; + /// + /// + /// 颜色的 24 位无符号整型原始值。 + /// 颜色原始值超过了 + public static implicit operator Color(uint rawValue) => new(rawValue); - /// - /// Converts the given to its raw value of . - /// - /// The to convert. - /// The raw value of the given . - public static implicit operator uint(Color color) => - color.RawValue; + /// + public static implicit operator uint(Color color) => color.RawValue; /// public override bool Equals([NotNullWhen(true)] object? obj) => @@ -256,27 +342,25 @@ public override bool Equals([NotNullWhen(true)] object? obj) => public override int GetHashCode() => RawValue.GetHashCode(); /// - /// Converts the given Kook.Net-defined to a .NET standard . + /// 将由 Kook.Net 定义的 颜色转换为由 .NET 定义的 颜色。 /// - /// The Kook.Net-defined to convert. - /// The .NET standard that represents the given Kook.Net-defined . + /// 要进行转换的 颜色。 + /// 与该 颜色具有相同色值的 .NET 颜色。 public static implicit operator StandardColor(Color color) => StandardColor.FromArgb((int)color.RawValue); /// - /// Converts the given .NET standard to a Kook.Net-defined . + /// 将由 .NET 定义的 颜色转换为由 Kook.Net 定义的 颜色。 /// - /// The .NET standard to convert. - /// The Kook.Net-defined that represents the given .NET standard . + /// 要进行转换的 .NET 颜色。 + /// 与该 .NET 颜色具有相同色值的 颜色。 public static explicit operator Color(StandardColor color) => new(((uint)color.ToArgb() << 8) >> 8); /// - /// Gets the hexadecimal representation of the color (e.g. #000ccc). + /// 获取此颜色带有 # 前缀的 RGB 十六进制字符串表示形式(例如 #000CCC)。 /// - /// - /// A hexadecimal string of the color. - /// + /// 此颜色带有 # 前缀的 RGB 十六进制字符串表示形式(例如 #000CCC)。 public override string ToString() => $"#{RawValue:X6}"; private string DebuggerDisplay => $"#{RawValue:X6} ({RawValue})"; diff --git a/src/Kook.Net.Core/Entities/Roles/ColorType.cs b/src/Kook.Net.Core/Entities/Roles/ColorType.cs index f0e6ce24..dad2b5e0 100644 --- a/src/Kook.Net.Core/Entities/Roles/ColorType.cs +++ b/src/Kook.Net.Core/Entities/Roles/ColorType.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Represents the type of color a role has. +/// 表示一个角色的颜色类型。 /// public enum ColorType : ushort { /// - /// The color is a solid color. + /// 实心纯色。 /// Solid = 1, /// - /// The color is a gradient. + /// 渐变色。 /// Gradient = 2 } diff --git a/src/Kook.Net.Core/Entities/Roles/GradientColor.cs b/src/Kook.Net.Core/Entities/Roles/GradientColor.cs index 4d2a8dea..5e901229 100644 --- a/src/Kook.Net.Core/Entities/Roles/GradientColor.cs +++ b/src/Kook.Net.Core/Entities/Roles/GradientColor.cs @@ -3,16 +3,16 @@ namespace Kook; /// -/// Represents a gradient color. +/// 表示一个渐变色。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public readonly struct GradientColor { /// - /// Initializes a new instance of . + /// 初始化一个 结构的新实例。 /// - /// The left color of the gradient. - /// The right color of the gradient. + /// 渐变色的左侧颜色。 + /// 渐变色的右侧颜色。 public GradientColor(Color left, Color right) { Left = left; @@ -20,27 +20,38 @@ public GradientColor(Color left, Color right) } /// - /// The left color of the gradient. + /// 获取此渐变色的左侧颜色。 /// public Color Left { get; } /// - /// The right color of the gradient. + /// 获取此渐变色的右侧颜色。 /// public Color Right { get; } /// - /// Converts the to a tuple of . + /// 将此渐变色解构为表示左右两个颜色的元组。 /// - /// The gradient color to convert. - /// The tuple of . + /// 左侧颜色。 + /// 右侧颜色。 + public void Deconstruct(out Color left, out Color right) + { + left = Left; + right = Right; + } + + /// + /// 将此渐变色转换为表示左右两个颜色的元组。 + /// + /// 要转换的渐变色。 + /// 表示左右两个颜色的元组。 public static implicit operator (Color Left, Color Right)(GradientColor gradient) => (gradient.Left, gradient.Right); /// - /// Converts the tuple of to a . + /// 将此表示左右两个颜色的元组转换为渐变色。 /// - /// The tuple of to convert. - /// The . + /// 要转换的表示左右两个颜色的元组。 + /// 转换后的渐变色。 public static implicit operator GradientColor((Color Left, Color Right) gradient) => new(gradient.Left, gradient.Right); private string DebuggerDisplay => $"{Left} -> {Right}"; diff --git a/src/Kook.Net.Core/Entities/Roles/IRole.cs b/src/Kook.Net.Core/Entities/Roles/IRole.cs index 2ae310bd..336bd94f 100644 --- a/src/Kook.Net.Core/Entities/Roles/IRole.cs +++ b/src/Kook.Net.Core/Entities/Roles/IRole.cs @@ -1,112 +1,103 @@ namespace Kook; /// -/// Represents a generic role object to be given to a guild user. +/// 表示一个基于网关的可授予服务器用户的角色。 /// public interface IRole : IEntity, IDeletable, IMentionable, IComparable { /// - /// Gets the guild that owns this role. + /// 获取拥有此角色的服务器。 /// - /// - /// A guild representing the parent guild of this role. - /// IGuild Guild { get; } /// - /// Gets the name of this role. + /// 获取此角色的名称。 /// - /// - /// A string containing the name of this role. - /// string Name { get; } /// - /// Gets the type of this role. + /// 获取此角色的类型。 /// - /// - /// A representing the type of this role. - /// RoleType Type { get; } /// - /// Gets the color given to users of this role. + /// 获取此角色的颜色。 /// - /// - /// A struct representing the color of this role. - /// + /// + /// 如果此用户所拥有的最高角色的颜色类型为渐变色,则此属性返回的颜色是渐变色权益失效后的回退颜色。 + /// Color Color { get; } /// - /// Gets the type of the color given to users of this role. + /// 获取此角色的颜色类型。 /// - /// - /// A struct representing the color type of this role. - /// ColorType ColorType { get; } /// - /// Gets the gradient color given to users of this role. + /// 获取此角色的渐变色。 /// - /// - /// A struct representing the gradient color of this role; - /// null if the role does not have a gradient color. - /// + /// + /// 如果此角色的颜色类型 不为 + /// ,则此属性会返回 。 + /// GradientColor? GradientColor { get; } /// - /// Gets this role's position relative to other roles in the same guild. + /// 获取此角色在服务器角色列表中的位置。 /// - /// - /// An representing the position of the role in the role list of the guild. - /// + /// + /// 更小的数值表示更靠近列表顶部的位置。 + /// int Position { get; } /// - /// Gets a value that indicates whether the role can be separated in the user list. + /// 获取拥有此角色的用户是否在用户列表中与普通在线成员分开显示。 /// - /// - /// true if users of this role are separated in the user list; otherwise false. - /// bool IsHoisted { get; } /// - /// Gets a value that indicates whether the role is mentionable. + /// 获取是否允许任何人提及此角色。 /// - /// - /// true if this role may be mentioned in messages; otherwise false. - /// bool IsMentionable { get; } /// - /// Gets the permissions granted to members of this role. + /// 获取此角色拥有的权限。 /// - /// - /// A struct that this role possesses. - /// GuildPermissions Permissions { get; } /// - /// Modifies this role. + /// 修改此角色。 /// /// - /// This method modifies this role with the specified properties. To see an example of this - /// method and what properties are available, please refer to . + /// 此方法使用指定的属性修改当前角色信息。要查看可用的属性,请参考 。 /// - /// A delegate containing the properties to modify the role with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// + /// 一个包含修改角色属性的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 Task ModifyAsync(Action func, RequestOptions? options = null); /// - /// Gets a collection of users with this role. + /// 获取拥有此角色的用户的集合。 /// - /// The that determines whether the object should be fetched from cache. - /// The options to be used when sending the request. - /// - /// Paged collection of users with this role. - /// + /// + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取拥有此角色的所有服务器用户。此方法会根据 + /// 将请求拆分。换句话说,如果存在 500 个用户拥有此角色,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 + ///
+ /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 分页的用户集合的异步可枚举对象。 IAsyncEnumerable> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs b/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs index 46739db5..af098e57 100644 --- a/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs +++ b/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs @@ -1,45 +1,49 @@ namespace Kook; /// -/// Properties that are used to modify an with the specified changes. +/// 提供用于修改 的属性。 /// -/// +/// public class RoleProperties { /// - /// Gets or sets the name of the role. + /// 获取或设置要设置到此角色的名称。 /// - /// - /// This value may not be set if the role is an @everyone role. - /// public string? Name { get; set; } /// - /// Gets or sets the color of the role. + /// 获取或设置要设置到此角色的颜色。 /// - /// - /// This value may not be set if the role is an @everyone role. - /// public Color? Color { get; set; } /// - /// Gets or sets whether this role should be displayed independently in the user list. + /// 获取或设置要设置到此角色拥有此角色的用户是否在用户列表中与普通在线成员分开显示。 /// - /// - /// This value may not be set if the role is an @everyone role. - /// - public bool? Hoist { get; set; } + public bool? IsHoisted { get; set; } + + /// + [Obsolete("Use IsHoisted instead.")] + public bool? Hoist + { + get => IsHoisted; + set => IsHoisted = value; + } /// - /// Gets or sets whether or not this role can be mentioned. + /// 获取或设置要设置到此角色是否允许任何人提及此角色。 /// - /// - /// This value may not be set if the role is an @everyone role. - /// - public bool? Mentionable { get; set; } + public bool? IsMentionable { get; set; } + + /// + [Obsolete("Use IsMentionable instead.")] + public bool? Mentionable + { + get => IsMentionable; + set => IsMentionable = value; + } /// - /// Gets or sets the role's . + /// 获取或设置要设置到此角色的权限。 /// public GuildPermissions? Permissions { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Guilds/RoleType.cs b/src/Kook.Net.Core/Entities/Roles/RoleType.cs similarity index 51% rename from src/Kook.Net.Core/Entities/Guilds/RoleType.cs rename to src/Kook.Net.Core/Entities/Roles/RoleType.cs index 4a73589e..2aaf1d55 100644 --- a/src/Kook.Net.Core/Entities/Guilds/RoleType.cs +++ b/src/Kook.Net.Core/Entities/Roles/RoleType.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// Represents the type of a role. +/// 表示角色的类型。 /// public enum RoleType : ushort { /// - /// Represents the role was created by a user. + /// 角色是由用户创建的。 /// UserCreated = 0, /// - /// Represents the role was created by system when a bot joined the guild. + /// 角色是在 Bot 加入服务器时由系统创建的。 /// BotSpecified = 1, /// - /// Represents the role representing a booster. + /// 角色表示服务器助力者。 /// Booster = 2, /// - /// Represents the role is the default everyone role. + /// 表示角色是默认的 @全体成员 全体成员角色。 /// Everyone = 255 } diff --git a/src/Kook.Net.Core/Entities/SortMode.cs b/src/Kook.Net.Core/Entities/SortMode.cs index d3ae8fc2..67d2a033 100644 --- a/src/Kook.Net.Core/Entities/SortMode.cs +++ b/src/Kook.Net.Core/Entities/SortMode.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the sorting mode. +/// 表示排序模式。 /// public enum SortMode { /// - /// The items are sorted in ascending order. + /// 项目按升序排序。 /// Ascending = 0, /// - /// The items are sorted in descending order. + /// 项目按降序排序。 /// Descending = 1 } diff --git a/src/Kook.Net.Core/Entities/Users/BoostSubscriptionMetadata.cs b/src/Kook.Net.Core/Entities/Users/BoostSubscriptionMetadata.cs index 4eedee46..279451ef 100644 --- a/src/Kook.Net.Core/Entities/Users/BoostSubscriptionMetadata.cs +++ b/src/Kook.Net.Core/Entities/Users/BoostSubscriptionMetadata.cs @@ -1,27 +1,27 @@ namespace Kook; /// -/// A metadata containing boost subscription information. +/// 表示一个包含服务器助力订阅信息的元数据。 /// public class BoostSubscriptionMetadata { /// - /// Gets the date and time when this subscription began. + /// 获取此订阅开始的日期和时间。 /// public DateTimeOffset Since { get; private set; } /// - /// Gets the date and time when this subscription will end or ended. + /// 获取此订阅将于或已于何时结束的日期和时间。 /// public DateTimeOffset Until { get; private set; } /// - /// Gets whether this subscription has not expired. + /// 获取此订阅是否仍在有效期内。 /// public bool IsValid => DateTimeOffset.Now < Until; /// - /// Gets how many boost packs the user used for this subscription. + /// 获取用户为此订阅所使用的助力包数量。 /// public int Count { get; private set; } diff --git a/src/Kook.Net.Core/Entities/Users/ClientType.cs b/src/Kook.Net.Core/Entities/Users/ClientType.cs index 23851f7b..9004275a 100644 --- a/src/Kook.Net.Core/Entities/Users/ClientType.cs +++ b/src/Kook.Net.Core/Entities/Users/ClientType.cs @@ -1,23 +1,23 @@ namespace Kook; /// -/// Defines the types of clients a user can be active on. +/// 表示一个用户所登录的客户端类型。 /// public enum ClientType { /// - /// The user is active using a WebSocket connection to the server. + /// 用户正在使用 WebSocket 连接到服务器。 /// WebSocket, /// - /// The user is active using the Android application. + /// 用户正在使用 Android 应用程序连接到服务器。 /// Android, + // ReSharper disable once InconsistentNaming /// - /// The user is active using the iOS application. + /// 用户正在使用 iOS 应用程序连接到服务器。 /// - // ReSharper disable once InconsistentNaming iOS } diff --git a/src/Kook.Net.Core/Entities/Users/FriendState.cs b/src/Kook.Net.Core/Entities/Users/FriendState.cs index d72a7790..a05a4882 100644 --- a/src/Kook.Net.Core/Entities/Users/FriendState.cs +++ b/src/Kook.Net.Core/Entities/Users/FriendState.cs @@ -1,22 +1,22 @@ namespace Kook; /// -/// Represents a state of a friend relationship with the current user. +/// 表示一个用户之间的好友关系状态。 /// public enum FriendState { /// - /// Represents a pending friend request that has not been accepted yet. + /// 表示一个尚未被接受的待处理好友请求。 /// Pending, /// - /// Represents an accepted friend request, where the user has been added to the current user's friend list. + /// 表示一个已接受的好友请求,即该用户已被添加到当前用户的好友列表中。 /// Accepted, /// - /// Represents a blocked friend status, where the user has been blocked by the current user. + /// 表示一个已屏蔽的好友状态,即该用户已被当前用户屏蔽。 /// Blocked } diff --git a/src/Kook.Net.Core/Entities/Users/IFriendRequest.cs b/src/Kook.Net.Core/Entities/Users/IFriendRequest.cs index 8b858b79..eda77a09 100644 --- a/src/Kook.Net.Core/Entities/Users/IFriendRequest.cs +++ b/src/Kook.Net.Core/Entities/Users/IFriendRequest.cs @@ -1,26 +1,26 @@ namespace Kook; /// -/// Represents a generic friend request. +/// 表示一个通用的好友请求。 /// public interface IFriendRequest : IEntity { /// - /// Gets the user who sent this friend request. + /// 获取发送此好友请求的用户。 /// IUser User { get; } /// - /// Accepts this friend request. + /// 接受此好友请求。 /// - /// The options to use when accepting this friend request. - /// A task that represents the asynchronous accept operation. + /// 发送请求时要使用的选项。 + /// 一个表示异步接受操作的任务。 Task AcceptAsync(RequestOptions? options = null); /// - /// Declines this friend request. + /// 拒绝此好友请求。 /// - /// The options to use when declining this friend request. - /// A task that represents the asynchronous decline operation. + /// 发送请求时要使用的选项。 + /// 一个表示异步拒绝操作的任务。 Task DeclineAsync(RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Users/IGuildUser.cs b/src/Kook.Net.Core/Entities/Users/IGuildUser.cs index 6ebb5995..5c67b2ba 100644 --- a/src/Kook.Net.Core/Entities/Users/IGuildUser.cs +++ b/src/Kook.Net.Core/Entities/Users/IGuildUser.cs @@ -1,106 +1,85 @@ namespace Kook; /// -/// Represents a generic guild user. +/// 表示一个通用的服务器用户。 /// public interface IGuildUser : IUser, IVoiceState { #region General /// - /// Gets the nickname for this user. + /// 获取此用户在该服务器内的昵称。 /// - /// - /// A string representing the nickname of the user; null if none is set. - /// + /// + /// 如果此用户在该服务器内没有设置昵称,则此属性返回 。 + /// string? Nickname { get; } /// - /// Gets the displayed name for this user. + /// 获取此用户的显示名称。 /// - /// - /// A string representing the display name of the user; If the nickname is null, this will be the username. - /// + /// + /// 如果此用户在该服务器内设置了昵称,则此属性返回昵称;否则返回用户名。 + /// string DisplayName { get; } /// - /// Gets a collection of IDs for the roles that this user currently possesses in the guild. + /// 获取此用户在该服务器内拥有的所有角色的 ID。 /// /// - /// This property returns a read-only collection of the identifiers of the roles that this user possesses. - /// For WebSocket users, a Roles property can be found in place of this property. Due to the REST - /// implementation, only a collection of identifiers can be retrieved instead of the full role objects. + /// 此属性返回此用户所拥有的所有角色的 ID。对于 WebSocket 服务器用户实体,`Roles` 属性可以用来获取所有角色对象;对于 REST + /// 服务器用户实体,受限于 KOOK API,在服务器用户实体上仅能直接获取其所拥有的所有角色的 ID。 /// - /// - /// A read-only collection of uint, each representing an identifier for a role that - /// this user possesses. - /// IReadOnlyCollection RoleIds { get; } /// - /// Gets the guild for this user. + /// 获取此服务器用户所属的服务器。 /// - /// - /// A guild object that this user belongs to. - /// IGuild Guild { get; } /// - /// Gets the ID of the guild for this user. + /// 获取此用户所属服务器的 ID。 /// - /// - /// An ulong representing the identifier of the guild that this user belongs to. - /// ulong GuildId { get; } /// - /// Gets whether the mobile number has been verified for this user. + /// 获取此用户的手机号码是否已验证。 /// - /// - /// true if the mobile number has been verified; false otherwise. - /// bool? IsMobileVerified { get; } /// - /// Gets when this user joined the guild. + /// 获取此用户加入服务器的时间。 /// - /// - /// The time of which the user has joined the guild. - /// DateTimeOffset? JoinedAt { get; } /// - /// Gets when this user was activated. + /// 获取此用户在该服务器内的最近活跃时间。 /// - /// - /// The time of which the user was activated. - /// DateTimeOffset? ActiveAt { get; } /// - /// Gets the color the user's displayed name is being displayed in. + /// 获取此用户的显示名称的颜色。 /// - /// - /// A struct representing the color the user's display name is being displayed in. - /// /// + /// 如果此用户所拥有的最高角色的颜色类型为渐变色,则此属性返回的颜色是渐变色权益失效后的回退颜色。
/// - /// At present, the color of a role may be a solid color or a gradient. See , - /// which is guaranteed due to the fact that the guild's user list API endpoint returns the color type - /// and the gradient color information if exists. However, the value of this property is fetched - /// from the guild's user list API endpoint, which does not return the color type and the gradient - /// color information. Hence, the value of this property may be incorrect if the color of a role is - /// a gradient. + /// 一个角色的颜色可能是纯色或渐变色,参见 。但由于服务器用户列表 API + /// 及服务器用户详情 API 所返回的用户信息均不包含角色的颜色类型和渐变色信息,因此,如果用户的最高角色的颜色是渐变色, + /// 则此属性的值可能是不正确的。如需获取该用户的准确的显示名称及颜色,请获取此用户的最高角色实体对象,访问其颜色类型及渐变色属性。 /// + /// + /// if (guildUser.RoleIds.Select(x => guildUser.Guild.GetRole(x)).OfType<IRole>().MinBy(x => x.Position) is { } topRole) + /// { + /// ColorType colorType = topRole.ColorType; + /// GradientColor? gradientColor = topRole.GradientColor; + /// } + /// ///
Color? Color { get; } /// - /// Gets whether this user owns the current guild. + /// 获取此用户是否为当前服务器的所有者。 /// - /// - /// true if this user owns the current guild; false otherwise. - /// bool? IsOwner { get; } #endregion @@ -108,22 +87,15 @@ public interface IGuildUser : IUser, IVoiceState #region Permissions /// - /// Gets the guild-level permissions for this user. + /// 获取此用户在该服务器内的权限。 /// - /// - /// A structure for this user, representing what - /// permissions this user has in the guild. - /// GuildPermissions GuildPermissions { get; } /// - /// Gets the level permissions granted to this user to a given channel. + /// 获取此用户在指定频道内所拥有的权限。 /// - /// The channel to get the permission from. - /// - /// A structure representing the permissions that a user has in the - /// specified channel. - /// + /// 要获取权限的频道。 + /// 一个表示此用户在指定频道内所拥有的频道权限的权限集。 ChannelPermissions GetPermissions(IGuildChannel channel); #endregion @@ -131,41 +103,32 @@ public interface IGuildUser : IUser, IVoiceState #region Guild /// - /// Kicks this user from this guild. + /// 将此用户从此服务器中踢出。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous kick operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步踢出操作的任务。 Task KickAsync(RequestOptions? options = null); /// - /// Modifies this user's nickname in this guild. + /// 修改此用户在该服务器内的昵称。 /// /// - /// This method modifies the nickname of current guild user. + /// 此方法使用指定的属性修改当前用户在该服务器内的昵称。
+ /// 如要清除此用户在该服务器内的昵称,请将 设置为
/// - /// The KOOK API will clear the nickname if the nickname is set to - /// the same as the username at present. Hence either setting the nickname - /// to the same as the username or setting the nickname to null will clear - /// the nickname. + /// 如果将昵称设置为与用户名相同,KOOK 也会将该用户在此服务器内的昵称清除,显示名称将跟随用户名,而不是固定为指定的昵称。 /// ///
- /// The nickname to modify the user with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// + /// 要设置到此用户在该服务器内的新昵称。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 Task ModifyNicknameAsync(string? name, RequestOptions? options = null); /// - /// Gets all subscriptions of this user for this guild. + /// 获取此用户在该服务器内的所有服务器助力包订阅信息。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous retrieval operation. The task result contains - /// a collection of , each representing the subscription information. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此用户在该服务器内的所有服务器助力包订阅信息。 Task> GetBoostSubscriptionsAsync(RequestOptions? options = null); #endregion @@ -173,83 +136,67 @@ public interface IGuildUser : IUser, IVoiceState #region Roles /// - /// Adds the specified role to this user in the guild. + /// 在该服务器内授予此用户指定的角色。 /// - /// The role to be added to the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role addition operation. - /// + /// 要在该服务器内为此用户授予的角色的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步授予操作的任务。 Task AddRoleAsync(uint roleId, RequestOptions? options = null); /// - /// Adds the specified role to this user in the guild. + /// 在该服务器内授予此用户指定的角色。 /// - /// The role to be added to the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role addition operation. - /// + /// 要在该服务器内为此用户授予的角色。 + /// 发送请求时要使用的选项。 + /// 一个表示异步授予操作的任务。 Task AddRoleAsync(IRole role, RequestOptions? options = null); /// - /// Adds the specified to this user in the guild. + /// 在该服务器内授予此用户指定的一些角色。 /// - /// The roles to be added to the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role addition operation. - /// + /// 要在该服务器内为此用户授予的所有角色的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步授予操作的任务。 Task AddRolesAsync(IEnumerable roleIds, RequestOptions? options = null); /// - /// Adds the specified to this user in the guild. + /// 在该服务器内授予此用户指定的一些角色。 /// - /// The roles to be added to the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role addition operation. - /// + /// 要在该服务器内为此用户授予的所有角色。 + /// 发送请求时要使用的选项。 + /// 一个表示异步授予操作的任务。 Task AddRolesAsync(IEnumerable roles, RequestOptions? options = null); /// - /// Removes the specified from this user in the guild. + /// 在该服务器内撤销此用户指定的角色。 /// - /// The role to be removed from the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role removal operation. - /// + /// 要在该服务器内为此用户撤销的角色的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步撤销操作的任务。 Task RemoveRoleAsync(uint roleId, RequestOptions? options = null); /// - /// Removes the specified from this user in the guild. + /// 在该服务器内撤销此用户指定的角色。 /// - /// The role to be removed from the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role removal operation. - /// + /// 要在该服务器内为此用户撤销的角色。 + /// 发送请求时要使用的选项。 + /// 一个表示异步撤销操作的任务。 Task RemoveRoleAsync(IRole role, RequestOptions? options = null); /// - /// Removes the specified from this user in the guild. + /// 在该服务器内撤销此用户指定的一些角色。 /// - /// The roles to be removed from the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role removal operation. - /// + /// 要在该服务器内为此用户撤销的所有角色的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步撤销操作的任务。 Task RemoveRolesAsync(IEnumerable roleIds, RequestOptions? options = null); /// - /// Removes the specified from this user in the guild. + /// 在该服务器内撤销此用户指定的一些角色。 /// - /// The roles to be removed from the user. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous role removal operation. - /// + /// 要在该服务器内为此用户撤销的所有角色。 + /// 发送请求时要使用的选项。 + /// 一个表示异步撤销操作的任务。 Task RemoveRolesAsync(IEnumerable roles, RequestOptions? options = null); #endregion @@ -257,49 +204,50 @@ public interface IGuildUser : IUser, IVoiceState #region Voice /// - /// Mute this user in this guild. + /// 在该服务器内关闭此用户的语音输入。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous muting operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步关闭操作的任务。 + /// + /// 此操作会使此用户无法在该服务器内的语音频道中发言。 + /// Task MuteAsync(RequestOptions? options = null); /// - /// Deafen this user in this guild. + /// 在该服务器内限制此用户的语音接收。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous deafening operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步静音操作的任务。 + /// + /// 此操作会使此用户无法在该服务器内的语音频道中接收来自其他用户的语音。 + /// Task DeafenAsync(RequestOptions? options = null); /// - /// Unmute this user in this guild. + /// 在该服务器内恢复此用户的语音输入。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous unmuting operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步恢复操作的任务。 + /// + /// 此操作会撤销由于服务器闭麦而导致的在语音频道中无法发言状态。 + /// Task UnmuteAsync(RequestOptions? options = null); /// - /// Undeafen this user in this guild. + /// 在该服务器内恢复此用户的语音接收。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous undeafening operation. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步恢复操作的任务。 + /// + /// 此操作会撤销由于服务器静音而导致的无法在语音频道中接收来自其他用户的语音的状态。 + /// Task UndeafenAsync(RequestOptions? options = null); /// - /// Gets a collection of voice channels a user. + /// 获取此用户当前所连接到的所有语音频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of - /// voice channels the user is connected to. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此用户当前所连接到的所有语音频道。 Task> GetConnectedVoiceChannelsAsync(RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/Entities/Users/IPresence.cs b/src/Kook.Net.Core/Entities/Users/IPresence.cs index 97eb739f..192c12b3 100644 --- a/src/Kook.Net.Core/Entities/Users/IPresence.cs +++ b/src/Kook.Net.Core/Entities/Users/IPresence.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Represents the user's presence status. This may include their online status and their activity. +/// 表示一个通用的用户实时状态。 /// public interface IPresence { /// - /// Gets the current status of this user. + /// 获取此用户当前是否在线。 /// bool? IsOnline { get; } /// - /// Gets the type of the client where this user is currently active. + /// 获取此用于当前登录的客户端类型。 /// ClientType? ActiveClient { get; } } diff --git a/src/Kook.Net.Core/Entities/Users/ISelfUser.cs b/src/Kook.Net.Core/Entities/Users/ISelfUser.cs index dd04d5c2..b437bf11 100644 --- a/src/Kook.Net.Core/Entities/Users/ISelfUser.cs +++ b/src/Kook.Net.Core/Entities/Users/ISelfUser.cs @@ -1,57 +1,60 @@ namespace Kook; /// -/// Represents the logged-in Kook user. +/// 表示一个通用的当前登录的用户信息。 /// public interface ISelfUser : IUser { /// - /// Gets the mobile prefix of the logged-in user. + /// 获取此用户的手机号码前缀。 /// string? MobilePrefix { get; } /// - /// Gets the mobile number of the logged-in user. + /// 获取此用户的手机号码。 /// string? Mobile { get; } /// - /// TODO: To be documented. + /// 获取此用户的邀请用户数。 /// int InvitedCount { get; } /// - /// Gets whether the mobile number of the logged-in user is verified. + /// 获取此用户是否验证了手机号码。 /// bool IsMobileVerified { get; } /// - /// Starts a new game activity. After this operation, a game activity will be displayed on the currently connected user's profile. + /// 开始一个新的游戏活动。 /// - /// The game to be played. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for starting a game activity. - /// + /// 要显示的游戏。 + /// 发送请求时要使用的选项。 + /// 一个表示异步开始操作的任务。 + /// + /// 此操作会使当前用户的资料卡片上显式指定的游戏信息。 + /// Task StartPlayingAsync(IGame game, RequestOptions? options = null); /// - /// Starts a new music activity. After this operation, a music activity will be displayed on the currently connected user's profile. + /// 开始一个新的听音乐活动。 /// - /// The music being listened to be showed. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for starting a music activity. - /// + /// 要播放的音乐。 + /// 发送请求时要使用的选项。 + /// 一个表示异步开始操作的任务。 + /// + /// 此操作会使当前用户的资料卡片上显式指定的音乐信息。 + /// Task StartPlayingAsync(Music music, RequestOptions? options = null); /// - /// Stops an activity. After this operation, the activity on the currently connected user's profile will disappear. + /// 停止活动。 /// - /// The type of the activity to stop - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for stopping an activity. - /// + /// 要停止的活动类型。 + /// 发送请求时要使用的选项。 + /// 一个表示异步停止操作的任务。 + /// + /// 此操作会使当前用户的资料卡片上不再显示指定的活动信息。 + /// Task StopPlayingAsync(ActivityType type, RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Users/IUser.cs b/src/Kook.Net.Core/Entities/Users/IUser.cs index 6fb467af..52a700ba 100644 --- a/src/Kook.Net.Core/Entities/Users/IUser.cs +++ b/src/Kook.Net.Core/Entities/Users/IUser.cs @@ -1,143 +1,161 @@ namespace Kook; /// -/// Represents a generic user. +/// 表示一个通用的用户。 /// public interface IUser : IEntity, IMentionable, IPresence { /// - /// Gets the username for this user. + /// 获取此用户的用户名。 /// string Username { get; } /// - /// Gets the per-username unique ID for this user. + /// 获取此用户的识别号。 /// string IdentifyNumber { get; } /// - /// Gets the per-username unique ID for this user. + /// 获取此用户识别号的数值形式。 /// ushort IdentifyNumberValue { get; } /// - /// Gets whether this user is a bot; null if unknown. + /// 获取此用户是否为 Bot。 /// + /// + /// 如果未知此用户是否为 Bot,则此属性返回 。 + /// bool? IsBot { get; } /// - /// Gets whether this user is banned; null if unknown. + /// 获取此用户是否被封禁。 /// + /// + /// 如果未知此用户是否被封禁,则此属性返回 。 + /// bool? IsBanned { get; } /// - /// Gets whether this user has subscribed to BUFF; null if unknown. + /// 获取此用户是否订阅了 BUFF 会员。 /// + /// + /// 如果未知此用户是否订阅了 BUFF 会员,则此属性返回 。 + /// bool? HasBuff { get; } /// - /// Gets whether this user's BUFF subscription is annual; null if unknown. + /// 获取此用户是否订阅了年度 BUFF 会员。 /// + /// + /// 如果未知此用户是否订阅了年度 BUFF 会员,则此属性返回 。 + /// bool? HasAnnualBuff { get; } /// - /// Gets the link to this user's avatar. + /// 获取此用户的头像图像的 URL。 /// + /// + /// 如果此用户为 BUFF 会员,且以 BUFF 会员权益设置了头像,则此属性返回的 URL 表示的是 BUFF 专属头像权益时效后的回退头像。 + /// string Avatar { get; } /// - /// Gets the link to this user's BUFF avatar. + /// 获取此用户以 BUFF 会员权益设置的头像图像的 URL。 /// + /// + /// 如果此用户不是 BUFF 会员,或未以 BUFF 会员权限设置头像,则此属性返回 。 + /// string? BuffAvatar { get; } /// - /// Gets the link to this user's banner. + /// 获取此用户的横幅图像的 URL。 /// + /// + /// 如果此用户不是 BUFF 会员,或未以 BUFF 会员权限设置横幅,则此属性返回 。 + /// string? Banner { get; } /// - /// Gets whether this user enabled denoise feature; null if unknown. + /// 获取此用户是否启用了降噪功能。 /// + /// + /// 如果未知此用户是否启用了降噪功能,则此属性返回 。 + /// bool? IsDenoiseEnabled { get; } /// - /// Get the tag this user has. + /// 获取此用户的标签信息。 /// + /// + /// 用户的标签会显示在服务器用户列表、私信列表、私信消息页、好友列表、个人信息面板、聊天消息的用户名的右侧。
+ /// 如果此用户没有标签,或未知此用户的标签信息,则此属性返回 。 + ///
UserTag? UserTag { get; } /// - /// Gets the nameplates this user has. + /// 获取此用户设置展示的所有铭牌。 /// + /// + /// 用户设置的首个铭牌会展示在该用户聊天消息的用户名的右侧,用户设置的所有铭牌会展示在个人信息面板内的用户名下方。 + /// IReadOnlyCollection Nameplates { get; } /// - /// Gets whether this user is a system user. + /// 获取此用户是否为系统用户。 /// bool IsSystemUser { get; } /// - /// Creates the direct message channel of this user. + /// 创建一个用于与此用户收发私信的频道。 /// - /// - /// This method is used to obtain or create a channel used to send a direct message. - /// - /// In event that the current user cannot send a message to the target user, a channel can and will - /// still be created by Kook. However, attempting to send a message will yield a - /// with a 403 as its - /// . There are currently no official workarounds by - /// Kook. - /// - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for getting or creating a DM channel. The task result - /// contains the DM channel associated with this user. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务结果包含与此用户相关的私信频道。 Task CreateDMChannelAsync(RequestOptions? options = null); /// - /// Gets the intimacy information with this user. + /// 获取与此用户的亲密度信息。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for getting the intimacy information. The task result - /// contains the intimacy information associated with this user. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务结果包含与此用户的亲密度信息。 Task GetIntimacyAsync(RequestOptions? options = null); /// - /// Updates the intimacy information with this user. + /// 修改与此用户的亲密度信息。 /// - /// A delegate containing the properties to modify the with. - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for updating the intimacy information. + /// + /// 此方法使用指定的属性修改与此用户的亲密度信息。要查看可用的属性,请参考 。 + /// + /// 一个用于修改亲密度信息的委托。 + /// 发送请求时要使用的选项。 + /// 一个表示异步修改操作的任务。 Task UpdateIntimacyAsync(Action func, RequestOptions? options = null); /// - /// Gets the friend state with this user. + /// 屏蔽此用户。 /// - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for getting the friend state. + /// 发送请求时要使用的选项。 + /// 一个表示异步屏蔽操作的任务。 Task BlockAsync(RequestOptions? options = null); /// - /// Gets the friend state with this user. + /// 取消屏蔽此用户。 /// - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for getting the friend state. + /// 发送请求时要使用的选项。 + /// 一个表示异步取消操作的任务。 Task UnblockAsync(RequestOptions? options = null); /// - /// Sends a friend request to this user. + /// 向此用户发送好友请求。 /// - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for sending the friend request. + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。 Task RequestFriendAsync(RequestOptions? options = null); /// - /// Gets the friend state with this user. + /// 移除与此用户的好友关系。 /// - /// The options to be used when sending the request. - /// A task that represents the asynchronous operation for getting the friend state. + /// 发送请求时要使用的选项。 + /// 一个表示异步移除操作的任务。 Task RemoveFriendAsync(RequestOptions? options = null); } diff --git a/src/Kook.Net.Core/Entities/Users/IVoiceState.cs b/src/Kook.Net.Core/Entities/Users/IVoiceState.cs index ab2ba875..678d74db 100644 --- a/src/Kook.Net.Core/Entities/Users/IVoiceState.cs +++ b/src/Kook.Net.Core/Entities/Users/IVoiceState.cs @@ -1,34 +1,33 @@ namespace Kook; /// -/// Represents a user's voice connection status. +/// 表示一个通用的用户语音连接状态。 /// public interface IVoiceState { /// - /// Gets a value that indicates whether this user is deafened by the guild. + /// 获取此用户是否被服务器静音。 /// - /// - /// true if the user is deafened (i.e. not permitted to listen to or speak to others) by the guild; - /// otherwise false; null if unknown. - /// + /// + /// 被服务器静音表示无法在语音频道内接收来自其他用户的语音。 + /// bool? IsDeafened { get; } /// - /// Gets a value that indicates whether this user is muted (i.e. not permitted to speak via voice) by the - /// guild. + /// 获取此用户是否被服务器闭麦。 /// - /// - /// true if this user is muted by the guild; otherwise false; null if unknown. - /// + /// + /// 被服务器闭麦表示无法在语音频道内发言。 + /// bool? IsMuted { get; } /// - /// Gets the voice channel this user is currently in. + /// 获取此用户当前所连接的语音频道。 /// - /// - /// A generic voice channel object representing the voice channel that the user is currently in; null - /// if none. - /// IVoiceChannel? VoiceChannel { get; } + + /// + /// 获取此用户连接的所有语音频道。 + /// + IReadOnlyCollection VoiceChannels { get; } } diff --git a/src/Kook.Net.Core/Entities/Users/Nameplate.cs b/src/Kook.Net.Core/Entities/Users/Nameplate.cs index d3baa947..fa0a67f8 100644 --- a/src/Kook.Net.Core/Entities/Users/Nameplate.cs +++ b/src/Kook.Net.Core/Entities/Users/Nameplate.cs @@ -4,28 +4,28 @@ namespace Kook; /// -/// Representing a nameplate an can have. +/// 表示一个用户的铭牌。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Nameplate : IEquatable { /// - /// Gets the name of the nameplate given to user. + /// 获取此铭牌的名称。 /// public string Name { get; } /// - /// Gets the type of the nameplate given to user. + /// 获取此铭牌的类型。 /// public int Type { get; } /// - /// Gets the resource uri of the icon of the nameplate given to user. + /// 获取此铭牌的图标的 URL。 /// public string Icon { get; } /// - /// Gets the tips of the nameplate given to user. + /// 获取此铭牌的提示信息。 /// public string Tips { get; } @@ -37,15 +37,10 @@ private Nameplate(string name, int type, string icon, string tips) Tips = tips; } - /// - /// Initializes a new instance of the class. - /// - /// The name of the nameplate given to user. - /// The type of the nameplate given to user. - /// The resource uri of the icon of the nameplate given to user. - /// The tips of the nameplate given to user. - /// A representing the given parameters. - public static Nameplate Create(string name, int type, string icon, string tips) => new(name, type, icon, tips); + internal static Nameplate Create(string name, int type, string icon, string tips) + { + return new Nameplate(name, type, icon, tips); + } private string DebuggerDisplay => Name; diff --git a/src/Kook.Net.Core/Entities/Users/RequestFriendSource.cs b/src/Kook.Net.Core/Entities/Users/RequestFriendSource.cs index 5c251948..7b74ef3d 100644 --- a/src/Kook.Net.Core/Entities/Users/RequestFriendSource.cs +++ b/src/Kook.Net.Core/Entities/Users/RequestFriendSource.cs @@ -1,19 +1,17 @@ namespace Kook; /// -/// Represents a source from which a friend request is sent. +/// 表示一个好友请求的来源。 /// public enum RequestFriendSource { /// - /// Represents the friend request is sent via the user's full qualification, - /// such as username#1234. + /// 请求发起自用户名及其标识号。 /// FullQualification = 0, /// - /// Represents the friend request is sent via a guild where the user and - /// the current user are in. + /// 请求发起自共同加入的服务器。 /// Guild = 2 } diff --git a/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs b/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs index 18bb7498..6168ba22 100644 --- a/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs +++ b/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs @@ -1,38 +1,50 @@ namespace Kook; /// -/// Properties that are used to search for a in a . +/// 提供用于搜索服务器用户的属性。 /// -/// +/// public class SearchGuildMemberProperties { /// - /// Gets or sets the name of the user to be searched for; - /// null to not search via a name. + /// 获取或设置要用于搜索用户的用户名关键字。 /// + /// + /// 如果此属性不为 ,则搜索结果中的用户的用户名必须包含此属性的值;否则不使用用户名关键字作为搜索条件。 + /// public string? SearchName { get; set; } /// - /// Gets or sets the ID of the role the user must have to be searched for; - /// null to not search via a role. + /// 获取或设置要用于搜索用户的角色 ID。 /// + /// + /// 如果此属性不为 ,则搜索结果中的用户必须拥有此属性的值对应的角色;否则不使用角色 ID 作为搜索条件。 + /// public uint? RoleId { get; set; } /// - /// Gets or sets whether the user must have his/her mobile verified to be searched for; - /// null to not search via a verified status. + /// 获取或设置搜索用户的结果中所有用户是否都必须已经验证了手机号码。 /// + /// + /// 如果此属性为 ,则搜索结果中的所有用户必须已经验证了手机号码;如果此属性为 + /// ,则搜索结果中的所有用户必须没有验证了手机号码;如果此属性为 + /// ,则不使用手机号码验证状态作为搜索条件。 + /// public bool? IsMobileVerified { get; set; } /// - /// Gets or sets whether and how the searching results should be sorted by the activating time of the user; - /// null to not sort by active time. + /// 获取或设置搜索用户的结果是否应该按用户在此服务器内的最近活跃时间排序。 /// + /// + /// 如果此属性不为 ,则搜索结果中的用户将按照其在此服务器内的最近活跃时间排序;否则不使用最近活跃时间作为排序条件。 + /// public SortMode? SortedByActiveTime { get; set; } /// - /// Gets or sets whether and how the searching results should be sorted by the joining time of the user; - /// null to not sort by joining time. + /// 获取或设置搜索用户的结果是否应该按用户加入此服务器的时间排序。 /// + /// + /// 如果此属性不为 ,则搜索结果中的用户将按照其加入此服务器的时间排序;否则不使用加入时间作为排序条件。 + /// public SortMode? SortedByJoinTime { get; set; } } diff --git a/src/Kook.Net.Core/Entities/Users/UserTag.cs b/src/Kook.Net.Core/Entities/Users/UserTag.cs index c30c2466..5de00b05 100644 --- a/src/Kook.Net.Core/Entities/Users/UserTag.cs +++ b/src/Kook.Net.Core/Entities/Users/UserTag.cs @@ -4,33 +4,24 @@ namespace Kook; /// -/// Representing a tag an can have. +/// 表示一个用户的标签。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class UserTag : IEquatable { /// - /// Gets the color of the tag given to user. + /// 获取此用户标签的颜色。 /// - /// - /// A struct representing the color of this tag. - /// public Color Color { get; } /// - /// Gets the background color of the tag given to user. + /// 获取此用户标签的背景色。 /// - /// - /// A struct representing the background color of this tag. - /// public AlphaColor BackgroundColor { get; } /// - /// Gets the text of the tag given to user. + /// 获取此用户标签的文本。 /// - /// - /// A string representing the text of this tag. - /// public string Text { get; } private UserTag(Color color, AlphaColor backgroundColor, string text) @@ -40,22 +31,10 @@ private UserTag(Color color, AlphaColor backgroundColor, string text) Text = text; } - /// - /// Initializes a new instance of the class. - /// - /// - /// The color of the tag given to user. - /// - /// - /// The background color of the tag given to user. - /// - /// - /// The text of the tag given to user. - /// - /// - /// A representing the given parameters. - /// - public static UserTag Create(Color color, AlphaColor backgroundColor, string text) => new(color, backgroundColor, text); + internal static UserTag Create(Color color, AlphaColor backgroundColor, string text) + { + return new UserTag(color, backgroundColor, text); + } private string DebuggerDisplay => Text; diff --git a/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs b/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs index 12a40dd0..a55505ec 100644 --- a/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs +++ b/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs @@ -1,18 +1,20 @@ namespace Kook; -/// An extension class for squashing . -/// -/// This set of extension methods will squash an into a -/// single . This is often associated with requests that has a -/// set limit when requesting. -/// +/// +/// 提供用于展开其异步可枚举成员是嵌套的 可枚举对象的 +/// 的扩展方法。 +/// public static class AsyncEnumerableExtensions { - /// Flattens the specified pages into one asynchronously. + /// public static async Task> FlattenAsync(this IAsyncEnumerable> source) => await source.Flatten().ToArrayAsync().ConfigureAwait(false); - /// Flattens the specified pages into one . + /// + /// 获取异步可枚举对象 的所有 + /// 成员,并将这些可枚举对象 中的所有成员迭代返回为一个 + /// 。 + /// public static IAsyncEnumerable Flatten(this IAsyncEnumerable> source) => source.SelectMany(enumerable => enumerable.ToAsyncEnumerable()); } diff --git a/src/Kook.Net.Core/Extensions/CardExtensions.cs b/src/Kook.Net.Core/Extensions/CardExtensions.cs index 7e491903..3449bff6 100644 --- a/src/Kook.Net.Core/Extensions/CardExtensions.cs +++ b/src/Kook.Net.Core/Extensions/CardExtensions.cs @@ -1,14 +1,14 @@ namespace Kook; /// -/// Provides extension methods for , and . +/// 提供用于 等卡片相关对象的扩展方法。 /// public static class CardExtensions { #region Elements /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static IElementBuilder ToBuilder(this IElement entity) { @@ -24,7 +24,7 @@ public static IElementBuilder ToBuilder(this IElement entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static PlainTextElementBuilder ToBuilder(this PlainTextElement entity) { @@ -36,7 +36,7 @@ public static PlainTextElementBuilder ToBuilder(this PlainTextElement entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static KMarkdownElementBuilder ToBuilder(this KMarkdownElement entity) { @@ -44,7 +44,7 @@ public static KMarkdownElementBuilder ToBuilder(this KMarkdownElement entity) } /// - /// Converts the to an with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ImageElementBuilder ToBuilder(this ImageElement entity) { @@ -58,7 +58,7 @@ public static ImageElementBuilder ToBuilder(this ImageElement entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ButtonElementBuilder ToBuilder(this ButtonElement entity) { @@ -72,7 +72,7 @@ public static ButtonElementBuilder ToBuilder(this ButtonElement entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ParagraphStructBuilder ToBuilder(this ParagraphStruct entity) { @@ -88,7 +88,7 @@ public static ParagraphStructBuilder ToBuilder(this ParagraphStruct entity) #region Modules /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static IModuleBuilder ToBuilder(this IModule entity) { @@ -111,7 +111,7 @@ public static IModuleBuilder ToBuilder(this IModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static HeaderModuleBuilder ToBuilder(this HeaderModule entity) { @@ -122,7 +122,7 @@ public static HeaderModuleBuilder ToBuilder(this HeaderModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static SectionModuleBuilder ToBuilder(this SectionModule entity) { @@ -135,7 +135,7 @@ public static SectionModuleBuilder ToBuilder(this SectionModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ImageGroupModuleBuilder ToBuilder(this ImageGroupModule entity) { @@ -146,7 +146,7 @@ public static ImageGroupModuleBuilder ToBuilder(this ImageGroupModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ContainerModuleBuilder ToBuilder(this ContainerModule entity) { @@ -157,7 +157,7 @@ public static ContainerModuleBuilder ToBuilder(this ContainerModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ActionGroupModuleBuilder ToBuilder(this ActionGroupModule entity) { @@ -168,7 +168,7 @@ public static ActionGroupModuleBuilder ToBuilder(this ActionGroupModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ContextModuleBuilder ToBuilder(this ContextModule entity) { @@ -179,7 +179,7 @@ public static ContextModuleBuilder ToBuilder(this ContextModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static DividerModuleBuilder ToBuilder(this DividerModule _) { @@ -187,7 +187,7 @@ public static DividerModuleBuilder ToBuilder(this DividerModule _) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static FileModuleBuilder ToBuilder(this FileModule entity) { @@ -199,7 +199,7 @@ public static FileModuleBuilder ToBuilder(this FileModule entity) } /// - /// Converts the to an with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static AudioModuleBuilder ToBuilder(this AudioModule entity) { @@ -212,7 +212,7 @@ public static AudioModuleBuilder ToBuilder(this AudioModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static VideoModuleBuilder ToBuilder(this VideoModule entity) { @@ -224,7 +224,7 @@ public static VideoModuleBuilder ToBuilder(this VideoModule entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static CountdownModuleBuilder ToBuilder(this CountdownModule entity) { @@ -237,7 +237,7 @@ public static CountdownModuleBuilder ToBuilder(this CountdownModule entity) } /// - /// Converts the to an with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static InviteModuleBuilder ToBuilder(this InviteModule entity) { @@ -252,7 +252,7 @@ public static InviteModuleBuilder ToBuilder(this InviteModule entity) #region Cards /// - /// Converts the to an with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static ICardBuilder ToBuilder(this ICard entity) { @@ -264,7 +264,7 @@ public static ICardBuilder ToBuilder(this ICard entity) } /// - /// Converts the to a with the same properties. + /// 将 实体转换为具有相同属性的 实体构建器。 /// public static CardBuilder ToBuilder(this Card entity) { diff --git a/src/Kook.Net.Core/Extensions/ChannelExtensions.cs b/src/Kook.Net.Core/Extensions/ChannelExtensions.cs index 0216922c..2488d057 100644 --- a/src/Kook.Net.Core/Extensions/ChannelExtensions.cs +++ b/src/Kook.Net.Core/Extensions/ChannelExtensions.cs @@ -1,15 +1,15 @@ namespace Kook; /// -/// Provides extension methods for . +/// 提供用于各种频道实体的扩展方法。 /// public static class ChannelExtensions { /// - /// Attempts to get the based off of the channel's interfaces. + /// 尝试基于频道所实现的接口类型获取频道的实际类型。 /// - /// The channel to get the type of. - /// The of the channel if found, otherwise null. + /// 要获取其类型的频道。 + /// 如果此频道的实际类型已知,则返回其类型;否则,返回 null public static ChannelType? GetChannelType(this IChannel channel) => channel switch { @@ -21,12 +21,10 @@ public static class ChannelExtensions }; /// - /// Gets a URL that jumps to the channel. + /// 获取一个跳转到频道的 URL。 /// - /// The channel to jump to. - /// - /// A string that contains a URL for jumping to the message in chat. - /// + /// 要获取跳转 URL 的频道。 + /// 一个包含用于在聊天中跳转到频道的 URL 的字符串。 public static string GetJumpUrl(this IChannel channel) => channel switch { diff --git a/src/Kook.Net.Core/Extensions/MessageExtensions.cs b/src/Kook.Net.Core/Extensions/MessageExtensions.cs index 06b65770..860c95f8 100644 --- a/src/Kook.Net.Core/Extensions/MessageExtensions.cs +++ b/src/Kook.Net.Core/Extensions/MessageExtensions.cs @@ -1,17 +1,15 @@ namespace Kook; /// -/// Provides extension methods for . +/// 提供用于各种消息实体的扩展方法。 /// public static class MessageExtensions { /// - /// Gets a URL that jumps to the message. + /// 获取一个跳转到消息的 URL。 /// - /// The message to jump to. - /// - /// A string that contains a URL for jumping to the message in chat. - /// + /// 要获取跳转 URL 的消息。 + /// 一个包含用于在聊天中跳转到消息的 URL 的字符串。 public static string GetJumpUrl(this IMessage msg) { IMessageChannel channel = msg.Channel; @@ -24,26 +22,16 @@ public static string GetJumpUrl(this IMessage msg) } /// - /// Add multiple reactions to a message. + /// 向消息添加多个回应。 /// /// - /// This method does not bulk add reactions! It will send a request for each reaction included. + /// 此方法会对每个要添加的回应分别发送请求。 /// - /// - /// - /// IEmote a = new Emoji("🅰"); - /// IEmote b = new Emoji("🅱"); - /// await msg.AddReactionsAsync([a, b]); - /// - /// - /// The message to add reactions to. - /// An array of reactions to add to the message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for adding a reaction to this message. - /// - /// - /// + /// 要添加回应的消息。 + /// 要用于向此消息添加回应的所有表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示异步添加操作的任务。 + /// public static async Task AddReactionsAsync(this IUserMessage msg, IEnumerable reactions, RequestOptions? options = null) { @@ -52,25 +40,17 @@ public static async Task AddReactionsAsync(this IUserMessage msg, IEnumerable - /// Remove multiple reactions from a message. + /// 移除消息上的多个回应。 ///
/// - /// This method does not bulk remove reactions! It will send a request for each reaction included. + /// 此方法会对每个要移除的回应分别发送请求。 /// - /// - /// - /// await msg.RemoveReactionsAsync(currentUser, [A, B]); - /// - /// - /// The message to remove reactions from. - /// The user who removed the reaction. - /// An array of reactions to remove from the message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for removing a reaction to this message. - /// - /// - /// + /// 要添加回应的消息。 + /// 要删除其回应的用户。 + /// 要从此消息移除的回应的所有表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除操作的任务。 + /// public static async Task RemoveReactionsAsync(this IUserMessage msg, IUser user, IEnumerable reactions, RequestOptions? options = null) { @@ -79,15 +59,15 @@ public static async Task RemoveReactionsAsync(this IUserMessage msg, IUser user, } /// - /// Sends an inline reply of file that references a message. + /// 向消息所属的频道回复文件消息。 /// - /// The message that is being replied on. - /// The file path of the file. - /// The name of the file. - /// The type of the file. - /// true if the source message will be quoted in this message; otherwise, false. - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// The options to be used when sending the request. + /// 要回复的消息。 + /// 文件的路径。 + /// 文件名。 + /// 文件的媒体类型。 + /// 是否在回复消息时引用被回复的消息。 + /// 是否以临时消息的方式回复。如果设置为 true,则仅该被回复的消息的作者可以看到此回复消息,否则所有人都可以看到此回复消息。 + /// 发送请求时要使用的选项。 public static async Task> ReplyFileAsync(this IUserMessage message, string path, string? filename = null, AttachmentType type = AttachmentType.File, bool isQuote = false, bool isEphemeral = false, RequestOptions? options = null) => @@ -98,15 +78,15 @@ await message.Channel.SendFileAsync(path, filename, type, .ConfigureAwait(false); /// - /// Sends an inline reply of file that references a message. + /// 向消息所属的频道回复文件消息。 /// - /// The message that is being replied on. - /// Stream of the file to be sent. - /// The name of the file. - /// The type of the file. - /// true if the source message will be quoted in this message; otherwise, false. - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// The options to be used when sending the request. + /// 要回复的消息。 + /// 文件的流。 + /// 文件名。 + /// 文件的媒体类型。 + /// 是否在回复消息时引用被回复的消息。 + /// 是否以临时消息的方式回复。如果设置为 true,则仅该被回复的消息的作者可以看到此回复消息,否则所有人都可以看到此回复消息。 + /// 发送请求时要使用的选项。 public static async Task> ReplyFileAsync(this IUserMessage message, Stream stream, string filename, AttachmentType type = AttachmentType.File, bool isQuote = false, bool isEphemeral = false, RequestOptions? options = null) => @@ -117,13 +97,13 @@ await message.Channel.SendFileAsync(stream, filename, type, .ConfigureAwait(false); /// - /// Sends an inline reply of file that references a message. + /// 向消息所属的频道回复文件消息。 /// - /// The message that is being replied on. - /// The attachment containing the file. - /// true if the source message will be quoted in this message; otherwise, false. - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// The options to be used when sending the request. + /// 要回复的消息。 + /// 文件的附件信息。 + /// 是否在回复消息时引用被回复的消息。 + /// 是否以临时消息的方式回复。如果设置为 true,则仅该被回复的消息的作者可以看到此回复消息,否则所有人都可以看到此回复消息。 + /// 发送请求时要使用的选项。 public static async Task> ReplyFileAsync(this IUserMessage message, FileAttachment attachment, bool isQuote = false, bool isEphemeral = false, RequestOptions? options = null) => await message.Channel.SendFileAsync(attachment, @@ -133,13 +113,13 @@ await message.Channel.SendFileAsync(attachment, .ConfigureAwait(false); /// - /// Sends an inline reply of text that references a message. + /// 向消息所属的频道回复文字消息。 /// - /// The message that is being replied on. + /// 要回复的消息。 /// Contents of the message. - /// true if the source message will be quoted in this message; otherwise, false. - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// The request options for this async request. + /// 是否在回复消息时引用被回复的消息。 + /// 是否以临时消息的方式回复。如果设置为 true,则仅该被回复的消息的作者可以看到此回复消息,否则所有人都可以看到此回复消息。 + /// 发送请求时要使用的选项。 public static async Task> ReplyTextAsync(this IUserMessage message, string content, bool isQuote = false, bool isEphemeral = false, RequestOptions? options = null) => await message.Channel.SendTextAsync(content, @@ -149,13 +129,13 @@ await message.Channel.SendTextAsync(content, .ConfigureAwait(false); /// - /// Sends a card message to the source channel. + /// 向消息所属的频道回复卡片消息。 /// - /// The message that is being replied on. - /// The cards to be sent. - /// true if the source message will be quoted in this message; otherwise, false. - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// The request options for this async request. + /// 要回复的消息。 + /// 要发送的卡片。 + /// 是否在回复消息时引用被回复的消息。 + /// 是否以临时消息的方式回复。如果设置为 true,则仅该被回复的消息的作者可以看到此回复消息,否则所有人都可以看到此回复消息。 + /// 发送请求时要使用的选项。 public static async Task> ReplyCardsAsync(this IUserMessage message, IEnumerable cards, bool isQuote = false, bool isEphemeral = false, RequestOptions? options = null) => await message.Channel.SendCardsAsync(cards, @@ -165,13 +145,13 @@ await message.Channel.SendCardsAsync(cards, .ConfigureAwait(false); /// - /// Sends a card message to the source channel. + /// 向消息所属的频道回复卡片消息。 /// - /// The message that is being replied on. - /// The card to be sent. - /// true if the source message will be quoted in this message; otherwise, false. - /// true if the message to be sent can be seen only by the command invoker; otherwise, false. - /// The request options for this async request. + /// 要回复的消息。 + /// 要发送的卡片。 + /// 是否在回复消息时引用被回复的消息。 + /// 是否以临时消息的方式回复。如果设置为 true,则仅该被回复的消息的作者可以看到此回复消息,否则所有人都可以看到此回复消息。 + /// 发送请求时要使用的选项。 public static async Task> ReplyCardAsync(this IUserMessage message, ICard card, bool isQuote = false, bool isEphemeral = false, RequestOptions? options = null) => await message.Channel.SendCardAsync(card, @@ -181,10 +161,10 @@ await message.Channel.SendCardAsync(card, .ConfigureAwait(false); /// - /// Gets whether the message may be a text image mixed message. + /// 获取此消息是否可能是图文混排消息。 /// - /// The message to check against. - /// true if the message may be a text image mixed message; otherwise, false. + /// 要判断的消息。 + /// 如果此消息可能是图文混排消息,则为 true;否则为 false public static bool MaybeTextImageMixedMessage(this IUserMessage msg) { if (msg.Cards.Count != 1) return false; diff --git a/src/Kook.Net.Core/Extensions/UserExtensions.cs b/src/Kook.Net.Core/Extensions/UserExtensions.cs index a4d2bed6..72e5895e 100644 --- a/src/Kook.Net.Core/Extensions/UserExtensions.cs +++ b/src/Kook.Net.Core/Extensions/UserExtensions.cs @@ -1,17 +1,20 @@ namespace Kook; -/// An extension class for various Kook user objects. +/// +/// 提供用于各种用户实体的扩展方法。 +/// public static class UserExtensions { /// - /// Sends a file via DM. + /// 通过私聊发送文件。 /// - /// The user to send the DM to. - /// The file path of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// The options to be used when sending the request. + /// 要发送消息的用户。 + /// 文件的路径。 + /// 文件名。 + /// 文件的媒体类型。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 public static async Task> SendFileAsync(this IUser user, string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null) @@ -21,14 +24,15 @@ public static async Task> SendFileAsync(this IUser } /// - /// Sends a file via DM. + /// 通过私聊发送文件。 /// - /// The user to send the DM to. - /// The stream of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// The options to be used when sending the request. + /// 要发送消息的用户。 + /// 文件的流。 + /// 文件名。 + /// 文件的媒体类型。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 public static async Task> SendFileAsync(this IUser user, Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null) @@ -38,12 +42,13 @@ public static async Task> SendFileAsync(this IUser } /// - /// Sends a file via DM. + /// 通过私聊发送文件。 /// - /// The user to send the DM to. - /// The attachment containing the file. - /// The message quote to be included. Used to reply to specific messages. - /// The options to be used when sending the request. + /// 要发送消息的用户。 + /// 文件的附件信息。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 public static async Task> SendFileAsync(this IUser user, FileAttachment attachment, IQuote? quote = null, RequestOptions? options = null) { @@ -52,12 +57,13 @@ public static async Task> SendFileAsync(this IUser } /// - /// Sends a text message via DM. + /// 通过私聊发送文本消息。 /// - /// The user to send the DM to. + /// 要发送消息的用户。 /// The KMarkdown content to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// The options to be used when sending the request. + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 public static async Task> SendTextAsync(this IUser user, string content, IQuote? quote = null, RequestOptions? options = null) { @@ -66,12 +72,13 @@ public static async Task> SendTextAsync(this IUser } /// - /// Sends a card message message via DM. + /// 通过私聊发送卡片消息。 /// - /// The user to send the DM to. - /// The cards to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// The request options for this async request. + /// 要发送消息的用户。 + /// 要发送的卡片。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 public static async Task> SendCardsAsync(this IUser user, IEnumerable cards, IQuote? quote = null, RequestOptions? options = null) { @@ -80,12 +87,13 @@ public static async Task> SendCardsAsync(this IUse } /// - /// Sends a card message message via DM. + /// 通过私聊发送卡片消息。 /// - /// The user to send the DM to. - /// The card to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// The request options for this async request. + /// 要发送消息的用户。 + /// 要发送的卡片。 + /// 消息引用,用于回复消息。 + /// 发送请求时要使用的选项。 + /// 一个表示异步发送操作的任务。任务的结果包含所发送消息的可延迟加载的消息对象。 public static async Task> SendCardAsync(this IUser user, ICard card, IQuote? quote = null, RequestOptions? options = null) { @@ -94,16 +102,14 @@ public static async Task> SendCardAsync(this IUser } /// - /// Bans the user from the guild and optionally prunes their recent messages. + /// 封禁服务器内的用户。 /// - /// The user to ban. - /// The number of days to remove messages from this for - must be between [0, 7] - /// The reason of the ban to be written in the audit log. - /// The options to be used when sending the request. - /// is not between 0 to 7. - /// - /// A task that represents the asynchronous operation for banning a user. - /// + /// 要封禁的用户。 + /// 要删除此服务器中来自此用户的最近几天的消息,范围为 070 表示不删除。 + /// 封禁原因。 + /// 发送请求时要使用的选项。 + /// 超出了 0 至 7 的范围。 + /// 一个表示异步封禁操作的任务。 public static Task BanAsync(this IGuildUser user, int pruneDays = 0, string? reason = null, RequestOptions? options = null) => user.Guild.AddBanAsync(user, pruneDays, reason, options); diff --git a/src/Kook.Net.Core/Format.cs b/src/Kook.Net.Core/Format.cs index 7a4d777c..e566af63 100644 --- a/src/Kook.Net.Core/Format.cs +++ b/src/Kook.Net.Core/Format.cs @@ -5,97 +5,106 @@ namespace Kook; /// -/// A helper class for formatting characters. +/// 提供用于格式化字符的帮助类。 /// public static class Format { private static readonly string[] SensitiveCharacters = ["\\", "*", "~", "`", ":", "-", "]", ")", ">"]; - /// Returns a markdown-formatted string with bold formatting. - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted text. + /// + /// 返回一个使用粗体格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// * with \*. + /// 设置 true 将会对文本中出现的所有 * 字符转义为 \*。 /// public static string Bold(this string? text, bool sanitize = true) => $"**{(sanitize ? text.Sanitize("*") : text)}**"; - /// Returns a markdown-formatted string with italics formatting. - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted text. + /// + /// 返回一个使用斜体格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// * with \*. + /// 设置 true 将会对文本中出现的所有 * 字符转义为 \*。 /// public static string Italics(this string? text, bool sanitize = true) => $"*{(sanitize ? text.Sanitize("*") : text)}*"; - /// Returns a markdown-formatted string with bold italics formatting. - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted text. + /// + /// 返回一个使用粗斜体格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// * with \*. + /// 设置 true 将会对文本中出现的所有 * 字符转义为 \*。 /// public static string BoldItalics(this string? text, bool sanitize = true) => $"***{(sanitize ? text.Sanitize("*") : text)}***"; - /// Returns a markdown-formatted string with strike-through formatting. - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted text. + /// + /// 返回一个使用删除线格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// ~ with \~. + /// 设置 true 将会对文本中出现的所有 ~ 字符转义为 \~。 /// public static string Strikethrough(this string? text, bool sanitize = true) => $"~~{(sanitize ? text.Sanitize("~") : text)}~~"; - /// Returns a markdown-formatted string colored with the specified . - /// The text to colorize. - /// The theme to colorize the text with. - /// Whether to sanitize the text. - /// Gets the colorized text. + /// + /// 返回一个使用彩色文本格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 要应用的文本颜色。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// /// - /// Colored text is only supported in cards. + /// 目前,KOOK 仅支持在卡片消息中使用 KMarkdown 彩色文本格式。 /// /// /// - /// Set to true will sanitize the text by replacing all occurrences of - /// ( and ) with \( and \). + /// 设置 true 将会对文本中出现的所有 () + /// 字符转分别义为 \(\)。 /// public static string Colorize(this string? text, TextTheme theme, bool sanitize = true) => $"(font){(sanitize ? text.Sanitize("(", ")") : text)}(font)[{theme.ToString().ToLowerInvariant()}]"; - /// Returns a markdown-formatted URL. - /// The text to format. - /// The URL to format. - /// Whether to sanitize the text and URL. - /// Gets the formatted URL. + /// + /// 返回格式化后的 KMarkdown 链接。 + /// + /// 要格式化的文本。 + /// 要链接到的 URL。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的链接文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// [ and ] with \[ and \], and the URL by replacing all occurrences of - /// ( and ) with \( and \). + /// 设置 true 将会对文本中出现的所有 [] 字符分别转义为 + /// \[\],并对 URL 中出现的所有 () 字符分别转义为 \(\)。 /// public static string Url(this string? text, string url, bool sanitize = true) => $"[{(sanitize ? text.Sanitize("[", "]") : text)}]({(sanitize ? url.Sanitize("(", ")") : url)})"; - /// + /// public static string Url(this string? text, Uri url, bool sanitize = true) => text.Url(url.ToString(), sanitize); - /// Sanitizes the string, safely escaping any Markdown sequences. - /// The text to sanitize. - /// The characters to sanitize. - /// Gets the sanitized text. + /// + /// 转义字符串,安全地转义任何 KMarkdown 序列。 + /// + /// 要转义的文本。 + /// 要转义的字符。 + /// 获取转义后的文本。 /// - /// If no sensitive characters are specified, the default sensitive characters are used. - /// The default sensitive characters are: \, *, ~, `, :, -, ], ), >. + /// 如果未指定要转移的字符,则将使用默认的转义字符列表。默认的待转义字符包括:
+ /// \*~`:-])>。 ///
[return: NotNullIfNotNull(nameof(text))] public static string? Sanitize(this string? text, params string[] sensitiveCharacters) @@ -107,31 +116,26 @@ public static string Url(this string? text, Uri url, bool sanitize = true) => } /// - /// Formats a string as split quotes seperated by multiple new lines. + /// 将字符串格式化为由多个换行符分隔的引用字符串。 /// - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted quote text. + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的引用文本。 /// + /// 此方法尽可能地保持字符串在 KOOK 中的渲染排版,保留换行与空格,各个文本块会被分别引用。
/// - /// Due to the mechanism of the KOOK KMarkdown renderer, this method recognizes multiple text blocks - /// based on two or more consecutive line breaks, and formats each block as a quote. For each text block, - /// a greater than sign (>) and a space is inserted at the beginning of the string, and a - /// zero-width joiner (\u200d) is inserted when the beginning of the block is a whitespace - /// character, to ensure proper display of the quote. When the user copies the text inside - /// the quote, they will not copy this special character. However, if you obtain the - /// message text from the server through message-related APIs, it will contain the - /// special character inserted by this method. An additional line break is also appended - /// at the end of the block to correct any missing line breaks caused by the quote formatting. - /// The appended line break is consistent with the style of the nearby line breaks. - /// To quote the entire text as a whole, use instead. + /// 此方法会将两个或更多连续的换行符识别多个独立文本块,并将每个块分别格式化为引用块。 + /// 对于每个文本块,在字符串的开头插入一个大于号 (>) 和一个空格;如果块的开头是一个空白字符,则还会插入一个 + /// 零宽连接符 (\u200d),以确保引用的正确显示。当用户复制引用内的文本时,他们不会复制到这个特殊字符。 + /// 但是,如果通过消息相关的 API 从服务器获取消息文本,返回的消息文本将包含此方法插入的特殊字符。 + /// 另外,在块的末尾还会附加一个额外的换行符,以修正由于引用格式化引起的换行缺失问题。附加的换行符与附近的换行符样式一致。 + /// 如果要引用整个文本块,请使用 。 /// - /// - /// Set to true will sanitize the text by replacing all occurrences of - /// > with \>. - /// + ///
+ /// 此方法会尝试分析字符串中的行分隔符,并在需要因要保持排版时插入行分隔符时,尽可能地使用原有的行分隔符。
+ /// 设置 true 将会对文本中出现的所有 > 字符转义为 \>。 ///
- /// + /// [return: NotNullIfNotNull(nameof(text))] public static string? Quote(this string? text, bool sanitize = true) { @@ -234,40 +238,48 @@ public static string Url(this string? text, Uri url, bool sanitize = true) => return result.ToString(); } - /// Returns a markdown-formatted string with underline formatting. - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted underlined text. + /// + /// 返回一个使用下划线格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// ( and ) with \( and \). + /// 设置 true 将会对文本中出现的所有 () 字符分别转义为 + /// \(\)。 /// public static string Underline(this string? text, bool sanitize = true) => $"(ins){(sanitize ? text.Sanitize("(", ")") : text)}(ins)"; - /// Returns a string with spoiler formatting. - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted spoiled text. + /// + /// 返回一个使用剧透格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的文本。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// ( and ) with \( and \). + /// 设置 true 将会对文本中出现的所有 () 字符分别转义为 + /// \(\)。 /// public static string Spoiler(this string? text, bool sanitize = true) => $"(spl){(sanitize ? text.Sanitize("(", ")") : text)}(spl)"; - /// Returns a markdown-formatted string with inline code or code block formatting. - /// The text to format. - /// The language of the code block. - /// Whether to sanitize the text. - /// Gets the formatted inline code or code block. + /// + /// 返回一个使用代码格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 代码块的语言。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的内联代码或代码块。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// ` with \`. + /// 设置 true 将会对文本中出现的所有 ` 字符转义为 \`
+ /// 当 不为 null 中包含换行符时,将返回一个代码块; + /// 否则,将返回一个内联代码块。 ///
public static string Code(this string? text, string? language = null, bool sanitize = true) { - if (text is null) return "`\u200d`"; + if (text is null) + return "`\u200d`"; string? newLine = null; int length = text.Length; @@ -286,14 +298,15 @@ public static string Code(this string? text, string? language = null, bool sanit return $"`{(sanitize ? text.Sanitize("`") : text)}`"; } - /// Returns a markdown-formatted string with code block formatting. - /// The text to format. - /// The language of the code block. - /// Whether to sanitize the text. - /// Gets the formatted code block. + /// + /// 返回一个使用代码块格式的 KMarkdown 格式化字符串。 + /// + /// 要格式化的文本。 + /// 代码块的语言。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的代码块。 /// - /// Set to true will sanitize the text by replacing all occurrences of - /// ` with \`. + /// 设置 true 将会对文本中出现的所有 ` 字符转义为 \`。 /// public static string CodeBlock(this string? text, string? language = null, bool sanitize = true) { @@ -313,30 +326,22 @@ public static string CodeBlock(this string? text, string? language = null, bool return $"```{language ?? ""}{newLine ?? "\n"}{(sanitize ? text.Sanitize("`") : text)}{newLine ?? "\n"}```"; } - /// - /// Formats a string as a block quote as a whole. + /// 返回一个使用引用块格式的 KMarkdown 格式化字符串。 /// - /// The text to format. - /// Whether to sanitize the text. - /// Gets the formatted block quote text. + /// 要格式化的文本。 + /// 是否要先对 中与当前格式化操作有冲突的字符进行转义。 + /// 获取格式化后的引用文本。 /// /// - /// Due to the working mechanism of the KOOK KMarkdown renderer, this method will - /// insert zero-width joiner special characters (\u200d) before the first empty line - /// and between each empty line in the text by default, so that the renderer can - /// display the entire text as a single quote. When the user copies the text inside - /// the quote, they will not copy this special character. However, if you obtain the - /// message text from the server through message-related APIs, it will contain the - /// special character inserted by this method. If you want to disable this feature, - /// please use instead. + /// 此方法默认会在文本中的第一个空行之前和每个空行之间插入零宽连接符特殊字符 (\u200d),以便渲染器能够将整个文本显示为单个引用。 + /// 当用户复制引用内的文本时,他们不会复制这个特殊字符。但是,如果通过消息相关的 API 从服务器获取消息文本, + /// 它将包含此方法插入的特殊字符。 /// - /// - /// Set to true will sanitize the text by replacing - /// all occurrences of > with \>. - /// + ///
+ /// 设置 true 将会对文本中出现的所有 > 字符转义为 \>。 ///
- /// + /// public static string BlockQuote(this string? text, bool sanitize = true) { if (text is null) return "> \u200d"; @@ -368,20 +373,25 @@ public static string BlockQuote(this string? text, bool sanitize = true) public static string StripMarkDown(this string text) => StripMarkdown(text); /// - /// Remove Kook supported markdown from text. + /// 移除文本中的 KMarkdown 格式字符。 /// - /// The text to remove markdown from. - /// Gets the unformatted text. + /// 要移除 KMarkdown 格式字符的文本。 + /// 获取移除 KMarkdown 格式字符后的文本。 + /// + /// 此方法不会过多地分析 KMarkdown 的复杂格式,只会简单地移除 KMarkdown 中的以下字符:
+ /// *(ins)(spl)`~>\、连续两个或更多地 -。 + ///
public static string StripMarkdown(this string text) => // Remove KOOK supported markdown Regex.Replace(text, @"\*|\(ins\)|\(spl\)|`|~|>|\\|-{2,}", "", RegexOptions.Compiled); /// - /// Formats a user's username + identify number while maintaining bidirectional unicode + /// 保持双向 Unicode 格式化的情况下格式化用户的用户名称 + 识别号。 /// - /// The user whose username and identify number to format. - /// To format the string in bidirectional unicode or not. - /// The username#identifyNumber. + /// 要格式化其用户名称与识别号的用户。 + /// 是否要保持双向 Unicode 进行格式化。 + /// 获取格式化后的用户名称与识别号。 + /// public static string UsernameAndIdentifyNumber(this IUser user, bool doBidirectional) => doBidirectional ? $"\u2066{user.Username}\u2069#{user.IdentifyNumber}" diff --git a/src/Kook.Net.Core/IKookClient.cs b/src/Kook.Net.Core/IKookClient.cs index 4c8d6280..f0773fbc 100644 --- a/src/Kook.Net.Core/IKookClient.cs +++ b/src/Kook.Net.Core/IKookClient.cs @@ -1,94 +1,100 @@ namespace Kook; /// -/// Represents a generic Kook client. +/// 表示一个通用的 KOOK 客户端。 /// public interface IKookClient : IDisposable { #region General /// - /// Gets the current state of connection. + /// 获取当前连接的状态。 /// ConnectionState ConnectionState { get; } /// - /// Gets the currently logged-in user. + /// 获取当前已登录的用户;如果没有用户登录,则为 null。 /// ISelfUser? CurrentUser { get; } /// - /// Gets the token type of the logged-in user. + /// 获取已登录用户的令牌类型。 /// TokenType TokenType { get; } /// - /// Starts the connection between Kook and the client.. + /// 启动客户端与 KOOK 之间的连接。 /// /// - /// This method will initialize the connection between the client and Kook. + /// 当前方法会初始化客户端与 KOOK 之间的连接。
/// - /// This method will immediately return after it is called, as it will initialize the connection on - /// another thread. + /// 此方法会在调用后立即返回,因为它会在另一个线程上初始化连接。 /// ///
- /// - /// A task that represents the asynchronous start operation. - /// + /// 一个表示异步启动操作的任务。 Task StartAsync(); /// - /// Stops the connection between Kook and the client. + /// 停止客户端与 KOOK 之间的连接。 /// - /// - /// A task that represents the asynchronous stop operation. - /// + /// 一个表示异步停止操作的任务。 Task StopAsync(); + /// + /// 登录到 KOOK API。 + /// + /// 要使用的令牌类型。 + /// 要使用的令牌。 + /// 是否验证令牌。 + /// 一个表示异步登录操作的任务。 + /// + /// 验证令牌的操作是通过 方法完成的。
+ /// 此方法用于向当前客户端设置后续 API 请求的身份验证信息,获取并设置当前所登录用户的信息。 + ///
+ Task LoginAsync(TokenType tokenType, string token, bool validateToken = true); + + /// + /// 从 KOOK API 退出登录。 + /// + /// 一个表示异步退出登录操作的任务。 + /// + /// 此方法用于清除当前客户端的身份验证信息及所缓存的当前所登录的用户信息。 + /// + Task LogoutAsync(); + #endregion #region Channels /// - /// Gets a generic channel. + /// 获取一个频道。 /// - /// The identifier of the channel. - /// 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 channel associated - /// with the identifier; null when the channel cannot be found. - /// + /// 频道的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的频道;若指定 ID 的频道不存在,则为 null Task GetChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a direct message channel. + /// 获取一个私聊频道。 /// - /// The identifier of the channel. - /// 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 a read-only collection - /// of direct-message channels that the user currently partakes in. - /// + /// 私聊频道的聊天代码。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定聊天代码的私聊频道;若指定聊天代码的私聊频道不存在,则为 null Task GetDMChannelAsync(Guid chatCode, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of direct message channels opened in this session. + /// 获取当前会话中已创建的所有私聊频道。 /// /// - /// This method returns a collection of currently opened direct message channels. /// - /// This method will not return previously opened DM channels outside of the current session! If you - /// have just started the client, this may return an empty collection. + /// 此方法不会返回当前会话之外已创建的私聊频道。如果客户端刚刚启动,这可能会返回一个空集合。 /// /// - /// 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 a read-only collection - /// of direct-message channels that the user currently partakes in. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是当前会话中已创建的所有私聊频道。 Task> GetDMChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion @@ -96,26 +102,20 @@ public interface IKookClient : IDisposable #region Guilds /// - /// Gets a guild. + /// 获取一个服务器。 /// - /// The guild identifier. - /// 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 guild associated - /// with the identifier; null when the guild cannot be found. - /// + /// 服务器的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的服务器;若指定 ID 的服务器不存在,则为 null Task GetGuildAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a collection of guilds that the user is currently in. + /// 获取当前用户所在的所有服务器。 /// - /// 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 a read-only collection - /// of guilds that the current user is in. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是当前用户所在的所有服务器。 Task> GetGuildsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion @@ -123,27 +123,21 @@ public interface IKookClient : IDisposable #region Users /// - /// Gets a user. + /// 获取一个用户。 /// - /// The identifier of the user. - /// 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 user associated with - /// the identifier; null if the user is not found. - /// + /// 用户的 ID。 + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的用户;若指定 ID 的用户不存在,则为 null Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets a user. + /// 获取一个用户。 /// - /// The name of the user (e.g. `Still`). - /// The identify value of the user (e.g. `2876`). - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the user associated with - /// the name and the identifyNumber; null if the user is not found. - /// + /// 用户的名称。 + /// 用户的识别号。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定的名称和识别号的用户;如果未找到该用户,则为 null Task GetUserAsync(string username, string identifyNumber, RequestOptions? options = null); #endregion @@ -151,36 +145,27 @@ public interface IKookClient : IDisposable #region Friends /// - /// Gets friends. + /// 获取所有好友。 /// - /// 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 a collection of users - /// that are friends with the current user. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有与当前用户是好友的用户。 Task> GetFriendsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets friend requests. + /// 获取所有好友请求。 /// - /// 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 a collection of users - /// that requested to be friends with the current user. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有请求与当前用户成为好友的用户。 Task> GetFriendRequestsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); /// - /// Gets blocked users. + /// 获取所有被当前用户屏蔽的用户。 /// - /// 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 a collection of users - /// that are blocked by the current user. - /// + /// 指示当前方法是否应该仅从缓存中获取结果,还是可以通过 API 请求获取数据。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有被当前用户屏蔽的用户。 Task> GetBlockedUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null); #endregion diff --git a/src/Kook.Net.Core/KookConfig.cs b/src/Kook.Net.Core/KookConfig.cs index 92afbc91..60238cb8 100644 --- a/src/Kook.Net.Core/KookConfig.cs +++ b/src/Kook.Net.Core/KookConfig.cs @@ -3,194 +3,142 @@ namespace Kook; /// -/// Defines various behaviors of Kook.Net. +/// 定义 Kook.Net 各种基础行为的配置项。 /// public class KookConfig { /// - /// Returns the API version Kook.Net uses. + /// 获取 Kook.Net 使用的 API 版本。 /// - /// - /// An int representing the API version that Kook.Net uses to communicate with Kook. - /// A list of available API version can be seen on the official - /// Kook API documentation - /// . - /// public const int APIVersion = 3; /// - /// Returns the Voice API version Kook.Net uses. + /// 获取 Kook.Net 用于与 KOOK 的语音服务器通信的 API 版本。 /// - /// - /// An representing the API version that Kook.Net uses to communicate with KOOK's - /// voice server. - /// public const int VoiceAPIVersion = 1; /// - /// Gets the Kook.Net version, including the build number. + /// 获取 Kook.Net 的版本,包括构建号。 /// - /// - /// A string containing the detailed version information, including its build number; Unknown when - /// the version fails to be fetched. - /// + /// 一个包含详细版本信息的字符串,包括构建号;当无法获取构建版本时为 Unknown public static string Version { get; } = typeof(KookConfig).GetTypeInfo().Assembly.GetCustomAttribute()?.InformationalVersion ?? typeof(KookConfig).GetTypeInfo().Assembly.GetName().Version?.ToString(3) ?? "Unknown"; /// - /// Gets the user agent that Kook.Net uses in its clients. + /// 获取 Kook.Net 在每个请求中使用的用户代理。 /// - /// - /// The user agent used in each Kook.Net request. - /// public static string UserAgent { get; } = $"KookBot (https://github.com/gehongyan/Kook.Net, v{Version})"; /// - /// Gets the accept language that Kook.Net uses in its clients. + /// 获取 Kook.Net 在每个请求所设置 Accept-Language 请求标头,用于指定所偏好的自然语言和区域设置。 /// - /// - /// The accept language used in each Kook.Net request. - /// + /// + /// 可用值包括: + /// + /// zh-CN - 简体中文(中国) + /// en-US - 英语(美国) + /// + /// 要查阅最新支持的语言列表,请参阅 https://developer.kookapp.cn/doc/reference 中的 i18N 节。 + /// public string AcceptLanguage { get; set; } = "zh-CN"; /// - /// Returns the base Kook API URL. + /// 获取 KOOK API 请求的根 URL。 /// - /// - /// The Kook API URL using . - /// public static readonly string APIUrl = $"https://www.kookapp.cn/api/v{APIVersion}/"; /// - /// Returns the default timeout for requests. + /// 获取请求超时的默认时间,以毫秒为单位。 /// - /// - /// The amount of time it takes in milliseconds before a request is timed out. - /// public const int DefaultRequestTimeout = 6000; /// - /// Returns the max length for a Kook message. + /// 获取 KOOK 允许的消息的最大长度。 /// - /// - /// The maximum length of a message allowed by Kook. - /// - /// - /// - /// The accurate value of this property is not known. - /// It is set to int.MaxValue at current so that it does not work. - /// - /// public const int MaxMessageSize = 20000; /// - /// Returns the max users allowed to be in a request. + /// 获取 KOOK 允许在每个请求中获取的最大用户数。 /// - /// - /// The maximum number of users that can be gotten per-batch. - /// public const int MaxUsersPerBatch = 50; /// - /// Returns the max messages allowed to be in a request. + /// 获取 KOOK 允许在每个请求中获取的最大消息数。 /// - /// - /// The maximum number of messages that can be gotten per-batch. - /// public const int MaxMessagesPerBatch = 50; /// - /// Returns the max items allowed to be in a request by default. + /// 获取默认情况下每个请求允许获取的最大项目数。 /// - /// - /// The maximum number of items that can be gotten per-batch by default. - /// public const int MaxItemsPerBatchByDefault = 100; /// - /// Returns the min length for a Kook guild nickname. + /// 获取 KOOK 允许的服务器用户昵称的最小长度。 /// - /// - /// The minimum length of a nickname allowed by Kook. - /// public const int MinNicknameSize = 2; /// - /// Returns the max length for a Kook guild nickname. + /// 获取 KOOK 允许的服务器用户昵称的最大长度。 /// - /// - /// The maximum length of a nickname allowed by Kook. - /// public const int MaxNicknameSize = 64; /// - /// Returns the min value for a Kook intimacy score. + /// 获取 KOOK 允许的亲密度分数的最小值。 /// - /// - /// The minimum value of an intimacy score allowed by Kook. - /// public const int MinIntimacyScore = 0; /// - /// Returns the max value for a Kook intimacy score. + /// 获取 KOOK 允许的亲密度分数的最大值。 /// - /// - /// The maximum value of an intimacy score allowed by Kook. - /// public const int MaxIntimacyScore = 2200; /// - /// Returns the duration of a Kook boost pack. + /// 获取每个服务器助力包的生效时长。 /// public static readonly TimeSpan BoostPackDuration = TimeSpan.FromDays(30); /// - /// Gets or sets how a request should act in the case of an error, by default. + /// 获取或设置请求在出现错误时的默认行为。 /// - /// - /// The currently set . - /// + /// public RetryMode DefaultRetryMode { get; set; } = RetryMode.AlwaysRetry; /// - /// Gets or sets the default callback for rate limits. + /// 获取或设置默认的速率限制回调委托。 /// /// - /// This property is mutually exclusive with . + /// 若同时设置了此属性与用于各个请求的 ,则将优先使用 + /// 。 /// public Func? DefaultRatelimitCallback { get; set; } /// - /// Gets or sets the minimum log level severity that will be sent to the Log event. + /// 获取或设置将发送到日志事件的最低日志严重性级别。 /// - /// - /// The currently set for logging level. - /// public LogSeverity LogLevel { get; set; } = LogSeverity.Info; /// - /// Gets or sets whether the initial log entry should be printed. + /// 获取或设置是否应打印初次启动时要打印的日志。 /// /// - /// If set to true, the library will attempt to print the current version of the library, as well as - /// the API version it uses on startup. + /// 如果设置为 true,则将在启动时打印库的当前版本,以及所使用的 API 版本。 /// internal bool DisplayInitialLog { get; set; } = true; /// - /// Gets the user identifier of the author who sends system messages from Kook official. + /// 获取由 KOOK 官方发送系统消息的用户的 ID。 /// internal const ulong SystemMessageAuthorID = 3900775823; /// - /// Gets or sets if the Rest/Socket user override formats the string in respect to bidirectional unicode. + /// 获取或设置 Rest 或 Socket 用户实体的 重写方法在格式化字符串时是否考虑双向 Unicode。 /// /// - /// By default, the returned value will be "?Kook?#1234", to work with bidirectional usernames. - ///
- /// If set to false, this value will be "Kook#1234". + /// 默认地,为了支持双向用户名,格式化字符串中的用户名部分的左侧会插入左到右嵌入控制字符(\u2066), + /// 右侧会插入嵌入段结束控制字符(\u2069),以确保在显示时不会出现混乱。如需禁用此行为,请将此属性设置为 false。 ///
+ /// public bool FormatUsersInBidirectionalUnicode { get; set; } = true; } diff --git a/src/Kook.Net.Core/KookErrorCode.cs b/src/Kook.Net.Core/KookErrorCode.cs index b70f22a9..76196db1 100644 --- a/src/Kook.Net.Core/KookErrorCode.cs +++ b/src/Kook.Net.Core/KookErrorCode.cs @@ -1,82 +1,82 @@ namespace Kook; /// -/// Represents a set of json error codes received by Kook. +/// 表示从 KOOK 接收到的错误代码。 /// public enum KookErrorCode { /// - /// The operation was successful. + /// 操作成功。 /// Success = 0, /// - /// The operation failed due to an unspecified error. + /// 操作失败,原因未通过错误代码明确。 /// GeneralError = 40000, #region Hello /// - /// The operation failed due to an missing argument. + /// 操作由于缺少参数而失败。 /// MissingArgument = 40100, /// - /// The operation failed due to an invalid authentication token. + /// 操作由于无效的身份验证令牌而失败。 /// InvalidAuthenticationToken = 40101, /// - /// The operation failed because the authentication token verification failed. + /// 操作由于身份验证令牌验证失败而失败。 /// TokenVerificationFailed = 40102, /// - /// The operation failed because the authentication token has expired. + /// 操作由于身份验证令牌已过期而失败。 /// TokenExpired = 40103, #endregion /// - /// The operation failed because the request was too large. + /// 操作由于请求传输的实体过大而失败。 /// RequestEntityTooLarge = 40014, #region Reconnect /// - /// The KOOK gateway requested a reconnect due to missing resume arguments. + /// KOOK 网关由于缺少恢复参数而要求重新连接。 /// MissingResumeArgument = 40106, /// - /// The KOOK gateway requested a reconnect because the session has expired. + /// KOOK 网关由于会话已过期而要求重新连接。 /// SessionExpired = 40107, /// - /// The KOOK gateway requested a reconnect due to an invalid sequence number. + /// KOOK 网关由于无效的消息序号而要求重新连接。 /// InvalidSequenceNumber = 40108, #endregion /// - /// The operation failed due to missing permissions. + /// 操作由于缺少权限而失败。 /// MissingPermissions = 40300, #region Friends /// - /// The operation failed because the user has become a friend of the current user. + /// 操作由于用户已是当前用户的好友而失败。 /// HasBeenFriend = 42007, /// - /// The operation failed because the current user has requested to be friends with the user too fast. + /// 操作由于当前用户请求与用户成为好友过于频繁而失败。 /// RequestFriendTooFast = 42008, diff --git a/src/Kook.Net.Core/KookJsonError.cs b/src/Kook.Net.Core/KookJsonError.cs index add5bf18..ca954fe1 100644 --- a/src/Kook.Net.Core/KookJsonError.cs +++ b/src/Kook.Net.Core/KookJsonError.cs @@ -3,17 +3,17 @@ namespace Kook; /// -/// Represents a generic parsed json error received from Kook after performing a rest request. +/// 表示一个在执行 API 请求后从 KOOK 接收到的 JSON 数据中解析出的错误。 /// public struct KookJsonError { /// - /// Gets the json path of the error. + /// 获取错误的 JSON 路径。 /// public string Path { get; } /// - /// Gets a collection of errors associated with the specific property at the path. + /// 获取与路径上的特定属性关联的错误集合。 /// public IReadOnlyCollection Errors { get; } @@ -25,17 +25,17 @@ internal KookJsonError(string path, KookError[] errors) } /// -/// Represents an error with a property. +/// 表示一个 KOOK 返回的错误。 /// public struct KookError { /// - /// Gets the code of the error. + /// 获取错误的代码。 /// public string Code { get; } /// - /// Gets the message describing what went wrong. + /// 获取错误的原因。 /// public string Message { get; } diff --git a/src/Kook.Net.Core/Logging/LogManager.cs b/src/Kook.Net.Core/Logging/LogManager.cs index b02ff8d3..8ee2a56c 100644 --- a/src/Kook.Net.Core/Logging/LogManager.cs +++ b/src/Kook.Net.Core/Logging/LogManager.cs @@ -59,7 +59,6 @@ await _messageEvent.InvokeAsync(new LogMessage(severity, source, message.ToStrin } } - public Task ErrorAsync(string source, Exception? ex) => LogAsync(LogSeverity.Error, source, ex); public Task ErrorAsync(string source, string message, Exception? ex = null) => @@ -68,7 +67,6 @@ public Task ErrorAsync(string source, string message, Exception? ex = null) => public Task ErrorAsync(string source, FormattableString message, Exception? ex = null) => LogAsync(LogSeverity.Error, source, message, ex); - public Task WarningAsync(string source, Exception? ex) => LogAsync(LogSeverity.Warning, source, ex); public Task WarningAsync(string source, string message, Exception? ex = null) => @@ -77,7 +75,6 @@ public Task WarningAsync(string source, string message, Exception? ex = null) => public Task WarningAsync(string source, FormattableString message, Exception? ex = null) => LogAsync(LogSeverity.Warning, source, message, ex); - public Task InfoAsync(string source, Exception? ex) => LogAsync(LogSeverity.Info, source, ex); public Task InfoAsync(string source, string message, Exception? ex = null) => @@ -86,7 +83,6 @@ public Task InfoAsync(string source, string message, Exception? ex = null) => public Task InfoAsync(string source, FormattableString message, Exception? ex = null) => LogAsync(LogSeverity.Info, source, message, ex); - public Task VerboseAsync(string source, Exception? ex) => LogAsync(LogSeverity.Verbose, source, ex); public Task VerboseAsync(string source, string message, Exception? ex = null) => @@ -95,7 +91,6 @@ public Task VerboseAsync(string source, string message, Exception? ex = null) => public Task VerboseAsync(string source, FormattableString message, Exception? ex = null) => LogAsync(LogSeverity.Verbose, source, message, ex); - public Task DebugAsync(string source, Exception? ex) => LogAsync(LogSeverity.Debug, source, ex); public Task DebugAsync(string source, string message, Exception? ex = null) => diff --git a/src/Kook.Net.Core/Logging/LogMessage.cs b/src/Kook.Net.Core/Logging/LogMessage.cs index 562bd809..ea0da89d 100644 --- a/src/Kook.Net.Core/Logging/LogMessage.cs +++ b/src/Kook.Net.Core/Logging/LogMessage.cs @@ -3,50 +3,37 @@ namespace Kook; /// -/// Provides a message object used for logging purposes. +/// 表示一个用于记录日志的消息对象。 /// public readonly struct LogMessage { /// - /// Gets the severity of the log entry. + /// 获取日志记录的严重性。 /// - /// - /// A enum to indicate the severeness of the incident or event. - /// public LogSeverity Severity { get; } /// - /// Gets the source of the log entry. + /// 获取日志记录的来源。 /// - /// - /// A string representing the source of the log entry. - /// public string Source { get; } /// - /// Gets the message of this log entry. + /// 获取日志记录的消息。 /// - /// - /// A string containing the message of this log entry. - /// public string? Message { get; } /// - /// Gets the exception of this log entry. + /// 获取此日志条目的异常。 /// - /// - /// A object associated with an incident; otherwise null. - /// public Exception? Exception { get; } /// - /// Initializes a new struct with the severity, source, message of the event, and - /// optionally, an exception. + /// 使用事件的严重性、来源、消息和可选的异常初始化 结构。 /// - /// The severity of the event. - /// The source of the event. - /// The message of the event. - /// The exception of the event. + /// 事件的严重性。 + /// 事件的来源。 + /// 事件的消息。 + /// 事件的异常。 public LogMessage(LogSeverity severity, string source, string? message, Exception? exception = null) { Severity = severity; @@ -56,20 +43,20 @@ public LogMessage(LogSeverity severity, string source, string? message, Exceptio } /// - /// Returns a string representation of this log message. + /// 返回此日志消息的字符串表示形式。 /// - /// A string representation of this log message. + /// 此日志消息的字符串表示形式。 public override string ToString() => ToString(); /// - /// Returns a string representation of this log message. + /// 返回此日志消息的字符串表示形式。 /// - /// The string builder to use. - /// Whether to include the full exception in the string. - /// Whether to prepend the timestamp to the string. - /// The kind of timestamp to use. - /// The amount of padding to use for the source. - /// A string representation of this log message. + /// 要使用的字符串构建器。 + /// 是否在字符串中包含完整的异常信息。 + /// 是否在字符串前添加时间戳。 + /// 要使用的时间戳类型。 + /// 源字符串的填充量。 + /// 此日志消息的字符串表示形式。 public string ToString(StringBuilder? builder = null, bool fullException = true, bool prependTimestamp = true, DateTimeKind timestampKind = DateTimeKind.Local, int? padSource = 11) { diff --git a/src/Kook.Net.Core/Logging/LogSeverity.cs b/src/Kook.Net.Core/Logging/LogSeverity.cs index abda942b..6e3ceaa3 100644 --- a/src/Kook.Net.Core/Logging/LogSeverity.cs +++ b/src/Kook.Net.Core/Logging/LogSeverity.cs @@ -1,38 +1,37 @@ namespace Kook; /// -/// Specifies the severity of the log message. +/// 表示日志消息的严重性。 /// public enum LogSeverity { /// - /// Logs that contain the most severe level of error. This type of error indicate that immediate attention - /// may be required. + /// 记录包含最高严重级别错误的日志,这类错误可能需要立即关注。 /// Critical = 0, /// - /// Logs that highlight when the flow of execution is stopped due to a failure. + /// 记录在执行流程因故障而停止时的日志。 /// Error = 1, /// - /// Logs that highlight an abnormal activity in the flow of execution. + /// 记录在执行流程中出现的异常活动。 /// Warning = 2, /// - /// Logs that track the general flow of the application. + /// 记录跟踪应用程序的一般流程的日志。 /// Info = 3, /// - /// Logs that are used for interactive investigation during development. + /// 记录用于在开发过程中进行交互式调查的日志。 /// Verbose = 4, /// - /// Logs that contain the most detailed messages. + /// 记录任何日志,包括最详细的诊断日志。 /// Debug = 5 } diff --git a/src/Kook.Net.Core/Logging/Logger.cs b/src/Kook.Net.Core/Logging/Logger.cs index 90d19d54..ab889123 100644 --- a/src/Kook.Net.Core/Logging/Logger.cs +++ b/src/Kook.Net.Core/Logging/Logger.cs @@ -23,7 +23,6 @@ public Task LogAsync(LogSeverity severity, string message, Exception? exception public Task LogAsync(LogSeverity severity, FormattableString message, Exception? exception = null) => _manager.LogAsync(severity, Name, message, exception); - public Task ErrorAsync(Exception? exception) => _manager.ErrorAsync(Name, exception); public Task ErrorAsync(string message, Exception? exception = null) => @@ -32,7 +31,6 @@ public Task ErrorAsync(string message, Exception? exception = null) => public Task ErrorAsync(FormattableString message, Exception? exception = null) => _manager.ErrorAsync(Name, message, exception); - public Task WarningAsync(Exception? exception) => _manager.WarningAsync(Name, exception); public Task WarningAsync(string message, Exception? exception = null) => @@ -41,7 +39,6 @@ public Task WarningAsync(string message, Exception? exception = null) => public Task WarningAsync(FormattableString message, Exception? exception = null) => _manager.WarningAsync(Name, message, exception); - public Task InfoAsync(Exception? exception) => _manager.InfoAsync(Name, exception); public Task InfoAsync(string message, Exception? exception = null) => _manager.InfoAsync(Name, message, exception); @@ -49,7 +46,6 @@ public Task WarningAsync(FormattableString message, Exception? exception = null) public Task InfoAsync(FormattableString message, Exception? exception = null) => _manager.InfoAsync(Name, message, exception); - public Task VerboseAsync(Exception? exception) => _manager.VerboseAsync(Name, exception); public Task VerboseAsync(string message, Exception? exception = null) => @@ -58,7 +54,6 @@ public Task VerboseAsync(string message, Exception? exception = null) => public Task VerboseAsync(FormattableString message, Exception? exception = null) => _manager.VerboseAsync(Name, message, exception); - public Task DebugAsync(Exception? exception) => _manager.DebugAsync(Name, exception); public Task DebugAsync(string message, Exception? exception = null) => diff --git a/src/Kook.Net.Core/LoginState.cs b/src/Kook.Net.Core/LoginState.cs index 73102bf2..d7db8f8b 100644 --- a/src/Kook.Net.Core/LoginState.cs +++ b/src/Kook.Net.Core/LoginState.cs @@ -1,17 +1,27 @@ namespace Kook; -/// Specifies the state of the client's login status. +/// +/// 表示客户端的登录状态。 +/// public enum LoginState : byte { - /// The client is currently logged out. + /// + /// 已退出登录。 + /// LoggedOut, - /// The client is currently logging in. + /// + /// 正在登录。 + /// LoggingIn, - /// The client is currently logged in. + /// + /// 已登录。 + /// LoggedIn, - /// The client is currently logging out. + /// + /// 正在退出登录。 + /// LoggingOut } diff --git a/src/Kook.Net.Core/Net/BucketId.cs b/src/Kook.Net.Core/Net/BucketId.cs index 0f85d02c..9b0b46e9 100644 --- a/src/Kook.Net.Core/Net/BucketId.cs +++ b/src/Kook.Net.Core/Net/BucketId.cs @@ -6,35 +6,35 @@ namespace Kook.Net; /// -/// Represents a ratelimit bucket. +/// 表示一个限速桶。 /// public sealed class BucketId : IEquatable { /// - /// Gets the http method used to make the request if available. + /// 获取用于发起请求的 HTTP 方法(如果可用)。 /// public HttpMethod? 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 Kook to group ratelimits. + /// 此哈希值由 KOOK 提供,用于分组限速。 /// public string? BucketHash { get; } /// - /// Gets if this bucket is a hash type. + /// 获取此限速桶是否为哈希分组限速桶。 /// public bool IsHashBucket => BucketHash != null; @@ -47,16 +47,12 @@ private BucketId(HttpMethod? httpMethod, string? endpoint, IEnumerable - /// 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. - /// + /// 用于发送请求的 HTTP 方法。 + /// 请求的终结点。 + /// 终结点的主要路由参数。 + /// 一个基于指定的 创建的 public static BucketId Create(HttpMethod? httpMethod, string? endpoint, Dictionary? majorParams) { Preconditions.NotNullOrWhitespace(endpoint, nameof(endpoint)); @@ -65,15 +61,11 @@ public static BucketId Create(HttpMethod? httpMethod, string? endpoint, Dictiona } /// - /// Creates a new based on a - /// and a previous . + /// 基于 和之前的 创建一个新的 。 /// - /// Bucket hash provided by Kook. - /// that is going to be upgraded to a hash type. - /// - /// A based on the - /// and . - /// + /// 由 KOOK 提供的分组限速哈希值。 + /// 要被升级为哈希分组限速桶的已有限速桶。 + /// 一个基于指定的 和之前的 创建的 public static BucketId Create(string hash, BucketId oldBucket) { Preconditions.NotNullOrWhitespace(hash, nameof(hash)); @@ -82,21 +74,19 @@ public static BucketId Create(string hash, BucketId oldBucket) } /// - /// Gets the string that will define this bucket as a hash based one. + /// 获取将此桶定义为哈希分组限速桶的字符串。 /// /// - /// A string 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 string that defines this bucket as an endpoint based one. - /// + /// 如果此桶是终结点限速桶,则返回此桶的终结点;否则返回 public string? GetUniqueEndpoint() => HttpMethod != null ? $"{HttpMethod} {Endpoint}" : Endpoint; /// diff --git a/src/Kook.Net.Core/Net/HttpException.cs b/src/Kook.Net.Core/Net/HttpException.cs index 4465951f..aeaa59a8 100644 --- a/src/Kook.Net.Core/Net/HttpException.cs +++ b/src/Kook.Net.Core/Net/HttpException.cs @@ -4,58 +4,53 @@ namespace Kook.Net; /// -/// The exception that is thrown if an error occurs while processing an Kook HTTP request. +/// 当处理 KOOK HTTP 请求时发生错误时引发的异常。 /// public class HttpException : Exception { /// - /// Gets the HTTP status code returned by Kook. + /// 获取 KOOK 返回的 HTTP 状态码。 /// - /// - /// An HTTP status code from Kook. - /// public HttpStatusCode HttpCode { get; } /// - /// Gets the JSON error code returned by Kook. + /// 获取由 KOOK 返回的 JSON 负载中的错误代码;也有可能是表示操作成功的代码; + /// 如果无法从响应中解析出错误代码,则为 。 /// - /// - /// A JSON error code from Kook, or null if none. - /// public KookErrorCode? KookCode { get; } /// - /// Gets the reason of the exception. + /// 获取异常的原因;也有可能是表示操作成功的消息;如果无法从响应中解析出原因,则为 。 /// public string? Reason { get; } /// - /// Gets the request object used to send the request. + /// 获取用于发送请求的请求对象。 /// public IRequest Request { get; } /// - /// Gets a collection of json errors describing what went wrong with the request. + /// 获取描述请求失败原因的所有 JSON 错误。 /// public IReadOnlyCollection Errors { get; } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The HTTP status code returned. - /// The request that was sent prior to the exception. - /// The Kook status code returned. - /// The reason behind the exception. - /// A collection of json errors describing what went wrong with the request. - public HttpException(HttpStatusCode httpCode, IRequest request, KookErrorCode? kookCode = null, string? reason = null, - KookJsonError[]? errors = null) + /// 返回的 HTTP 状态码。 + /// 引发异常前发送的请求。 + /// 由 KOOK 返回的 JSON 负载中解析出的状态码。 + /// 引发异常的原因。 + /// 描述请求错误的所有 JSON 错误。 + public HttpException(HttpStatusCode httpCode, IRequest request, + KookErrorCode? kookCode = null, string? reason = null, KookJsonError[]? errors = null) : base(CreateMessage(httpCode, (int?)kookCode, reason)) { HttpCode = httpCode; Request = request; KookCode = kookCode; Reason = reason; - Errors = errors?.ToImmutableArray() ?? ImmutableArray.Empty; + Errors = errors?.ToImmutableArray() ?? []; } private static string CreateMessage(HttpStatusCode httpCode, int? kookCode = null, string? reason = null) diff --git a/src/Kook.Net.Core/Net/IRequest.cs b/src/Kook.Net.Core/Net/IRequest.cs index 3fa58bac..f54a9e07 100644 --- a/src/Kook.Net.Core/Net/IRequest.cs +++ b/src/Kook.Net.Core/Net/IRequest.cs @@ -1,17 +1,17 @@ namespace Kook.Net; /// -/// Represents a generic request to be sent to Kook. +/// 表示一个要发送到 KOOK 的通用的请求。 /// public interface IRequest { /// - /// Gets how long the request should wait before timing out. + /// 获取请求在超时之前应等待的时间。 /// DateTimeOffset? TimeoutAt { get; } /// - /// Gets the options to be used when sending the request. + /// 获取发送请求时要使用的选项。 /// RequestOptions Options { get; } } diff --git a/src/Kook.Net.Core/Net/Queue/BaseMessageQueue.cs b/src/Kook.Net.Core/Net/Queue/BaseMessageQueue.cs index 410db5ac..556e0a51 100644 --- a/src/Kook.Net.Core/Net/Queue/BaseMessageQueue.cs +++ b/src/Kook.Net.Core/Net/Queue/BaseMessageQueue.cs @@ -3,36 +3,36 @@ namespace Kook.Net.Queue; /// -/// Represents a base class for message queue. +/// 表示一个通用的消息队列抽象类。 /// public abstract class BaseMessageQueue : IMessageQueue { /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The event handler for the message queue. + /// 用于处理消息的事件处理程序。 protected BaseMessageQueue(Func eventHandler) { EventHandler = eventHandler; } /// - /// Gets the event handler for the message queue. + /// 获取消息队列的事件处理程序。 /// protected Func EventHandler { get; } /// - /// Starts the message queue processing. + /// 启动消息队列的处理。 /// - /// The cancellation token to cancel the operation. - /// A task that represents the asynchronous operation. + /// 用于取消该操作的取消令牌。 + /// 表示一个异步启动操作的任务。 public abstract Task StartAsync(CancellationToken cancellationToken = default); /// - /// Stops the message queue processing. + /// 停止消息队列的处理。 /// - /// The cancellation token to cancel the operation. - /// A task that represents the asynchronous operation. + /// 用于取消该操作的取消令牌。 + /// 表示一个异步停止操作的任务。 public abstract Task StopAsync(CancellationToken cancellationToken = default); /// diff --git a/src/Kook.Net.Core/Net/Queue/IMessageQueue.cs b/src/Kook.Net.Core/Net/Queue/IMessageQueue.cs index 28c0c414..2fef8d09 100644 --- a/src/Kook.Net.Core/Net/Queue/IMessageQueue.cs +++ b/src/Kook.Net.Core/Net/Queue/IMessageQueue.cs @@ -3,16 +3,16 @@ namespace Kook.Net.Queue; /// -/// Represents a message queue used to send and receive messages from KOOK gateway. +/// 表示一个消息队列,用于从 KOOK 网关接收并处理事件。 /// public interface IMessageQueue { /// - /// Enqueues a message to the queue. + /// 将网关消息添加到队列中。 /// - /// The payload of the message. - /// The sequence of the message. - /// - /// A task that represents the asynchronous operation. + /// 网管消息的有效负载。 + /// 网关消息的序号。 + /// 用于取消该操作的取消令牌。 + /// 表示一个异步入队操作的任务。 Task EnqueueAsync(JsonElement payload, int sequence, CancellationToken cancellationToken = default); } diff --git a/src/Kook.Net.Core/Net/Queue/MessageQueueProvider.cs b/src/Kook.Net.Core/Net/Queue/MessageQueueProvider.cs index ee8c83d9..a39a9711 100644 --- a/src/Kook.Net.Core/Net/Queue/MessageQueueProvider.cs +++ b/src/Kook.Net.Core/Net/Queue/MessageQueueProvider.cs @@ -3,6 +3,6 @@ namespace Kook.Net.Queue; /// -/// Represents a delegate that provides a new instance. +/// 表示一个提供新的 实例的委托。 /// public delegate BaseMessageQueue MessageQueueProvider(Func eventHandler); diff --git a/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueue.cs b/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueue.cs index a3ccee66..ea4752f4 100644 --- a/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueue.cs +++ b/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueue.cs @@ -3,8 +3,13 @@ namespace Kook.Net.Queue.SynchronousImmediate; /// -/// Represents a synchronous immediate message queue. +/// 表示一个同步处理消息队列。 /// +/// +/// 此消息队列会在接收到网关事件后调用 +/// +/// 时立即使用构造函数中传入的 eventHandler 委托同步进行处理,处理完成后,该方法才会返回。 +/// public class SynchronousImmediateMessageQueue : BaseMessageQueue { /// diff --git a/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueueProvider.cs b/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueueProvider.cs index 362b69c9..ba561e56 100644 --- a/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueueProvider.cs +++ b/src/Kook.Net.Core/Net/Queue/SynchronousImmediateMessageQueueProvider.cs @@ -1,13 +1,14 @@ namespace Kook.Net.Queue.SynchronousImmediate; /// -/// Represents a delegate that provides a new instance of . +/// 表示一个默认的使用同步处理机制的 ,用于创建 实例。 /// public static class SynchronousImmediateMessageQueueProvider { /// - /// A delegate that creates a default instance. + /// 创建一个新的用于创建默认的使用同步处理机制的 实例的委托。 /// + /// 当默认的 在当前平台上不受支持时引发。 public static readonly MessageQueueProvider Instance = eventHandler => { try diff --git a/src/Kook.Net.Core/Net/RateLimitedException.cs b/src/Kook.Net.Core/Net/RateLimitedException.cs index b9ccdf24..eafcee62 100644 --- a/src/Kook.Net.Core/Net/RateLimitedException.cs +++ b/src/Kook.Net.Core/Net/RateLimitedException.cs @@ -1,19 +1,19 @@ namespace Kook.Net; /// -/// The exception that is thrown when the user is being rate limited by Kook. +/// 表示一个由 KOOK 限制请求频率时引发的异常。 /// public class RateLimitedException : TimeoutException { /// - /// Gets the request object used to send the request. + /// 获取引发此异常的请求对象。 /// public IRequest Request { get; } /// - /// Initializes a new instance of the class using the - /// sent. + /// 使用发送的 初始化 类的新实例。 /// + /// 引发异常的请求。 public RateLimitedException(IRequest request) : base("You are being rate limited.") { diff --git a/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs b/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs index 467dca60..93577a1e 100644 --- a/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs +++ b/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs @@ -1,52 +1,52 @@ namespace Kook; /// -/// Represents a generic ratelimit info. +/// 表示一个通用的限速信息。 /// public interface IRateLimitInfo { /// - /// Gets whether this ratelimit info is global. + /// 获取此限速信息是否为全局限速。 /// bool IsGlobal { get; } /// - /// Gets the number of requests that can be made. + /// 获取在更新时限内可以进行的请求数量。 /// int? Limit { get; } /// - /// Gets the number of remaining requests that can be made. + /// 获取目前可以立即进行的请求数量。 /// int? Remaining { get; } // /// - // /// Gets the total time (in seconds) of when the current rate limit bucket will reset. Can have decimals to match previous millisecond ratelimit precision. + // /// 获取当前限速桶将在何时重置的总时间(以秒为单位)。 // /// // int? RetryAfter { get; } // /// - // /// Gets the at which the rate limit resets. + // /// 获取此限速重置的绝对时间。 // /// // DateTimeOffset? Reset { get; } /// - /// Gets the absolute time when this ratelimit resets. + /// 获取相对于此刻此限速重置的相对时间间隔。 /// TimeSpan? ResetAfter { get; } /// - /// Gets a unique string denoting the rate limit being encountered (non-inclusive of major parameters in the route path). + /// 获取一个唯一的字符串,表示所遇到的限速桶(不包括路由路径中的主要参数)。 /// string? Bucket { get; } /// - /// Gets the amount of lag for the request. This is used to denote the precise time of when the ratelimit expires. + /// 获取请求的延迟,用于支持计算限速重置的精确时间。 /// TimeSpan? Lag { get; } /// - /// Gets the endpoint that this ratelimit info came from. + /// 获取此限速信息所属的终结点。 /// string Endpoint { get; } } diff --git a/src/Kook.Net.Core/Net/Rest/IRestClient.cs b/src/Kook.Net.Core/Net/Rest/IRestClient.cs index 4ae78c02..ea9914f8 100644 --- a/src/Kook.Net.Core/Net/Rest/IRestClient.cs +++ b/src/Kook.Net.Core/Net/Rest/IRestClient.cs @@ -5,60 +5,60 @@ namespace Kook.Net.Rest; /// -/// Represents a generic REST-based client. +/// 表示一个通用的基于 RESTful API 的客户端。 /// public interface IRestClient : IDisposable { /// - /// Sets the HTTP header of this client for all requests. + /// 设置此客户端的 HTTP 头部,这将应用于所有请求。 /// - /// The field name of the header. - /// The value of the header. + /// HTTP 头部的键。 + /// HTTP 头部的值。 void SetHeader(string key, string? value); /// - /// Sets the cancellation token for this client. + /// 设置此客户端的取消令牌。 /// - /// The cancellation token. + /// 用于取消任务的取消令牌。 void SetCancellationToken(CancellationToken cancellationToken); /// - /// Sends a REST request. + /// 发送一个 RESTful API 请求。 /// - /// The method used to send this request (see ). - /// The endpoint to send this request to. - /// The cancellation token used to cancel the task. - /// The audit log reason. - /// Additional headers to be sent with the request. - /// A task that represents an asynchronous send operation. The task result contains the REST response of the request. + /// 用于发送此请求的方法。 + /// 要发送此请求的端点。 + /// 用于取消任务的取消令牌。 + /// 用于审计日志的操作原因。 + /// 要随请求一起发送的附加标头。 + /// 表示一个异步发送操作的任务。任务的结果包含请求的响应。 Task SendAsync(HttpMethod method, string endpoint, CancellationToken cancellationToken, string? reason = null, IEnumerable>>? requestHeaders = null); /// - /// Sends a REST request with a JSON body. + /// 发送一个带有 JSON 请求体的 RESTful API 请求。 /// - /// The method used to send this request (see ). - /// The endpoint to send this request to. - /// The JSON body of the request. - /// The cancellation token used to cancel the task. - /// The audit log reason. - /// Additional headers to be sent with the request. - /// A task that represents an asynchronous send operation. The task result contains the REST response of the request. + /// 用于发送此请求的方法。 + /// 要发送此请求的端点。 + /// 要发送的 JSON 请求体。 + /// 用于取消任务的取消令牌。 + /// 用于审计日志的操作原因。 + /// 要随请求一起发送的附加标头。 + /// 表示一个异步发送操作的任务。任务的结果包含请求的响应。 Task SendAsync(HttpMethod method, string endpoint, string json, CancellationToken cancellationToken, string? reason = null, IEnumerable>>? requestHeaders = null); /// - /// Sends a REST request with multipart parameters. + /// 发送一个带有多部分数据参数的 RESTful API 请求。 /// - /// The method used to send this request (see ). - /// The endpoint to send this request to. - /// The multipart parameters. - /// The cancellation token used to cancel the task. - /// The audit log reason. - /// Additional headers to be sent with the request. - /// A task that represents an asynchronous send operation. The task result contains the REST response of the request. + /// 用于发送此请求的方法。 + /// 要发送此请求的端点。 + /// 要发送的多部分数据参数。 + /// 用于取消任务的取消令牌。 + /// 用于审计日志的操作原因。 + /// 要随请求一起发送的附加标头。 + /// 表示一个异步发送操作的任务。任务的结果包含请求的响应。 Task SendAsync(HttpMethod method, string endpoint, IReadOnlyDictionary multipartParams, CancellationToken cancellationToken, string? reason = null, IEnumerable>>? requestHeaders = null); diff --git a/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs b/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs index f018bf1f..043ebcc5 100644 --- a/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs +++ b/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs @@ -1,6 +1,6 @@ namespace Kook.Net.Rest; /// -/// Represents a delegate that provides a instance. +/// 表示一个用于创建 实例的委托。 /// public delegate IRestClient RestClientProvider(string baseUrl); diff --git a/src/Kook.Net.Core/Net/Rest/RestResponse.cs b/src/Kook.Net.Core/Net/Rest/RestResponse.cs index d5d961a2..1f2612d4 100644 --- a/src/Kook.Net.Core/Net/Rest/RestResponse.cs +++ b/src/Kook.Net.Core/Net/Rest/RestResponse.cs @@ -4,27 +4,27 @@ namespace Kook.Net.Rest; /// -/// Represents a REST response. +/// 表示一个 RESTful API 请求的响应。 /// public struct RestResponse { /// - /// Gets the status code of the response. + /// 获取响应的 HTTP 状态码。 /// public HttpStatusCode StatusCode { get; } /// - /// Gets the headers of the response. + /// 获取响应的头部。 /// public Dictionary Headers { get; } /// - /// Gets the stream of the response. + /// 获取响应的流。 /// public Stream Stream { get; } /// - /// Gets the media type header of the response. + /// 获取响应的媒体类型头部。 /// public MediaTypeHeaderValue? MediaTypeHeader { get; } diff --git a/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs b/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs index 67d8fe69..fd4322b1 100644 --- a/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs +++ b/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs @@ -1,51 +1,59 @@ namespace Kook.Net.Udp; /// -/// Represents a generic UDP socket. +/// 表示一个通用的 UDP 套接字。 /// public interface IUdpSocket : IDisposable { /// - /// Fired when a datagram is received. + /// 当接收到数据报时引发。 /// + /// + /// 事件参数: + /// + /// [] 参数是接收到的数据报的字节数组。 + /// 参数是接收到的数据报的字节数组的起始位置。 + /// 参数是接收到的数据报的字节数组的长度。 + /// + /// event Func? ReceivedDatagram; /// - /// Gets the port of the socket. + /// 获取 UDP 套接字的端口号。 /// ushort Port { get; } /// - /// Sets the cancellation token. + /// 设置此客户端的取消令牌。 /// - /// The cancellation token. + /// 用于取消任务的取消令牌。 void SetCancellationToken(CancellationToken cancellationToken); /// - /// Sets the destination of the socket. + /// 设置 UDP 套接字的目标通信端点,包括 IP 地址和端口号。 /// - /// The IP address of the destination. - /// The port of the destination. + /// 目标通信端点的 IP 地址。 + /// 目标通信端点的端口号。 void SetDestination(string ip, int port); /// - /// Starts the socket. + /// 启动套接字。 /// - /// A task that represents the asynchronous operation. + /// 一个表示异步启动操作的任务。 Task StartAsync(); /// - /// Stops the socket. + /// 停止套接字。 /// - /// A task that represents the asynchronous operation. + /// 一个表示异步停止操作的任务。 Task StopAsync(); /// - /// Sends a datagram. + /// 发送数据报。 /// - /// The data to send. - /// The index of the data to start sending from. - /// The number of bytes to send. - /// A task that represents the asynchronous operation. + /// 要发送的数据报的字节数组。 + /// 要发送的数据报的字节数组的起始位置。 + /// 要发送的数据报的字节数组的长度。 + /// 一个表示异步发送操作的任务。 Task SendAsync(byte[] data, int index, int count); } diff --git a/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs b/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs index 683cbdd1..5f3a24f9 100644 --- a/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs +++ b/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs @@ -1,6 +1,6 @@ namespace Kook.Net.Udp; /// -/// Represents a delegate that provides a new instance. +/// 表示一个用于创建 实例的委托。 /// public delegate IUdpSocket UdpSocketProvider(); diff --git a/src/Kook.Net.Core/Net/WebSocketClosedException.cs b/src/Kook.Net.Core/Net/WebSocketClosedException.cs index 6ed8ad32..707c1102 100644 --- a/src/Kook.Net.Core/Net/WebSocketClosedException.cs +++ b/src/Kook.Net.Core/Net/WebSocketClosedException.cs @@ -1,27 +1,25 @@ namespace Kook.Net; /// -/// The exception that is thrown when the WebSocket session is closed by Kook. +/// 表示一个由 KOOK 意外关闭 WebSocket 会话时引发的异常。 /// public class WebSocketClosedException : Exception { /// - /// Gets the close code sent by Kook. + /// 获取由 KOOK 发送的关闭代码。 /// - /// - /// A close code from Kook. See https://developer.kookapp.cn/doc/websocket - /// public int? CloseCode { get; } /// - /// Gets the reason of the interruption. + /// 获取中断的原因。 /// public string? Reason { get; } /// - /// Initializes a new instance of the using a Kook close code - /// and an optional reason. + /// 使用 KOOK 发送的关闭代码及原因初始化一个 类的新实例。 /// + /// 由 KOOK 发送的关闭代码。 + /// 中断的原因。 public WebSocketClosedException(int? closeCode, string? reason = null) : base($"The server sent close {closeCode}{(reason != null ? $": \"{reason}\"" : "")}") { diff --git a/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs b/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs index 77e370a8..c5e02382 100644 --- a/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs +++ b/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs @@ -1,69 +1,89 @@ namespace Kook.Net.WebSockets; /// -/// Represents a generic WebSocket client. +/// 表示一个通用的 WebSocket 客户端。 /// public interface IWebSocketClient : IDisposable { /// - /// Fired when a binary message is received. + /// 当接收到二进制消息时触发。 /// + /// + /// 事件参数: + /// + /// [] 参数是接收到的二进制消息的字节数组。 + /// 参数是接收到的二进制消息的字节数组的起始位置。 + /// 参数是接收到的二进制消息的字节数组的长度。 + /// + /// event Func? BinaryMessage; /// - /// Fired when a text message is received. + /// 当接收到文本消息时触发。 /// + /// + /// 事件参数: + /// + /// 参数是接收到的文本消息的字符串。 + /// + /// event Func? TextMessage; /// - /// Fired when the WebSocket connection is closed. + /// 当 WebSocket 连接关闭时触发。 /// + /// + /// 事件参数: + /// + /// 参数是导致连接关闭的异常。 + /// + /// event Func? Closed; /// - /// Sets a header to be sent with the future requests. + /// 设置一个将与未来请求一起发送的标头。 /// - /// The field name of the header. - /// The value of the header. + /// 标头的键。 + /// 标头的值。 void SetHeader(string key, string value); /// - /// Sets the keep-alive interval for this client. + /// 设置此客户端的保持活动间隔。 /// - /// The keep-alive interval to be used. + /// 保持活动间隔。 /// - /// If this method is not called, the default keep-alive interval will be - /// . + /// 如果未调用此方法,则默认的保持活动间隔是 。 /// + /// void SetKeepAliveInterval(TimeSpan keepAliveInterval); /// - /// Sets the cancellation token for this client. + /// 设置此客户端的取消令牌。 /// - /// The cancellation token to be used. + /// 用于取消任务的取消令牌。 void SetCancellationToken(CancellationToken cancellationToken); /// - /// Connects to the specified host. + /// 连接到指定的主机。 /// - /// The host to connect to. - /// A task that represents an asynchronous connect operation. + /// 要连接的主机。 + /// 一个表示异步连接操作的任务。 Task ConnectAsync(string host); /// - /// Disconnects from the host. + /// 断开与主机的连接。 /// - /// The close code to be sent to the host. - /// A task that represents an asynchronous disconnect operation. + /// 要发送给对方主机的关闭代码。 + /// 一个表示异步断开操作的任务。 Task DisconnectAsync(int closeCode = 1000); /// - /// Sends a message to the host. + /// 向对方主机发送文本消息。 /// - /// The data to be sent. - /// The index of the data to start sending from. - /// The amount of data to send. - /// Whether the data is text or binary. - /// A task that represents an asynchronous send operation. + /// 要发送的数据。 + /// 要发送的数据的起始位置。 + /// 要发送的数据的长度。 + /// 发送的是否为文本消息。 + /// 一个表示异步发送操作的任务。 Task SendAsync(byte[] data, int index, int count, bool isText); } diff --git a/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs b/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs index c297bb3f..0d9b33a7 100644 --- a/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs +++ b/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs @@ -1,6 +1,6 @@ namespace Kook.Net.WebSockets; /// -/// Represents a delegate that provides a new instance. +/// 表示一个用于创建 实例的委托。 /// public delegate IWebSocketClient WebSocketProvider(); diff --git a/src/Kook.Net.Core/RequestOptions.cs b/src/Kook.Net.Core/RequestOptions.cs index f57470b6..4875c503 100644 --- a/src/Kook.Net.Core/RequestOptions.cs +++ b/src/Kook.Net.Core/RequestOptions.cs @@ -3,53 +3,45 @@ namespace Kook; /// -/// Represents options that should be used when sending a request. +/// 表示发送请求时要使用的选项。 /// public class RequestOptions { - /// - /// Creates a new class with its default settings. - /// + /// public static RequestOptions Default => new(); /// - /// Gets or sets the maximum time to wait for this request to complete. + /// 获取或设置等待此请求完成的最大时间,以毫秒为单位。 /// /// - /// Gets or set the max time, in milliseconds, to wait for this request to complete. If - /// null, a request will not time out. If a rate limit has been triggered for this request's bucket - /// and will not be unpaused in time, this request will fail immediately. + /// 获取或设置等待此请求完成的最大时间,以毫秒为单位。如果为 null,则请求不会超时。 + /// 如果此请求的桶触发了速率限制并且在超时前不会恢复,此请求将立即失败。 /// - /// - /// An int in milliseconds for when the request times out. - /// public int? Timeout { get; set; } /// - /// Gets or sets the cancellation token for this request. + /// 获取或设置此请求的取消令牌。 /// - /// - /// A for this request. - /// public CancellationToken CancellationToken { get; set; } = CancellationToken.None; /// - /// Gets or sets the retry behavior when the request fails. + /// 获取或设置请求失败时的重试行为;如果为 null,则使用配置的默认的重试行为。 /// + /// public RetryMode? RetryMode { get; set; } /// - /// Gets or sets the reason for this action in the guild's audit log. + /// 获取或设置要写入到服务器审计日志中的操作原因。 /// /// - /// Gets or sets the reason that will be written to the guild's audit log if applicable. This may not apply - /// to all actions. + /// 默认的 API 客户端不支持设置此属性。 /// public string? AuditLogReason { get; set; } /// - /// Gets or sets the callback to execute regarding ratelimits for this request. + /// 获取或设置此请求触发速率限制时要执行的回调委托。 /// + /// public Func? RatelimitCallback { get; set; } internal bool IgnoreState { get; set; } @@ -71,18 +63,17 @@ internal void ExecuteRatelimitCallback(IRateLimitInfo info) } /// - /// Initializes a new class with the default request timeout set in - /// . + /// 使用默认设置创建一个新的 类的实例。 /// + /// + /// 默认的请求超时时间是 。 + /// public RequestOptions() { Timeout = KookConfig.DefaultRequestTimeout; RequestHeaders = new Dictionary>(); } - /// - /// Memberwise clones this object. - /// - /// A cloned object. + /// public RequestOptions Clone() => (RequestOptions) MemberwiseClone(); } diff --git a/src/Kook.Net.Core/RetryMode.cs b/src/Kook.Net.Core/RetryMode.cs index e944a1a5..5b6ba032 100644 --- a/src/Kook.Net.Core/RetryMode.cs +++ b/src/Kook.Net.Core/RetryMode.cs @@ -1,23 +1,39 @@ namespace Kook; -/// Specifies how a request should act in the case of an error. +/// +/// 表示请求在发生错误时应如何处理。 +/// [Flags] public enum RetryMode { - /// If a request fails, an exception is thrown immediately. + /// + /// 如果请求失败,将立即引发异常。 + /// AlwaysFail = 0x0, - /// Retry if a request timed out. + /// + /// 如果请求超时,则重试。 + /// RetryTimeouts = 0x1, - // /// Retry if a request failed due to a network error. - //RetryErrors = 0x2, - /// Retry if a request failed due to a rate-limit. + // /// + // /// 如果请求因网络错误而失败,则重试。 + // /// + // RetryErrors = 0x2, + + /// + /// 如果请求因速率限制而失败,则重试。 + /// RetryRatelimit = 0x4, - /// Retry if a request failed due to an HTTP error 502. + /// + /// 如果请求因 HTTP 状态码 502 而失败,则重试。 + /// + /// Retry502 = 0x8, - /// Continuously retry a request until it times out, its cancel token is triggered, or the server responds with a non-502 error. + /// + /// 总是重试失败的请求,直到超时、取消令牌被触发或服务器响应非 502 错误。 + /// AlwaysRetry = RetryTimeouts | /*RetryErrors |*/ RetryRatelimit | Retry502 } diff --git a/src/Kook.Net.Core/TokenType.cs b/src/Kook.Net.Core/TokenType.cs index 1f3bc38b..f8d80d9b 100644 --- a/src/Kook.Net.Core/TokenType.cs +++ b/src/Kook.Net.Core/TokenType.cs @@ -1,17 +1,17 @@ namespace Kook; /// -/// Specifies the type of token to use with the client. +/// 表示客户端所使用的令牌类型。 /// public enum TokenType { /// - /// An OAuth2 token type. + /// OAuth2 令牌类型。 /// Bearer, /// - /// A bot token type. + /// Bot 令牌类型。 /// Bot } diff --git a/src/Kook.Net.Core/Utils/Cacheable.cs b/src/Kook.Net.Core/Utils/Cacheable.cs index ca3b1c65..1c454625 100644 --- a/src/Kook.Net.Core/Utils/Cacheable.cs +++ b/src/Kook.Net.Core/Utils/Cacheable.cs @@ -5,10 +5,10 @@ namespace Kook; /// -/// Represents a cached entity. +/// 表示一个可延迟加载的缓存实体。 /// -/// The type of entity that is cached. -/// The type of this entity's ID. +/// 可延迟加载的缓存实体的类型。 +/// 可延迟加载的缓存实体的 ID 的类型。 #if DEBUG [DebuggerDisplay("{DebuggerDisplay,nq}")] #endif @@ -17,22 +17,21 @@ public readonly struct Cacheable where TId : IEquatable { /// - /// Gets whether this entity is cached. + /// 获取此实体是否已缓存。 /// [MemberNotNullWhen(true, nameof(Value))] public bool HasValue { get; } /// - /// Gets the ID of this entity. + /// 获取此实体的唯一标识符。 /// public TId Id { get; } /// - /// Gets the entity if it could be pulled from cache. + /// 如果可以从缓存中获取实体,则获取该实体。 /// /// - /// This value is not guaranteed to be set; in cases where the entity cannot be pulled from cache, it is - /// null. + /// 此属性不保证非空;在无法从缓存中拉取实体的情况下,此属性返回 null。 /// public TEntity? Value { get; } @@ -47,24 +46,20 @@ internal Cacheable(TEntity? value, TId id, bool hasValue, Func> d } /// - /// Downloads this entity to cache. + /// 将此实体下载到缓存中。 /// - /// Thrown when used from a user account. - /// Thrown when the entity is deleted. /// - /// A task that represents the asynchronous download operation. The task result contains - /// the downloaded entity. + /// 一个表示异步下载操作的任务。任务结果包含下载的实体;如果无法通过 API 请求下载实体,或下载的实体无法转换为 + /// ,则为 null。 /// public async Task DownloadAsync() => await DownloadFunc().ConfigureAwait(false); /// - /// Returns the cached entity if it exists; otherwise downloads it. + /// 如果实体已存在于缓存中,则返回该实体;否则下载该实体并返回。 /// - /// Thrown when used from a user account. - /// Thrown when the entity is deleted and is not in cache. /// - /// A task that represents the asynchronous operation that attempts to get the entity via cache or to - /// download the entity. The task result contains the downloaded entity. + /// 一个表示异步获取或下载操作的任务。任务结果包含所获取或下载的实体;如果无法通过 API 请求下载实体,或下载的实体无法转换为 + /// ,则为 null。 /// public async Task GetOrDownloadAsync() => HasValue ? Value : await DownloadAsync().ConfigureAwait(false); @@ -76,12 +71,12 @@ internal Cacheable(TEntity? value, TId id, bool hasValue, Func> d } /// -/// Represents a cached entity that can be downloaded. +/// 表示一个可延迟加载的缓存实体。 /// -/// The type of entity that is cached. -/// The type of entity that can be downloaded. -/// The common type of and . -/// The type of the corresponding entity's ID. +/// 可延迟加载的缓存实体的类型。 +/// 可从 API 请求下载的实体的类型。 +/// 共同继承或实现的类型。 +/// 可延迟加载的缓存实体的 ID 的类型。 #if DEBUG [DebuggerDisplay("{DebuggerDisplay,nq}")] #endif @@ -91,21 +86,20 @@ public readonly struct Cacheable { /// - /// Gets whether this entity is cached. + /// 获取此实体是否已缓存。 /// public bool HasValue { get; } /// - /// Gets the ID of this entity. + /// 获取此实体的唯一标识符。 /// public TId Id { get; } /// - /// Gets the entity if it could be pulled from cache. + /// 如果可以从缓存中获取实体,则获取该实体。 /// /// - /// This value is not guaranteed to be set; in cases where the entity cannot be pulled from cache, it is - /// null. + /// 此属性不保证非空;在无法从缓存中拉取实体的情况下,此属性返回 null。 /// public TCachedEntity? Value { get; } @@ -120,24 +114,20 @@ internal Cacheable(TCachedEntity? value, TId id, bool hasValue, Func - /// Downloads this entity. + /// 将此实体下载到缓存中。 ///
- /// Thrown when used from a user account. - /// Thrown when the entity is deleted. /// - /// A task that represents the asynchronous download operation. The task result contains the downloaded - /// entity. + /// 一个表示异步下载操作的任务。任务结果包含下载的实体;如果无法通过 API 请求下载实体,或下载的实体无法转换为 + /// ,则为 null。 /// public async Task DownloadAsync() => await DownloadFunc().ConfigureAwait(false); /// - /// Returns the cached entity if it exists; otherwise downloads it. + /// 如果实体已存在于缓存中,则返回该实体;否则下载该实体并返回。 /// - /// Thrown when used from a user account. - /// Thrown when the entity is deleted and is not in cache. /// - /// A task that represents the asynchronous operation that attempts to get the entity via cache or to - /// download the entity. The task result contains the downloaded entity. + /// 一个表示异步获取或下载操作的任务。任务结果包含所获取或下载的实体;如果无法通过 API 请求下载实体,或下载的实体无法转换为 + /// ,则为 null。 /// public async Task GetOrDownloadAsync() => HasValue ? Value : await DownloadAsync().ConfigureAwait(false); diff --git a/src/Kook.Net.Core/Utils/MentionUtils.cs b/src/Kook.Net.Core/Utils/MentionUtils.cs index ebf5b37a..03b82abe 100644 --- a/src/Kook.Net.Core/Utils/MentionUtils.cs +++ b/src/Kook.Net.Core/Utils/MentionUtils.cs @@ -5,7 +5,7 @@ namespace Kook; /// -/// Provides a series of helper methods for parsing mentions. +/// 提供一组用于生成与解析提及标签的辅助方法。 /// public static class MentionUtils { @@ -22,7 +22,6 @@ public static class MentionUtils @"(@[^#]+?#\d{1,20})|(@role:\d{1,10};)|(#channel:\d{1,20}?;)|(\[:[^:]{1,32}?:[\w\/]{1,40}?\])", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); - internal static readonly Regex KMarkdownUserRegex = new(@"(\(met\))(?\d{1,20}?)\1", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); @@ -36,76 +35,65 @@ public static class MentionUtils @"(\((met|rol|chn)\)\d{1,20}?\(\2\))|(\(emj\)[^\(\)]{1,32}?\(emj\)\[[\w\/]{1,40}?\])", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); - private const char SanitizeChar = '\u200b'; internal static string KMarkdownMentionUser(string id) => $"(met){id}(met)"; /// - /// Returns a KMarkdown formatted mention string based on the user ID. + /// 返回基于用户 ID 的 KMarkdown 格式化用户提及字符串。 /// - /// - /// A user mention string formatted to KMarkdown. - /// + /// 格式化为 KMarkdown 的用户提及字符串。 public static string KMarkdownMentionUser(ulong id) => KMarkdownMentionUser(id.ToString()); internal static string KMarkdownMentionChannel(string id) => $"(chn){id}(chn)"; /// - /// Returns a KMarkdown formatted mention string based on the channel ID. + /// 返回基于频道 ID 的 KMarkdown 格式化频道提及字符串。 /// - /// - /// A channel mention string formatted to KMarkdown. - /// + /// 格式化为 KMarkdown 的频道提及字符串。 public static string KMarkdownMentionChannel(ulong id) => KMarkdownMentionChannel(id.ToString()); internal static string KMarkdownMentionRole(string id) => $"(rol){id}(rol)"; /// - /// Returns a KMarkdown formatted mention string based on the role ID. + /// 返回基于角色 ID 的 KMarkdown 格式化角色提及字符串。 /// - /// - /// A role mention string formatted to KMarkdown. - /// + /// 格式化为 KMarkdown 的角色提及字符串。 public static string KMarkdownMentionRole(uint id) => KMarkdownMentionRole(id.ToString()); internal static string PlainTextMentionUser(string username, string id) => $"@{username}#{id}"; /// - /// Returns a plain text formatted mention string based on the user ID. + /// 返回基于用户名称与用户 ID 的纯文本格式化用户提及字符串。 /// - /// - /// A user mention string formatted to plain text. - /// + /// 格式化为纯文本的用户提及字符串。 public static string PlainTextMentionUser(string username, ulong id) => PlainTextMentionUser(username, id.ToString()); internal static string PlainTextMentionChannel(string id) => $"#channel:{id};"; /// - /// Returns a plain text formatted mention string based on the channel ID. + /// 返回基于频道 ID 的纯文本格式化频道提及字符串。 /// - /// - /// A channel mention string formatted to plain text. - /// + /// 格式化为纯文本的频道提及字符串。 public static string PlainTextMentionChannel(ulong id) => PlainTextMentionChannel(id.ToString()); internal static string PlainTextMentionRole(string id) => $"@role:{id};"; /// - /// Returns a plain text formatted mention string based on the role ID. + /// 返回基于角色 ID 的纯文本格式化角色提及字符串。 /// - /// - /// A role mention string formatted to plain text. - /// + /// 格式化为纯文本的角色提及字符串。 public static string PlainTextMentionRole(uint id) => PlainTextMentionRole(id.ToString()); /// - /// Parses a provided user mention string. + /// 将指定的用户提及字符串解析为用户 ID。 /// - /// The user mention. - /// - /// Invalid mention format. + /// 要解析的用户提及字符串。 + /// 提及标签的语法模式。 + /// 解析的用户 ID。 + /// 无效的用户提及字符串格式。 + /// 不是有效的标签语法模式。 public static ulong ParseUser(string text, TagMode tagMode) { if (TryParseUser(text, out ulong id, tagMode)) @@ -115,11 +103,13 @@ public static ulong ParseUser(string text, TagMode tagMode) } /// - /// Tries to parse a provided user mention string. + /// 尝试解析指定的用户提及字符串。 /// - /// The user mention. - /// The UserId of the user. - /// Parse as PlainText or KMarkdown. + /// 要解析的用户提及字符串。 + /// 如果解析成功,则为用户 ID;否则为 0。 + /// 提及标签的语法模式。 + /// 如果解析成功,则为 true;否则为 false + /// 不是有效的标签语法模式。 public static bool TryParseUser(string text, out ulong userId, TagMode tagMode) { Match match = tagMode switch @@ -137,11 +127,14 @@ public static bool TryParseUser(string text, out ulong userId, TagMode tagMode) return false; } - /// - /// Parses a provided channel mention string. + /// 解析指定的频道提及字符串。 /// - /// Invalid mention format. + /// 要解析的频道提及字符串。 + /// 提及标签的语法模式。 + /// 解析的频道 ID。 + /// 无效的频道提及字符串格式。 + /// 不是有效的标签语法模式。 public static ulong ParseChannel(string text, TagMode tagMode) { if (TryParseChannel(text, out ulong id, tagMode)) @@ -151,8 +144,13 @@ public static ulong ParseChannel(string text, TagMode tagMode) } /// - /// Tries to parse a provided channel mention string. + /// 尝试解析指定的频道提及字符串。 /// + /// 要解析的频道提及字符串。 + /// 如果解析成功,则为频道 ID;否则为 0。 + /// 提及标签的语法模式。 + /// 如果解析成功,则为 true;否则为 false + /// 不是有效的标签语法模式。 public static bool TryParseChannel(string text, out ulong channelId, TagMode tagMode) { Match match = tagMode switch @@ -171,9 +169,13 @@ public static bool TryParseChannel(string text, out ulong channelId, TagMode tag } /// - /// Parses a provided role mention string. + /// 解析指定的角色提及字符串。 /// - /// Invalid mention format. + /// 要解析的角色提及字符串。 + /// 提及标签的语法模式。 + /// 解析的角色 ID。 + /// 无效的角色提及字符串格式。 + /// 不是有效的标签语法模式。 public static ulong ParseRole(string text, TagMode tagMode) { if (TryParseRole(text, out uint id, tagMode)) return id; @@ -182,8 +184,13 @@ public static ulong ParseRole(string text, TagMode tagMode) } /// - /// Tries to parse a provided role mention string. + /// 尝试解析指定的角色提及字符串。 /// + /// T 要解析的角色提及字符串。 + /// 如果解析成功,则为角色 ID;否则为 0。 + /// 提及标签的语法模式。 + /// 如果解析成功,则为 true;否则为 false + /// 不是有效的标签语法模式。 public static bool TryParseRole(string text, out uint roleId, TagMode tagMode) { Match match = tagMode switch @@ -315,7 +322,7 @@ internal static string ResolveEveryoneMention(ITag tag, TagHandling mode) { TagHandling.Name or TagHandling.FullName => "@全体成员", TagHandling.NameNoPrefix or TagHandling.FullNameNoPrefix => "全体成员", - TagHandling.Sanitize => $"@{SanitizeChar}全体成员", + TagHandling.Sanitize => $"@{SanitizeChar}all", _ => string.Empty }; } @@ -328,7 +335,7 @@ internal static string ResolveHereMention(ITag tag, TagHandling mode) { TagHandling.Name or TagHandling.FullName => "@在线成员", TagHandling.NameNoPrefix or TagHandling.FullNameNoPrefix => "在线成员", - TagHandling.Sanitize => $"@{SanitizeChar}在线成员", + TagHandling.Sanitize => $"@{SanitizeChar}here", _ => "" }; } @@ -348,7 +355,7 @@ internal static string ResolveEmoji(ITag tag, TagHandling mode) { TagHandling.Name or TagHandling.FullName => $":{emoji.Name}:", TagHandling.NameNoPrefix or TagHandling.FullNameNoPrefix => $"{emoji.Name}", - TagHandling.Sanitize => $"[{SanitizeChar}{emoji.Name}{SanitizeChar}:{emoji.Id}]", + TagHandling.Sanitize => $"(emj){SanitizeChar}{emoji.Name}(emj)[{SanitizeChar}{emoji.Id}]", _ => "" }; } diff --git a/src/Kook.Net.Core/Utils/Permissions.cs b/src/Kook.Net.Core/Utils/Permissions.cs index 98407526..e7bb4e6a 100644 --- a/src/Kook.Net.Core/Utils/Permissions.cs +++ b/src/Kook.Net.Core/Utils/Permissions.cs @@ -93,7 +93,6 @@ public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, u [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void UnsetFlag(ref ulong value, ulong flag) => value &= ~flag; - public static ChannelPermissions ToChannelPerms(IGuildChannel channel, ulong guildPermissions) => new(guildPermissions & ChannelPermissions.All(channel).RawValue); diff --git a/src/Kook.Net.Core/Utils/Preconditions.cs b/src/Kook.Net.Core/Utils/Preconditions.cs index cfb6f5b7..b43d8d15 100644 --- a/src/Kook.Net.Core/Utils/Preconditions.cs +++ b/src/Kook.Net.Core/Utils/Preconditions.cs @@ -1,17 +1,18 @@ using System.Diagnostics.CodeAnalysis; +using System.Numerics; namespace Kook; #nullable enable /// -/// Provides methods to check preconditions. +/// 提供用于检查先决条件的方法。 /// -public static class Preconditions +internal static class Preconditions { #region Objects - /// must not be null. + /// 不可为 null. public static void NotNull([NotNull] T? obj, string name, string? msg = null) where T : class { if (obj == null) @@ -25,22 +26,22 @@ private static ArgumentNullException CreateNotNullException(string name, string? #region Strings - /// cannot be blank. + /// 不可为空白内容. public static void NotEmpty(string obj, string name, string? msg = null) { if (obj.Length == 0) throw CreateNotEmptyException(name, msg); } - /// cannot be blank. - /// must not be null. + /// 不可为空白内容. + /// 不可为 null. public static void NotNullOrEmpty([NotNull] string? obj, string name, string? msg = null) { if (obj == null || obj.Length == 0) throw CreateNotNullException(name, msg); } - /// cannot be blank. - /// must not be null. + /// 不可为空白内容. + /// 不可为 null. public static void NotNullOrWhitespace([NotNull] string? obj, string name, string? msg = null) { if (obj == null || obj.Trim().Length == 0) @@ -53,185 +54,236 @@ private static ArgumentException CreateNotEmptyException(string name, string? ms #endregion #region Numerics - /// Value may not be equal to . + +#if NET7_0_OR_GREATER + /// 不可与 相等。 + public static void NotEqual(T? obj, T value, string name, string? msg = null) + where T : struct, IEqualityOperators + { + if (obj.HasValue && obj == value) + throw CreateNotEqualException(name, msg, value); + } +#endif + + /// 不可与 相等。 public static void NotEqual(sbyte obj, sbyte value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(byte obj, byte value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(short obj, short value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(ushort obj, ushort value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(int obj, int value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(uint obj, uint value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(long obj, long value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(ulong obj, ulong value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(Guid obj, Guid value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(sbyte? obj, sbyte value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(byte? obj, byte value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(short? obj, short value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(ushort? obj, ushort value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(int? obj, int value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(uint? obj, uint value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(long? obj, long value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(ulong? obj, ulong value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } - /// Value may not be equal to . + /// 不可与 相等。 public static void NotEqual(Guid? obj, Guid value, string name, string? msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } private static ArgumentException CreateNotEqualException(string name, string? msg, T value) => new ArgumentException(message: msg ?? $"Value may not be equal to {value}.", paramName: name); - /// Value must be at least . +#if NET7_0_OR_GREATER + /// 不可小于 + public static void AtLeast(T? obj, T value, string name, string? msg = null) + where T : struct, IComparisonOperators + { + if (obj.HasValue && obj < value) + throw CreateAtLeastException(name, msg, value); + } +#endif + + /// 不可小于 public static void AtLeast(sbyte obj, sbyte value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(byte obj, byte value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(short obj, short value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(ushort obj, ushort value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(int obj, int value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(uint obj, uint value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(long obj, long value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(ulong obj, ulong value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(sbyte? obj, sbyte value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(byte? obj, byte value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(short? obj, short value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(ushort? obj, ushort value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(int? obj, int value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(uint? obj, uint value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(long? obj, long value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } - /// Value must be at least . + /// 不可小于 public static void AtLeast(ulong? obj, ulong value, string name, string? msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } private static ArgumentException CreateAtLeastException(string name, string? msg, T value) => new ArgumentException(message: msg ?? $"Value must be at least {value}.", paramName: name); - /// Value must be greater than . +#if NET7_0_OR_GREATER + /// 必须大于 + public static void GreaterThan(T? obj, T value, string name, string? msg = null) + where T : struct, IComparisonOperators + { + if (obj.HasValue && obj <= value) + throw CreateGreaterThanException(name, msg, value); + } +#endif + + /// 必须大于 public static void GreaterThan(sbyte obj, sbyte value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(byte obj, byte value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(short obj, short value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(ushort obj, ushort value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(int obj, int value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(uint obj, uint value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(long obj, long value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(ulong obj, ulong value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(sbyte? obj, sbyte value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(byte? obj, byte value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(short? obj, short value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(ushort? obj, ushort value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(int? obj, int value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(uint? obj, uint value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(long? obj, long value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } - /// Value must be greater than . + /// 必须大于 public static void GreaterThan(ulong? obj, ulong value, string name, string? msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } private static ArgumentException CreateGreaterThanException(string name, string? msg, T value) => new ArgumentException(message: msg ?? $"Value must be greater than {value}.", paramName: name); - /// Value must be at most . +#if NET7_0_OR_GREATER + /// 不可大于 + public static void AtMost(T? obj, T value, string name, string? msg = null) + where T : struct, IComparisonOperators + { + if (obj.HasValue && obj > value) + throw CreateAtMostException(name, msg, value); + } +#endif + + /// 不可大于 public static void AtMost(sbyte obj, sbyte value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(byte obj, byte value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(short obj, short value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(ushort obj, ushort value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(int obj, int value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(uint obj, uint value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(long obj, long value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(ulong obj, ulong value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(sbyte? obj, sbyte value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(byte? obj, byte value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(short? obj, short value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(ushort? obj, ushort value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(int? obj, int value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(uint? obj, uint value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(long? obj, long value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } - /// Value must be at most . + /// 不可大于 public static void AtMost(ulong? obj, ulong value, string name, string? msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } private static ArgumentException CreateAtMostException(string name, string? msg, T value) => new ArgumentException(message: msg ?? $"Value must be at most {value}.", paramName: name); - /// Value must be less than . +#if NET7_0_OR_GREATER + /// 必须小于 + public static void LessThan(T? obj, T value, string name, string? msg = null) + where T : struct, IComparisonOperators + { + if (obj.HasValue && obj >= value) + throw CreateLessThanException(name, msg, value); + } +#endif + + /// 必须小于 public static void LessThan(sbyte obj, sbyte value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(byte obj, byte value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(short obj, short value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(ushort obj, ushort value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(int obj, int value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(uint obj, uint value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(long obj, long value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(ulong obj, ulong value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(sbyte? obj, sbyte value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(byte? obj, byte value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(short? obj, short value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(ushort? obj, ushort value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(int? obj, int value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(uint? obj, uint value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(long? obj, long value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } - /// Value must be less than . + /// 必须小于 public static void LessThan(ulong? obj, ulong value, string name, string? msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } private static ArgumentException CreateLessThanException(string name, string? msg, T value) => diff --git a/src/Kook.Net.Core/Utils/TagUtils.cs b/src/Kook.Net.Core/Utils/TagUtils.cs new file mode 100644 index 00000000..dafd97fb --- /dev/null +++ b/src/Kook.Net.Core/Utils/TagUtils.cs @@ -0,0 +1,59 @@ +namespace Kook; + +/// +/// 提供用于转换 为强类型实现类的工具方法。 +/// +public static class TagUtils +{ + /// + /// 将标签转换为用户标签。 + /// + /// 要转换的标签。 + /// 转换后的用户标签。 + /// 标签不是用户提及标签。 + public static Tag AsUserTag(this ITag tag) + { + if (tag.Type is not TagType.UserMention) + throw new InvalidCastException("The tag is not a user mention tag."); + return (Tag)tag; + } + + /// + /// 将标签转换为频道标签。 + /// + /// 要转换的标签。 + /// 转换后的频道标签。 + /// 标签不是频道提及标签。 + public static Tag AsChannelTag(this ITag tag) + { + if (tag.Type is not TagType.ChannelMention) + throw new InvalidCastException("The tag is not a channel mention tag."); + return (Tag)tag; + } + + /// + /// 将标签转换为角色标签。 + /// + /// 要转换的标签。 + /// 转换后的角色标签。 + /// 标签不是角色提及标签。 + public static Tag AsRoleTag(this ITag tag) + { + if (tag.Type is not (TagType.RoleMention or TagType.HereMention or TagType.EveryoneMention)) + throw new InvalidCastException("The tag is not a role mention tag."); + return (Tag)tag; + } + + /// + /// 将标签转换为表情符号标签。 + /// + /// 要转换的标签。 + /// 转换后的表情符号标签。 + /// 标签不是表情符号标签。 + public static Tag AsEmojiTag(this ITag tag) + { + if (tag.Type is not TagType.Emoji) + throw new InvalidCastException("The tag is not an emoji tag."); + return (Tag)tag; + } +} diff --git a/src/Kook.Net.Core/Utils/TokenUtils.cs b/src/Kook.Net.Core/Utils/TokenUtils.cs index da1b8569..17faa365 100644 --- a/src/Kook.Net.Core/Utils/TokenUtils.cs +++ b/src/Kook.Net.Core/Utils/TokenUtils.cs @@ -4,51 +4,45 @@ namespace Kook; /// -/// Provides a series of helper methods for handling Kook login tokens. +/// 提供一组用于处理 KOOK 登录令牌的辅助方法。 /// public static class TokenUtils { /// - /// The minimum length of a Bot token. + /// Bot 令牌的最小长度。 /// /// - /// This value was determined by comparing against the examples in the Kook - /// documentation, and pre-existing tokens. + /// 此值是通过与 KOOK 文档和现有令牌的示例进行比较确定的。 /// internal const int MinBotTokenLength = 33; /// - /// The standard length of a Bot token. + /// Bot 令牌的标准长度。 /// /// - /// This value was determined by comparing against the examples in the Kook - /// documentation, and pre-existing tokens. + /// 此值是通过与 KOOK 文档和现有令牌的示例进行比较确定的。 /// internal const int StandardBotTokenLength = 35; /// - /// The padding character used in base64 encoding. + /// Base64 编码中使用的填充字符。 /// internal const char Base64Padding = '='; /// - /// Pads a base64-encoded string with 0, 1, or 2 '=' characters, - /// if the string is not a valid multiple of 4. - /// Does not ensure that the provided string contains only valid base64 characters. - /// Strings that already contain padding will not have any more padding applied. + /// 如果一个 Base64 编码的字符串长度不是 4 的倍数,则使用 0、1 或 2 个 '=' 字符对其进行填充。 + /// 此方法不保证提供的字符串仅包含有效的 Base64 字符,已经包含填充的字符串不会再添加额外的填充字符。 /// /// - /// A string that would require 3 padding characters is considered to be already corrupt. - /// Some older bot tokens may require padding, as the format provided by Kook - /// does not include this padding in the token. + /// 需要 3 个填充字符的 base64 字符串会被视为其格式不正确。 /// - /// The base64 encoded string to pad with characters. - /// A string containing the base64 padding. + /// 要用字符填充的 base64 编码字符串。 + /// 包含 base64 填充字符的字符串。 /// - /// Thrown if would require an invalid number of padding characters. + /// 如果 需要无效数量的填充字符,将引发异常。 /// /// - /// Thrown if is null, empty, or whitespace. + /// 如果 为 null、空字符串或仅包含空白字符,将引发异常。 /// internal static string PadBase64String(string encodedBase64) { @@ -71,11 +65,11 @@ internal static string PadBase64String(string encodedBase64) } /// - /// Decodes a base 64 encoded string into a ulong value. + /// 解码 Base64 编码的字符串为 ulong 类型的数值。 /// - /// A base 64 encoded string containing a User Id. - /// A ulong containing the decoded value of the string, or null if the value was invalid. - internal static ulong? DecodeBase64UserId(string encoded) + /// 由 Base64 编码的数值字符串。 + /// 包含解码值的 ulong 类型的数值,如果值无效则返回 null + internal static ulong? DecodeBase64AsNumber(string encoded) { if (string.IsNullOrWhiteSpace(encoded)) return null; @@ -106,52 +100,44 @@ internal static string PadBase64String(string encodedBase64) } /// - /// Checks the validity of a bot token by attempting to decode a ulong userid - /// from the bot token. + /// 校验 Bot 令牌的有效性。 /// - /// - /// The bot token to validate. - /// - /// - /// true if the token is valid, false otherwise. - /// - internal static bool CheckBotTokenValidity(string message) + /// 要校验的 Bot 令牌。 + /// 如果校验成功,则返回 true;否则返回 false + internal static bool CheckBotTokenValidity(string token) { - if (string.IsNullOrWhiteSpace(message)) return false; + if (string.IsNullOrWhiteSpace(token)) return false; // split each component of the JWT - string[] segments = message.Split('/'); + string[] segments = token.Split('/'); // ensure that there are three parts if (segments.Length < 3) return false; // return true if the user id could be determined - return DecodeBase64UserId(segments[1]).HasValue; + return DecodeBase64AsNumber(segments[1]).HasValue; } /// - /// The set of all characters that are not allowed inside of a token. + /// 令牌中不允许的所有字符。 /// internal static readonly char[] IllegalTokenCharacters = [' ', '\t', '\r', '\n']; /// - /// Checks if the given token contains a whitespace or newline character - /// that would fail to log in. + /// 检查给定的令牌是否包含会导致登录失败的空格或换行符。 /// - /// The token to validate. - /// - /// true if the token contains a whitespace or newline character. - /// + /// 要检查的令牌。 + /// 如果令牌包含空格或换行符,则返回 true;否则返回 false internal static bool CheckContainsIllegalCharacters(string token) => token.IndexOfAny(IllegalTokenCharacters) != -1; /// - /// Checks the validity of the supplied token of a specific type. + /// 检查指定类型的令牌的有效性。 /// - /// The type of token to validate. - /// The token value to validate. - /// Thrown when the supplied token string is null, empty, or contains only whitespace. - /// Thrown when the supplied or token value is invalid. + /// 令牌的类型。 + /// 要校验的令牌。 + /// 当提供的令牌值为 null、空字符串或仅包含空白字符时引发异常。 + /// 当提供的令牌类型或令牌值无效时引发异常。 public static void ValidateToken(TokenType tokenType, string token) { // A Null or WhiteSpace token of any type is invalid. diff --git a/src/Kook.Net.Core/Utils/UrlValidation.cs b/src/Kook.Net.Core/Utils/UrlValidation.cs index dbcff26c..38b193fb 100644 --- a/src/Kook.Net.Core/Utils/UrlValidation.cs +++ b/src/Kook.Net.Core/Utils/UrlValidation.cs @@ -5,12 +5,15 @@ namespace Kook.Utils; internal static class UrlValidation { /// - /// Not full URL validation right now. Just ensures protocol is present and that it's either http or https. + /// 检查 URL 是否有效。 /// - /// The URL to validate before sending to Kook. - /// A URL cannot be null or empty. - /// A URL must include a protocol (http or https). - /// true if URL is valid by our standard, false if null, throws an error upon invalid. + /// 要校验的 URL。 + /// URL 不能为空。 + /// URL 必须包含协议(HTTP 或 HTTPS)。 + /// 如果 URL 有效,则为 true,否则为 false + /// + /// 当前方法仅检查 URL 是否非空,且指定了了 HTTP 或 HTTPS 协议。 + /// public static void Validate(string url) { if (string.IsNullOrEmpty(url)) @@ -22,21 +25,21 @@ public static void Validate(string url) } /// - /// Ensures that the URL represents an asset on the Kook OSS server. + /// 确保 URL 表示的是 KOOK 对象存储服务器上的资源。 /// /// - /// This method checks the URL from 3 parts: + /// 此方法从 3 个部分检查 URL: /// - /// The scheme must be either http or https + /// URL 的协议必须是 HTTP 或 HTTPS。 /// - /// The host must be one of the following: + /// URL 的主机名必须是以下之一: /// /// img.kaiheila.cn /// img.kookapp.cn /// kaiheila.oss-cn-beijing.aliyuncs.com /// /// - /// The path must in the form of the following: + /// URL 的路径的格式必需形如: /// /// /assets/2021-01/7kr4FkWpLV0ku0ku.jpeg /// /assets/2022-01/21/HwuGGgpohG0ku0ku.jpeg @@ -45,9 +48,9 @@ public static void Validate(string url) /// /// /// - /// The URL to validate before sending to Kook. - /// The URL provided is not an asset on the Kook OSS. - /// true if URL represents a valid asset on the Kook OSS, false if null, throws an error upon invalid. + /// 要校验的 URL。 + /// URL 不是有效的 KOOK 对象存储服务器上的资源地址。 + /// 如果 URL 指向了有效的 KOOK 对象存储服务器上的资源,则为 true,否则为 false public static bool ValidateKookAssetUrl(string url) { if (string.IsNullOrEmpty(url)) return false; diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfigurator.cs index fba54883..8aadac22 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfigurator.cs @@ -3,30 +3,30 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Represents a configurator for a Kook client. +/// 表示一个通用的 KOOK 客户端配置器。 /// -/// The type of the client. -/// The type of the configuration. +/// 客户端的类型。 +/// 配置的类型。 public interface IKookClientConfigurator where TClient : IKookClient where TConfig : KookConfig { /// - /// Gets the service collection to append services. + /// 获取用于添加服务的服务集合。 /// IServiceCollection ServiceCollection { get; } /// - /// Appends a configuration action, which is executed on the created configuration instance. + /// 添加一个配置操作,该操作将在创建的配置实例上执行。 /// - /// The configuration action. - /// The configurator. + /// 配置操作。 + /// 添加了配置操作的配置器。 IKookClientConfigurator AppendConfigure(Action configure); /// - /// Appends a service action, which is executed on the service collection. + /// 添加一个服务操作,该操作将在服务集合上执行。 /// - /// The service action. - /// The configurator. + /// 服务操作。 + /// 添加了服务操作的配置器。 IKookClientConfigurator AppendService(Action service); } diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfiguratorCompleter.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfiguratorCompleter.cs index b5e563fe..8e287ff7 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfiguratorCompleter.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientConfiguratorCompleter.cs @@ -1,12 +1,12 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Represents a generic completer for a Kook client configurator. +/// 表示一个通用的 KOOK 客户端配置器的完成器。 /// public interface IKookClientConfiguratorCompleter { /// - /// Completes the configuration. + /// 完成配置。 /// void Complete(); } diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientServiceConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientServiceConfigurator.cs index 129a347b..963b41b3 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientServiceConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/IKookClientServiceConfigurator.cs @@ -6,32 +6,32 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Represents a configurator for a Kook client. +/// 表示一个通用的 KOOK 客户端服务配置器。 /// public interface IKookClientServiceConfigurator : IKookClientConfiguratorCompleter { /// - /// Configures the Kook service to use the REST client. + /// 配置使用 REST 客户端。 /// - /// The configuration action. - /// The configurator. + /// 配置操作。 + /// 配置了 REST 客户端的配置器。 IKookClientConfigurator UseRestClient(Action configure); /// - /// Configures the Kook service to use the socket client. + /// 配置使用网关客户端。 /// - /// The configuration action. - /// The configurator. + /// 配置操作。 + /// 配置了网关客户端的配置器。 IKookClientConfigurator UseSocketClient(Action configure); /// - /// Configures the Kook service to use the webhook client. + /// 配置使用基于 Webhook 的网关客户端。 /// - /// The client factory. - /// The configuration action. - /// The type of the client. - /// The type of the configuration. - /// The configurator. + /// 客户端创建委托。 + /// 配置操作。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了基于 Webhook 的网关客户端的配置器。 IKookClientConfigurator UseWebhookClient( Func, TClient> clientFactory, Action configure) where TClient : KookWebhookClient diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfigurator.cs index b626fb35..44d8d9ed 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfigurator.cs @@ -3,7 +3,11 @@ namespace Kook.Net.DependencyInjection.Microsoft; -/// +/// +/// 表示一个 KOOK 客户端配置器基类。 +/// +/// 客户端的类型。 +/// 配置的类型。 public abstract class KookClientConfigurator : IKookClientConfigurator, IKookClientConfiguratorCompleter where TClient : IKookClient diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfiguratorExtensions.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfiguratorExtensions.cs index d1681214..998117e9 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfiguratorExtensions.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientConfiguratorExtensions.cs @@ -4,18 +4,18 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Provides extension methods for to configure Kook clients. +/// 为 提供配置 KOOK 客户端的扩展方法。 /// public static class KookClientConfiguratorExtensions { /// - /// Configures a Kook client to use a message queue provider. + /// 配置 KOOK 客户端使用指定的消息队列提供程序。 /// - /// The configurator. - /// The message queue provider. - /// The type of the client. - /// The type of the configuration. - /// The configurator. + /// 配置器。 + /// 消息队列提供程序。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了消息队列的配置器。 public static IKookClientConfigurator UseMessageQueue( this IKookClientConfigurator configurator, MessageQueueProvider messageQueueProvider) @@ -27,13 +27,13 @@ public static IKookClientConfigurator UseMessageQueue - /// Configures a Kook client to use a message queue provider. + /// 配置 KOOK 客户端使用指定的消息队列提供程序。 /// - /// The configurator. - /// The message queue provider. - /// The type of the client. - /// The type of the configuration. - /// The configurator. + /// 配置器。 + /// 消息队列提供程序。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了消息队列的配置器。 public static IKookClientConfigurator UseMessageQueue( this IKookClientConfigurator configurator, Func messageQueueProvider) diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientServiceConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientServiceConfigurator.cs index 5c8cd791..cef84f7e 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientServiceConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookClientServiceConfigurator.cs @@ -7,7 +7,7 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Represents a configurator for a Kook client. +/// 表示一个 KOOK 客户端配置器。 /// public class KookClientServiceConfigurator : IKookClientServiceConfigurator { diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookConfiguratorExtensions.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookConfiguratorExtensions.cs index c3d2bce7..8824c760 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookConfiguratorExtensions.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookConfiguratorExtensions.cs @@ -3,19 +3,19 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Provides extension methods for to add Kook clients and services. +/// 提供用于向 添加 KOOK 客户端和服务的扩展方法。 /// public static class KookConfiguratorExtensions { /// - /// Adds a Kook client to the service collection. + /// 向指定的 添加 KOOK 客户端和服务。 /// - /// The service collection. - /// The configuration action. - /// The service collection. + /// 要向其添加 KOOK 客户端和服务的服务集合。 + /// 用于配置 KOOK 客户端和服务的配置委托。 + /// 添加了 KOOK 客户端和服务的服务集合。 public static IServiceCollection AddKook(this IServiceCollection services, Action configure) { - IKookClientServiceConfigurator configurator = new KookClientServiceConfigurator(services); + KookClientServiceConfigurator configurator = new(services); configure(configurator); configurator.Complete(); return services; diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookRestClientConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookRestClientConfigurator.cs index f4c57a72..15ee5ac0 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookRestClientConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookRestClientConfigurator.cs @@ -3,10 +3,7 @@ namespace Kook.Net.DependencyInjection.Microsoft; -/// -/// Represents a configurator for a Kook REST client. -/// -public class KookRestClientConfigurator : KookClientConfigurator +internal class KookRestClientConfigurator : KookClientConfigurator { internal KookRestClientConfigurator(IServiceCollection services, Action configure) : base(services, configure) diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookSocketClientConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookSocketClientConfigurator.cs index f27023a9..33d1c64e 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookSocketClientConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookSocketClientConfigurator.cs @@ -3,10 +3,7 @@ namespace Kook.Net.DependencyInjection.Microsoft; -/// -/// Represents a configurator for a Kook socket client. -/// -public class KookSocketClientConfigurator : KookClientConfigurator +internal class KookSocketClientConfigurator : KookClientConfigurator { internal KookSocketClientConfigurator(IServiceCollection services, Action configure) : base(services, configure) diff --git a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookWebhookClientConfigurator.cs b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookWebhookClientConfigurator.cs index bec18823..1a872391 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookWebhookClientConfigurator.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/Configurators/KookWebhookClientConfigurator.cs @@ -4,12 +4,7 @@ namespace Kook.Net.DependencyInjection.Microsoft; -/// -/// Represents a configurator for a Kook webhook client. -/// -/// The type of the client. -/// The type of the configuration. -public class KookWebhookClientConfigurator : KookClientConfigurator +internal class KookWebhookClientConfigurator : KookClientConfigurator where TClient : KookWebhookClient where TConfig : KookWebhookConfig { diff --git a/src/Kook.Net.DependencyInjection.Microsoft/KookClientDependencyInjectionExtensions.cs b/src/Kook.Net.DependencyInjection.Microsoft/KookClientDependencyInjectionExtensions.cs index b121657e..eea58652 100644 --- a/src/Kook.Net.DependencyInjection.Microsoft/KookClientDependencyInjectionExtensions.cs +++ b/src/Kook.Net.DependencyInjection.Microsoft/KookClientDependencyInjectionExtensions.cs @@ -7,17 +7,19 @@ namespace Kook.Net.DependencyInjection.Microsoft; /// -/// Provides extension methods for Kook.Net to add clients using the . +/// 提供用于与 Microsoft.Extensions.DependencyInjection 集成,注册与配置 Kook.Net 客户端作为服务的扩展方法。 /// public static class KookClientDependencyInjectionExtensions { + #region REST + /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The action to configure the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端的服务集合。 + /// 用于配置 KOOK REST 客户端的配置委托。 + /// 添加了 KOOK REST 客户端的服务集合。 public static IServiceCollection AddKookRestClient(this IServiceCollection services, Action configure) { services.Configure(configure); @@ -26,12 +28,12 @@ public static IServiceCollection AddKookRestClient(this IServiceCollection servi } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The action to configure the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端的服务集合。 + /// 用于配置 KOOK REST 客户端的配置。 + /// 添加了 KOOK REST 客户端的服务集合。 public static IServiceCollection AddKookRestClient(this IServiceCollection services, KookRestConfig config) { services.AddSingleton(config); @@ -40,11 +42,11 @@ public static IServiceCollection AddKookRestClient(this IServiceCollection servi } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端的服务集合。 + /// 添加了 KOOK REST 客户端的服务集合。 public static IServiceCollection AddKookRestClient(this IServiceCollection services) { services.AddSingleton(provider => provider.GetService>()?.Value is { } config @@ -55,13 +57,17 @@ public static IServiceCollection AddKookRestClient(this IServiceCollection servi return services; } + #endregion + + #region Socket + /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The action to configure the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端的服务集合。 + /// 用于配置 KOOK 网关客户端的配置委托。 + /// 添加了 KOOK 网关客户端的服务集合。 public static IServiceCollection AddKookSocketClient(this IServiceCollection services, Action configure) { services.Configure(configure); @@ -70,12 +76,12 @@ public static IServiceCollection AddKookSocketClient(this IServiceCollection ser } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The action to configure the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端的服务集合。 + /// 用于配置 KOOK 网关客户端的配置。 + /// 添加了 KOOK 网关客户端的服务集合。 public static IServiceCollection AddKookSocketClient(this IServiceCollection services, KookSocketConfig config) { services.AddSingleton(config); @@ -84,11 +90,11 @@ public static IServiceCollection AddKookSocketClient(this IServiceCollection ser } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端的服务集合。 + /// 添加了 KOOK 网关客户端的服务集合。 public static IServiceCollection AddKookSocketClient(this IServiceCollection services) { services.AddSingleton(provider => provider.GetService>()?.Value is { } config @@ -100,15 +106,20 @@ public static IServiceCollection AddKookSocketClient(this IServiceCollection ser return services; } + #endregion + + #region Webhook + /// - /// Adds a to the specified with + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The factory to create the . - /// The action to configure the . - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK Webhook 客户端的服务集合。 + /// 用于创建 KOOK Webhook 客户端的委托。 + /// 用于配置 KOOK Webhook 客户端的配置委托。 + /// Webhook 客户端的类型。 + /// Webhook 客户端的配置类型。 + /// 添加了 KOOK Webhook 客户端的服务集合。 public static IServiceCollection AddKookWebhookClient(this IServiceCollection services, Func, TClient> clientFactory, Action configure) where TClient: KookWebhookClient @@ -120,14 +131,15 @@ public static IServiceCollection AddKookWebhookClient(this ISe } /// - /// Adds a to the specified with + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The factory to create the . - /// The action to configure the . - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK Webhook 客户端的服务集合。 + /// 用于创建 KOOK Webhook 客户端的委托。 + /// 用于配置 KOOK Webhook 客户端的配置。 + /// Webhook 客户端的类型。 + /// Webhook 客户端的配置类型。 + /// 添加了 KOOK Webhook 客户端的服务集合。 public static IServiceCollection AddKookWebhookClient(this IServiceCollection services, Func clientFactory, TConfig config) where TClient: KookWebhookClient @@ -139,13 +151,14 @@ public static IServiceCollection AddKookWebhookClient(this ISe } /// - /// Adds a to the specified with + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The factory to create the . - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK Webhook 客户端的服务集合。 + /// 用于创建 KOOK Webhook 客户端的委托。 + /// Webhook 客户端的类型。 + /// Webhook 客户端的配置类型。 + /// 添加了 KOOK Webhook 客户端的服务集合。 public static IServiceCollection AddKookWebhookClient(this IServiceCollection services, Func, TClient> clientFactory) where TClient: KookWebhookClient @@ -157,13 +170,14 @@ public static IServiceCollection AddKookWebhookClient(this ISe } /// - /// Adds a to the specified with + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The factory to create the . - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK Webhook 客户端的服务集合。 + /// 用于创建 KOOK Webhook 客户端的委托。 + /// Webhook 客户端的类型。 + /// Webhook 客户端的配置类型。 + /// 添加了 KOOK Webhook 客户端的服务集合。 public static IServiceCollection AddKookWebhookClient(this IServiceCollection services, Func clientFactory) where TClient: KookWebhookClient @@ -175,12 +189,13 @@ public static IServiceCollection AddKookWebhookClient(this ISe } /// - /// Adds a to the specified with + /// 向指定的 + /// 添加 客户端。 /// - /// The to add the services. - /// The factory to create the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加 KOOK Webhook 客户端的服务集合。 + /// 用于创建 KOOK Webhook 客户端的委托。 + /// Webhook 客户端的类型。 + /// 添加了 KOOK Webhook 客户端的服务集合。 public static IServiceCollection AddKookWebhookClient(this IServiceCollection services, Func clientFactory) where TClient: KookWebhookClient @@ -199,4 +214,6 @@ internal static void AddKookWebhookClient(this IServiceCollection servi services.AddSingleton(provider => provider.GetRequiredService()); services.AddSingleton(provider => provider.GetRequiredService()); } + + #endregion } diff --git a/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs b/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs deleted file mode 100644 index eb5c5b86..00000000 --- a/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs +++ /dev/null @@ -1,84 +0,0 @@ -namespace Kook; - -/// -/// Provides properties that are used to modify an with the specified changes. -/// -/// -/// -/// This entity is still in experimental state, which means that it is not for official API implementation -/// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. -/// -/// -public class GuildProperties -{ - /// - /// Gets or sets the region for the guild's voice connections. - /// - public IVoiceRegion? Region { get; set; } - - /// - /// Gets or sets the ID of the region for the guild's voice connections. - /// - public string? RegionId { get; set; } - - /// - /// Gets or sets the ID of the default channel. - /// - /// - /// An ulong representing the identifier of the default channel. - /// null if nothing changes. 0 if set to none. - /// - public ulong? DefaultChannelId { get; set; } - - /// - /// Gets or sets the default channel. - /// - /// - /// An which is the default channel; null if nothing changes. - /// To clear the manually assigned default channel, set to 0 instead. - /// - public ITextChannel? DefaultChannel { get; set; } - - /// - /// Gets or sets the ID of welcome channel. - /// - /// - /// An ulong representing the identifier of the channel where welcome messages are sent; - /// null if nothing changes. 0 if set to none. - /// - public ulong? WelcomeChannelId { get; set; } - - /// - /// Gets or sets the welcome channel. - /// - /// - /// An where welcome messages are sent; null if nothing changes. - /// To clear the welcome channel, set to 0 instead. - /// - public ITextChannel? WelcomeChannel { get; set; } - - /// - /// Gets or sets whether the guild is open. - /// - public bool? EnableOpen { get; set; } - - /// - /// Gets the ID of the channel assigned to the widget of this guild. - /// - /// - /// A ulong representing the identifier of the channel assigned to the widget found - /// within the widget settings of this guild; null if nothing changes; 0 if - /// set to none. - /// - public ulong? WidgetChannelId { get; set; } - - /// - /// Gets the channel assigned to the widget of this guild. - /// - /// - /// An assigned to the widget found within the widget settings of this guild; - /// null if nothing changes; To clear the widget channel, - /// set to 0 instead. - /// - public ITextChannel? WidgetChannel { get; set; } -} diff --git a/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs b/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs deleted file mode 100644 index 5777b2d5..00000000 --- a/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace Kook; - -/// -/// Represents a region of which the user connects to when using voice. -/// -/// -/// -/// This entity is still in experimental state, which means that it is not for official API implementation -/// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. -/// -/// -public interface IVoiceRegion -{ - /// - /// Gets the unique identifier for this voice region. - /// - /// - /// A string that represents the identifier for this voice region (e.g. eu-central). - /// - string Id { get; } - - /// - /// Gets the name of this voice region. - /// - /// - /// A string that represents the human-readable name of this voice region (e.g. Central Europe). - /// - string Name { get; } - - /// - /// Gets the crowding of this voice region. - /// - /// - /// A decimal between 0.0 and 1.0 that represents the crowding of this voice region. - /// - decimal Crowding { get; } - - /// - /// Gets the minimum boost level required to use this voice region. - /// - /// - /// A that represents the minimum boost level required to use this voice region. - /// - BoostLevel MinimumBoostLevel { get; } -} diff --git a/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs b/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs deleted file mode 100644 index 4395a6fa..00000000 --- a/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Kook.API; - -internal class VoiceRegion -{ - [JsonPropertyName("id")] - public required string Id { get; set; } - - [JsonPropertyName("name")] - public required string Name { get; set; } - - [JsonPropertyName("crowding")] - public int Crowding { get; set; } - - [JsonPropertyName("level")] - public BoostLevel MinimumBoostLevel { get; set; } -} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs deleted file mode 100644 index 70e41755..00000000 --- a/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Kook.Net.Converters; -using System.Text.Json.Serialization; - -namespace Kook.API.Rest; - -internal class CreateGuildParams -{ - [JsonPropertyName("name")] - public required string Name { get; set; } - - [JsonPropertyName("icon")] - [JsonIgnore(Condition = JsonIgnoreCondition.Never)] - [JsonConverter(typeof(ImageBase64DataUriConverter))] - public Image? Icon { get; set; } - - [JsonPropertyName("region")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public string? RegionId { get; set; } - - [JsonPropertyName("template_id")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public int? TemplateId { get; set; } -} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs deleted file mode 100644 index c5b8c7b3..00000000 --- a/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Kook.API.Rest; - -internal class DeleteGuildParams -{ - [JsonPropertyName("guild_id")] - public required ulong GuildId { get; set; } - - public static implicit operator DeleteGuildParams(ulong guildId) => new() { GuildId = guildId }; -} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs deleted file mode 100644 index d1213211..00000000 --- a/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Kook.API.Rest; - -internal class DisconnectUserParams -{ - [JsonPropertyName("channel_id")] - public required ulong ChannelId { get; set; } - - [JsonPropertyName("user_id")] - public required ulong UserId { get; set; } -} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs deleted file mode 100644 index 273d9be5..00000000 --- a/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Kook.API.Rest; - -internal class ModifyGuildParams -{ - [JsonPropertyName("guild_id")] - public ulong GuildId { get; set; } - - [JsonPropertyName("region")] - public string? RegionId { get; set; } - - [JsonPropertyName("default_channel_id")] - public ulong? DefaultChannelId { get; set; } - - [JsonPropertyName("welcome_channel_id")] - public ulong? WelcomeChannelId { get; set; } - - [JsonPropertyName("enable_open")] - public bool? EnableOpen { get; set; } - - [JsonPropertyName("widget_invite_channel_id")] - public ulong? WidgetChannelId { get; set; } -} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs b/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs deleted file mode 100644 index 212de5a4..00000000 --- a/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Kook.API.Rest; -using Kook.Rest.Extensions; - -namespace Kook.Rest; - -internal static class ExperimentalChannelHelper -{ - #region Permissions - - /// This channel does not have a parent channel. - public static async Task SyncPermissionsAsync(INestedChannel channel, BaseKookClient client, RequestOptions? options) - { - ICategoryChannel? category = await ChannelHelper.GetCategoryAsync(channel, client, options).ConfigureAwait(false); - if (category == null) - throw new InvalidOperationException("This channel does not have a parent channel."); - - SyncChannelPermissionsParams args = new() - { - ChannelId = channel.Id - }; - await client.ApiClient.SyncChannelPermissionsAsync(args, options).ConfigureAwait(false); - } - - #endregion - - #region Voice - - public static async Task DisconnectUserAsync(IVoiceChannel channel, BaseKookClient client, IGuildUser user, RequestOptions? options) - { - DisconnectUserParams args = new() { UserId = user.Id, ChannelId = channel.Id }; - await client.ApiClient.DisconnectUserAsync(args, options).ConfigureAwait(false); - } - - #endregion -} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs deleted file mode 100644 index 79d91130..00000000 --- a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace Kook.Rest; - -/// -/// Provides extension methods of experimental functionalities for s. -/// -public static class RestTextChannelExperimentalExtensions -{ - /// - /// Syncs the permissions of this nested channel with its parent's. - /// - /// The nested channel whose permissions will be synced. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for syncing channel permissions with its parent's. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task SyncPermissionsAsync(this RestTextChannel channel, RequestOptions? options = null) => - ExperimentalChannelHelper.SyncPermissionsAsync(channel, channel.Kook, options); -} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs deleted file mode 100644 index 48397db9..00000000 --- a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Kook.Rest; - -/// -/// Provides extension methods of experimental functionalities for s. -/// -public static class RestVoiceChannelExperimentalExtensions -{ - /// - /// Syncs the permissions of this nested channel with its parent's. - /// - /// The nested channel whose permissions will be synced. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for syncing channel permissions with its parent's. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task SyncPermissionsAsync(this RestVoiceChannel channel, RequestOptions? options = null) => - ExperimentalChannelHelper.SyncPermissionsAsync(channel, channel.Kook, options); - - /// - /// Disconnects the specified user from the voice channel. - /// - /// The voice channel where the use is connected to. - /// The user to disconnect. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for disconnecting the user from the voice channel. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task DisconnectUserAsync(this RestVoiceChannel channel, IGuildUser user, RequestOptions? options = null) => - ExperimentalChannelHelper.DisconnectUserAsync(channel, channel.Kook, user, options); -} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs b/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs deleted file mode 100644 index 0dafebe5..00000000 --- a/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Kook.API.Rest; -using Kook.Rest.Extensions; -using RichModel = Kook.API.Rest.RichGuild; - -namespace Kook.Rest; - -internal static class ExperimentalGuildHelper -{ - /// is null. - public static async Task ModifyAsync(IGuild guild, BaseKookClient client, - Action func, RequestOptions? options) - { - if (func == null) throw new ArgumentNullException(nameof(func)); - - GuildProperties args = new(); - func(args); - - ModifyGuildParams apiArgs = new() - { - GuildId = guild.Id, - EnableOpen = args.EnableOpen - }; - - if (args.Region is not null) - apiArgs.RegionId = args.Region.Id; - else if (!string.IsNullOrWhiteSpace(args.RegionId)) - apiArgs.RegionId = args.RegionId; - - if (args.DefaultChannel is not null) - apiArgs.DefaultChannelId = args.DefaultChannel.Id; - else if (args.DefaultChannelId is not null) - apiArgs.DefaultChannelId = args.DefaultChannelId.Value; - - if (args.WelcomeChannel is not null) - apiArgs.WelcomeChannelId = args.WelcomeChannel.Id; - else if (args.WelcomeChannelId is not null) - apiArgs.WelcomeChannelId = args.WelcomeChannelId.Value; - - if (args.WidgetChannel is not null) - apiArgs.WidgetChannelId = args.WidgetChannel.Id; - else if (args.WidgetChannelId is not null) - apiArgs.WidgetChannelId = args.WidgetChannelId.Value; - - return await client.ApiClient.ModifyGuildAsync(guild.Id, apiArgs, options).ConfigureAwait(false); - } - - public static async Task DeleteAsync(IGuild guild, BaseKookClient client, RequestOptions? options) => - await client.ApiClient.DeleteGuildAsync(guild.Id, options).ConfigureAwait(false); -} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestGuildExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestGuildExperimentalExtensions.cs deleted file mode 100644 index 3238eb42..00000000 --- a/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestGuildExperimentalExtensions.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Kook.API.Rest; - -namespace Kook.Rest; - -/// -/// Provides extension methods of experimental functionalities for s. -/// -public static class RestGuildExperimentalExtensions -{ - /// - /// Deletes this guild. - /// - /// The guild to delete. - /// The options to be used when sending the request. - /// A task that represents the asynchronous deletion operation. - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task DeleteAsync(this RestGuild guild, RequestOptions? options = null) => - ExperimentalGuildHelper.DeleteAsync(guild, guild.Kook, options); - - /// - /// Modifies this guild. - /// - /// The guild to modify. - /// The delegate containing the properties to modify the guild with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// - /// is null. - public static async Task ModifyAsync(this RestGuild guild, Action func, RequestOptions? options = null) - { - RichGuild model = await ExperimentalGuildHelper.ModifyAsync(guild, guild.Kook, func, options).ConfigureAwait(false); - guild.Update(model); - } -} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs b/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs deleted file mode 100644 index 54158c30..00000000 --- a/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Diagnostics; -using Model = Kook.API.VoiceRegion; - -namespace Kook.Rest; - -/// -/// Represents a REST-based voice region. -/// -/// -/// -/// This entity is still in experimental state, which means that it is not for official API implementation -/// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. -/// -/// -[DebuggerDisplay("{DebuggerDisplay,nq}")] -public class RestVoiceRegion : RestEntity, IVoiceRegion -{ - /// - public string Name { get; private set; } - - /// - public decimal Crowding { get; private set; } - - /// - public BoostLevel MinimumBoostLevel { get; set; } - - internal RestVoiceRegion(BaseKookClient kook, string id) - : base(kook, id) - { - Name = string.Empty; - } - - internal static RestVoiceRegion Create(BaseKookClient kook, Model model) - { - RestVoiceRegion entity = new(kook, model.Id); - entity.Update(model); - return entity; - } - - internal void Update(Model model) - { - Name = model.Name; - Crowding = model.Crowding / 100M; - MinimumBoostLevel = model.MinimumBoostLevel; - } - - /// - public override string ToString() => Name; - - private string DebuggerDisplay => $"{Name} ({Id}, {Crowding:F2}%)"; -} diff --git a/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs b/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs index afcd5149..514339b5 100644 --- a/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs +++ b/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs @@ -9,21 +9,6 @@ internal static class ExperimentalClientHelper { #region Guild - public static async Task CreateGuildAsync(BaseKookClient client, - string name, IVoiceRegion? region = null, Stream? icon = null, int? templateId = null, RequestOptions? options = null) - { - CreateGuildParams args = new() - { - Name = name, - RegionId = region?.Id, - TemplateId = templateId - }; - if (icon != null) - args.Icon = new Image(icon); - RichGuild model = await client.ApiClient.CreateGuildAsync(args, options).ConfigureAwait(false); - return RestGuild.Create(client, model); - } - public static async Task> GetAdminGuildsAsync(BaseKookClient client, RequestOptions? options) { ImmutableArray.Builder guilds = ImmutableArray.CreateBuilder(); @@ -38,22 +23,6 @@ public static async Task> GetAdminGuildsAsync(Bas #endregion - #region Voice Region - - public static async Task> GetVoiceRegionsAsync(BaseKookClient client, RequestOptions? options) - { - IEnumerable models = await client.ApiClient.GetVoiceRegionsAsync(options: options).FlattenAsync().ConfigureAwait(false); - return [..models.Select(x => RestVoiceRegion.Create(client, x))]; - } - - public static async Task GetVoiceRegionAsync(BaseKookClient client, string id, RequestOptions? options) - { - IEnumerable models = await client.ApiClient.GetVoiceRegionsAsync(options: options).FlattenAsync().ConfigureAwait(false); - return models.Select(x => RestVoiceRegion.Create(client, x)).FirstOrDefault(x => x.Id == id); - } - - #endregion - #region Messages public static Task ValidateCardsAsync(KookRestClient client, IEnumerable cards, RequestOptions? options) diff --git a/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs index b8282132..be9824b5 100644 --- a/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs @@ -22,91 +22,6 @@ public static IAsyncEnumerable> GetAdminGuildsAsync(t ids, ClientBucketType.SendEdit, new PageMeta(fromPage, limit), options); } - public static async Task CreateGuildAsync(this KookRestApiClient client, - CreateGuildParams args, RequestOptions? options = null) - { - Preconditions.NotNull(args, nameof(args)); - Preconditions.NotNullOrWhitespace(args.Name, nameof(args.Name)); - options = RequestOptions.CreateOrClone(options); - - KookRestApiClient.BucketIds ids = new(); - return await client.SendJsonAsync(HttpMethod.Post, - () => "guild/create", args, ids, ClientBucketType.SendEdit, false, options) - .ConfigureAwait(false); - } - - public static async Task DeleteGuildAsync(this KookRestApiClient client, - DeleteGuildParams args, RequestOptions? options = null) - { - Preconditions.NotNull(args, nameof(args)); - Preconditions.NotEqual(args.GuildId, 0, nameof(args.GuildId)); - options = RequestOptions.CreateOrClone(options); - - KookRestApiClient.BucketIds ids = new(args.GuildId); - await client.SendJsonAsync(HttpMethod.Post, - () => $"guild/delete", args, ids, ClientBucketType.SendEdit, options) - .ConfigureAwait(false); - } - - public static async Task ModifyGuildAsync(this KookRestApiClient client, - ulong guildId, ModifyGuildParams args, RequestOptions? options = null) - { - Preconditions.NotEqual(guildId, 0, nameof(guildId)); - Preconditions.NotNull(args, nameof(args)); - options = RequestOptions.CreateOrClone(options); - - KookRestApiClient.BucketIds ids = new(guildId); - return await client.SendJsonAsync(HttpMethod.Post, - () => $"guild/update", args, ids, ClientBucketType.SendEdit, false, options) - .ConfigureAwait(false); - } - - public static async Task SyncChannelPermissionsAsync(this KookRestApiClient client, - SyncChannelPermissionsParams args, RequestOptions? options = null) - { - Preconditions.NotNull(args, nameof(args)); - Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); - options = RequestOptions.CreateOrClone(options); - - KookRestApiClient.BucketIds ids = new(channelId: args.ChannelId); - await client.SendJsonAsync(HttpMethod.Post, - () => $"channel-role/sync", args, ids, ClientBucketType.SendEdit, options) - .ConfigureAwait(false); - } - - #endregion - - #region Voice Regions - - public static IAsyncEnumerable> GetVoiceRegionsAsync(this KookRestApiClient client, - int limit = KookConfig.MaxUsersPerBatch, int fromPage = 1, RequestOptions? options = null) - { - options = RequestOptions.CreateOrClone(options); - KookRestApiClient.BucketIds ids = new(); - PageMeta pageMeta = new(fromPage, limit); - return client.SendPagedAsync(HttpMethod.Get, - (pageSize, page) => $"guild/regions&page_size={pageSize}&page={page}", - ids, ClientBucketType.SendEdit, pageMeta, options); - } - - #endregion - - #region Voice - - public static async Task DisconnectUserAsync(this KookRestApiClient client, - DisconnectUserParams args, RequestOptions? options = null) - { - Preconditions.NotNull(args, nameof(args)); - Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); - Preconditions.NotEqual(args.UserId, 0, nameof(args.UserId)); - options = RequestOptions.CreateOrClone(options); - - KookRestApiClient.BucketIds ids = new(channelId: args.ChannelId); - await client.SendJsonAsync(HttpMethod.Post, - () => $"channel/kickout", args, ids, ClientBucketType.SendEdit, options) - .ConfigureAwait(false); - } - #endregion #region Messages diff --git a/src/Kook.Net.Experimental/Rest/KookRestClientExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/KookRestClientExperimentalExtensions.cs index 2419e981..a4661de3 100644 --- a/src/Kook.Net.Experimental/Rest/KookRestClientExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/Rest/KookRestClientExperimentalExtensions.cs @@ -1,122 +1,46 @@ namespace Kook.Rest; /// -/// Provides extension methods of experimental functionalities for s. +/// 提供用于 的实验性功能的扩展方法。 /// public static class KookRestClientExperimentalExtensions { /// - /// Gets a collection of the available voice regions. + /// 获取当前用户具有 权限的服务器的集合。 /// - /// The KOOK rest client instance. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection - /// with all of the available voice regions in this session. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task> GetVoiceRegionsAsync(this KookRestClient client, RequestOptions? options = null) => - ExperimentalClientHelper.GetVoiceRegionsAsync(client, options); - - /// - /// Gets a voice region. - /// - /// The KOOK rest client instance. - /// The identifier of the voice region (e.g. eu-central ). - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the voice region - /// associated with the identifier; null if the voice region is not found. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task GetVoiceRegionAsync(this KookRestClient client, string id, RequestOptions? options = null) => - ExperimentalClientHelper.GetVoiceRegionAsync(client, id, options); - - /// - /// Creates a guild for the logged-in user. - /// - /// - /// This method creates a new guild on behalf of the logged-in user. - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - /// The KOOK rest client instance. - /// The name of the new guild. - /// The voice region to create the guild with. - /// The icon of the new guild. - /// The identifier of the guild template to be used to create the new guild. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the created guild. - /// - public static async Task CreateGuildAsync(this KookRestClient client, string name, - IVoiceRegion? region = null, Stream? icon = null, int? templateId = null, RequestOptions? options = null) - { - RestGuild guild = await ExperimentalClientHelper - .CreateGuildAsync(client, name, region, icon, templateId, options) - .ConfigureAwait(false); - await guild.UpdateAsync().ConfigureAwait(false); - return guild; - } - - /// - /// Gets a collection of guilds where the current user has the - /// permission. - /// - /// The KOOK rest client instance. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection - /// of guilds where the current user has the permission. - /// + /// KOOK REST 客户端实例。 + /// 发送请求时要使用的选项。 + /// 一个表示异步操作的任务,任务的结果包含当前用户具有 权限的使用服务器。 public static Task> GetAdminGuildsAsync(this KookRestClient client, RequestOptions? options = null) => ExperimentalClientHelper.GetAdminGuildsAsync(client, options); /// - /// Validates a card. + /// 验证卡片。 /// - /// The KOOK rest client instance. - /// The card to be validated. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous validation operation. - /// + /// KOOK REST 客户端实例。 + /// 要验证的卡片。 + /// 发送请求时要使用的选项。 + /// 一个表示异步验证操作的任务。 public static Task ValidateCardAsync(this KookRestClient client, ICard card, RequestOptions? options = null) => ValidateCardsAsync(client, [card], options); /// - /// Validates a collection of cards. + /// 验证卡片。 /// - /// The KOOK rest client instance. - /// The cards to be validated. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous validation operation. - /// + /// KOOK REST 客户端实例。 + /// 要验证的卡片。 + /// 发送请求时要使用的选项。 + /// 一个表示异步验证操作的任务。 public static Task ValidateCardsAsync(this KookRestClient client, IEnumerable cards, RequestOptions? options = null) => ExperimentalClientHelper.ValidateCardsAsync(client, cards, options); /// - /// Validates a collection of cards. + /// 验证卡片。 /// - /// The KOOK rest client instance. - /// The JSON representation of the cards to be validated. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous validation operation. - /// + /// KOOK REST 客户端实例。 + /// 要验证的卡片的 JSON 字符串。 + /// 发送请求时要使用的选项。 + /// 一个表示异步验证操作的任务。 public static Task ValidateCardsAsync(this KookRestClient client, string cardsJson, RequestOptions? options = null) => ExperimentalClientHelper.ValidateCardsAsync(client, cardsJson, options); } diff --git a/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs b/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs deleted file mode 100644 index da47732d..00000000 --- a/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; - -namespace Kook.Net.Converters; - -internal class ImageBase64DataUriConverter : JsonConverter -{ - public override bool HandleNull => true; - - public override Image? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - string? raw = reader.GetString(); - if (string.IsNullOrWhiteSpace(raw)) - return null; - - Match match = Regex.Match(raw, @"^data:image/(\w+?-)?(?\w+?);base64,(?.+)$"); - string type = match.Groups["type"].Value; - string data = match.Groups["data"].Value; - byte[] binaryData = Convert.FromBase64String(data); - MemoryStream stream = new(binaryData); - return new Image(stream, type); - } - - public override void Write(Utf8JsonWriter writer, Image? value, JsonSerializerOptions options) - { - if (!value.HasValue) - { - writer.WriteStringValue(string.Empty); - return; - } - - byte[] bytes; - using (MemoryStream memoryStream = new()) - { - value.Value.Stream.CopyTo(memoryStream); - bytes = memoryStream.ToArray(); - } - - string base64 = Convert.ToBase64String(bytes); - string? extension = !string.IsNullOrWhiteSpace(value.Value.FileExtension) - ? value.Value.FileExtension - : "png"; - writer.WriteStringValue($"data:image/{extension};base64,{base64}"); - } -} diff --git a/src/Kook.Net.Experimental/WebSocket/BaseSocketClientExperimentalExtensions.cs b/src/Kook.Net.Experimental/WebSocket/BaseSocketClientExperimentalExtensions.cs deleted file mode 100644 index 69e245ec..00000000 --- a/src/Kook.Net.Experimental/WebSocket/BaseSocketClientExperimentalExtensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Kook.Rest; - -namespace Kook.WebSocket; - -/// -/// Provides extension methods of experimental functionalities for s. -/// -public static class BaseSocketClientExperimentalExtensions -{ - /// - /// Creates a guild for the logged-in user. - /// - /// - /// This method creates a new guild on behalf of the logged-in user. - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable,and may be changed or removed in the future. - /// - /// - /// The KOOK rest client instance. - /// The name of the new guild. - /// The voice region to create the guild with. - /// The icon of the new guild. - /// The identifier of the guild template to be used to create the new guild. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the created guild. - /// - public static Task CreateGuildAsync(this BaseSocketClient client, string name, - IVoiceRegion? region = null, Stream? icon = null, int? templateId = null, RequestOptions? options = null) => - ExperimentalClientHelper.CreateGuildAsync(client, name, region, icon, templateId, options); -} diff --git a/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs deleted file mode 100644 index 065f2255..00000000 --- a/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Kook.Rest; - -namespace Kook.WebSocket; - -/// -/// Provides extension methods of experimental functionalities for s. -/// -public static class SocketVoiceChannelExperimentalExtensions -{ - /// - /// Disconnects the specified user from the voice channel. - /// - /// The voice channel where the use is connected to. - /// The user to disconnect. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for disconnecting the user from the voice channel. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task DisconnectUserAsync(this SocketVoiceChannel channel, IGuildUser user, RequestOptions? options = null) => - ExperimentalChannelHelper.DisconnectUserAsync(channel, channel.Kook, user, options); -} diff --git a/src/Kook.Net.Experimental/WebSocket/Entities/Guilds/SocketGuildExperimentalExtensions.cs b/src/Kook.Net.Experimental/WebSocket/Entities/Guilds/SocketGuildExperimentalExtensions.cs deleted file mode 100644 index 0c7b0d6a..00000000 --- a/src/Kook.Net.Experimental/WebSocket/Entities/Guilds/SocketGuildExperimentalExtensions.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Kook.Rest; - -namespace Kook.WebSocket; - -/// -/// Provides extension methods of experimental functionalities for s. -/// -public static class SocketGuildExperimentalExtensions -{ - /// - /// Deletes this guild. - /// - /// The guild to delete. - /// The options to be used when sending the request. - /// A task that represents the asynchronous deletion operation. - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - public static Task DeleteAsync(this SocketGuild guild, RequestOptions? options = null) => - ExperimentalGuildHelper.DeleteAsync(guild, guild.Kook, options); - - /// - /// Modifies this guild. - /// - /// The guild to modify. - /// The delegate containing the properties to modify the guild with. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous modification operation. - /// - /// - /// - /// This method is still in experimental state, which means that it is not for official API implementation - /// usage, may violate the developer rules or policies, not guaranteed to be stable, and may be changed or removed in the future. - /// - /// - /// is null. - public static Task ModifyAsync(this SocketGuild guild, Action func, RequestOptions? options = null) => - ExperimentalGuildHelper.ModifyAsync(guild, guild.Kook, func, options); -} diff --git a/src/Kook.Net.Hosting/KookClientConfiguratorExtensions.cs b/src/Kook.Net.Hosting/KookClientConfiguratorExtensions.cs index 3af4ad1a..26b16c9e 100644 --- a/src/Kook.Net.Hosting/KookClientConfiguratorExtensions.cs +++ b/src/Kook.Net.Hosting/KookClientConfiguratorExtensions.cs @@ -9,18 +9,21 @@ namespace Kook.Net.Hosting; /// -/// Provides extension methods for to configure hosted clients. +/// 提供用于配置 +/// 添加客户端托管服务的扩展方法。 /// public static class KookClientConfiguratorExtensions { /// - /// Configures a hosted client with the specified token. + /// 配置指定的 KOOK 客户端配置器添加客户端托管服务。 /// - /// The configurator. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The configurator. + /// KOOK 服务配置器。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedClient( this IKookClientConfigurator configurator, TokenType tokenType, string token, bool validateToken = true) @@ -35,13 +38,15 @@ public static IKookClientConfigurator UseHostedClient - /// Configures a hosted client with the specified token. + /// 配置指定的 KOOK 客户端配置器添加客户端托管服务。 /// - /// The configurator. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The configurator. + /// KOOK 服务配置器。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedClient( this IKookClientConfigurator configurator, Func tokenType, Func token, @@ -58,14 +63,14 @@ public static IKookClientConfigurator UseHostedClient - /// Configures a hosted REST client with the specified token. + /// 配置指定的 KOOK 客户端配置器添加基于 REST 的客户端并添加客户端托管服务。 /// - /// The configurator. - /// The configuration action. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The configurator. + /// KOOK 服务配置器。 + /// 用于配置 KOOK REST 客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 配置了 REST 客户端及客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedRestClient( this IKookClientServiceConfigurator configurator, Action configure, TokenType tokenType, string token, bool validateToken = true) => @@ -74,14 +79,14 @@ public static IKookClientConfigurator UseHostedR .UseHostedClient(tokenType, token, validateToken); /// - /// Configures a hosted REST client with the specified token. + /// 配置指定的 KOOK 客户端配置器添加基于 REST 的客户端并添加客户端托管服务。 /// - /// The configurator. - /// The configuration action. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The configurator. + /// KOOK 服务配置器。 + /// 用于配置 KOOK REST 客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 配置了 REST 客户端及客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedRestClient( this IKookClientServiceConfigurator configurator, Action configure, Func tokenType, Func token, @@ -91,14 +96,14 @@ public static IKookClientConfigurator UseHostedR .UseHostedClient(tokenType, token, validateToken); /// - /// Configures a hosted socket client with the specified token. + /// 配置指定的 KOOK 客户端配置器添加基于网关的客户端并添加客户端托管服务。 /// - /// The configurator. - /// The configuration action. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The configurator. + /// KOOK 服务配置器。 + /// 用于配置 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 配置了网关客户端及客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedSocketClient( this IKookClientServiceConfigurator configurator, Action configure, TokenType tokenType, string token, bool validateToken = true) => @@ -107,14 +112,14 @@ public static IKookClientConfigurator UseHos .UseHostedClient(tokenType, token, validateToken); /// - /// Configures a hosted socket client with the specified token. + /// 配置指定的 KOOK 客户端配置器添加基于网关的客户端并添加客户端托管服务。 /// - /// The configurator. - /// The configuration action. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The configurator. + /// KOOK 服务配置器。 + /// 用于配置 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 配置了网关客户端及客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedSocketClient( this IKookClientServiceConfigurator configurator, Action configure, Func tokenType, Func token, @@ -124,17 +129,17 @@ public static IKookClientConfigurator UseHos .UseHostedClient(tokenType, token, validateToken); /// - /// Configures a hosted webhook client with the specified token. + /// 配置指定的基于 Webhook 的 KOOK 客户端配置器添加基于网关的客户端并添加客户端托管服务。 /// - /// The configurator. - /// The client factory. - /// The configuration action. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The type of the client. - /// The type of the configuration. - /// The configurator. + /// KOOK 服务配置器。 + /// 客户端创建委托。 + /// 用于配置基于 Webhook 的 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了基于 Webhook 的网关客户端及客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedWebhookClient( this IKookClientServiceConfigurator configurator, Func, TClient> clientFactory, Action configure, TokenType tokenType, string token, bool validateToken = true) @@ -145,17 +150,17 @@ public static IKookClientConfigurator UseHostedWebhookClient - /// Configures a hosted webhook client with the specified token. + /// 配置指定的基于 Webhook 的 KOOK 客户端配置器添加基于网关的客户端并添加客户端托管服务。 /// - /// The configurator. - /// The client factory. - /// The configuration action. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The type of the client. - /// The type of the configuration. - /// The configurator. + /// KOOK 服务配置器。 + /// 客户端创建委托。 + /// 用于配置基于 Webhook 的 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了基于 Webhook 的网关客户端及客户端托管服务的 KOOK 客户端配置器。 public static IKookClientConfigurator UseHostedWebhookClient( this IKookClientServiceConfigurator configurator, Func, TClient> clientFactory, Action configure, Func tokenType, diff --git a/src/Kook.Net.Hosting/KookClientHostExtensions.cs b/src/Kook.Net.Hosting/KookClientHostExtensions.cs index c8db69d2..24983dee 100644 --- a/src/Kook.Net.Hosting/KookClientHostExtensions.cs +++ b/src/Kook.Net.Hosting/KookClientHostExtensions.cs @@ -9,20 +9,21 @@ namespace Kook.Net.Hosting; /// -/// Provides extension methods for Kook.Net to host clients using the . +/// 提供用于与 Microsoft.Extensions.Hosting 集成,注册与配置 Kook.Net 客户端作为服务的扩展方法。 /// public static class KookClientHostExtensions { /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端及服务的服务集合。 + /// 用于配置 KOOK REST 客户端的配置。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK REST 客户端及服务的服务集合。 public static IServiceCollection AddHostedKookRestClient(this IServiceCollection services, KookRestConfig config, TokenType tokenType, string token, bool validateToken = true) { @@ -33,15 +34,16 @@ public static IServiceCollection AddHostedKookRestClient(this IServiceCollection } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端及服务的服务集合。 + /// 用于配置 KOOK REST 客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK REST 客户端及服务的服务集合。 public static IServiceCollection AddHostedKookRestClient(this IServiceCollection services, Action configure, TokenType tokenType, string token, bool validateToken = true) { @@ -52,15 +54,16 @@ public static IServiceCollection AddHostedKookRestClient(this IServiceCollection } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端及服务的服务集合。 + /// 用于配置 KOOK REST 客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK REST 客户端及服务的服务集合。 public static IServiceCollection AddHostedKookRestClient(this IServiceCollection services, Action configure, Func tokenType, Func token, Func? validateToken = null) @@ -73,15 +76,16 @@ public static IServiceCollection AddHostedKookRestClient(this IServiceCollection } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK REST 客户端及服务的服务集合。 + /// 用于配置 KOOK REST 客户端的配置。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK REST 客户端及服务的服务集合。 public static IServiceCollection AddHostedKookRestClient(this IServiceCollection services, KookRestConfig config, Func tokenType, Func token, Func? validateToken = null) @@ -94,15 +98,16 @@ public static IServiceCollection AddHostedKookRestClient(this IServiceCollection } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端及服务的服务集合。 + /// 用于配置 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookSocketClient(this IServiceCollection services, Action configure, TokenType tokenType, string token, bool validateToken = true) { @@ -113,15 +118,16 @@ public static IServiceCollection AddHostedKookSocketClient(this IServiceCollecti } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端及服务的服务集合。 + /// 用于配置 KOOK 网关客户端的配置。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookSocketClient(this IServiceCollection services, KookSocketConfig config, TokenType tokenType, string token, bool validateToken = true) { @@ -132,15 +138,16 @@ public static IServiceCollection AddHostedKookSocketClient(this IServiceCollecti } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端及服务的服务集合。 + /// 用于配置 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookSocketClient(this IServiceCollection services, Action configure, Func tokenType, Func token, Func? validateToken = null) @@ -153,15 +160,16 @@ public static IServiceCollection AddHostedKookSocketClient(this IServiceCollecti } /// - /// Adds a to the specified with - /// the specified configuration action and login information. + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK 网关客户端及服务的服务集合。 + /// 用于配置 KOOK 网关客户端的配置。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 添加了 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookSocketClient(this IServiceCollection services, KookSocketConfig config, Func tokenType, Func token, Func? validateToken = null) @@ -174,17 +182,19 @@ public static IServiceCollection AddHostedKookSocketClient(this IServiceCollecti } /// - /// Adds a to the specified with + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The factory to create the . - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 + /// 客户端创建委托。 + /// 用于配置基于 Webhook 的 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 添加了基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookWebhookClient(this IServiceCollection services, Func, TClient> clientFactory, Action configure, Func tokenType, Func token, @@ -202,17 +212,19 @@ public static IServiceCollection AddHostedKookWebhookClient(th } /// - /// Adds a to the specified with + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The factory to create the . - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 + /// 客户端创建委托。 + /// 用于配置基于 Webhook 的 KOOK 网关客户端的配置。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 添加了基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookWebhookClient(this IServiceCollection services, Func clientFactory, TConfig config, Func tokenType, Func token, @@ -230,17 +242,19 @@ public static IServiceCollection AddHostedKookWebhookClient(th } /// - /// Adds a to the specified with + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The factory to create the . - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 + /// 客户端创建委托。 + /// 用于配置基于 Webhook 的 KOOK 网关客户端的配置委托。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 添加了基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookWebhookClient(this IServiceCollection services, Func, TClient> clientFactory, Action configure, TokenType tokenType, string token, bool validateToken = true) @@ -257,17 +271,19 @@ public static IServiceCollection AddHostedKookWebhookClient(th } /// - /// Adds a to the specified with + /// 向指定的 添加 + /// 客户端,并添加包装为 + /// 的服务。 /// - /// The to add the services. - /// The factory to create the . - /// The action to configure the . - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. - /// The type of the . - /// The type of the . - /// The so that additional calls can be chained. + /// 要向其添加基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 + /// 客户端创建委托。 + /// 用于配置基于 Webhook 的 KOOK 网关客户端的配置。 + /// 令牌的类型。 + /// 令牌。 + /// 是否在登录前验证令牌。 + /// 客户端的类型。 + /// 配置的类型。 + /// 添加了基于 Webhook 的 KOOK 网关客户端及服务的服务集合。 public static IServiceCollection AddHostedKookWebhookClient(this IServiceCollection services, Func clientFactory, TConfig config, TokenType tokenType, string token, bool validateToken = true) diff --git a/src/Kook.Net.MessageQueue.InMemory/InMemoryMessageQueueProvider.cs b/src/Kook.Net.MessageQueue.InMemory/InMemoryMessageQueueProvider.cs index 13bf0976..404c7484 100644 --- a/src/Kook.Net.MessageQueue.InMemory/InMemoryMessageQueueProvider.cs +++ b/src/Kook.Net.MessageQueue.InMemory/InMemoryMessageQueueProvider.cs @@ -1,12 +1,12 @@ namespace Kook.Net.Queue.InMemory; /// -/// Represents a delegate that provides a new instance of . +/// 表示一个默认的使用内存队列的 ,用于创建 实例。 /// public static class InMemoryMessageQueueProvider { /// - /// A delegate that creates a default instance. + /// 创建一个新的用于创建默认的使用内存队列的 实例的委托。 /// public static readonly MessageQueueProvider Instance = eventHandler => { diff --git a/src/Kook.Net.MessageQueue.MassTransit/DefaultMassTransitMessageQueueProvider.cs b/src/Kook.Net.MessageQueue.MassTransit/DefaultMassTransitMessageQueueProvider.cs index 31075434..77f400ae 100644 --- a/src/Kook.Net.MessageQueue.MassTransit/DefaultMassTransitMessageQueueProvider.cs +++ b/src/Kook.Net.MessageQueue.MassTransit/DefaultMassTransitMessageQueueProvider.cs @@ -3,16 +3,14 @@ namespace Kook.Net.Queue.MassTransit; /// -/// Represents a delegate that provides a new instance of . +/// 表示一个默认的使用 MassTransit 消息队列的 ,用于创建 实例。 /// public class DefaultMassTransitMessageQueueProvider { /// - /// Creates a delegate that provides a new instance of . + /// 创建一个新的用于创建默认的使用 MassTransit 消息队列的 实例的委托。 /// - /// The MassTransit bus. - /// A new instance of . - /// The default is not supported on this platform. + /// 用于创建消息队列的 MassTransit 消息总线。 public static MessageQueueProvider Create(IBus bus) { try diff --git a/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitConsumer.cs b/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitConsumer.cs index 890504ff..f7a1351c 100644 --- a/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitConsumer.cs +++ b/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitConsumer.cs @@ -1,20 +1,12 @@ -using System.Text.Json; -using Kook.WebSocket; +using Kook.WebSocket; using MassTransit; namespace Kook.Net.Queue.MassTransit; -/// -/// Represents a MassTransit consumer for Kook message queue. -/// internal class KookMessageQueueMassTransitConsumer : IConsumer { private readonly KookSocketClient _client; - /// - /// Initializes a new instance of the class. - /// - /// The Kook socket client. public KookMessageQueueMassTransitConsumer(KookSocketClient client) { _client = client; diff --git a/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitExtensions.cs b/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitExtensions.cs index 063b648a..6bbb3103 100644 --- a/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitExtensions.cs +++ b/src/Kook.Net.MessageQueue.MassTransit/KookMessageQueueMassTransitExtensions.cs @@ -6,15 +6,16 @@ namespace Kook.Net.Queue.MassTransit; /// -/// Provides extension methods for to configure MassTransit message queues. +/// 提供用于配置 +/// 使用 MassTransit 消息队列的扩展方法。 /// public static class KookMassTransitMessageQueueExtensions { /// - /// Adds a MassTransit message queue consumer to the . + /// 配置一个 MassTransit 消息队列消费者到 。 /// - /// The configurator. - /// The configurator. + /// MassTransit 配置器。 + /// 配置了 MassTransit 消息队列消费者的配置器。 public static IBusRegistrationConfigurator AddMessageQueueMassTransitConsumer( this IBusRegistrationConfigurator configurator) { @@ -23,11 +24,13 @@ public static IBusRegistrationConfigurator AddMessageQueueMassTransitConsumer( } /// - /// Configures a Kook client to use a MassTransit message queue. + /// 配置一个 KOOK 客户端配置器使用 MassTransit 消息队列。 /// - /// The configurator. - /// The MassTransit configuration action. - /// The configurator. + /// KOOK 客户端配置器。 + /// MassTransit 配置操作。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了 MassTransit 消息队列的配置器。 public static IKookClientConfigurator UseMassTransitMessageQueue( this IKookClientConfigurator configurator, Action massTransitConfigure) @@ -44,10 +47,12 @@ public static IKookClientConfigurator UseMassTransitMessageQue } /// - /// Configures a Kook client to use a MassTransit message queue. + /// 配置一个 KOOK 客户端配置器使用 MassTransit 消息队列。 /// - /// The configurator. - /// The configurator. + /// KOOK 客户端配置器。 + /// 客户端的类型。 + /// 配置的类型。 + /// 配置了 MassTransit 消息队列的配置器。 public static IKookClientConfigurator UseMassTransitMessageQueue( this IKookClientConfigurator configurator) where TClient : BaseSocketClient diff --git a/src/Kook.Net.Rest/API/Common/Role.cs b/src/Kook.Net.Rest/API/Common/Role.cs index b22d34d4..f946ab60 100644 --- a/src/Kook.Net.Rest/API/Common/Role.cs +++ b/src/Kook.Net.Rest/API/Common/Role.cs @@ -27,11 +27,11 @@ internal class Role [JsonPropertyName("hoist")] [JsonConverter(typeof(NumberBooleanConverter))] - public bool Hoist { get; set; } + public bool IsHoisted { get; set; } [JsonPropertyName("mentionable")] [JsonConverter(typeof(NumberBooleanConverter))] - public bool Mentionable { get; set; } + public bool IsMentionable { get; set; } [JsonPropertyName("permissions")] public ulong Permissions { get; set; } diff --git a/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs index 358bdf7b..5789d3c6 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs @@ -22,11 +22,11 @@ internal class ModifyGuildRoleParams [JsonPropertyName("hoist")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public int? Hoist { get; set; } + public int? IsHoisted { get; set; } [JsonPropertyName("mentionable")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public int? Mentionable { get; set; } + public int? IsMentionable { get; set; } [JsonPropertyName("permissions")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] diff --git a/src/Kook.Net.Rest/BaseKookClient.cs b/src/Kook.Net.Rest/BaseKookClient.cs index 8621f9ec..9a38e8ad 100644 --- a/src/Kook.Net.Rest/BaseKookClient.cs +++ b/src/Kook.Net.Rest/BaseKookClient.cs @@ -8,15 +8,21 @@ namespace Kook.Rest; /// -/// Represents a client that can connect to the Kook API. +/// 表示一个可以连接到 KOOK API 的通用的 KOOK 客户端。 /// public abstract class BaseKookClient : IKookClient { #region BaseKookClient /// - /// Fired when a log message is sent. + /// 当生成一条日志消息时引发。 /// + /// + /// 事件参数: + /// + /// 参数是描述日志消息的结构。 + /// + /// public event Func Log { add => _logEvent.Add(value); @@ -26,7 +32,7 @@ public event Func Log internal readonly AsyncEvent> _logEvent = new(); /// - /// Fired when the client has logged in. + /// 当客户端登录成功时引发。 /// public event Func LoggedIn { @@ -37,7 +43,7 @@ public event Func LoggedIn internal readonly AsyncEvent> _loggedInEvent = new(); /// - /// Fired when the client has logged out. + /// 当客户端退出登录时引发。 /// public event Func LoggedOut { @@ -48,13 +54,20 @@ public event Func LoggedOut internal readonly AsyncEvent> _loggedOutEvent = new(); /// - /// Fired when a REST request is sent to the API. First parameter is the HTTP method, - /// second is the endpoint, and third is the time taken to complete the request. + /// 当向 API 发送 REST 请求时引发。 /// + /// + /// 事件参数: + /// + /// 参数是 HTTP 方法。 + /// 参数是终结点。 + /// 参数是完成请求所花费的时间,以毫秒为单位。 + /// + /// public event Func SentRequest { - add { _sentRequest.Add(value); } - remove { _sentRequest.Remove(value); } + add => _sentRequest.Add(value); + remove => _sentRequest.Remove(value); } internal readonly AsyncEvent> _sentRequest = new(); @@ -68,12 +81,12 @@ public event Func SentRequest internal LogManager LogManager { get; } /// - /// Gets the login state of the client. + /// 获取此客户端的登录状态。 /// public LoginState LoginState { get; protected set; } /// - /// Gets the logged-in user. + /// 获取登录到此客户端的当前用户;如果未登录,则为 null。 /// public ISelfUser? CurrentUser { get; protected set; } @@ -120,12 +133,7 @@ internal virtual void Dispose(bool disposing) /// public void Dispose() => Dispose(true); - /// - /// Logs in to the Kook API. - /// - /// The type of token to use. - /// The token to use. - /// Whether to validate the token before logging in. + /// public async Task LoginAsync(TokenType tokenType, string token, bool validateToken = true) { await _stateLock.WaitAsync().ConfigureAwait(false); @@ -184,9 +192,7 @@ internal virtual async Task LoginInternalAsync(TokenType tokenType, string token internal virtual Task OnLoginAsync(TokenType tokenType, string token) => Task.CompletedTask; - /// - /// Logs out from the Kook API. - /// + /// public async Task LogoutAsync() { await _stateLock.WaitAsync().ConfigureAwait(false); diff --git a/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs b/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs index 3d0b7142..507220ed 100644 --- a/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs +++ b/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs @@ -287,7 +287,6 @@ public static Task DeleteDirectMessageAsync(IMessageChannel channel, Guid messageId, BaseKookClient client, RequestOptions? options) => MessageHelper.DeleteDirectAsync(messageId, client, options); - public static async Task ModifyMessageAsync(IMessageChannel channel, Guid messageId, Action func, BaseKookClient client, RequestOptions? options) => await MessageHelper.ModifyAsync(messageId, client, func, options).ConfigureAwait(false); diff --git a/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs b/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs index 00043ae0..971e9662 100644 --- a/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs @@ -1,6 +1,6 @@ namespace Kook.Rest; /// -/// Represents a generic REST-based audio channel. +/// 表示一个基于 REST 的通用的音频频道。 /// public interface IRestAudioChannel : IAudioChannel; diff --git a/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs b/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs index 564c7021..6e6d5b64 100644 --- a/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs @@ -1,71 +1,97 @@ namespace Kook.Rest; /// -/// Represents a REST-based channel that can send and receive messages. +/// 表示一个基于 REST 的通用的消息频道,可以用来发送和接收消息。 /// public interface IRestMessageChannel : IMessageChannel { /// - /// Gets a message from this message channel. + /// 从此消息频道获取一条消息。 /// - /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. - /// - /// The identifier of the message. - /// The options to be used when sending the request. - /// - /// A task that represents an asynchronous get operation for retrieving the message. The task result contains - /// the retrieved message; null if no message is found with the specified identifier. - /// + /// 消息的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务结果包含检索到的消息;如果未找到具有指定 ID 的消息,则返回 null Task GetMessageAsync(Guid id, RequestOptions? options = null); /// - /// Gets the last N messages from this message channel. + /// 获取此消息频道中的最新的一些消息。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 IAsyncEnumerable> GetMessagesAsync( int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The ID of the starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息的 ID。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null); } diff --git a/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs b/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs index f5c1048c..d86a428e 100644 --- a/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs @@ -1,12 +1,10 @@ namespace Kook.Rest; /// -/// Represents a REST-based channel that is private to select recipients. +/// 表示一个基于 REST 的通用的私有频道,只有特定的用户可以访问。 /// public interface IRestPrivateChannel : IPrivateChannel { - /// - /// Users that can access this channel. - /// + /// new IReadOnlyCollection Recipients { get; } } diff --git a/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs index be2a2853..f2ee7df7 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based category channel. +/// 表示一个基于 REST 的分组频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestCategoryChannel : RestGuildChannel, ICategoryChannel @@ -31,12 +31,12 @@ internal RestCategoryChannel(BaseKookClient kook, IGuild guild, ulong id) #region IChannel /// - /// This method is not supported with category channels. + /// 分组频道不支持此操作。 IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions? options) => throw new NotSupportedException(); /// - /// This method is not supported with category channels. + /// 分组频道不支持此操作。 Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions? options) => throw new NotSupportedException(); diff --git a/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs index 66f615c5..bfacb59e 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs @@ -3,7 +3,7 @@ namespace Kook.Rest; /// -/// Represents a generic REST-based channel. +/// 表示一个基于 REST 的频道。 /// public class RestChannel : RestEntity, IChannel, IUpdateable { diff --git a/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs index 3b08d2a2..d710d477 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs @@ -5,39 +5,35 @@ namespace Kook.Rest; /// -/// Represents a REST-based direct-message channel. +/// 表示一个基于 REST 的私聊频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestDMChannel : RestChannel, IDMChannel, IRestPrivateChannel, IRestMessageChannel { #region RestDMChannel - /// - /// Get the identifier of the DM channel. - /// + /// /// - /// This property is the same as . + /// 此属性的值与 相同。 /// public new Guid Id { get; } /// /// - /// This property is the same as . + /// 此属性的值与 相同。 /// public Guid ChatCode => Id; /// - /// Gets the current logged-in user. + /// 获取参与到此私聊频道中的当前用户。 /// public RestUser CurrentUser { get; } - /// - /// Gets the recipient of the channel. - /// + /// public RestUser Recipient { get; } /// - /// Gets a collection that is the current logged-in user and the recipient. + /// 获取参与到此私聊频道中的所有用户。 /// public IReadOnlyCollection Users => [CurrentUser, Recipient]; @@ -75,111 +71,42 @@ public Task CloseAsync(RequestOptions? options = null) => ChannelHelper.DeleteDMChannelAsync(this, Kook, options); /// - /// Gets a user in this channel from the provided . + /// 获取此私聊频道中具体指定 ID 的用户。 /// - /// The identifier of the user. - /// - /// A object that is a recipient of this channel; otherwise null. - /// + /// 要获取的用户的 ID。 + /// 此私聊频道中具有指定 ID 的用户;如果指定 ID 的用户不存在,或该用户并未参与到此私聊频道中,则返回 null public RestUser? GetUser(ulong id) { if (id == Recipient.Id) return Recipient; return id == Kook.CurrentUser?.Id ? CurrentUser : null; } - /// - /// Sends a text message to this message channel. - /// - /// The message to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendTextAsync(string text, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectMessageAsync(this, Kook, MessageType.KMarkdown, text, quote, options); - /// - /// Sends a file to this message channel. - /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The file path of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, path, filename, type, quote, options); - /// - /// Sends a file to this message channel. - /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The stream of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, stream, filename, type, quote, options); - /// - /// Sends a file to this message channel. - /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The attachment containing the file. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendFileAsync(FileAttachment attachment, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, attachment, quote, options); - /// - /// Sends a card message to this message channel. - /// - /// The cards to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendCardsAsync(IEnumerable cards, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectCardsAsync(this, Kook, cards, quote, options); - /// - /// Sends a card message to this message channel. - /// - /// The card to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendCardAsync(ICard card, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectCardAsync(this, Kook, card, quote, options); @@ -304,11 +231,10 @@ Task> IMessageChannel.SendCardAsync(ICard card, #endregion /// - /// Gets a string that represents the Username#IdentifyNumber of the recipient. + /// 获取此参与到此私聊频道的另外一位用户的包含 @ 前缀的用户名及识别号格式化字符串。 /// - /// - /// A string that resolves to the Recipient of this channel. - /// + /// 一个表示此私聊频道的格式化字符串。 + /// public override string ToString() => $"@{Recipient}"; private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)"; diff --git a/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs index 640a393e..1bb67beb 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs @@ -5,7 +5,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based guild channel in a guild. +/// 表示一个基于 REST 的服务器频道。 /// public class RestGuildChannel : RestChannel, IGuildChannel { @@ -20,13 +20,8 @@ public class RestGuildChannel : RestChannel, IGuildChannel /// public virtual IReadOnlyCollection UserPermissionOverwrites => _userPermissionOverwrites; - /// - /// Gets the guild associated with this channel. - /// - /// - /// A guild object that this channel belongs to. - /// - internal IGuild Guild { get; } + /// + public IGuild Guild { get; } /// public ChannelType Type { get; internal set; } @@ -95,17 +90,15 @@ public async Task ModifyAsync(Action func, Request } /// - /// Gets the creator of this channel. + /// 获取此频道的创建者。 /// /// - /// This method will try to get the user as a global user. To get the creator as a guild member, - /// you will need to get the user through - /// ."/> + /// 此方法会尝试获取服务器创建者的非服务器特定的用户实体。要获取该用户作为此服务器成员的服务器用户实体,请在 + /// 上调用 + /// 。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the creator of this channel. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果为此频道的创建者;如果没有找到则为 null public async Task GetCreatorAsync(RequestOptions? options = null) { if (CreatorId.HasValue) @@ -124,34 +117,15 @@ public override async Task UpdateAsync(RequestOptions? options = null) Update(model); } - /// - /// Gets the permission overwrite for a specific user. - /// - /// The user to get the overwrite from. - /// - /// An overwrite object for the targeted user; null if none is set. - /// + /// public OverwritePermissions? GetPermissionOverwrite(IUser user) => _userPermissionOverwrites.FirstOrDefault(x => x.Target.Id == user.Id)?.Permissions; - /// - /// Gets the permission overwrite for a specific role. - /// - /// The role to get the overwrite from. - /// - /// An overwrite object for the targeted role; null if none is set. - /// + /// public OverwritePermissions? GetPermissionOverwrite(IRole role) => _rolePermissionOverwrites.FirstOrDefault(x => x.Target == role.Id)?.Permissions; - /// - /// Adds the permission overwrite for the given user. - /// - /// The user to add the overwrite to. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. - /// + /// public async Task AddPermissionOverwriteAsync(IGuildUser user, RequestOptions? options = null) { UserPermissionOverwrite permissionOverwrite = await ChannelHelper @@ -160,14 +134,7 @@ public async Task AddPermissionOverwriteAsync(IGuildUser user, RequestOptions? o _userPermissionOverwrites = [.._userPermissionOverwrites, permissionOverwrite]; } - /// - /// Adds the permission overwrite for the given role. - /// - /// The role to add the overwrite to. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. - /// + /// public async Task AddPermissionOverwriteAsync(IRole role, RequestOptions? options = null) { RolePermissionOverwrite permissionOverwrite = await ChannelHelper @@ -176,43 +143,21 @@ public async Task AddPermissionOverwriteAsync(IRole role, RequestOptions? option _rolePermissionOverwrites = [.._rolePermissionOverwrites, permissionOverwrite]; } - /// - /// Removes the permission overwrite for the given user, if one exists. - /// - /// The user to remove the overwrite from. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task RemovePermissionOverwriteAsync(IGuildUser user, RequestOptions? options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Kook, user, options).ConfigureAwait(false); _userPermissionOverwrites = [.._userPermissionOverwrites.Where(x => x.Target.Id != user.Id)]; } - /// - /// Removes the permission overwrite for the given role, if one exists. - /// - /// The role to remove the overwrite from. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions? options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Kook, role, options).ConfigureAwait(false); _rolePermissionOverwrites = [.._rolePermissionOverwrites.Where(x => x.Target != role.Id)]; } - /// - /// Updates the permission overwrite for the given user, if one exists. - /// - /// The user to modify the overwrite for. - /// A delegate containing the values to modify the permission overwrite with. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions? options = null) { @@ -222,15 +167,7 @@ public async Task ModifyPermissionOverwriteAsync(IGuildUser user, _userPermissionOverwrites = [.._userPermissionOverwrites.Where(x => x.Target.Id != user.Id), permission]; } - /// - /// Updates the permission overwrite for the given role, if one exists. - /// - /// The role to remove the overwrite for. - /// A delegate containing the values to modify the permission overwrite with. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task ModifyPermissionOverwriteAsync(IRole role, Func func, RequestOptions? options = null) { @@ -240,12 +177,8 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, _rolePermissionOverwrites = [.._rolePermissionOverwrites.Where(x => x.Target != role.Id), permission]; } - /// - /// Gets the name of this channel. - /// - /// - /// A string that is the name of this channel. - /// + /// + /// 此频道的名称。 public override string ToString() => Name; #endregion diff --git a/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs index 4ef8fed2..8555365f 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based channel in a guild that can send and receive messages. +/// 表示服务器中一个基于 REST 的具有文字聊天能力的频道,可以发送和接收消息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestTextChannel : RestGuildChannel, IRestMessageChannel, ITextChannel @@ -65,32 +65,32 @@ public override Task UpdateAsync(RequestOptions? options = null) => ChannelHelper.UpdateAsync(this, Kook, options); /// - /// Gets a user in this channel. + /// 获取此频道中的用户。 /// - /// The identifier of the user. - /// The options to be used when sending the request. - /// - /// Resolving permissions requires the parent guild to be downloaded. - /// - /// - /// A task representing the asynchronous get operation. The task result contains a guild user object that - /// represents the user; null if none is found. - /// + /// 要获取的用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果为此频道中的服务器用户;如果没有找到则为 null public Task GetUserAsync(ulong id, RequestOptions? options = null) => ChannelHelper.GetUserAsync(this, Guild, Kook, id, options); /// - /// Gets a collection of users that are able to view the channel. + /// 获取能够查看频道或当前在此频道中的所有用户。 /// - /// The options to be used when sending the request. - /// - /// Resolving permissions requires the parent guild to be downloaded. - /// - /// - /// A paged collection containing a collection of guild users that can access this channel. Flattening the - /// paginated response into a collection of users with - /// is required if you wish to access the users. - /// + /// + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// 此方法将尝试获取所有能够查看该频道或当前在该频道中的用户。此方法会根据 + /// 将请求拆分。换句话说,如果有 3000 名用户,而 的常量为 + /// 50,则请求将被拆分为 60 个单独请求,因此异步枚举器会异步枚举返回 60 个响应。 + /// + /// 方法可以展开这 60 个响应返回的集合,并将其合并为一个集合。 + ///
+ /// 发送请求时要使用的选项。 + /// 分页的服务器用户集合的异步可枚举对象。 public IAsyncEnumerable> GetUsersAsync(RequestOptions? options = null) => ChannelHelper.GetUsersAsync(this, Guild, Kook, KookConfig.MaxUsersPerBatch, 1, options); @@ -115,11 +115,11 @@ public virtual IAsyncEnumerable> GetMessagesAsy RequestOptions? options = null) => ChannelHelper.GetMessagesAsync(this, Kook, referenceMessage.Id, dir, limit, true, options); - /// + /// public virtual Task> GetPinnedMessagesAsync(RequestOptions? options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Kook, options); - /// + /// public Task> SendFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) @@ -128,40 +128,37 @@ public Task> SendFileAsync(string path, string? fi return ChannelHelper.SendFileAsync(this, Kook, path, name, type, quote, ephemeralUser, options); } - /// + /// public Task> SendFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendFileAsync(this, Kook, stream, filename, type, quote, ephemeralUser, options); - /// + /// public Task> SendFileAsync(FileAttachment attachment, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendFileAsync(this, Kook, attachment, quote, ephemeralUser, options); - /// + /// public Task> SendTextAsync(string text, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendMessageAsync(this, Kook, MessageType.KMarkdown, text, quote, ephemeralUser, options); - /// + /// public Task> SendCardsAsync(IEnumerable cards, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendCardsAsync(this, Kook, cards, quote, ephemeralUser, options); - /// + /// public Task> SendCardAsync(ICard card, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendCardAsync(this, Kook, card, quote, ephemeralUser, options); /// - /// Gets the parent (category) channel of this channel. + /// 获取此频道的所属分组频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the category channel - /// representing the parent of this channel; null if none is set. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此频道所属的分组频道,如果当前频道不属于任何分组频道,则为 null public Task GetCategoryAsync(RequestOptions? options = null) => ChannelHelper.GetCategoryAsync(this, Kook, options); diff --git a/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs index c2971d41..0d927365 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs @@ -6,7 +6,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based voice channel in a guild. +/// 表示服务器中一个基于 REST 的具有语音聊天能力的频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestVoiceChannel : RestTextChannel, IVoiceChannel, IRestAudioChannel @@ -68,12 +68,10 @@ public override Task UpdateAsync(RequestOptions? options = null) => ChannelHelper.UpdateAsync(this, Kook, options); /// - /// Gets the users connected to this voice channel. + /// 获取连接到此频道的用户。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of users. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含连接到此频道的所有服务器用户。 public async Task> GetConnectedUsersAsync(RequestOptions? options) => await ChannelHelper.GetConnectedUsersAsync(this, Guild, Kook, options).ConfigureAwait(false); @@ -84,27 +82,27 @@ public async Task> GetConnectedUsersAsync(RequestOpti #region TextOverrides /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override IAsyncEnumerable> GetMessagesAsync( int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override IAsyncEnumerable> GetMessagesAsync( Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override IAsyncEnumerable> GetMessagesAsync( IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override Task> GetPinnedMessagesAsync(RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); @@ -113,13 +111,16 @@ public override Task> GetPinnedMessagesAsync(Re #region IAudioChannel /// - /// Connecting to a REST-based channel is not supported. + IAudioClient? IAudioChannel.AudioClient => null; + + /// + /// 不支持连接到基于 REST 的语音频道。 Task IAudioChannel.ConnectAsync( /*bool selfDeaf, bool selfMute, */ bool external, bool disconnect, string? password) => throw new NotSupportedException(); /// - /// Connecting to a REST-based channel is not supported. + /// 不支持连接到基于 REST 的语音频道。 Task IAudioChannel.DisconnectAsync() => throw new NotSupportedException(); #endregion @@ -149,11 +150,11 @@ IAsyncEnumerable> IGuildChannel.GetUsersAsync( #region IVoiceChannel - async Task> IVoiceChannel.GetConnectedUsersAsync( + async Task> IVoiceChannel.GetConnectedUsersAsync( CacheMode mode, RequestOptions? options) => mode is CacheMode.AllowDownload ? await ChannelHelper.GetConnectedUsersAsync(this, Guild, Kook, options).ConfigureAwait(false) - : ImmutableArray.Create(); + : ImmutableArray.Create(); #endregion } diff --git a/src/Kook.Net.Rest/Entities/Games/RestGame.cs b/src/Kook.Net.Rest/Entities/Games/RestGame.cs index 981c6237..37f903d8 100644 --- a/src/Kook.Net.Rest/Entities/Games/RestGame.cs +++ b/src/Kook.Net.Rest/Entities/Games/RestGame.cs @@ -5,7 +5,7 @@ namespace Kook.Rest; /// -/// Represents a game object. +/// 表示一个基于 REST 的游戏信息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestGame : RestEntity, IGame diff --git a/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs b/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs index ef64a6ea..870b3c90 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a recommendation information for a guild. +/// 获取一个推荐信息。 /// public class RecommendInfo : IRecommendInfo { diff --git a/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs b/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs index aa264cdd..d2e2778c 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based ban object. +/// 表示一个基于 REST 的封禁对象。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestBan : IBan @@ -12,11 +12,8 @@ public class RestBan : IBan #region RestBan /// - /// Gets the banned user. + /// 获取被封禁的用户。 /// - /// - /// A generic object that was banned. - /// public RestUser User { get; } /// @@ -36,11 +33,11 @@ internal static RestBan Create(BaseKookClient client, Model model) => new(RestUser.Create(client, model.User), model.Reason, model.CreatedAt); /// - /// Gets the name of the banned user. + /// 获取被封禁用户的包含用户名及识别号的格式化字符串。 /// - /// - /// A string containing the name of the user that was banned. - /// + /// 被封禁用户的包含用户名及识别号的格式化字符串。 + /// + /// public override string ToString() => User.ToString(); private string DebuggerDisplay => $"{User}: {Reason}"; diff --git a/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs b/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs index ae95d700..349397d8 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs @@ -8,7 +8,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based guild/server. +/// 表示一个基于 REST 的服务器。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestGuild : RestEntity, IGuild, IUpdateable @@ -37,17 +37,23 @@ public class RestGuild : RestEntity, IGuild, IUpdateable public string Banner { get; private set; } /// - /// Gets the nickname of the current user in this guild. + /// 获取当前用户在此服务器的昵称。 /// + /// + /// 如果当前用户在此服务器未设置昵称,或所设置的昵称与当前用户的用户名相同,则此属性为 null。 + /// public string? CurrentUserNickname { get; private set; } /// - /// Gets the display name of the current user in this guild. + /// 获取当前用户在此服务器的显示名称。 /// + /// + /// 如果当前用户在此服务器内设置了昵称,则此属性为设置的昵称;否则为当前用户的用户名。 + /// public string CurrentUserDisplayName { get; private set; } /// - /// Gets the roles of the current user in this guild. + /// 获取当前用户在此服务器所拥有的所有角色。 /// public IReadOnlyCollection CurrentUserRoles => _currentUserRoles.ToReadOnlyCollection(); @@ -69,7 +75,8 @@ public class RestGuild : RestEntity, IGuild, IUpdateable /// public ulong? WelcomeChannelId { get; private set; } - internal bool Available { get; private set; } + /// + public bool IsAvailable { get; private set; } /// public int MaxBitrate => GuildHelper.GetMaxBitrate(this); @@ -77,75 +84,47 @@ public class RestGuild : RestEntity, IGuild, IUpdateable /// public ulong MaxUploadLimit => GuildHelper.GetUploadLimit(this); - /// - /// Gets the built-in role containing all users in this guild. - /// + /// public RestRole EveryoneRole => GetRole(0) ?? new RestRole(Kook, this, 0); - /// + /// /// /// - /// This property may contain no elements if the current guild is fetched - /// via . In this case, you must - /// use to retrieve all emotes. + /// 如果当前服务器是通过 获取的,此属性可能不包含任何元素。访问 + /// + /// 以获取所有服务器自定义表情。 /// /// public IReadOnlyCollection Emotes => _emotes.ToReadOnlyCollection(); - /// - /// Gets a collection of all roles in this guild. - /// + /// public IReadOnlyCollection Roles => _roles.ToReadOnlyCollection(); /// - /// Gets a collection of all text channels in this guild. + /// 获取此服务器中所有具有文字聊天能力的频道。 /// - /// - /// A read-only collection of message channels found within this guild. - /// - public IReadOnlyCollection TextChannels => - Channels.OfType().ToImmutableArray(); + /// + /// 语音频道也是一种文字频道,此计算属性本意用于获取所有具有文字聊天能力的频道,通过此方法获取到的文字频道列表中也包含了语音频道。 + /// 如需获取频道的实际类型,请参考 。 + /// + public IReadOnlyCollection TextChannels => Channels.OfType().ToImmutableArray(); /// - /// Gets a collection of all voice channels in this guild. + /// 获取此服务器中所有具有语音聊天能力的频道。 /// - /// - /// A read-only collection of voice channels found within this guild. - /// - public IReadOnlyCollection VoiceChannels => - Channels.OfType().ToImmutableArray(); + public IReadOnlyCollection VoiceChannels => Channels.OfType().ToImmutableArray(); /// - /// Gets a collection of all stage channels in this guild. - /// - /// - /// A read-only collection of stage channels found within this guild. - /// - /// - /// Gets a collection of all category channels in this guild. + /// 获取此服务器中的所有分组频道。 /// - /// - /// A read-only collection of category channels found within this guild. - /// - public IReadOnlyCollection CategoryChannels => - Channels.OfType().ToImmutableArray(); + public IReadOnlyCollection CategoryChannels => Channels.OfType().ToImmutableArray(); /// - /// Gets a collection of all channels in this guild. + /// 获取此服务器中的所有频道。 /// public IReadOnlyCollection Channels => _channels.ToReadOnlyCollection(); - /// - /// Gets the features of this guild. - /// - /// - /// An array of objects representing the features of this guild. - /// - /// - /// - /// What this property represents is not well investigated. - /// - /// + /// public GuildFeatures Features { get; private set; } /// @@ -167,7 +146,7 @@ public class RestGuild : RestEntity, IGuild, IUpdateable /// public string? AutoDeleteTime { get; private set; } - /// + /// public RecommendInfo? RecommendInfo { get; private set; } internal RestGuild(BaseKookClient client, ulong id) @@ -252,7 +231,7 @@ internal void Update(Model model) else DefaultChannelId = null; WelcomeChannelId = model.WelcomeChannelId != 0 ? model.WelcomeChannelId : null; - Available = true; + IsAvailable = true; if (model.Roles is { Length: 0 }) { @@ -302,39 +281,15 @@ public Task - /// Gets a collection of all users banned in this guild. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// ban objects that this guild currently possesses, with each object containing the user banned and reason - /// behind the ban. - /// + /// public Task> GetBansAsync(RequestOptions? options = null) => GuildHelper.GetBansAsync(this, Kook, options); - /// - /// Gets a ban object for a banned user. - /// - /// The banned user. - /// 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. - /// + /// public Task GetBanAsync(IUser user, RequestOptions? options = null) => GuildHelper.GetBanAsync(this, Kook, user.Id, options); - /// - /// Gets a ban object for a banned user. - /// - /// The identifier for the banned user. - /// 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. - /// + /// public Task GetBanAsync(ulong userId, RequestOptions? options = null) => GuildHelper.GetBanAsync(this, Kook, userId, options); @@ -372,24 +327,10 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxA #region Roles - /// - /// Gets a role in this guild. - /// - /// The identifier for the role. - /// - /// A role that is associated with the specified ; null if none is found. - /// + /// public RestRole? GetRole(uint id) => _roles.TryGetValue(id, out RestRole? value) ? value : null; - /// - /// Creates a new role with the provided name. - /// - /// The new name for the role. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// role. - /// + /// public async Task CreateRoleAsync(string? name = null, RequestOptions? options = null) { RestRole role = await GuildHelper.CreateRoleAsync(this, Kook, name, options).ConfigureAwait(false); @@ -402,42 +343,27 @@ public async Task CreateRoleAsync(string? name = null, RequestOptions? #region Users /// - /// Gets a collection of all users in this guild. + /// 获取此服务器内的所有用户。 /// - /// - /// This method retrieves all users found within this guild. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of guild - /// users found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器内的所有用户。 public IAsyncEnumerable> GetUsersAsync(RequestOptions? options = null) => GuildHelper.GetUsersAsync(this, Kook, KookConfig.MaxUsersPerBatch, 1, options); /// - /// Gets a user from this guild. + /// 获取此服务器内的用户。 /// - /// - /// This method retrieves a user found within this guild. - /// - /// The identifier of the user. - /// 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. - /// + /// 要获取的用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的用户;如果未找到,则返回 null public Task GetUserAsync(ulong id, RequestOptions? options = null) => GuildHelper.GetUserAsync(this, Kook, id, options); /// - /// Gets the current user for this guild. + /// 获取此服务器内当前登录的用户。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the currently logged-in - /// user within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器内当前登录的用户。 public Task GetCurrentUserAsync(RequestOptions? options = null) { if (Kook.CurrentUser is null) @@ -446,32 +372,35 @@ public Task GetCurrentUserAsync(RequestOptions? options = null) } /// - /// Gets the owner of this guild. + /// 获取此服务器的所有者。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the owner of this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有者。 public Task GetOwnerAsync(RequestOptions? options = null) => GuildHelper.GetUserAsync(this, Kook, OwnerId, options); /// - /// Gets a collection of users in this guild that the name or nickname contains the - /// provided string at . + /// 获取此服务器内与指定搜索条件匹配的用户。 /// /// - /// The can not be higher than . + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// 此方法将尝试获取所有与指定搜索条件匹配的用户。此方法会根据 + /// 将请求拆分。换句话说,如果搜索结果有 3000 名用户,而 的常量为 + /// 50,则请求将被拆分为 60 个单独请求,因此异步枚举器会异步枚举返回 60 个响应。 + /// + /// 方法可以展开这 60 个响应返回的集合,并将其合并为一个集合。 ///
- /// A delegate containing the properties to search users with. - /// The maximum number of users to be gotten. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of guild - /// users that matches the properties with the provided at . - /// + /// 一个包含设置服务器用户搜索条件属性的委托。 + /// 要获取搜索到的服务器用户的数量。 + /// 发送请求时要使用的选项。 + /// 分页的服务器用户集合的异步可枚举对象。 public IAsyncEnumerable> SearchUsersAsync( - Action func, int limit = KookConfig.MaxUsersPerBatch, - RequestOptions? options = null) => + Action func, int limit = KookConfig.MaxUsersPerBatch, RequestOptions? options = null) => GuildHelper.SearchUsersAsync(this, Kook, func, limit, options); #endregion @@ -479,37 +408,32 @@ public IAsyncEnumerable> SearchUsersAsync( #region Channels /// - /// Gets a collection of all channels in this guild. + /// 获取此服务器的所有频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// generic channels found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有频道。 public Task> GetChannelsAsync(RequestOptions? options = null) => GuildHelper.GetChannelsAsync(this, Kook, options); /// - /// Gets a channel in this guild. + /// 获取此服务器内的频道。 /// - /// The identifier for the channel. - /// 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. - /// + /// 要获取的频道的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null public Task GetChannelAsync(ulong id, RequestOptions? options = null) => GuildHelper.GetChannelAsync(this, Kook, id, options); /// - /// Gets a text channel in this guild. + /// 获取此服务器内指定具有文字聊天能力的频道。 /// - /// The identifier for the text channel. - /// 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. - /// + /// 要获取的频道的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null + /// + /// 语音频道也是一种文字频道,此方法本意用于获取具有文字聊天能力的频道。如果通过此方法传入的 ID 对应的频道是语音频道,那么也会返回对应的语音频道实体。 + /// 如需获取频道的实际类型,请参考 。 + /// public async Task GetTextChannelAsync(ulong id, RequestOptions? options = null) { RestGuildChannel channel = await GuildHelper @@ -519,13 +443,14 @@ public Task GetChannelAsync(ulong id, RequestOptions? options } /// - /// Gets a collection of all text channels in this guild. + /// 获取此服务器中所有具有文字聊天能力的频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// message channels found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有具有文字聊天能力的频道。 + /// + /// 语音频道也是一种文字频道,此方法本意用于获取所有具有文字聊天能力的频道,通过此方法获取到的文字频道列表中也包含了语音频道。 + /// 如需获取频道的实际类型,请参考 。 + /// public async Task> GetTextChannelsAsync(RequestOptions? options = null) { IReadOnlyCollection channels = await GuildHelper @@ -535,14 +460,11 @@ public async Task> GetTextChannelsAsync(Req } /// - /// Gets a voice channel in this guild. + /// 获取此服务器内指定具有语音聊天能力的频道。 /// - /// The identifier for the voice channel. - /// 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. - /// + /// 要获取的频道的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null public async Task GetVoiceChannelAsync(ulong id, RequestOptions? options = null) { RestGuildChannel channel = await GuildHelper @@ -552,13 +474,10 @@ public async Task> GetTextChannelsAsync(Req } /// - /// Gets a collection of all voice channels in this guild. + /// 获取此服务器中所有具有语音聊天能力的频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// voice channels found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有具有语音聊天能力的频道。 public async Task> GetVoiceChannelsAsync(RequestOptions? options = null) { IReadOnlyCollection channels = await GuildHelper @@ -568,14 +487,11 @@ public async Task> GetVoiceChannelsAsync(R } /// - /// Gets a category channel in this guild. + /// 获取此服务器内指定的分组频道。 /// - /// The identifier for the category channel. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the category channel associated - /// with the specified ; null if none is found. - /// + /// 要获取的频道的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null public async Task GetCategoryChannelAsync(ulong id, RequestOptions? options = null) { RestGuildChannel channel = await GuildHelper @@ -585,13 +501,10 @@ public async Task> GetVoiceChannelsAsync(R } /// - /// Gets a collection of all category channels in this guild. + /// 获取此服务器中的所有分组频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - /// category channels found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的所有分组频道。 public async Task> GetCategoryChannelsAsync(RequestOptions? options = null) { IReadOnlyCollection channels = await GuildHelper @@ -601,13 +514,10 @@ public async Task> GetCategoryChannelsA } /// - /// Gets the default text channel 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 default text channel of this guild; - /// null if none is found. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的默认文字频道;如果未找到,则返回 null public async Task GetDefaultChannelAsync(RequestOptions? options = null) { if (!DefaultChannelId.HasValue) return null; @@ -618,13 +528,10 @@ public async Task> GetCategoryChannelsA } /// - /// Gets the welcome text channel 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 welcome text channel of this guild; - /// null if none is found. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器的欢迎通知频道;如果未找到,则返回 null public async Task GetWelcomeChannelAsync(RequestOptions? options = null) { if (!WelcomeChannelId.HasValue) return null; @@ -634,44 +541,17 @@ public async Task> GetCategoryChannelsA return channel as RestTextChannel; } - /// - /// Creates a new text channel in this guild. - /// - /// The new name for the text channel. - /// The delegate containing the properties to be applied to the channel upon its creation. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// text channel. - /// + /// public Task CreateTextChannelAsync(string name, Action? func = null, RequestOptions? options = null) => GuildHelper.CreateTextChannelAsync(this, Kook, name, func, options); - /// - /// Creates a voice channel with the provided name. - /// - /// 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. - /// - /// The created voice channel. - /// + /// public Task CreateVoiceChannelAsync(string name, Action? func = null, RequestOptions? options = null) => GuildHelper.CreateVoiceChannelAsync(this, Kook, name, func, options); - /// - /// Creates a category channel with the provided name. - /// - /// 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. - /// - /// The created category channel. - /// + /// public Task CreateCategoryChannelAsync(string name, Action? func = null, RequestOptions? options = null) => GuildHelper.CreateCategoryChannelAsync(this, Kook, name, func, options); @@ -735,9 +615,6 @@ async Task IGuild.CreateInviteAsync(InviteMaxAge maxAge, InviteMaxUses IReadOnlyDictionary IGuild.AudioClients => ImmutableDictionary.Empty; - /// - bool IGuild.Available => Available; - /// IReadOnlyCollection IGuild.Roles => Roles; @@ -776,15 +653,15 @@ async Task> IGuild.GetUsersAsync(CacheMode mode, : []; /// - /// Downloading users is not supported for a REST-based guild. + /// 不支持在基于 REST 的服务器上下载用户。 Task IGuild.DownloadUsersAsync(RequestOptions? options) => throw new NotSupportedException(); /// - /// Downloading voice states is not supported for a REST-based guild. + /// 不支持在基于 REST 的服务器上下载语音状态。 Task IGuild.DownloadVoiceStatesAsync(RequestOptions? options) => throw new NotSupportedException(); /// - /// Downloading boost subscriptions is not supported for a REST-based guild. + /// 不支持在基于 REST 的服务器上下载服务器助力西南西。 Task IGuild.DownloadBoostSubscriptionsAsync(RequestOptions? options) => throw new NotSupportedException(); /// @@ -890,12 +767,8 @@ public async Task GetBadgeAsync(BadgeStyle style = BadgeStyle.GuildName, #endregion - /// - /// Returns the name of the guild. - /// - /// - /// The name of the guild. - /// + /// + /// 此服务器的名称。 public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; diff --git a/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs b/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs index a72d0d1e..7d6c9292 100644 --- a/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs +++ b/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs @@ -4,8 +4,12 @@ namespace Kook.Rest; /// -/// Gets the intimacy information associated with the specified user. +/// 表示一个基于 REST 的亲密度。 /// +/// +/// 由于亲密度的使用率较低,官方已隐藏亲密度的管理入口。如要管理亲密度,请访问 +/// https://developer.kookapp.cn/bot/cohesion,在左上角切换至要管理其亲密度的应用。 +/// public class RestIntimacy : RestEntity, IIntimacy { private ImmutableArray _images; diff --git a/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs b/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs index 30b5a359..45ce7b10 100644 --- a/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs +++ b/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs @@ -5,7 +5,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based invite. +/// 表示一个基于 REST 的邀请。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestInvite : RestEntity, IInvite, IUpdateable @@ -108,12 +108,8 @@ public async Task UpdateAsync(RequestOptions? options = null) public Task DeleteAsync(RequestOptions? options = null) => InviteHelper.DeleteAsync(this, Kook, options); - /// - /// Gets the URL of the invite. - /// - /// - /// A string that resolves to the Url of the invite. - /// + /// + /// 此邀请的 URL,URL 的路径中包含 属性的值。 public override string ToString() => Url; private string DebuggerDisplay => $"{Url} ({GuildName} / {ChannelName ?? "Channel not specified"})"; diff --git a/src/Kook.Net.Rest/Entities/Messages/Attachment.cs b/src/Kook.Net.Rest/Entities/Messages/Attachment.cs index c704fd75..44b141c4 100644 --- a/src/Kook.Net.Rest/Entities/Messages/Attachment.cs +++ b/src/Kook.Net.Rest/Entities/Messages/Attachment.cs @@ -3,7 +3,9 @@ namespace Kook.Rest; -/// +/// +/// 表示一个消息内基于的附件。 +/// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Attachment : IAttachment { @@ -60,12 +62,8 @@ internal static Attachment Create(Model model) model.Size, model.FileType, duration, model.Width, model.Height); } - /// - /// Returns the filename of this attachment. - /// - /// - /// A string containing the filename of this attachment. - /// + /// + /// 此附件的文件名。 public override string? ToString() => Filename; private string DebuggerDisplay => $"{Filename}{(Size.HasValue ? $" ({Size} bytes)" : "")}"; diff --git a/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs b/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs index 36cf57b7..723c6a7a 100644 --- a/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs +++ b/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs @@ -14,14 +14,14 @@ namespace Kook.Rest; internal static class MessageHelper { /// - /// Regex used to check if some text is formatted as inline code. + /// 用于匹配内联代码块的正则表达式。 /// private static readonly Regex InlineCodeRegex = new(@"[^\\]?(`).+?[^\\](`)", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); /// - /// Regex used to check if some text is formatted as a code block. + /// 用于匹配代码块的正则表达式。 /// private static readonly Regex BlockCodeRegex = new(@"[^\\]?(```).+?[^\\](```)", @@ -180,7 +180,7 @@ public static async Task ModifyAsync(IUserMessage msg, BaseKookClient client, Ac { MessageProperties args = new() { - Cards = msg.Cards, + Cards = [..msg.Cards], Quote = msg.Quote }; func(args); @@ -367,20 +367,20 @@ public static ImmutableArray ParseTags(string text, IMessageChannel? chann { IUser? mentionedUser = userMentions.FirstOrDefault(x => x.Id == userId); IUser? channelUser = channel?.GetUserAsync(userId, CacheMode.CacheOnly).GetAwaiter().GetResult(); - tags.Add(new Tag(TagType.UserMention, index, content.Length, userId, channelUser ?? mentionedUser)); + tags.Add(new Tag(TagType.UserMention, index, content.Length, userId, channelUser ?? mentionedUser)); } else if (MentionUtils.TryParseChannel(content, out ulong channelId, tagMode)) { IGuildChannel? mentionedChannel = guild?.GetChannelAsync(channelId, CacheMode.CacheOnly).GetAwaiter().GetResult(); - tags.Add(new Tag(TagType.ChannelMention, index, content.Length, channelId, mentionedChannel)); + tags.Add(new Tag(TagType.ChannelMention, index, content.Length, channelId, mentionedChannel)); } else if (MentionUtils.TryParseRole(content, out uint roleId, tagMode)) { IRole? mentionedRole = guild?.GetRole(roleId); - tags.Add(new Tag(TagType.RoleMention, index, content.Length, roleId, mentionedRole)); + tags.Add(new Tag(TagType.RoleMention, index, content.Length, roleId, mentionedRole)); } else if (Emote.TryParse(content, out Emote? emoji, tagMode)) - tags.Add(new Tag(TagType.Emoji, index, content.Length, emoji.Id, emoji)); + tags.Add(new Tag(TagType.Emoji, index, content.Length, emoji.Id, emoji)); // Bad Tag } @@ -396,7 +396,7 @@ public static ImmutableArray ParseTags(string text, IMessageChannel? chann int? tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { - Tag everyoneMention = new(TagType.EveryoneMention, index, "@全体成员".Length, 0, guild?.EveryoneRole); + Tag everyoneMention = new(TagType.EveryoneMention, index, "@全体成员".Length, 0U, guild?.EveryoneRole); tags.Insert(tagIndex.Value, everyoneMention); } index++; @@ -412,7 +412,7 @@ public static ImmutableArray ParseTags(string text, IMessageChannel? chann int? tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { - Tag everyoneMention = new(TagType.EveryoneMention, index, "(met)all(met)".Length, 0, guild?.EveryoneRole); + Tag everyoneMention = new(TagType.EveryoneMention, index, "(met)all(met)".Length, 0U, guild?.EveryoneRole); tags.Insert(tagIndex.Value, everyoneMention); } index++; @@ -431,7 +431,7 @@ public static ImmutableArray ParseTags(string text, IMessageChannel? chann int? tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { - Tag hereMention = new(TagType.HereMention, index, "@在线成员".Length, 0, null); + Tag hereMention = new(TagType.HereMention, index, "@在线成员".Length, 0U, null); tags.Insert(tagIndex.Value, hereMention); } index++; @@ -447,7 +447,7 @@ public static ImmutableArray ParseTags(string text, IMessageChannel? chann int? tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { - Tag hereMention = new(TagType.HereMention, index, "(met)here(met)".Length, 0, guild?.EveryoneRole); + Tag hereMention = new(TagType.HereMention, index, "(met)here(met)".Length, 0U, guild?.EveryoneRole); tags.Insert(tagIndex.Value, hereMention); } index++; diff --git a/src/Kook.Net.Rest/Entities/Messages/Poke.cs b/src/Kook.Net.Rest/Entities/Messages/Poke.cs index eb1760ab..5968d233 100644 --- a/src/Kook.Net.Rest/Entities/Messages/Poke.cs +++ b/src/Kook.Net.Rest/Entities/Messages/Poke.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a poke in messages. +/// 表示一个基于 REST 的 POKE。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Poke : IPoke @@ -71,12 +71,8 @@ internal static Poke Create(Model model) quality, pokeResource, model.MessageScenarios); } - /// - /// Returns the name of the poke. - /// - /// - /// A string containing the name of the poke. - /// + /// + /// POKE 的名称。 public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Resource.Type})"; diff --git a/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs b/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs index 37ee1e7f..19829625 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based message. +/// 表示一个基于 REST 的消息。 /// public abstract class RestMessage : RestEntity, IMessage, IUpdateable { @@ -17,9 +17,7 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable /// public IMessageChannel Channel { get; } - /// - /// Gets the Author of the message. - /// + /// public IUser Author { get; } /// @@ -31,7 +29,7 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable /// public string CleanContent => MessageHelper.SanitizeMessage(this); - /// + /// public virtual IReadOnlyCollection Attachments { get; private set; } /// @@ -46,26 +44,20 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable /// public virtual bool MentionedHere => false; - /// - /// Gets a collection of the 's on the message. - /// + /// public virtual IReadOnlyCollection Cards => ImmutableArray.Create(); - /// - /// Gets a collection of the 's on the message. - /// + /// public virtual IReadOnlyCollection Embeds => ImmutableArray.Create(); - /// - /// Gets a collection of the 's on the message. - /// + /// public virtual IReadOnlyCollection Pokes => ImmutableArray.Create(); /// public virtual IReadOnlyCollection MentionedRoleIds => ImmutableArray.Create(); /// - /// Gets a collection of the mentioned users in the message. + /// 获取此消息中提及的所有用户。 /// public IReadOnlyCollection MentionedUsers => _userMentions; @@ -75,12 +67,8 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable /// public virtual bool? IsPinned { get; internal set; } - /// - /// Gets the of the message. - /// - /// - /// A string that is the of the message. - /// + /// + /// 此消息的内容。 public override string ToString() => Content; internal RestMessage(BaseKookClient kook, Guid id, MessageType messageType, @@ -149,9 +137,7 @@ internal virtual void Update(DirectMessage model) public Task DeleteAsync(RequestOptions? options = null) => MessageHelper.DeleteAsync(this, Kook, options); /// - /// - /// This message is neither a guild channel message nor a direct message. - /// + /// 此类型的消息不支持此操作。 public async Task UpdateAsync(RequestOptions? options = null) { if (Channel is IGuildChannel) @@ -174,6 +160,7 @@ public async Task UpdateAsync(RequestOptions? options = null) } /// + /// 此类型的消息不支持此操作。 public Task AddReactionAsync(IEmote emote, RequestOptions? options = null) => Channel switch { @@ -183,6 +170,7 @@ public Task AddReactionAsync(IEmote emote, RequestOptions? options = null) => }; /// + /// 此类型的消息不支持此操作。 public Task RemoveReactionAsync(IEmote emote, IUser user, RequestOptions? options = null) => Channel switch { @@ -192,6 +180,7 @@ public Task RemoveReactionAsync(IEmote emote, IUser user, RequestOptions? option }; /// + /// 此类型的消息不支持此操作。 public Task RemoveReactionAsync(IEmote emote, ulong userId, RequestOptions? options = null) => Channel switch { @@ -201,6 +190,7 @@ public Task RemoveReactionAsync(IEmote emote, ulong userId, RequestOptions? opti }; /// + /// 此类型的消息不支持此操作。 public Task> GetReactionUsersAsync(IEmote emote, RequestOptions? options = null) => Channel switch { @@ -211,17 +201,9 @@ public Task> GetReactionUsersAsync(IEmote emote, Requ #region IMessage - IUser IMessage.Author => Author; - /// IReadOnlyCollection IMessage.Attachments => Attachments; - /// - IReadOnlyCollection IMessage.Cards => Cards; - - /// - IReadOnlyCollection IMessage.Embeds => Embeds; - /// IReadOnlyCollection IMessage.Pokes => Pokes; diff --git a/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs b/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs index d48b0edf..f82754af 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs @@ -3,17 +3,17 @@ namespace Kook.Rest; /// -/// Represents a single REST-based poke action. +/// 表示一个基于 REST 的 POKE 动作。 /// public class RestPokeAction : IPokeAction { - /// + /// public IUser Operator { get; } - /// + /// public IReadOnlyCollection Targets { get; } - /// + /// public Poke Poke { get; } internal RestPokeAction(IUser @operator, IEnumerable targets, Poke poke) @@ -31,12 +31,6 @@ internal static RestPokeAction Create(BaseKookClient kook, IUser @operator, IEnu #region IPokeAction - /// - IUser IPokeAction.Operator => Operator; - - /// - IReadOnlyCollection IPokeAction.Targets => Targets; - /// IPoke IPokeAction.Poke => Poke; diff --git a/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs b/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs index 95c77c3a..ea83ca26 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs @@ -3,7 +3,7 @@ namespace Kook.Rest; /// -/// Represents a single REST-based reaction. +/// 表示一个基于 REST 的回应。 /// public class RestReaction : IReaction { @@ -11,12 +11,12 @@ public class RestReaction : IReaction public IEmote Emote { get; } /// - /// Gets the number of reactions added. + /// 获取添加或跟随此回应的用户数量。 /// public int Count { get; } /// - /// Gets whether the reactions is added by the user. + /// 获取当前用户是否添加或跟随了此回应。 /// public bool Me { get; } diff --git a/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs b/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs index 598ccb5b..84830994 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs @@ -4,8 +4,13 @@ namespace Kook.Rest; /// -/// Represents a REST-based system message. +/// 表示一个基于 REST 的系统消息。 /// +/// +/// +/// KOOK 未统一规范系统消息类型,此类并未在 之上封装更多的实用功能。 +/// +/// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestSystemMessage : RestMessage, ISystemMessage { @@ -15,6 +20,7 @@ public class RestSystemMessage : RestMessage, ISystemMessage internal RestSystemMessage(BaseKookClient kook, Guid id, MessageType messageType, IMessageChannel channel, IUser author) : base(kook, id, messageType, channel, author, MessageSource.System) { + SystemMessageType = SystemMessageType.Unknown; } internal static new RestSystemMessage Create(BaseKookClient kook, IMessageChannel channel, IUser author, Message model) diff --git a/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs b/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs index b0806fba..41817d8a 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs @@ -5,7 +5,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based message sent by a user. +/// 表示一个基于 REST 的用户消息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestUserMessage : RestMessage, IUserMessage @@ -49,12 +49,12 @@ public class RestUserMessage : RestMessage, IUserMessage public override IReadOnlyCollection MentionedRoleIds => _roleMentionIds; /// - /// Gets a collection of the mentioned roles in the message. + /// 获取此消息中提及的所有角色。 /// public IReadOnlyCollection MentionedRoles => _roleMentions; /// - /// Gets a collection of the mentioned channels in the message. + /// 获取此消息中提及的所有频道。 /// public IReadOnlyCollection MentionedChannels => _channelMentions; @@ -173,14 +173,15 @@ internal override void Update(DirectMessage model) } /// - /// Transforms this message's text into a human-readable form by resolving its tags. + /// 转换消息文本中的提及与表情符号为可读形式。 /// - /// The zero-based index at which to begin the resolving for the specified value. - /// Determines how the user tag should be handled. - /// Determines how the channel tag should be handled. - /// Determines how the role tag should be handled. - /// Determines how the @everyone tag should be handled. - /// Determines how the emoji tag should be handled. + /// 指定解析的起始位置。 + /// 指定用户提及标签的处理方式。 + /// 指定频道提及标签的处理方式。 + /// 指定角色提及标签的处理方式。 + /// 指定全体成员与在线成员提及标签的处理方式。 + /// 指定表情符号标签的处理方式。 + /// 转换后的消息文本。 public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name) => @@ -208,21 +209,12 @@ public string Resolve(TagHandling userHandling = TagHandling.Name, public async Task ModifyAsync(Action func, RequestOptions? options = null) { await MessageHelper.ModifyAsync(this, Kook, func, options).ConfigureAwait(false); - MessageProperties properties = new() { Content = Content, Cards = Cards, Quote = Quote }; + MessageProperties properties = new() { Content = Content, Cards = [..Cards], Quote = Quote }; func(properties); Content = properties.Content; _cards = properties.Cards?.ToImmutableArray() ?? ImmutableArray.Empty; Quote = properties.Quote?.QuotedMessageId == Guid.Empty ? null : properties.Quote; } - /// - bool? IMessage.IsPinned => IsPinned; - - /// - IReadOnlyCollection IMessage.Cards => Cards; - - /// - IReadOnlyCollection IMessage.Embeds => Embeds; - #endregion } diff --git a/src/Kook.Net.Rest/Entities/RestEntity.cs b/src/Kook.Net.Rest/Entities/RestEntity.cs index 0131335c..3953fb23 100644 --- a/src/Kook.Net.Rest/Entities/RestEntity.cs +++ b/src/Kook.Net.Rest/Entities/RestEntity.cs @@ -1,18 +1,18 @@ namespace Kook.Rest; /// -/// Represents a generic REST-based entity. +/// 表示一个基于 REST 的具有唯一标识符的实体。 /// -/// -public abstract class RestEntity : IEntity - where T : IEquatable +/// 唯一标识符的类型。 +public abstract class RestEntity : IEntity + where TId : IEquatable { internal BaseKookClient Kook { get; } /// - public T Id { get; } + public TId Id { get; } - internal RestEntity(BaseKookClient kook, T id) + internal RestEntity(BaseKookClient kook, TId id) { Kook = kook; Id = id; diff --git a/src/Kook.Net.Rest/Entities/Roles/RestRole.cs b/src/Kook.Net.Rest/Entities/Roles/RestRole.cs index 1dc371db..89281986 100644 --- a/src/Kook.Net.Rest/Entities/Roles/RestRole.cs +++ b/src/Kook.Net.Rest/Entities/Roles/RestRole.cs @@ -4,20 +4,15 @@ namespace Kook.Rest; /// -/// Represents a REST-based role. +/// 表示一个基于 REST 的可授予服务器用户的角色。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestRole : RestEntity, IRole { #region RestRole - /// - /// Gets the guild that owns this role. - /// - /// - /// An representing the parent guild of this role. - /// - internal IGuild Guild { get; } + /// + public IGuild Guild { get; } /// public RoleType Type { get; private set; } @@ -47,11 +42,8 @@ public class RestRole : RestEntity, IRole public int Position { get; private set; } /// - /// Returns a value that determines if the role is an @everyone role. + /// 获取此角色是否为 @全体成员 全体成员角色。 /// - /// - /// true if the role is @everyone; otherwise false. - /// public bool IsEveryone => Id == 0; /// @@ -82,8 +74,8 @@ internal void Update(Model model) ColorType = model.ColorType; GradientColor = model.GradientColor; Position = model.Position; - IsHoisted = model.Hoist; - IsMentionable = model.Mentionable; + IsHoisted = model.IsHoisted; + IsMentionable = model.IsMentionable; Permissions = new GuildPermissions(model.Permissions); } @@ -99,10 +91,27 @@ public Task DeleteAsync(RequestOptions? options = null) => RoleHelper.DeleteAsync(this, Kook, options); /// - /// Gets a collection of users that have this role. + /// 获取拥有此角色的用户的集合。 /// - /// The options to be used when fetching the users. - /// An asynchronous enumerable that contains a collection of users that have this role. + /// + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取拥有此角色的所有服务器用户。此方法会根据 + /// 将请求拆分。换句话说,如果存在 500 个用户拥有此角色,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 + ///
+ /// 发送请求时要使用的选项。 + /// 分页的用户集合的异步可枚举对象。 public IAsyncEnumerable> GetUsersAsync(RequestOptions? options = null) => GuildHelper.SearchUsersAsync(Guild, Kook, x => x.RoleId = Id, KookConfig.MaxUsersPerBatch, options); @@ -113,9 +122,6 @@ public IAsyncEnumerable> GetUsersAsync(RequestOp #region IRole - /// - IGuild IRole.Guild => Guild; - /// IAsyncEnumerable> IRole.GetUsersAsync(CacheMode mode, RequestOptions? options) => mode == CacheMode.AllowDownload @@ -124,12 +130,8 @@ IAsyncEnumerable> IRole.GetUsersAsync(CacheMode #endregion - /// - /// Gets the name of the role. - /// - /// - /// A string that is the name of the role. - /// + /// + /// 此角色的名称。 public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; diff --git a/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs b/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs index 400c53a8..cef032f0 100644 --- a/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs +++ b/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs @@ -28,13 +28,13 @@ public static async Task ModifyAsync(IRole role, BaseKookClient client, RoleId = role.Id, Name = args.Name, Color = args.Color, - Hoist = args.Hoist switch + IsHoisted = args.IsHoisted switch { true => 1, false => 0, _ => null }, - Mentionable = args.Mentionable switch + IsMentionable = args.IsMentionable switch { true => 1, false => 0, diff --git a/src/Kook.Net.Rest/Entities/Users/RestFriendRequest.cs b/src/Kook.Net.Rest/Entities/Users/RestFriendRequest.cs index 9a9bbffb..5159705d 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestFriendRequest.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestFriendRequest.cs @@ -5,7 +5,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based friend request. +/// 表示一个基于 REST 的好友请求。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestFriendRequest : RestEntity, IFriendRequest diff --git a/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs b/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs index da8bf638..a54d0ea9 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs @@ -6,7 +6,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based guild user. +/// 表示一个基于 REST 的服务器用户。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestGuildUser : RestUser, IGuildUser @@ -21,7 +21,8 @@ public class RestGuildUser : RestUser, IGuildUser /// public string? Nickname { get; private set; } - internal IGuild Guild { get; private set; } + /// + public IGuild Guild { get; } /// public ulong GuildId => Guild.Id; @@ -42,16 +43,10 @@ public class RestGuildUser : RestUser, IGuildUser public bool? IsOwner { get; private set; } /// - /// Resolving permissions requires the parent guild to be downloaded. - public GuildPermissions GuildPermissions - { - get - { - if (!Guild.Available) - throw new InvalidOperationException("Resolving permissions requires the parent guild to be downloaded."); - return new GuildPermissions(Permissions.ResolveGuild(Guild, this)); - } - } + /// 解析服务器用户的权限需要所属服务器的基础数据已完整下载。 + public GuildPermissions GuildPermissions => Guild.IsAvailable + ? new GuildPermissions(Permissions.ResolveGuild(Guild, this)) + : throw new InvalidOperationException("Resolving permissions requires the parent guild to be downloaded."); /// public IReadOnlyCollection RoleIds => _roleIds; @@ -144,66 +139,34 @@ public Task KickAsync(RequestOptions? options = null) => UserHelper.KickAsync(this, Kook, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task AddRoleAsync(uint roleId, RequestOptions? options = null) => AddRolesAsync(new[] { roleId }, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task AddRoleAsync(IRole role, RequestOptions? options = null) => AddRoleAsync(role.Id, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task AddRolesAsync(IEnumerable roleIds, RequestOptions? options = null) => UserHelper.AddRolesAsync(this, Kook, roleIds, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task AddRolesAsync(IEnumerable roles, RequestOptions? options = null) => AddRolesAsync(roles.Select(x => x.Id), options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task RemoveRoleAsync(uint roleId, RequestOptions? options = null) => RemoveRolesAsync(new[] { roleId }, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task RemoveRoleAsync(IRole role, RequestOptions? options = null) => RemoveRoleAsync(role.Id, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task RemoveRolesAsync(IEnumerable roleIds, RequestOptions? options = null) => UserHelper.RemoveRolesAsync(this, Kook, roleIds, options); /// - /// - /// This method will update the cached roles of this user. - /// To update the cached roles of this user, please use . - /// public Task RemoveRolesAsync(IEnumerable roles, RequestOptions? options = null) => RemoveRolesAsync(roles.Select(x => x.Id)); @@ -228,7 +191,6 @@ public Task> GetConnectedVoiceChannelsAsync(R UserHelper.GetConnectedChannelAsync(this, Kook, options); /// - /// Resolving permissions requires the parent guild to be downloaded. public ChannelPermissions GetPermissions(IGuildChannel channel) { GuildPermissions guildPerms = GuildPermissions; @@ -241,13 +203,6 @@ public override Task RequestFriendAsync(RequestOptions? options = null) => #endregion - #region IGuildUser - - /// - IGuild IGuildUser.Guild => Guild; - - #endregion - #region IVoiceState /// @@ -259,5 +214,8 @@ public override Task RequestFriendAsync(RequestOptions? options = null) => /// IVoiceChannel? IVoiceState.VoiceChannel => null; + /// + IReadOnlyCollection IVoiceState.VoiceChannels => []; + #endregion } diff --git a/src/Kook.Net.Rest/Entities/Users/RestPresence.cs b/src/Kook.Net.Rest/Entities/Users/RestPresence.cs index 190b09da..35943aa1 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestPresence.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestPresence.cs @@ -3,7 +3,7 @@ namespace Kook.Rest; /// -/// Represents the REST user's presence status. This may include their online status and their activity. +/// 表示一个基于 REST 的当前登录的用户信息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestPresence : IPresence @@ -38,15 +38,6 @@ internal void Update(bool? isOnline, string? activeClient) ActiveClient = ConvertClientType(activeClient); } - /// - /// The client type where a user is active. - /// - /// - /// A string representing the client type. - /// - /// - /// A that this user is active. - /// private static ClientType? ConvertClientType(string? clientType) { if (string.IsNullOrWhiteSpace(clientType)) diff --git a/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs b/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs index 0aabb531..bd9881f2 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents the logged-in REST-based user. +/// 表示一个基于 REST 的当前登录的用户信息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestSelfUser : RestUser, ISelfUser @@ -45,7 +45,7 @@ internal void Update(Model model) } /// - /// Unable to update this object using a different token. + /// 无法使用不同的用户令牌更新此对象。 public override async Task UpdateAsync(RequestOptions? options = null) { Model model = await Kook.ApiClient.GetSelfUserAsync(options).ConfigureAwait(false); diff --git a/src/Kook.Net.Rest/Entities/Users/RestUser.cs b/src/Kook.Net.Rest/Entities/Users/RestUser.cs index e4aba34e..635a2566 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestUser.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestUser.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based user. +/// 表示一个基于 REST 的用户。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RestUser : RestEntity, IUser, IUpdateable @@ -139,24 +139,11 @@ internal virtual void UpdatePresence(bool? isOnline, string? activeClient) Presence.Update(isOnline, activeClient); } - /// - /// Creates a direct message channel to this user. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a rest DM channel where the user is the recipient. - /// + /// public Task CreateDMChannelAsync(RequestOptions? options = null) => UserHelper.CreateDMChannelAsync(this, Kook, options); - /// - /// Gets the intimacy information with this user. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for getting the intimacy information. The task result - /// contains the intimacy information associated with this user. - /// + /// public Task GetIntimacyAsync(RequestOptions? options = null) => UserHelper.GetIntimacyAsync(this, Kook, options); @@ -183,11 +170,10 @@ public Task RemoveFriendAsync(RequestOptions? options = null) => #endregion /// - /// Gets the Username#IdentifyNumber of the user. + /// 获取此用户的包含用户名及识别号的格式化字符串。 /// - /// - /// A string that resolves to Username#IdentifyNumber of the user. - /// + /// 一个表示此用户的包含用户名及识别号的格式化字符串。 + /// public override string ToString() => this.UsernameAndIdentifyNumber(Kook.FormatUsersInBidirectionalUnicode); private string DebuggerDisplay => diff --git a/src/Kook.Net.Rest/Extensions/CardJsonExtension.cs b/src/Kook.Net.Rest/Extensions/CardJsonExtension.cs index 98359b97..4aeab0ab 100644 --- a/src/Kook.Net.Rest/Extensions/CardJsonExtension.cs +++ b/src/Kook.Net.Rest/Extensions/CardJsonExtension.cs @@ -8,7 +8,7 @@ namespace Kook.Rest; /// -/// Provides extension methods for and . +/// 提供一系列用于 的扩展方法。 /// public static class CardJsonExtension { @@ -20,11 +20,11 @@ public static class CardJsonExtension }); /// - /// Tries to parse a string into an . + /// 尝试将字符串解析为单个卡片构造器 。 /// - /// The json string to parse. - /// The with populated values. An empty instance if method returns false. - /// true if was successfully parsed. false if not. + /// 要解析的 JSON 字符串。 + /// 如果所提供的 JSON 字符串可以解析为单个卡片构造器实例,则返回该实例;否则返回 null。 + /// 如果成功解析 ,则为 true;否则为 false public static bool TryParseSingle(string json, [NotNullWhen(true)] out ICardBuilder? builder) { try @@ -48,11 +48,11 @@ public static bool TryParseSingle(string json, [NotNullWhen(true)] out ICardBuil } /// - /// Tries to parse a string into an . + /// 尝试将字符串解析为多个卡片构造器 。 /// - /// The json string to parse. - /// A collection of with populated values. An empty instance if method returns false. - /// true if was successfully parsed. false if not. + /// 要解析的 JSON 字符串。 + /// 如果所提供的 JSON 字符串可以解析为多个卡片构造器实例,则返回该实例;否则返回 null。 + /// 如果成功解析 ,则为 true;否则为 false public static bool TryParseMany(string json, [NotNullWhen(true)] out IEnumerable? builders) { try @@ -76,11 +76,11 @@ public static bool TryParseMany(string json, [NotNullWhen(true)] out IEnumerable } /// - /// Parses a string into an . + /// 将字符串解析为单个卡片构造器 。 /// - /// The json string to parse. - /// An with populated values from the passed . - /// Thrown if the string passed is not valid json. + /// 要解析的 JSON 字符串。 + /// 单个卡片构造器实例。 + /// 如果无法将 JSON 解析为单个卡片构造器。 public static ICardBuilder ParseSingle(string json) { CardBase model = JsonSerializer.Deserialize(json, _options.Value) @@ -89,11 +89,11 @@ public static ICardBuilder ParseSingle(string json) } /// - /// Parses a string into a collection of s. + /// 将字符串解析为多个卡片构造器 。 /// - /// The json string to parse. - /// A collection of s with populated values from the passed . - /// Thrown if the string passed is not valid json. + /// 要解析的 JSON 字符串。 + /// 多个卡片构造器实例。 + /// 如果无法将 JSON 解析为多个卡片构造器。 public static IEnumerable ParseMany(string json) { IEnumerable models = JsonSerializer.Deserialize>(json, _options.Value) @@ -102,26 +102,20 @@ public static IEnumerable ParseMany(string json) } /// - /// Gets a Json formatted string from an . + /// 将卡片构造器 序列化为 JSON 格式的字符串。 /// - /// - /// See to parse Json back into card. - /// - /// The builder to format as Json string. - /// Whether to write the json with indents. - /// A Json string containing the data from the . + /// 要序列化的卡片构造器。 + /// 是否使用缩进写入 JSON。 + /// 包含来自 的数据的 JSON 字符串。 public static string ToJsonString(this ICardBuilder builder, bool writeIndented = true) => ToJsonString(builder.Build(), writeIndented); /// - /// Gets a Json formatted string from an . + /// 将卡片 序列化为 JSON 格式的字符串。 /// - /// - /// See to parse Json back into card. - /// - /// The card to format as Json string. - /// Whether to write the json with indents. - /// A Json string containing the data from the . + /// 要序列化的卡片构造器。 + /// 是否使用缩进写入 JSON。 + /// 包含来自 的数据的 JSON 字符串。 public static string ToJsonString(this ICard card, bool writeIndented = true) { JsonSerializerOptions options = new() diff --git a/src/Kook.Net.Rest/Extensions/EntityExtensions.cs b/src/Kook.Net.Rest/Extensions/EntityExtensions.cs index a0e9a138..fe5fe524 100644 --- a/src/Kook.Net.Rest/Extensions/EntityExtensions.cs +++ b/src/Kook.Net.Rest/Extensions/EntityExtensions.cs @@ -155,7 +155,6 @@ public static CountdownModule ToEntity(this API.CountdownModule model) => public static InviteModule ToEntity(this API.InviteModule model) => new(model.Code); - public static API.ModuleBase ToModel(this IModule entity) { return entity switch diff --git a/src/Kook.Net.Rest/KookRestClient.cs b/src/Kook.Net.Rest/KookRestClient.cs index 781a9ea3..125943a2 100644 --- a/src/Kook.Net.Rest/KookRestClient.cs +++ b/src/Kook.Net.Rest/KookRestClient.cs @@ -7,7 +7,7 @@ namespace Kook.Rest; /// -/// Represents a REST-based KOOK client. +/// 表示一个基于 REST 的 KOOK 客户端。 /// public class KookRestClient : BaseKookClient, IKookClient { @@ -19,9 +19,7 @@ public class KookRestClient : BaseKookClient, IKookClient NumberHandling = JsonNumberHandling.AllowReadingFromString }; - /// - /// Gets the logged-in user. - /// + /// public new RestSelfUser? CurrentUser { get => base.CurrentUser as RestSelfUser; @@ -29,7 +27,7 @@ public class KookRestClient : BaseKookClient, IKookClient } /// - /// Initializes a new REST-based KOOK client with the default configuration. + /// 使用默认配置初始化一个 类的新实例。 /// public KookRestClient() : this(new KookRestConfig()) @@ -37,9 +35,9 @@ public KookRestClient() } /// - /// Initializes a new REST-based KOOK client with the specified configuration. + /// 使用指定的配置初始化一个 类的新实例。 /// - /// The configuration to use. + /// 用于初始化客户端的配置。 public KookRestClient(KookRestConfig config) : base(config, CreateApiClient(config)) { @@ -79,25 +77,19 @@ internal override async Task OnLoginAsync(TokenType tokenType, string token) #region Guilds /// - /// Gets a guild. + /// 获取一个服务器。 /// - /// The guild identifier. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the guild associated - /// with the identifier; null when the guild cannot be found. - /// + /// 服务器的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的服务器;若指定 ID 的服务器不存在,则为 null public Task GetGuildAsync(ulong id, RequestOptions? options = null) => ClientHelper.GetGuildAsync(this, id, options); /// - /// Gets a collection of guilds that the user is currently in. + /// 获取当前用户所在的所有服务器。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection - /// of guilds that the current user is in. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是当前用户所在的所有服务器。 public Task> GetGuildsAsync(RequestOptions? options = null) => ClientHelper.GetGuildsAsync(this, options); @@ -106,44 +98,33 @@ public Task> GetGuildsAsync(RequestOptions? optio #region Channels /// - /// Gets a generic channel. + /// 获取一个频道。 /// - /// The identifier of the channel. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the channel associated - /// with the identifier; null when the channel cannot be found. - /// + /// 频道的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的频道;若指定 ID 的频道不存在,则为 null public Task GetChannelAsync(ulong id, RequestOptions? options = null) => ClientHelper.GetChannelAsync(this, id, options); /// - /// Gets a direct message channel. + /// 获取一个私聊频道。 /// - /// The identifier of the channel. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection - /// of direct-message channels that the user currently partakes in. - /// + /// 私聊频道的聊天代码。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定聊天代码的私聊频道;若指定聊天代码的私聊频道不存在,则为 null public Task GetDMChannelAsync(Guid chatCode, RequestOptions? options = null) => ClientHelper.GetDMChannelAsync(this, chatCode, options); /// - /// Gets a collection of direct message channels opened in this session. + /// 获取当前会话中已创建的所有私聊频道。 /// /// - /// This method returns a collection of currently opened direct message channels. /// - /// This method will not return previously opened DM channels outside of the current session! If you - /// have just started the client, this may return an empty collection. + /// 此方法不会返回当前会话之外已创建的私聊频道。如果客户端刚刚启动,这可能会返回一个空集合。 /// /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a read-only collection - /// of direct-message channels that the user currently partakes in. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是当前会话中已创建的所有私聊频道。 public Task> GetDMChannelsAsync(RequestOptions? options = null) => ClientHelper.GetDMChannelsAsync(this, options); @@ -152,27 +133,25 @@ public Task> GetDMChannelsAsync(RequestOption #region Roles /// - /// Adds the specified role to this user in the guild. + /// 在指定服务器内授予指定用户指定的角色。 /// - /// The guild where the role and user are located. - /// The user to add the role to. - /// The role to be added to the user. - /// - /// A task that represents the asynchronous role addition operation. - /// - public Task AddRoleAsync(ulong guildId, ulong userId, uint roleId) => + /// 要授予的角色及服务器用户所在的服务器的 ID。 + /// 要为其授予角色的用户的 ID。 + /// 要授予的角色的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步授予操作的任务。 + public Task AddRoleAsync(ulong guildId, ulong userId, uint roleId, RequestOptions? options = null) => ClientHelper.AddRoleAsync(this, guildId, userId, roleId); /// - /// Removes the specified from this user in the guild. + /// 在指定服务器内撤销指定用户指定的角色。 /// - /// The guild where the role and user are located. - /// The user to remove the role from. - /// The role to be removed from the user. - /// - /// A task that represents the asynchronous role removal operation. - /// - public Task RemoveRoleAsync(ulong guildId, ulong userId, uint roleId) => + /// 要撤销的角色及服务器用户所在的服务器的 ID。 + /// 要为其撤销角色的用户的 ID。 + /// 要撤销的角色的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步撤销操作的任务。 + public Task RemoveRoleAsync(ulong guildId, ulong userId, uint roleId, RequestOptions? options = null) => ClientHelper.RemoveRoleAsync(this, guildId, userId, roleId); #endregion @@ -180,27 +159,21 @@ public Task RemoveRoleAsync(ulong guildId, ulong userId, uint roleId) => #region Users /// - /// Gets a user. + /// 获取一个用户。 /// - /// The identifier of the user (e.g. `168693960628371456`). - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the user associated with - /// the identifier; null if the user is not found. - /// + /// 用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的用户;若指定 ID 的用户不存在,则为 null public Task GetUserAsync(ulong id, RequestOptions? options = null) => ClientHelper.GetUserAsync(this, id, options); /// - /// Gets a user from a guild. + /// 获取一个服务器用户。 /// - /// The identifier of the guild where the user is located. - /// The identifier of the user (e.g. `168693960628371456`). - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the user from a guild - /// associated with the identifier; null if the user is not found in the guild. - /// + /// 服务器的 ID。 + /// 用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是在具有指定 ID 的服务器内具有指定 ID 的用户;若指定 ID 的服务器内指定 ID 的用户不存在,则为 null public Task GetGuildUserAsync(ulong guildId, ulong id, RequestOptions? options = null) => ClientHelper.GetGuildMemberAsync(this, guildId, id, options); @@ -209,35 +182,26 @@ public Task GetUserAsync(ulong id, RequestOptions? options = null) => #region Friends /// - /// Gets friends. + /// 获取所有好友。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of users - /// that are friends with the current user. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有与当前用户是好友的用户。 public Task> GetFriendsAsync(RequestOptions? options = null) => ClientHelper.GetFriendsAsync(this, options); /// - /// Gets friend requests. + /// 获取所有好友请求。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of - /// friend requests that the current user has received. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有请求与当前用户成为好友的用户。 public Task> GetFriendRequestsAsync(RequestOptions? options = null) => ClientHelper.GetFriendRequestsAsync(this, options); /// - /// Gets blocked users. + /// 获取所有被当前用户屏蔽的用户。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of users - /// that are blocked by the current user. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是所有被当前用户屏蔽的用户。 public Task> GetBlockedUsersAsync(RequestOptions? options = null) => ClientHelper.GetBlockedUsersAsync(this, options); @@ -246,56 +210,44 @@ public Task> GetBlockedUsersAsync(RequestOptions? #region Reactions /// - /// Adds a reaction to a message. + /// 向指定的消息添加一个回应。 /// - /// The identifier of the message. - /// The emoji used to react to the message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for adding a reaction to the message. - /// - /// + /// 要为其添加回应的消息的 ID。 + /// 要用于向指定消息添加回应的表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示添加添加异步操作的任务。 public Task AddReactionAsync(Guid messageId, IEmote emote, RequestOptions? options = null) => MessageHelper.AddReactionAsync(messageId, emote, this, options); /// - /// Removes a reaction from a message. + /// 从指定的消息移除一个回应。 /// - /// The identifier of the message. - /// The identifier of the user who added the reaction. - /// The emoji used to remove from the message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for removing a reaction from the message. - /// - /// + /// 要从中移除回应的消息的 ID。 + /// 要移除其回应的用户的 ID。 + /// 要从指定消息移除的回应的表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除操作的任务。 public Task RemoveReactionAsync(Guid messageId, ulong userId, IEmote emote, RequestOptions? options = null) => MessageHelper.RemoveReactionAsync(messageId, userId, emote, this, options); /// - /// Adds a reaction to a direct message. + /// 向指定的私聊消息添加一个回应。 /// - /// The identifier of the direct message. - /// The emoji used to react to the message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for adding a reaction to the direct message. - /// - /// + /// 要为其添加回应的消息的 ID。 + /// 要用于向指定消息添加回应的表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示添加添加异步操作的任务。 public Task AddDirectMessageReactionAsync(Guid messageId, IEmote emote, RequestOptions? options = null) => MessageHelper.AddDirectMessageReactionAsync(messageId, emote, this, options); /// - /// Removes a reaction from a direct message. + /// 从指定的私聊消息移除一个回应。 /// - /// The identifier of the direct message. - /// The identifier of the user who added the reaction. - /// The emoji used to remove from the message. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous operation for removing a reaction from the direct message. - /// - /// + /// 要从中移除回应的消息的 ID。 + /// 要移除其回应的用户的 ID。 + /// 要从指定消息移除的回应的表情符号。 + /// 发送请求时要使用的选项。 + /// 一个表示异步移除操作的任务。 public Task RemoveDirectMessageReactionAsync(Guid messageId, ulong userId, IEmote emote, RequestOptions? options = null) => MessageHelper.RemoveDirectMessageReactionAsync(messageId, userId, emote, this, options); @@ -304,12 +256,12 @@ public Task RemoveDirectMessageReactionAsync(Guid messageId, ulong userId, IEmot #region Assets /// - /// Creates an asset from a file path. + /// 从文件路径上传并创建一个资源。 /// - /// The path to the file. - /// The name of the file. - /// The options to be used when sending the request. - /// The asset resource URI of the uploaded file. + /// 文件的路径。 + /// 文件名。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果是上传文件后的资源地址 URL。 public async Task CreateAssetAsync(string path, string? filename = null, RequestOptions? options = null) { #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER @@ -322,12 +274,12 @@ public async Task CreateAssetAsync(string path, string? filename = null, } /// - /// Creates an asset from a stream. + /// 从文件的流上传并创建一个资源。 /// - /// The stream to the file. - /// The name of the file. - /// The options to be used when sending the request. - /// The asset resource URI of the uploaded file. + /// 文件的流。 + /// 文件名。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果是上传文件后的资源地址 URL。 public Task CreateAssetAsync(Stream stream, string filename, RequestOptions? options = null) => ClientHelper.CreateAssetAsync(this, stream, filename, options); @@ -336,26 +288,36 @@ public Task CreateAssetAsync(Stream stream, string filename, RequestOpti #region Games /// - /// Gets games information. + /// 获取所有游戏信息。 /// - /// - /// Specifies whether to return games information created by the current user or - /// by the system by default; null to return all games information. - /// - /// The options to be used when sending the request. - /// A collection of games information. + /// + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// 此方法将尝试获取所有具有指定创建源的游戏信息。此方法会根据 + /// 将请求拆分。换句话说,如果有 3000 款游戏的信息,而 的常量为 + /// 100,则请求将被拆分为 30 个单独请求,因此异步枚举器会异步枚举返回 30 个响应。 + /// + /// 方法可以展开这 30 个响应返回的集合,并将其合并为一个集合。 + ///
+ /// 要获取的游戏信息的创建来源。 + /// 发送请求时要使用的选项。 + /// 分页的游戏信息集合的异步可枚举对象。 public IAsyncEnumerable> GetGamesAsync( GameCreationSource? source = null, RequestOptions? options = null) => ClientHelper.GetGamesAsync(this, source, options); /// - /// Creates game information. + /// 创建一款游戏的信息。 /// - /// The name of the game. - /// The process name of the game. - /// The icon URI of the game. - /// The options to be used when sending the request. - /// + /// 游戏的名称。 + /// 游戏进程的名称。 + /// 游戏图标的资源地址 URL。 + /// 发送请求时要使用的选项。 + /// 一个表示异步创建操作的任务。任务的结果是所创建的游戏信息。 public Task CreateGameAsync(string name, string? processName = null, string? iconUrl = null, RequestOptions? options = null) => ClientHelper.CreateGameAsync(this, name, processName, iconUrl, options); diff --git a/src/Kook.Net.Rest/KookRestConfig.cs b/src/Kook.Net.Rest/KookRestConfig.cs index 3c800020..2857cc6a 100644 --- a/src/Kook.Net.Rest/KookRestConfig.cs +++ b/src/Kook.Net.Rest/KookRestConfig.cs @@ -3,12 +3,15 @@ namespace Kook.Rest; /// -/// Represents a configuration class for . +/// 定义 Kook.Net 有关 REST 各种行为的配置类。 /// +/// +/// 此配置基于 ,在基础配置的基础上,定义了有关 REST 的配置。 +/// public class KookRestConfig : KookConfig { /// - /// Gets or sets the to use. + /// 获取或设置要用于创建 REST 客户端的 委托。 /// public RestClientProvider RestClientProvider { get; set; } = DefaultRestClientProvider.Instance; } diff --git a/src/Kook.Net.Rest/Net/DefaultRestClient.cs b/src/Kook.Net.Rest/Net/DefaultRestClient.cs index 27808392..16d305e1 100644 --- a/src/Kook.Net.Rest/Net/DefaultRestClient.cs +++ b/src/Kook.Net.Rest/Net/DefaultRestClient.cs @@ -39,12 +39,10 @@ public DefaultRestClient(string baseUrl, bool useProxy = false) { _baseUrl = baseUrl; -#pragma warning disable IDISP014 _client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, UseCookies = false, UseProxy = useProxy }); -#pragma warning restore IDISP014 SetHeader("accept-encoding", "gzip, deflate"); _cancellationToken = CancellationToken.None; @@ -125,9 +123,7 @@ public async Task SendAsync(HttpMethod method, string endpoint, // // See this comment explaining why this is safe: https://github.com/aspnet/Security/issues/886#issuecomment-229181249 // See also the source for HttpRequestMessage: https://github.com/microsoft/referencesource/blob/master/System/net/System/Net/Http/HttpRequestMessage.cs -#pragma warning disable IDISP004 var restRequest = new HttpRequestMessage(method, uri); -#pragma warning restore IDISP004 if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); diff --git a/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs b/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs index ee3a3e2e..3b025796 100644 --- a/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs +++ b/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs @@ -1,21 +1,22 @@ namespace Kook.Net.Rest; /// -/// Represents a default that creates instances. +/// 表示一个默认的 ,用于创建 +/// 的默认实现的实例。 /// public static class DefaultRestClientProvider { /// - /// Gets a delegate that creates instances. + /// 获取一个默认的 委托,用于创建 + /// 的默认实现的实例。 /// public static readonly RestClientProvider Instance = Create(); /// - /// Creates a delegate that creates a new instance. + /// 创建一个新的 委托。 /// - /// Whether to use the system proxy. - /// A delegate that creates a new instance. - // /// The default RestClientProvider is not supported on this platform. + /// 是否使用系统代理。 + /// 一个新的 委托。 public static RestClientProvider Create(bool useProxy = false) => url => { diff --git a/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs b/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs index 84165e79..43d6c0e8 100644 --- a/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs +++ b/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs @@ -3,8 +3,6 @@ using System.Diagnostics; #endif -#pragma warning disable CS8073 - namespace Kook.Net.Queue; internal class RequestQueue : IDisposable, IAsyncDisposable diff --git a/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs b/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs index b2a9e59f..69be4fa2 100644 --- a/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs +++ b/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs @@ -124,12 +124,7 @@ public async Task SendAsync(RestRequest request) responseBase?.Code, responseBase?.Message, responseBase?.Data is not null - ? - [ - new("root", - [new(((int)responseBase.Code).ToString(), responseBase.Message)] - ) - ] + ? [new KookJsonError("root", [new KookError(((int)responseBase.Code).ToString(), responseBase.Message)])] : null ); } @@ -150,12 +145,7 @@ public async Task SendAsync(RestRequest request) responseBase.Code, responseBase.Message, responseBase.Data is not null - ? - [ - new KookJsonError("root", - [new KookError(((int)responseBase.Code).ToString(), responseBase.Message)] - ) - ] + ? [new KookJsonError("root", [new KookError(((int)responseBase.Code).ToString(), responseBase.Message)])] : null ); } diff --git a/src/Kook.Net.Rest/Net/RateLimitInfo.cs b/src/Kook.Net.Rest/Net/RateLimitInfo.cs index b1c8a05f..572c32bc 100644 --- a/src/Kook.Net.Rest/Net/RateLimitInfo.cs +++ b/src/Kook.Net.Rest/Net/RateLimitInfo.cs @@ -3,7 +3,7 @@ namespace Kook.Net; /// -/// Represents a REST-Based ratelimit info. +/// 表示一个基于 REST 的速率限制信息。 /// public struct RateLimitInfo : IRateLimitInfo { diff --git a/src/Kook.Net.WebSocket/Audio/AudioClient.cs b/src/Kook.Net.WebSocket/Audio/AudioClient.cs index 5efa4c8d..8f6f5d52 100644 --- a/src/Kook.Net.WebSocket/Audio/AudioClient.cs +++ b/src/Kook.Net.WebSocket/Audio/AudioClient.cs @@ -6,6 +6,9 @@ namespace Kook.Audio; +/// +/// 表示一个音频客户端。 +/// internal partial class AudioClient : IAudioClient { private const int ConnectionTimeoutMs = 30000; // 30 seconds @@ -49,7 +52,9 @@ internal partial class AudioClient : IAudioClient internal bool IsFinished { get; private set; } public ConnectionState ConnectionState => Connection.State; - /// Creates a new REST/WebSocket kook client. + /// + /// 初始化一个 类的新实例。 + /// internal AudioClient(SocketVoiceChannel voiceChannel, int clientId, string? password) { Channel = voiceChannel; diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs index 4f5a5868..19bb1a34 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs @@ -1,7 +1,7 @@ namespace Kook.Audio; /// -/// Represents the application type for Opus encoding. +/// 表示 Opus 编码的应用程序类型。 /// internal enum OpusApplication { @@ -9,11 +9,9 @@ internal enum OpusApplication /// OPUS_APPLICATION_VOIP /// /// - /// OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice signals. - /// It enhances the input signal by high-pass filtering and emphasizing formants and harmonics. - /// Optionally it includes in-band forward error correction to protect against packet loss. - /// Use this mode for typical VoIP applications. Because of the enhancement, - /// even at high bitrates the output may sound different from the input. + /// OPUS_APPLICATION_VOIP 在给定比特率下针对语音信号提供最佳质量。 + /// 它通过高通滤波、强调共振峰和谐波来增强输入信号,可以包括带内前向纠错以防止丢包。 + /// 在典型的 VoIP 应用中应使用此模式。由于增强效果,即使在高比特率下,输出的声音也可能与输入不同。 /// Voice = 2048, @@ -21,9 +19,8 @@ internal enum OpusApplication /// OPUS_APPLICATION_AUDIO /// /// - /// OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most non-voice signals like music. - /// Use this mode for music and mixed (music/voice) content, broadcast, and applications - /// requiring less than 15 ms of coding delay. + /// OPUS_APPLICATION_AUDIO 在给定比特率下针对大多数非语音信号(如音乐)提供最佳质量。 + /// 适用于音乐、混合(音乐/语音)内容、广播以及需要少于 15 毫秒编码延迟的应用程序。 /// MusicOrMixed = 2049, @@ -31,8 +28,7 @@ internal enum OpusApplication /// OPUS_APPLICATION_RESTRICTED_LOWDELAY /// /// - /// OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that disables - /// the speech-optimized mode in exchange for slightly reduced delay. + /// OPUS_APPLICATION_RESTRICTED_LOWDELAY 为低延迟模式,禁用了针对语音优化的模式,来换取稍微减少的延迟。 /// LowLatency = 2051 } diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs index 5fdba5a1..43ee60bc 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs @@ -1,44 +1,44 @@ namespace Kook.Audio; /// -/// Represents a generic Opus converter. +/// 表示一个通用的 Opus 转换器。 /// internal abstract class OpusConverter : IDisposable { protected IntPtr _ptr; /// - /// Gets the sampling rate of the audio, typically 48000. + /// 获取音频的采样率,通常为 48000。 /// public const int SamplingRate = 48000; /// - /// Gets the number of channels of the audio, typically 2. + /// 获取音频的通道数,通常为 2。 /// public const int Channels = 2; /// - /// Gets the milliseconds per frame, typically 40. + /// 获取每帧的毫秒数,通常为 40。 /// public const int FrameMillis = 40; /// - /// Gets the sample size, in bytes, of the audio, typically 4. + /// 获取音频的样本大小,单位为字节,通常为 4。 /// public const int SampleBytes = sizeof(short) * Channels; /// - /// Gets the number of samples per channel per frame, typically 1920. + /// 获取每帧每个通道的样本数,通常为 1920。 /// public const int FrameSamplesPerChannel = SamplingRate / 1000 * FrameMillis; /// - /// Gets the number of samples per frame, typically 3840. + /// 获取每帧的样本数,通常为 3840。 /// public const int FrameSamples = FrameSamplesPerChannel * Channels; /// - /// Gets the number of bytes per frame, typically 7680. + /// 获取每帧的字节数,通常为 7680。 /// public const int FrameBytes = FrameSamplesPerChannel * SampleBytes; diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs index 2fda6300..1be778c8 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs @@ -1,10 +1,10 @@ namespace Kook.Audio; /// -/// Represents the Opus control codes. +/// 表示 Opus 控制码。 /// /// -/// See https://github.com/gcp/opus/blob/master/include/opus_defines.h +/// 参见 https://github.com/gcp/opus/blob/master/include/opus_defines.h /// internal enum OpusCtl { @@ -12,7 +12,7 @@ internal enum OpusCtl /// OPUS_SET_BITRATE /// /// - /// Configures the bitrate in the encoder. + /// 配置编码器中的比特率。 /// SetBitrate = 4002, @@ -20,7 +20,7 @@ internal enum OpusCtl /// OPUS_SET_BANDWIDTH_REQUEST /// /// - /// Configures the maximum bandwidth in the encoder. + /// 配置编码器中的最大带宽。 /// SetBandwidth = 4008, @@ -28,7 +28,7 @@ internal enum OpusCtl /// OPUS_SET_PACKET_LOSS_PERC_REQUEST /// /// - /// Configures the expected packet loss percentage in the encoder. + /// 配置编码器中预期的丢包百分比。 /// SetPacketLossPercent = 4014, @@ -36,7 +36,7 @@ internal enum OpusCtl /// OPUS_SET_SIGNAL_REQUEST /// /// - /// Configures the type of signal being encoded. + /// 配置正在编码的信号类型。 /// SetSignal = 4024 } diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs index 2d997060..df78983a 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs @@ -1,7 +1,7 @@ namespace Kook.Audio; /// -/// Represents the Opus error codes. +/// 表示 Opus 错误代码。 /// internal enum OpusError { @@ -9,7 +9,7 @@ internal enum OpusError /// OPUS_OK /// /// - /// No error. + /// 没有错误。 /// OK = 0, @@ -17,7 +17,7 @@ internal enum OpusError /// OPUS_BAD_ARG /// /// - /// One or more invalid/out of range arguments. + /// 一个或多个参数无效/超出范围。 /// BadArg = -1, @@ -25,7 +25,7 @@ internal enum OpusError /// OPUS_BUFFER_TOO_SMALL /// /// - /// Not enough bytes allocated in the buffer. + /// 缓冲区中分配的字节不足。 /// BufferTooSmall = -2, @@ -33,7 +33,7 @@ internal enum OpusError /// OPUS_INTERNAL_ERROR /// /// - /// An internal error was detected. + /// 检测到内部错误。 /// InternalError = -3, @@ -41,7 +41,7 @@ internal enum OpusError /// OPUS_INVALID_PACKET /// /// - /// The compressed data passed is corrupted. + /// 传递的压缩数据已损坏。 /// InvalidPacket = -4, @@ -49,7 +49,7 @@ internal enum OpusError /// OPUS_UNIMPLEMENTED /// /// - /// Invalid/unsupported request number. + /// 请求号无效/不支持。 /// Unimplemented = -5, @@ -57,7 +57,7 @@ internal enum OpusError /// OPUS_INVALID_STATE /// /// - /// An encoder or decoder structure is invalid or already freed. + /// 编码器或解码器结构无效或已释放。 /// InvalidState = -6, @@ -65,7 +65,7 @@ internal enum OpusError /// OPUS_ALLOC_FAIL /// /// - /// Memory allocation has failed. + /// 内存分配失败。 /// AllocFail = -7 } diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs index 17223d52..891e9b5a 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs @@ -1,7 +1,7 @@ namespace Kook.Audio; /// -/// Represents the signal type for Opus. +/// 表示 Opus 信号类型。 /// internal enum OpusSignal { @@ -9,7 +9,7 @@ internal enum OpusSignal /// OPUS_SIGNAL_AUTO /// /// - /// Signal type is automatically detected. + /// 自动检测信号类型。 /// Auto = -1000, @@ -17,7 +17,7 @@ internal enum OpusSignal /// OPUS_SIGNAL_VOICE /// /// - /// Signal being encoded is voice. + /// 被编码的信号是语音。 /// Voice = 3001, @@ -25,7 +25,7 @@ internal enum OpusSignal /// OPUS_SIGNAL_MUSIC /// /// - /// Signal being encoded is music. + /// 被编码的信号是音乐。 /// - Music = 3002, + Music = 3002 } diff --git a/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs index 277743e4..e0f326b4 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs @@ -3,7 +3,9 @@ namespace Kook.Audio.Streams; -/// Wraps another stream with a timed buffer. +/// +/// 表示一个定时缓冲的音频写入流,用于将定时缓冲的音频数据写入到下一个音频流中。 +/// public class BufferedWriteStream : AudioOutStream { private const int MaxSilenceFrames = 10; diff --git a/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs index 2d554006..ea4386ff 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs @@ -2,7 +2,9 @@ namespace Kook.Audio.Streams; -/// Reads the payload from an RTP frame +/// +/// 表示输入音频流,用于在 实例中,从语音服务器接收语音数据。 +/// public class InputStream : AudioInStream { private const int MaxFrames = 100; //1-2 Seconds diff --git a/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs index 461435b0..d1097a22 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs @@ -1,11 +1,11 @@ namespace Kook.Audio.Streams; -/// Converts Opus to PCM +/// +/// 表示一个 Opus 解码音频流。 +/// public class OpusDecodeStream : AudioOutStream { - /// - /// Gets the sample rate. - /// + /// public const int SampleRate = OpusEncodeStream.SampleRate; private readonly AudioStream _next; @@ -14,7 +14,9 @@ public class OpusDecodeStream : AudioOutStream private bool _nextMissed; private bool _hasHeader; - /// + /// + /// 初始化一个 类的新实例。 + /// public OpusDecodeStream(AudioStream next) { _next = next; @@ -22,7 +24,8 @@ public OpusDecodeStream(AudioStream next) _decoder = new OpusDecoder(); } - /// Header received with no payload. + /// + /// 该流接收到没有有效负载的 RTP 头部。 public override void WriteHeader(ushort seq, uint timestamp, bool missed) { if (_hasHeader) @@ -33,7 +36,8 @@ public override void WriteHeader(ushort seq, uint timestamp, bool missed) _next.WriteHeader(seq, timestamp, missed); } - /// Received payload without an RTP header. + /// + /// 该流接收到没有 RTP 头部的有效负载。 public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!_hasHeader) diff --git a/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs index 9f9cb586..2d325843 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs @@ -1,10 +1,12 @@ namespace Kook.Audio.Streams; -/// Converts PCM to Opus +/// +/// 表示一个 Opus 编码音频流。 +/// public class OpusEncodeStream : AudioOutStream { /// - /// Gets the sample rate of the audio stream. + /// 获取音频流的采样率。 /// public const int SampleRate = 48000; @@ -16,12 +18,12 @@ public class OpusEncodeStream : AudioOutStream private uint _timestamp; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The next audio stream to write to. - /// The bitrate of the audio stream. - /// The audio application to use. - /// The packet loss percentage of the audio stream. + /// 要写入编码数据的音频流,是音频流写入链中的下一个音频流对象。 + /// 音频流的比特率。 + /// 音频应用程序的应用场景。 + /// 音频流的丢包率。 public OpusEncodeStream(AudioStream next, int bitrate, AudioApplication application, int packetLoss) { _next = next; @@ -30,13 +32,11 @@ public OpusEncodeStream(AudioStream next, int bitrate, AudioApplication applicat } /// - /// Sends silent frames to avoid interpolation errors after breaks in data transmission. + /// 发送静默帧以避免数据传输中断后的插值错误。 /// - /// A task representing the asynchronous operation of sending a silent frame. + /// 一个表示写入静默帧操作的异步任务。 public async Task WriteSilentFramesAsync() { - // https://kook.com/developers/docs/topics/voice-connections#voice-data-interpolation - byte[] frameBytes = new byte[OpusConverter.FrameBytes]; // Magic silence numbers. diff --git a/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs index ba15ffef..c944d6da 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs @@ -1,6 +1,8 @@ namespace Kook.Audio.Streams; -/// Wraps an IAudioClient, sending voice data on write. +/// +/// 表示输出音频流,用于包装一个 ,在写入时向语音服务器发送语音数据。 +/// public class OutputStream : AudioOutStream { private readonly KookVoiceAPIClient _client; diff --git a/src/Kook.Net.WebSocket/Audio/Streams/RtpReadStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/RtpReadStream.cs index 4c106a62..d0a1c37f 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/RtpReadStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/RtpReadStream.cs @@ -1,6 +1,8 @@ namespace Kook.Audio.Streams; -/// Reads the payload from an RTP frame +/// +/// 表示一个 RTP 帧读取流。 +/// public class RtpReadStream : AudioOutStream { private readonly AudioStream _next; @@ -24,8 +26,7 @@ public RtpReadStream(AudioStream next, int bufferSize = 4000) _nonce = new byte[24]; } - /// The token has had cancellation requested. - /// The associated has been disposed. + /// public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -45,8 +46,12 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati } /// - /// Tries to read SSRC from UDP packet. + /// 尝试从 RTP 数据报中读取 SSRC。 /// + /// 要从中读取 SSRC 的数据报。 + /// 数据报的偏移量。 + /// 如果读取成功,则为 SSRC 值;否则为 0。 + /// 读取是否成功。 public static bool TryReadSsrc(byte[] buffer, int offset, out uint ssrc) { ssrc = 0; @@ -68,8 +73,11 @@ public static bool TryReadSsrc(byte[] buffer, int offset, out uint ssrc) } /// - /// Gets the header size. + /// 获取 RTP 数据报的头部大小。 /// + /// 要获取头部大小的数据报。 + /// 数据报的偏移量。 + /// 数据报的头部大小。 public static int GetHeaderSize(byte[] buffer, int offset) { byte headerByte = buffer[offset]; diff --git a/src/Kook.Net.WebSocket/Audio/Streams/RtpWriteStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/RtpWriteStream.cs index c86fd179..03ff19a0 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/RtpWriteStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/RtpWriteStream.cs @@ -1,6 +1,8 @@ namespace Kook.Audio.Streams; -/// Wraps data in a RTP frame +/// +/// 表示一个 RTP 帧写入流。 +/// public class RtpWriteStream : AudioOutStream { private readonly AudioStream _next; @@ -11,12 +13,12 @@ public class RtpWriteStream : AudioOutStream private bool _hasHeader; /// - /// Creates a new instance of . + /// 初始化一个 类的新实例。 /// - /// The next stream in the chain. - /// The SSRC of the RTP connection. - /// The payload type to use. - /// The buffer size to use. + /// 要写入 RTP 帧数据的音频流,是音频流写入链中的下一个音频流对象。 + /// RTP 连接的同步源标识符。 + /// RTP 连接的负载类型。 + /// RTP 帧缓冲区的大小,默认为 4000 字节。 public RtpWriteStream(AudioStream next, uint ssrc, byte payloadType, int bufferSize = 4000) { if ((payloadType & 0x80) != 0) diff --git a/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs b/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs index e287b7cd..ae259f58 100644 --- a/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs +++ b/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs @@ -4,17 +4,14 @@ public abstract partial class BaseSocketClient { #region Channels - /// Fired when a channel is created. + /// + /// 当服务器频道被创建时引发。 + /// /// - /// - /// This event is fired when a generic channel has been created. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The newly created channel is passed into the event handler parameter. The given channel type may - /// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); - /// see the derived classes of for more details. - /// + /// 事件参数: + /// + /// 参数是新创建的服务器频道。 + /// /// public event Func ChannelCreated { @@ -24,17 +21,14 @@ public event Func ChannelCreated internal readonly AsyncEvent> _channelCreatedEvent = new(); - /// Fired when a channel is destroyed. + /// + /// 当服务器频道被删除时引发。 + /// /// - /// - /// This event is fired when a generic channel has been destroyed. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The destroyed channel is passed into the event handler parameter. The given channel type may - /// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); - /// see the derived classes of for more details. - /// + /// 事件参数: + /// + /// 参数是被删除的服务器频道。 + /// /// public event Func ChannelDestroyed { @@ -44,18 +38,15 @@ public event Func ChannelDestroyed internal readonly AsyncEvent> _channelDestroyedEvent = new(); - /// Fired when a channel is updated. + /// + /// 当服务器频道信息被更新时引发。 + /// /// - /// - /// This event is fired when a generic channel has been updated. The event handler must return a - /// and accept 2 as its parameters. - /// - /// - /// The original (prior to update) channel is passed into the first , while - /// the updated channel is passed into the second. The given channel type may include, but not limited - /// to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); see the derived classes of - /// for more details. - /// + /// 事件参数: + /// + /// 参数是更新前的服务器频道。 + /// 参数是更新后的服务器频道。 + /// /// public event Func ChannelUpdated { @@ -65,34 +56,23 @@ public event Func ChannelUpdated internal readonly AsyncEvent> _channelUpdatedEvent = new(); - /// Fired when a reaction is added to a channel message. + /// + /// 当服务器内的消息上被添加了新的回应时引发。 + /// /// - /// - /// This event is fired when a reaction is added to a message in a channel. The event handler must return a - /// and accept a , an - /// , a , and a - /// as its parameter. - /// - /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// - /// - /// The source channel of the reaction addition will be passed into the - /// parameter. - /// - /// - /// The user who added the reaction will be passed into the . - /// - /// - /// The reaction that was added will be passed into the parameter. - /// - /// - /// When fetching the reaction from this event, a user may not be provided under - /// . Please see the documentation of the property for more - /// information. - /// + /// 事件参数: + /// + /// + /// 参数是被添加了回应的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是消息所在的频道。 + /// + /// 参数是添加了此回应的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是被添加的回应。 + /// /// public event Func, SocketTextChannel, Cacheable, SocketReaction, Task> ReactionAdded { @@ -102,34 +82,23 @@ public event Func, SocketTextChannel, Cacheable, SocketTextChannel, Cacheable, SocketReaction, Task>> _reactionAddedEvent = new(); - /// Fired when a reaction is removed from a message. + /// + /// 当服务器内的消息上存在的回应被用户移除时引发。 + /// /// - /// - /// This event is fired when a reaction is removed from a message in a channel. The event handler must return a - /// and accept a , an - /// , a , and a - /// as its parameter. - /// - /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// - /// - /// The source channel of the reaction addition will be passed into the - /// parameter. - /// - /// - /// The user who removed the reaction will be passed into the . - /// - /// - /// The reaction that was removed will be passed into the parameter. - /// - /// - /// When fetching the reaction from this event, a user may not be provided under - /// . Please see the documentation of the property for more - /// information. - /// + /// 事件参数: + /// + /// + /// 参数是被移除了回应的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是消息所在的频道。 + /// + /// 参数是移除了此回应的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是被移除的回应。 + /// /// public event Func, SocketTextChannel, Cacheable, SocketReaction, Task> ReactionRemoved { @@ -139,36 +108,26 @@ public event Func, SocketTextChannel, Cacheable, SocketTextChannel, Cacheable, SocketReaction, Task>> _reactionRemovedEvent = new(); - /// Fired when a reaction is added to a direct message. + /// + /// 当私聊频道内的消息上被添加了新的回应时引发。 + /// /// - /// - /// This event is fired when a reaction is added to a user message in a private channel. The event handler must return a - /// and accept a , a - /// , a , and a - /// as its parameter. - /// - /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - /// - /// - /// If a direct message was sent by the current user to this user, or the recipient had sent a message before - /// in current session, the entity will contains the direct message channel; - /// otherwise, the direct message channel has not been created yet, and the as chat code will be preserved. - /// - /// - /// The user who removed the reaction will be passed into the . - /// - /// - /// The reaction that was added will be passed into the parameter. - /// - /// - /// When fetching the reaction from this event, a user may not be provided under - /// . Please see the documentation of the property for more - /// information. - /// + /// 事件参数: + /// + /// + /// 参数是被添加了回应的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息;否则,包含 消息 ID,以供按需下载实体。 + /// + /// + /// 参数是消息所在的可缓存私聊频道。如果缓存中存在此私聊频道实体,那么该结构内包含该 + /// 私聊频道;否则,包含 私聊频道聊天代码,以供按需下载实体。 + /// + /// + /// 参数是添加了此回应的可缓存用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是被添加的回应。 + /// /// public event Func, Cacheable, Cacheable, SocketReaction, Task> DirectReactionAdded { @@ -178,36 +137,26 @@ public event Func, Cacheable, C internal readonly AsyncEvent, Cacheable, Cacheable, SocketReaction, Task>> _directReactionAddedEvent = new(); - /// Fired when a reaction is removed from a message. + /// + /// 当私聊频道内的消息上存在的回应被用户移除时引发。 + /// /// - /// - /// This event is fired when a reaction is removed from a user message in a private channel. The event handler must return a - /// and accept a , a - /// , a , and a - /// as its parameter. - /// - /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - /// - /// - /// If a direct message was sent by the current user to this user, or the recipient had sent a message before - /// in current session, the entity will contains the direct message channel; - /// otherwise, the direct message channel has not been created yet, and the as chat code will be preserved. - /// - /// - /// The user who added the reaction will be passed into the . - /// - /// - /// The reaction that was added will be passed into the parameter. - /// - /// - /// When fetching the reaction from this event, a user may not be provided under - /// . Please see the documentation of the property for more - /// information. - /// + /// 事件参数: + /// + /// + /// 参数是被移除了回应的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息;否则,包含 消息 ID,以供按需下载实体。 + /// + /// + /// 参数是消息所在的可缓存私聊频道。如果缓存中存在此私聊频道实体,那么该结构内包含该 + /// 私聊频道;否则,包含 私聊频道聊天代码,以供按需下载实体。 + /// + /// + /// 参数是移除了此回应的可缓存用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是被移除的回应。 + /// /// public event Func, Cacheable, Cacheable, SocketReaction, Task> DirectReactionRemoved { @@ -221,27 +170,16 @@ public event Func, Cacheable, C #region Messages - /// Fired when a message is received. + /// + /// 当接收到新的服务器消息时引发。 + /// /// - /// - /// This event is fired when a message is received. The event handler must return a - /// and accept a , a - /// , and a as its parameter. - /// - /// - /// The message that is sent to the client is passed into the event handler parameter as - /// . This message may be a system message (i.e. - /// ) or a user message (i.e. . See the - /// derived classes of for more details. - /// - /// - /// The guild member that sent this message is passed into the event handler parameter as - /// . - /// - /// - /// The source channel of the removed message will be passed into the - /// parameter. - /// + /// 事件参数: + /// + /// 参数是新接收到的服务器消息。 + /// 参数是发送消息的服务器用户。 + /// 参数是消息所在的服务器频道。 + /// /// public event Func MessageReceived { @@ -251,28 +189,22 @@ public event Func Messa internal readonly AsyncEvent> _messageReceivedEvent = new(); - /// Fired when a message is deleted. + /// + /// 当服务器内的消息被删除时引发。 + /// /// - /// - /// This event is fired when a message is deleted. The event handler must return a - /// and accept a , and a - /// as its parameter. - /// - /// + /// 事件参数: + /// + /// + /// 参数是被删除的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 被删除的消息;否则,包含 消息 ID。 + ///
/// - /// It is not possible to retrieve the message via - /// ; the message cannot be retrieved by Kook - /// after the message has been deleted. + /// 消息被删除后无法通过 方法下载。 /// - /// If caching is enabled via , the - /// entity will contain the deleted message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - ///
- /// - /// The source channel of the removed message will be passed into the - /// parameter. - /// + /// + /// 参数是消息被删除前所在的服务器频道。 + /// ///
public event Func, SocketTextChannel, Task> MessageDeleted { @@ -282,34 +214,26 @@ public event Func, SocketTextChannel, Task> MessageDel internal readonly AsyncEvent, SocketTextChannel, Task>> _messageDeletedEvent = new(); - /// Fired when a message is updated. + /// + /// 当服务器内的消息被更新时引发。 + /// /// - /// - /// This event is fired when a message is updated. The event handler must return a - /// and accept a , - /// a , and as its parameters. - /// - /// + /// 事件参数: + /// + /// + /// 参数是可缓存消息被更新前的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被更新前的状态;否则,包含 消息 ID。 + ///
/// - /// It is not possible to retrieve the message via - /// ; the original message cannot be retrieved by - /// Kook after the message has been updated. + /// 消息被更新前的状态无法通过 方法下载。 /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - ///
- /// - /// If caching is enabled via , the - /// entity will contain the updated message; otherwise, in event - /// that the entire message entity cannot be retrieved, the ID of the message is preserved in the - /// . - /// - /// - /// The source channel of the updated message will be passed into the - /// parameter. - /// + /// + /// + /// 参数是可缓存消息被更新后的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被更新后的状态;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是消息所在的服务器频道。 + /// ///
public event Func, Cacheable, SocketTextChannel, Task> MessageUpdated { @@ -319,40 +243,30 @@ public event Func, Cacheable, SocketTe internal readonly AsyncEvent, Cacheable, SocketTextChannel, Task>> _messageUpdatedEvent = new(); - /// Fired when a message is pinned. + /// + /// 当服务器内的消息被置顶时引发。 + /// /// - /// - /// This event is fired when a message is pinned. The event handler must return a - /// and accept a , , - /// and as its parameters. - /// - /// + /// 事件参数: + /// + /// + /// 参数是可缓存消息被置顶前的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被置顶前的状态;否则,包含 消息 ID。 + ///
/// - /// It is not possible to retrieve the message via - /// ; the original message cannot be retrieved by - /// Kook after the message has been updated. + /// 消息被置顶前的状态无法通过 方法下载。 /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - ///
- /// - /// If caching is enabled via , the - /// entity will contain the pinned message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - /// - /// - /// The source channel of the updated message will be passed into the - /// parameter. - /// - /// - /// The guild member that pinned this message is passed into the event handler parameter as - /// , which contains a when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// + /// + /// + /// 参数是可缓存消息被置顶后的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被置顶后的状态;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是消息所在的服务器频道。 + /// + /// 参数是置顶了该消息的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// ///
public event Func, Cacheable, SocketTextChannel, Cacheable, Task> MessagePinned { @@ -362,40 +276,30 @@ public event Func, Cacheable, SocketTe internal readonly AsyncEvent, Cacheable, SocketTextChannel, Cacheable, Task>> _messagePinnedEvent = new(); - /// Fired when a message is unpinned. + /// + /// 当服务器内的消息被取消置顶时引发。 + /// /// - /// - /// This event is fired when a message is unpinned. The event handler must return a - /// and accept a , , - /// and as its parameters. - /// - /// + /// 事件参数: + /// + /// + /// 参数是可缓存消息被取消置顶前的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被取消置顶前的状态;否则,包含 消息 ID。 + ///
/// - /// It is not possible to retrieve the message via - /// ; the original message cannot be retrieved by - /// Kook after the message has been updated. + /// 消息被取消置顶前的状态无法通过 方法下载。 /// - /// If caching is enabled via , the - /// entity will contain the original message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - ///
- /// - /// If caching is enabled via , the - /// entity will contain the unpinned message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// . - /// - /// - /// The source channel of the updated message will be passed into the - /// parameter. - /// - /// - /// The guild member that unpinned this message is passed into the event handler parameter as - /// , which contains a when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// + /// + /// + /// 参数是可缓存消息被取消置顶后的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被取消置顶后的状态;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是消息所在的服务器频道。 + /// + /// 参数是取消置顶了该消息的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// ///
public event Func, Cacheable, SocketTextChannel, Cacheable, Task> MessageUnpinned { @@ -409,28 +313,16 @@ public event Func, Cacheable, SocketTe #region Direct Messages - /// Fired when a direct message is received. + /// + /// 当接收到新的私聊消息时引发。 + /// /// - /// - /// This event is fired when a direct message is received. The event handler must return a - /// and accept a , a - /// , and a - /// as its parameters. - /// - /// - /// The message that is sent to the client is passed into the event handler parameter as - /// . This message may be a system message (i.e. - /// ) or a user message (i.e. . See the - /// derived classes of for more details. - /// - /// - /// The user that sent this direct message is passed into the event handler parameter as - /// . - /// - /// - /// The source direct channel of the removed message will be passed into the - /// parameter. - /// + /// 事件参数: + /// + /// 参数是新接收到的私聊消息。 + /// 参数是发送消息的用户。 + /// 参数是消息所在的私聊频道。 + /// /// public event Func DirectMessageReceived { @@ -440,36 +332,26 @@ public event Func DirectMessag internal readonly AsyncEvent> _directMessageReceivedEvent = new(); - /// Fired when a direct message is deleted. + /// + /// 当私聊频道内的消息被删除时引发。 + /// /// - /// - /// This event is fired when a direct message is deleted. The event handler must return a - /// and accept a , - /// a , and a - /// as its parameters. - /// - /// + /// 事件参数: + /// + /// + /// 参数是被删除的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 被删除的消息;否则,包含 消息 ID。 + ///
/// - /// It is not possible to retrieve the direct message via - /// ; the original direct message cannot be retrieved by Kook - /// after the message has been deleted. + /// 消息被删除后无法通过 方法下载。 /// - /// If caching is enabled via , the - /// entity will contain the deleted direct message; otherwise, in event - /// that the message cannot be retrieved, the ID of the direct message is preserved in the - /// . - ///
- /// - /// The user that originally sent this direct message is passed into the event handler parameter as - /// , which contains a when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// - /// - /// If a direct message was sent by the current user to this user, or the recipient had sent a message before - /// in current session, the entity will contains the direct message channel; - /// otherwise, the direct message channel has not been created yet, and the as chat code will be preserved. - /// + /// + /// + /// 参数是该消息的作者的可缓存用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是消息被删除前所在的服务器频道。 + /// ///
public event Func, Cacheable, Cacheable, Task> DirectMessageDeleted { @@ -479,36 +361,30 @@ public event Func, Cacheable, Cache internal readonly AsyncEvent, Cacheable, Cacheable, Task>> _directMessageDeletedEvent = new(); - /// Fired when a message is updated. + /// + /// 当私聊频道内的消息被更新时引发。 + /// /// - /// - /// This event is fired when a direct message is updated. The event handler must return a - /// and accept a , - /// a , a , - /// and a as its parameters. - /// - /// + /// 事件参数: + /// + /// + /// 参数是可缓存消息被更新前的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被更新前的状态;否则,包含 消息 ID。 + ///
/// - /// It is not possible to retrieve the direct message via - /// ; the original direct message cannot be retrieved by Kook - /// after the message has been updated. + /// 消息被更新前的状态无法通过 方法下载。 /// - /// If caching is enabled via , the - /// entity will contain the updated direct message; otherwise, in event - /// that the message cannot be retrieved, the ID of the direct message is preserved in the - /// . - ///
- /// - /// The user that originally sent this direct message is passed into the event handler parameter as - /// , which contains a when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// - /// - /// If a direct message was sent by the current user to this user, or the recipient had sent a message before - /// in current session, the entity will contains the direct message channel; - /// otherwise, the direct message channel has not been created yet, and the as chat code will be preserved. - /// + /// + /// + /// 参数是可缓存消息被更新后的状态。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被更新后的状态;否则,包含 消息 ID,以供按需下载实体。 + /// + /// + /// 参数是该消息的作者的可缓存用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是消息所在的私聊频道。 + /// ///
public event Func, Cacheable, Cacheable, Cacheable, Task> DirectMessageUpdated { @@ -522,22 +398,22 @@ public event Func, Cacheable, Cacheabl #region Users - /// Fired when a user joins a guild. + /// + /// 当用户加入服务器时引发。 + /// /// /// - /// It is reported that this event will not be fired if a guild contains more than 2000 members. + /// 有消息称,那么此事件不会在其成员数量超过 2000 人的服务器内被触发。 /// - /// - /// This event is fired when a user joins a guild. The event handler must return a - /// and accept a and a - /// as its parameters. - /// - /// - /// The joined user will be passed into the parameter. - /// - /// - /// The time at which the user joined the guild will be passed into the parameter. - /// + ///
+ /// 事件参数: + /// + /// + /// 参数是加入服务器的可缓存服务器用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是用户加入服务器的时间。 + /// ///
public event Func, DateTimeOffset, Task> UserJoined { @@ -547,24 +423,23 @@ public event Func, DateTimeOffset, Task> UserJ internal readonly AsyncEvent, DateTimeOffset, Task>> _userJoinedEvent = new(); - /// Fired when a user leaves a guild. + /// + /// 当用户离开服务器时引发。 + /// /// /// - /// It is reported that this event will not be fired if a guild contains more than 2000 members. + /// 有消息称,那么此事件不会在其成员数量超过 2000 人的服务器内被触发。 /// - /// - /// This event is fired when a user leaves a guild. The event handler must return a - /// and accept a and a - /// as its parameters. - /// - /// - /// If the left user presents in the cache, the entity - /// will contain the left user; otherwise, in event that the user cannot be retrieved, - /// the ID of the left user is preserved in the . - /// - /// - /// The time at which the user left the guild will be passed into the parameter. - /// + ///
+ /// 事件参数: + /// + /// 参数是用户离开的服务器。 + /// + /// 参数是离开服务器的可缓存用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是用户加入服务器的时间。 + /// ///
public event Func, DateTimeOffset, Task> UserLeft { @@ -574,37 +449,24 @@ public event Func, DateTimeOffset, Tas internal readonly AsyncEvent, DateTimeOffset, Task>> _userLeftEvent = new(); - /// Fired when a user is banned from a guild. + /// + /// 当用户被服务器封禁时引发。 + /// /// - /// - /// This event is fired when a user is banned. The event handler must return a - /// and accept an , a , - /// a string and a as its parameter. - /// - /// - /// - /// It is not possible to retrieve the user via - /// ; the original user cannot be retrieved by - /// Kook after the user has been banned. - /// - /// The users that are banned are passed into the event handler parameter as - /// , where T is , - /// each of which contains a when the user presents in the cache; otherwise, - /// in event that the user cannot be retrieved, the ID of the user is preserved in the . - /// - /// - /// The users who operated the bans is passed into the event handler parameter as - /// , which contains a when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// - /// - /// The guild where the banning action takes place is passed in the event handler parameter as - /// . - /// - /// - /// The reason of the ban is passed into the event handler parameter as string. - /// + /// 事件参数: + /// + /// + /// 参数是所有此批次被封禁的用户。每个用户都由一个 + /// 表示。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// + /// 参数是操作此批次封禁的可缓存服务器用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是封禁操作所在的服务器。 + /// 参数是封禁的原因。 + /// /// public event Func>, Cacheable, SocketGuild, string?, Task> UserBanned { @@ -614,34 +476,23 @@ public event Func, DateTimeOffset, Tas internal readonly AsyncEvent>, Cacheable, SocketGuild, string?, Task>> _userBannedEvent = new(); - /// Fired when a user is unbanned from a guild. + /// + /// 当用户在服务器内的封禁被解除时引发。 + /// /// - /// - /// This event is fired when a user is unbanned. The event handler must return a - /// and accept an , a - /// and a as its parameter. - /// - /// - /// - /// It is not possible to retrieve the user via - /// ; the original user cannot be retrieved by - /// Kook after the user has been unbanned. - /// - /// The users that are unbanned are passed into the event handler parameter as - /// , where T is , - /// each of which contains a when the user presents in the cache; otherwise, - /// in event that the user cannot be retrieved, the ID of the user is preserved in the . - /// - /// - /// The users who operated the unbans is passed into the event handler parameter as - /// , which contains a when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// - /// - /// The guild where the unbanning action takes place is passed in the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// + /// 参数是所有此批次被解除封禁的用户。每个用户都由一个 + /// 表示。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// + /// 参数是操作此批次解除封禁的可缓存服务器用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是解除封禁操作所在的服务器。 + /// /// public event Func>, Cacheable, SocketGuild, Task> UserUnbanned { @@ -651,30 +502,27 @@ public event Func>, Cacheable>, Cacheable, SocketGuild, Task>> _userUnbannedEvent = new(); - /// Fired when a user is updated. + /// + /// 当用户信息被更新时引发。 + /// /// - /// - /// This event is fired when a user is updated. The event handler must return a - /// and accept a , - /// and a as its parameter. - /// - /// + /// 当用户的用户名或头像变更,且该用户与当前用户存在聊天会话或互为好友时,此事件会被引发。 + ///
+ /// 事件参数: + /// + /// + /// 参数是可缓存用户被更新前的状态。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户被更新前的状态;否则,包含 用户 ID。 + ///
/// - /// It is not possible to retrieve the user via - /// ; the original user cannot be retrieved by - /// Kook after the user has been updated. + /// 用户被更新前的状态无法通过 方法下载。 /// - /// The user that is updated is passed into the event handler parameter as - /// , which contains the original when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - ///
- /// - /// The user that is updated is passed into the event handler parameter as - /// , which contains a when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// + /// + /// + /// 参数是可缓存用户被更新后的状态。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户被更新后的状态;否则,包含 用户 ID,以供按需下载实体。 + /// + /// ///
public event Func, Cacheable, Task> UserUpdated { @@ -684,21 +532,15 @@ public event Func, Cacheable, Ta internal readonly AsyncEvent, Cacheable, Task>> _userUpdatedEvent = new(); - /// Fired when the connected account is updated. + /// + /// 当当前用户信息被更新时引发。 + /// /// - /// - /// This event is fired when the connected account is updated. The event handler must return a - /// and accept a , - /// and a as its parameter. - /// - /// - /// The current user before the update is passed into the event handler parameter as - /// . - /// - /// - /// The current user after the update is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是当前用户被更新前的状态。 + /// 参数是当前用户被更新后的状态。 + /// /// public event Func CurrentUserUpdated { @@ -708,30 +550,25 @@ public event Func CurrentUserUpdated internal readonly AsyncEvent> _currentUserUpdatedEvent = new(); - /// Fired when a guild member is updated. + /// + /// 当服务器用户信息被更新时引发。 + /// /// - /// - /// This event is fired when a guild member is updated. The event handler must return a - /// and accept a , - /// and a as its parameter. - /// - /// + /// 事件参数: + /// + /// + /// 参数是可缓存服务器用户被更新前的状态。如果缓存中存在此用户实体,那么该结构内包含该 + /// 服务器用户被更新前的状态;否则,包含 用户 ID。 + ///
/// - /// It is not possible to retrieve the guild member via - /// ; the original guild member cannot be retrieved by - /// Kook after the guild member has been updated. + /// 服务器用户被更新前的状态无法通过 方法下载。 /// - /// The guild member that is updated is passed into the event handler parameter as - /// , which contains the original when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - ///
- /// - /// The guild member that is updated is passed into the event handler parameter as - /// , which contains a when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// + /// + /// + /// 参数是可缓存服务器用户被更新后的状态。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户被更新后的状态;否则,包含 用户 ID,以供按需下载实体。 + /// + /// ///
public event Func, Cacheable, Task> GuildMemberUpdated { @@ -741,23 +578,19 @@ public event Func, Cacheable, Cacheable, Task>> _guildMemberUpdatedEvent = new(); - /// Fired when a guild member is online. + /// + /// 当服务器用户的在线状态变更为在线时引发。 + /// /// - /// - /// This event is fired when a guild member is online. The event handler must return a - /// and accept a , - /// and a as its parameter. - /// - /// - /// The guild member that is online is passed into the event handler parameter as - /// , which contains the original when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// - /// - /// The time when the guild member is online is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// + /// 参数是所有此批次在线状态变更为在线的服务器用户。每个服务器用户都由一个 + /// 表示。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是在线状态变更为在线的时间。 + /// /// public event Func>, DateTimeOffset, Task> GuildMemberOnline { @@ -767,23 +600,19 @@ public event Func>, DateTi internal readonly AsyncEvent>, DateTimeOffset, Task>> _guildMemberOnlineEvent = new(); - /// Fired when a guild member is offline. + /// + /// 当服务器用户的在线状态变更为离线时引发。 + /// /// - /// - /// This event is fired when a guild member is offline. The event handler must return a - /// and accept a , - /// and a as its parameter. - /// - /// - /// The guild member that is offline is passed into the event handler parameter as - /// , which contains the original when the guild member - /// presents in the cache; otherwise, in event that the guild member cannot be retrieved, the ID of the guild member - /// is preserved in the . - /// - /// - /// The time when the guild member is offline is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// + /// 参数是所有此批次在线状态变更为离线的服务器用户。每个服务器用户都由一个 + /// 表示。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是在线状态变更为离线的时间。 + /// /// public event Func>, DateTimeOffset, Task> GuildMemberOffline { @@ -794,13 +623,19 @@ public event Func>, DateTi internal readonly AsyncEvent>, DateTimeOffset, Task>> _guildMemberOfflineEvent = new(); /// - /// Fired when a user's voice state is updated. + /// 当服务器用户的语音状态发生变化时引发。 /// - /// - /// A representing the result of the asynchronous operation. - /// The task result contains the updated , the previous , - /// and the current . - /// + /// + /// 事件参数: + /// + /// + /// 参数是其语音状态发生变化的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是用户语音状态变更前的状态。 + /// 参数是用户语音状态变更后的状态。 + /// + /// public event Func, SocketVoiceState, SocketVoiceState, Task> UserVoiceStateUpdated { add => _userVoiceStateUpdatedEvent.Add(value); @@ -813,28 +648,19 @@ public event Func, SocketVoiceState, SocketVoi #region Voices - /// Fired when a user connected to a voice channel. + /// + /// 当服务器用户连接到语音频道时引发。 + /// /// - /// - /// This event is fired when a user connected to a voice channel. The event handler must return a - /// and accept a , - /// a , a , and a - /// as its parameter. - /// - /// - /// The user that connected to a voice channel is passed into the event handler parameter as - /// , which contains the original when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// - /// - /// The voice channel that the user connected to is passed into the event handler parameter as - /// . - /// - /// - /// The time when the user is offline is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// + /// 参数是连接到语音频道的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是用户连接到的语音频道。 + /// 参数是用户连接到语音频道的时间。 + /// /// public event Func, SocketVoiceChannel, DateTimeOffset, Task> UserConnected { @@ -844,28 +670,19 @@ public event Func, SocketVoiceChannel, DateTim internal readonly AsyncEvent, SocketVoiceChannel, DateTimeOffset, Task>> _userConnectedEvent = new(); - /// Fired when a user disconnected to a voice channel. + /// + /// 当服务器用户从语音频道断开连接时引发。 + /// /// - /// - /// This event is fired when a user disconnected to a voice channel. The event handler must return a - /// and accept a , - /// a , a , and a - /// as its parameter. - /// - /// - /// The user that disconnected to a voice channel is passed into the event handler parameter as - /// , which contains the original when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// - /// - /// The voice channel that the user disconnected to is passed into the event handler parameter as - /// . - /// - /// - /// The time when the user is offline is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// + /// 参数是从语音频道断开连接的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// 参数是用户断开连接的语音频道。 + /// 参数是用户断开连接的时间。 + /// /// public event Func, SocketVoiceChannel, DateTimeOffset, Task> UserDisconnected { @@ -876,27 +693,17 @@ public event Func, SocketVoiceChannel, DateTim internal readonly AsyncEvent, SocketVoiceChannel, DateTimeOffset, Task>> _userDisconnectedEvent = new(); // /// - // /// Fired when a user started a livestream in a voice channel. + // /// 当服务器用户开始直播时引发。 // /// // /// - // /// - // /// This event is fired when a user started a livestream in a voice channel. The event handler must return a - // /// and accept a and a - // /// as its parameters. - // /// - // /// - // /// The user that started the livestream is passed into the event handler parameter as - // /// , which contains the original when the user - // /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - // /// is preserved in the . - // /// - // /// - // /// The voice channel where the livestream is started is passed into the event handler parameter as - // /// . - // /// - // /// - // /// To retrieve the details of the livestream status, see . - // /// + // /// 事件参数: + // /// + // /// + // /// 参数是开始直播的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + // /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + // /// + // /// 参数是用户开始直播的语音频道。 + // /// // /// // public event Func, SocketVoiceChannel, Task> LivestreamBegan // { @@ -907,27 +714,17 @@ public event Func, SocketVoiceChannel, DateTim // internal readonly AsyncEvent, SocketVoiceChannel, Task>> _livestreamBeganEvent = new(); // // /// - // /// Fired when a user stopped a livestream in a voice channel. + // /// 当服务器用户结束直播时引发。 // /// // /// - // /// - // /// This event is fired when a user stopped a livestream in a voice channel. The event handler must return a - // /// and accept a and a - // /// as its parameters. - // /// - // /// - // /// The user that stopped the livestream is passed into the event handler parameter as - // /// , which contains the original when the user - // /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - // /// is preserved in the . - // /// - // /// - // /// The voice channel where the livestream is stopped is passed into the event handler parameter as - // /// . - // /// - // /// - // /// To retrieve the details of the livestream status, see . - // /// + // /// 事件参数: + // /// + // /// + // /// 参数是结束直播的可缓存服务器用户。如果缓存中存在此服务器用户实体,那么该结构内包含该 + // /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + // /// + // /// 参数是用户结束直播的语音频道。 + // /// // /// // public event Func, SocketVoiceChannel, Task> LivestreamEnded // { @@ -941,16 +738,14 @@ public event Func, SocketVoiceChannel, DateTim #region Roles - /// Fired when a role is created. + /// + /// 当服务器内的角色被创建时引发。 + /// /// - /// - /// This event is fired when a role is created. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The role that is created is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是被创建的角色。 + /// /// public event Func RoleCreated { @@ -960,16 +755,14 @@ public event Func RoleCreated internal readonly AsyncEvent> _roleCreatedEvent = new(); - /// Fired when a role is deleted. + /// + /// 当服务器内的角色被删除时引发。 + /// /// - /// - /// This event is fired when a role is deleted. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The role that is deleted is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是被删除的角色。 + /// /// public event Func RoleDeleted { @@ -979,21 +772,15 @@ public event Func RoleDeleted internal readonly AsyncEvent> _roleDeletedEvent = new(); - /// Fired when a role is updated. + /// + /// 当服务器内的角色被更新时引发。 + /// /// - /// - /// This event is fired when a role is deleted. The event handler must return a - /// and accept a and a - /// as its parameter. - /// - /// - /// The original role entity is passed into the event handler parameter as - /// . - /// - /// - /// The updated role entity is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是角色被更新前的状态。 + /// 参数是角色被更新后的状态。 + /// /// public event Func RoleUpdated { @@ -1007,21 +794,15 @@ public event Func RoleUpdated #region Emotes - /// Fired when an emote is created. + /// + /// 当服务器内的自定义表情被创建时引发。 + /// /// - /// - /// This event is fired when an emote is created. The event handler must return a - /// and accept a and a - /// as its parameter. - /// - /// - /// The emote that is created is passed into the event handler parameter as - /// . - /// - /// - /// The guild where the emote is created is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是被创建的自定义表情。 + /// 参数是自定义表情所在的服务器。 + /// /// public event Func EmoteCreated { @@ -1031,21 +812,15 @@ public event Func EmoteCreated internal readonly AsyncEvent> _emoteCreatedEvent = new(); - /// Fired when a emote is deleted. + /// + /// 当服务器内的自定义表情被删除时引发。 + /// /// - /// - /// This event is fired when an emote is deleted. The event handler must return a - /// and accept a and a - /// as its parameter. - /// - /// - /// The emote that is deleted is passed into the event handler parameter as - /// . - /// - /// - /// The guild where the emote is deleted is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是被删除的自定义表情。 + /// 参数是自定义表情被删除前所在的服务器。 + /// /// public event Func EmoteDeleted { @@ -1055,25 +830,16 @@ public event Func EmoteDeleted internal readonly AsyncEvent> _emoteDeletedEvent = new(); - /// Fired when a emote is updated. + /// + /// 当服务器内的自定义表情被更新时引发。 + /// /// - /// - /// This event is fired when an emote is updated. The event handler must return a - /// and accept a , a - /// and a as its parameter. - /// - /// - /// The original emote entity is passed into the event handler parameter as - /// . - /// - /// - /// The updated emote entity is passed into the event handler parameter as - /// . - /// - /// - /// The guild where the emote is updated is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是自定义表情被更新前的状态,如果缓存中不存在此自定义表情实体,则为 + /// 参数是自定义表情被更新后的状态。 + /// 参数是自定义表情所在的服务器。 + /// /// public event Func EmoteUpdated { @@ -1087,16 +853,14 @@ public event Func EmoteDeleted #region Guilds - /// Fired when the connected account joins a guild. + /// + /// 当当前用户新加入服务器时引发。 + /// /// - /// - /// This event is fired when the connected account joins a guild. The event handler must - /// return a and accept a as its parameter. - /// - /// - /// The guild where the account joins is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是当前用户新加入的服务器。 + /// /// public event Func JoinedGuild { @@ -1106,21 +870,14 @@ public event Func JoinedGuild internal readonly AsyncEvent> _joinedGuildEvent = new(); - /// Fired when the connected account leaves a guild. + /// + /// 当当前用户离开服务器时引发。 + /// /// - /// - /// This event is fired when the connected account leaves a guild. The event handler must - /// return a and accept a as its parameter. - /// - /// - /// - /// This parameter must be accessed within the current thread context. After - /// waiting for completion of the task in this asynchronous event, the object - /// passed to it will be disposed. - /// - /// The guild where the account leaves is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是当前用户离开的服务器。 + /// /// public event Func LeftGuild { @@ -1130,21 +887,15 @@ public event Func LeftGuild internal readonly AsyncEvent> _leftGuildEvent = new(); - /// Fired when a guild is updated. + /// + /// 当服务器信息被更新时引发。 + /// /// - /// - /// This event is fired when a guild is updated. The event handler must return a - /// and accept a , - /// and a as its parameter. - /// - /// - /// The guild before the update is passed into the event handler parameter as - /// . - /// - /// - /// The guild after the update is passed into the event handler parameter as - /// . - /// + /// 事件参数: + /// + /// 参数是服务器信息被更新前的状态。 + /// 参数是服务器信息被更新后的状态。 + /// /// public event Func GuildUpdated { @@ -1154,16 +905,17 @@ public event Func GuildUpdated internal readonly AsyncEvent> _guildUpdatedEvent = new(); - /// Fired when a guild becomes available. + /// + /// 当服务器状态变更为可用时引发。 + /// /// - /// - /// This event is fired when a guild becomes available. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The guild that becomes available is passed into the event handler parameter as - /// . - /// + /// 服务器状态变更为可用,表示此服务器实体已完整缓存基础数据,并与网关同步。
+ /// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 + ///
+ /// 事件参数: + /// + /// 参数是服务器状态变更为可用的服务器。 + /// ///
public event Func GuildAvailable { @@ -1173,16 +925,16 @@ public event Func GuildAvailable internal readonly AsyncEvent> _guildAvailableEvent = new(); - /// Fired when a guild becomes unavailable. + /// + /// 当服务器状态变更为不可用时引发。 + /// /// - /// - /// This event is fired when a guild becomes unavailable. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The guild that becomes unavailable is passed into the event handler parameter as - /// . - /// + /// 服务器状态变更为不可用,表示此服务器实体丢失与网关的同步,所缓存的数据不可靠,这通常发生在服务器被删除、当前用户离开服务器、网关连接断开等情况。 + ///
+ /// 事件参数: + /// + /// 参数是服务器状态变更为不可用的服务器。 + /// ///
public event Func GuildUnavailable { @@ -1196,32 +948,26 @@ public event Func GuildUnavailable #region Interactions - /// Fired when a button is clicked in a card message. + /// + /// 当用户点击服务器频道内的卡片消息按钮时引发。 + /// /// - /// - /// This event is fired when a button is clicked in a card message. The event handler must - /// return a and accept a string, - /// a , a , - /// a , and a as its parameter. - /// - /// - /// The button value is passed into the event handler parameter as string. - /// - /// - /// The users who clicked the button is passed into the event handler parameter as - /// , which contains a when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// - /// - /// If caching is enabled via , the - /// entity will contain the card message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// - /// - /// The channel where the button is clicked is passed into the event handler parameter as - /// . - /// + /// 卡片消息中的按钮包含多种点击事件类型,当该类型为 + /// 时,用户点击按钮后会引发此事件。 + ///
+ /// 事件参数: + /// + /// 参数是按钮的值。 + /// + /// 参数是点击按钮的可缓存服务器用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 服务器用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// + /// 参数是点击按钮所在的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被更新后的状态;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是点击按钮所在的服务器频道。 + /// ///
public event Func, Cacheable, SocketTextChannel, Task> MessageButtonClicked { @@ -1231,32 +977,26 @@ public event Func, Cacheable, Cacheable, SocketTextChannel, Task>> _messageButtonClickedEvent = new(); - /// Fired when a button is clicked in a direct card message. + /// + /// 当用户点击私聊频道内的卡片消息按钮时引发。 + /// /// - /// - /// This event is fired when a button is clicked in a direct card message. The event handler must - /// return a and accept a string, - /// a , a , - /// and a as its parameter. - /// - /// - /// The button value is passed into the event handler parameter as string. - /// - /// - /// The users who clicked the button is passed into the event handler parameter as - /// , which contains a when the user - /// presents in the cache; otherwise, in event that the user cannot be retrieved, the ID of the user - /// is preserved in the . - /// - /// - /// If caching is enabled via , the - /// entity will contain the direct card message; otherwise, in event - /// that the message cannot be retrieved, the ID of the message is preserved in the - /// - /// - /// The channel where the button is clicked is passed into the event handler parameter as - /// . - /// + /// 卡片消息中的按钮包含多种点击事件类型,当该类型为 + /// 时,用户点击按钮后会引发此事件。 + ///
+ /// 事件参数: + /// + /// 参数是按钮的值。 + /// + /// 参数是点击按钮的可缓存用户。如果缓存中存在此用户实体,那么该结构内包含该 + /// 用户;否则,包含 用户 ID,以供按需下载实体。 + /// + /// + /// 参数是点击按钮所在的可缓存消息。如果缓存中存在此消息实体,那么该结构内包含该 + /// 消息被更新后的状态;否则,包含 消息 ID,以供按需下载实体。 + /// + /// 参数是点击按钮所在的私聊频道。 + /// ///
public event Func, Cacheable, SocketDMChannel, Task> DirectMessageButtonClicked { diff --git a/src/Kook.Net.WebSocket/BaseSocketClient.cs b/src/Kook.Net.WebSocket/BaseSocketClient.cs index 20e89456..bcfe727b 100644 --- a/src/Kook.Net.WebSocket/BaseSocketClient.cs +++ b/src/Kook.Net.WebSocket/BaseSocketClient.cs @@ -4,35 +4,32 @@ namespace Kook.WebSocket; /// -/// Represents an abstract base class for WebSocket-based clients. +/// 表示一个基于网关的客户端的抽象基类。 /// public abstract partial class BaseSocketClient : BaseKookClient, IKookClient { /// - /// Gets the configuration used by this client. + /// 获取此客户端使用的配置。 /// protected readonly KookSocketConfig BaseConfig; /// - /// Gets the estimated round-trip latency, in milliseconds, to the gateway server. + /// 获取到网关服务器的往返延迟估计值(以毫秒为单位)。 /// - /// - /// An int that represents the round-trip latency to the WebSocket server. Please - /// note that this value does not represent a "true" latency for operations such as sending a message. - /// + /// + /// 此往返估计值源于心跳包的延迟,不代表诸如发送消息等操作的真实延迟。 + /// public abstract int Latency { get; protected set; } /// - /// Provides access to a REST-only client with a shared state from this client. + /// 获取一个与此客户端共享状态的仅限于 REST 的客户端。 /// public abstract KookSocketRestClient Rest { get; } internal new KookSocketApiClient ApiClient => base.ApiClient as KookSocketApiClient ?? throw new InvalidOperationException("The API client is not a WebSocket-based client."); - /// - /// Gets the current logged-in user. - /// + /// public new virtual SocketSelfUser? CurrentUser { get => base.CurrentUser as SocketSelfUser; @@ -40,11 +37,8 @@ public abstract partial class BaseSocketClient : BaseKookClient, IKookClient } /// - /// Gets a collection of guilds that the user is currently in. + /// 获取当前用户所在的所有服务器。 /// - /// - /// A read-only collection of guilds that the current user is in. - /// public abstract IReadOnlyCollection Guilds { get; } internal BaseSocketClient(KookSocketConfig config, KookRestApiClient client) @@ -54,132 +48,86 @@ internal BaseSocketClient(KookSocketConfig config, KookRestApiClient client) } /// - /// Gets a generic user. + /// 获取用户。 /// - /// The user ID. /// - /// This method gets the user present in the WebSocket cache with the given condition. - /// - /// Sometimes a user may return null due to Kook not sending offline users in large guilds - /// (i.e. guild with 100+ members) actively. To download users on startup and to see more information - /// about this subject, see . - /// - /// - /// This method does not attempt to fetch users that the logged-in user does not have access to (i.e. - /// users who don't share mutual guild(s) with the current user). If you wish to get a user that you do - /// not have access to, consider using the REST implementation of - /// . - /// + /// 此方法可能返回 null,因为此方法仅会返回网关缓存中存在的用户,如果在当前 Bot + /// 登录会话中,要获取的用户未引发过任何事件,那么该用户实体则不会存在于缓存中。 /// - /// - /// A generic WebSocket-based user; null when the user cannot be found. - /// + /// 要获取的用户的 ID。 + /// 与指定的 关联的用户;如果未找到,则返回 null public abstract SocketUser? GetUser(ulong id); /// - /// Gets a user. + /// 获取用户。 /// /// - /// This method gets the user present in the WebSocket cache with the given condition. - /// - /// Sometimes a user may return null due to Kook not sending offline users in large guilds - /// (i.e. guild with 100+ members) actively. To download users on startup and to see more information - /// about this subject, see . - /// - /// - /// This method does not attempt to fetch users that the logged-in user does not have access to (i.e. - /// users who don't share mutual guild(s) with the current user). If you wish to get a user that you do - /// not have access to, consider using the REST implementation of - /// . - /// + /// 此方法可能返回 null,因为此方法仅会返回网关缓存中存在的用户,如果在当前 Bot + /// 登录会话中,要获取的用户未引发过任何事件,那么该用户实体则不会存在于缓存中。 /// - /// The name of the user. - /// The identify value of the user. - /// - /// A generic WebSocket-based user; null when the user cannot be found. - /// + /// 用户的名称。 + /// 用户的识别号。 + /// 与指定的名称和识别号关联的用户;如果未找到,则返回 null public abstract SocketUser? GetUser(string username, string identifyNumber); /// - /// Gets a channel. + /// 获取一个服务器频道。 /// - /// The identifier of the channel. - /// - /// A generic WebSocket-based channel object (voice, text, category, etc.) associated with the identifier; - /// null when the channel cannot be found. - /// + /// 要获取的频道的 ID。 + /// 与指定的 关联的频道;如果未找到,则返回 null public abstract SocketChannel? GetChannel(ulong id); /// - /// Gets a channel. + /// 获取一个私聊频道。 /// - /// The chat code of the direct-message channel. - /// - /// A generic WebSocket-based channel object (voice, text, category, etc.) associated with the identifier; - /// null when the channel cannot be found. - /// + /// 私聊频道的聊天代码。 + /// 具有指定聊天代码的私聊频道;如果未找到,则返回 null public abstract SocketDMChannel? GetDMChannel(Guid chatCode); /// - /// Gets a channel. + /// 获取一个私聊频道。 /// - /// The user identifier of the direct-message channel. - /// - /// A generic WebSocket-based channel object (voice, text, category, etc.) associated with the identifier; - /// null when the channel cannot be found. - /// + /// 私聊频道中另一位用户的 ID。 + /// 另一位用户具有指定用户 ID 的私聊频道;如果未找到,则返回 null public abstract SocketDMChannel? GetDMChannel(ulong userId); /// - /// Gets a guild. + /// 获取一个服务器。 /// - /// The guild identifier. - /// - /// A WebSocket-based guild associated with the identifier; null when the guild cannot be - /// found. - /// + /// 要获取的服务器的 ID。 + /// 与指定的 关联的服务器;如果未找到,则返回 null public abstract SocketGuild? GetGuild(ulong id); - /// - /// Starts the WebSocket connection. - /// - /// A task that represents the asynchronous start operation. + /// public abstract Task StartAsync(); - /// - /// Stops the WebSocket connection. - /// - /// A task that represents the asynchronous stop operation. + /// public abstract Task StopAsync(); /// - /// Attempts to download users into the user cache for the selected guilds. + /// 下载全部或指定服务器的用户到缓存中。 /// - /// The guilds to download the members from. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous download operation. - /// + /// 要下载用户的服务器。如果为 null,则下载所有可用的服务器。 + /// 发送请求时要使用的选项。 + /// 一个表示异步下载操作的任务。 public abstract Task DownloadUsersAsync(IEnumerable? guilds = null, RequestOptions? options = null); /// - /// Downloads all voice states for the specified guilds. + /// 下载全部或指定服务器的语音状态到缓存中。 /// - /// - /// The guilds to download the voice states for. If null, all available guilds will be downloaded. - /// - /// The options to be used when sending the request. + /// 要下载语音状态的服务器。如果为 null,则下载所有可用的服务器。 + /// 发送请求时要使用的选项。 + /// 一个表示异步下载操作的任务。 public abstract Task DownloadVoiceStatesAsync(IEnumerable? guilds = null, RequestOptions? options = null); /// - /// Downloads all boost subscriptions for the specified guilds. + /// 下载全部或指定服务器的服务器助力信息到缓存中。 /// - /// - /// The guilds to download the boost subscriptions for. If null, all available guilds will be downloaded. - /// To download all boost subscriptions, the current user must has the - /// permission. - /// - /// The options to be used when sending the request. + /// 要下载服务器助力信息的服务器。如果为 null,则下载所有可用的服务器。 + /// + /// 对于要下载服务器助力信息的服务器,当前用户在该服务器中必须具有 权限。 + /// + /// 发送请求时要使用的选项。 public abstract Task DownloadBoostSubscriptionsAsync(IEnumerable? guilds = null, RequestOptions? options = null); diff --git a/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs b/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs index 18f3c120..7b60e395 100644 --- a/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs +++ b/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs @@ -3,47 +3,47 @@ namespace Kook.Commands; /// -/// Represents a WebSocket-based context of a command. This may include the client, guild, channel, user, and message. +/// 表示一个基于网关的客户端的命令的上下文。这可能包括客户端、公会、频道、用户和消息。 /// public class SocketCommandContext : ICommandContext { #region SocketCommandContext /// - /// Gets the that the command is executed with. + /// 获取命令执行时所使用的 。 /// public KookSocketClient Client { get; } /// - /// Gets the that the command is executed in. + /// 获取命令执行所在的 。 /// public SocketGuild? Guild { get; } /// - /// Gets the that the command is executed in. + /// 获取命令执行所在的 。 /// public ISocketMessageChannel Channel { get; } /// - /// Gets the who executed the command. + /// 获取执行命令的 。 /// public SocketUser User { get; } /// - /// Gets the that the command is interpreted from. + /// 获取命令解析的源 。 /// public SocketUserMessage Message { get; } /// - /// Indicates whether the channel that the command is executed in is a private channel. + /// 指示命令执行所在的频道是否为 私聊频道。 /// public bool IsPrivate => Channel is IPrivateChannel; /// - /// Initializes a new class with the provided client and message. + /// 使用提供的客户端和消息初始化一个 类的新实例。 /// - /// The underlying client. - /// The underlying message. + /// 底层客户端。 + /// 底层消息。 public SocketCommandContext(KookSocketClient client, SocketUserMessage msg) { Client = client; diff --git a/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs index 39f55b7b..b88c11f6 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs @@ -1,6 +1,6 @@ namespace Kook.WebSocket; /// -/// Represents a generic WebSocket-based audio channel. +/// 表示一个基于网关的音频频道。 /// public interface ISocketAudioChannel : IAudioChannel; diff --git a/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs index 4180c943..93da1ec9 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs @@ -1,106 +1,88 @@ namespace Kook.WebSocket; /// -/// Represents a generic WebSocket-based channel that can send and receive messages. +/// 表示一个基于网关的消息频道,可以用来发送和接收消息。 /// public interface ISocketMessageChannel : IMessageChannel { /// - /// Gets all messages in this channel's cache. + /// 获取此频道缓存的所有消息。 /// - /// - /// A read-only collection of WebSocket-based messages. - /// + /// + /// + /// 要想通过此属性获取缓存的消息,需要启用缓存功能,否则此属性将始终返回空集合。缓存功能是默认禁用的,要想启用缓存,请参考 + /// 。 + /// + ///
+ /// 此属性从本地的内存缓存中获取消息实体,不会向 KOOK 发送额外的 API 请求。所获取的消息也可能是已经被删除的消息。 + ///
IReadOnlyCollection CachedMessages { get; } /// - /// Gets a cached message from this channel. + /// 获取此频道缓存的消息。 /// /// /// - /// This method requires the use of cache, which is not enabled by default; if caching is not enabled, - /// this method will always return null. Please refer to - /// for more details. + /// 要想通过此方法获取缓存的消息,需要启用缓存功能,否则此方法将始终返回 null。缓存功能是默认禁用的,要想启用缓存,请参考 + /// 。 /// - /// - /// This method retrieves the message from the local WebSocket cache and does not send any additional - /// request to Kook. This message may be a message that has been deleted. - /// + ///
+ /// 此方法从本地的内存缓存中获取消息实体,不会向 KOOK 发送额外的 API 请求。所获取的消息也可能是已经被删除的消息。 ///
- /// The Guid of the message. + /// 消息的 ID。 /// - /// A WebSocket-based message object; null if it does not exist in the cache or if caching is not - /// enabled. + /// 如果获取到了缓存的消息,则返回该消息实体;否则返回 null。 /// SocketMessage? GetCachedMessage(Guid id); /// - /// Gets the last N cached messages from this message channel. + /// 获取此频道缓存的多条消息。 /// + /// 要获取的缓存消息的数量。 /// + /// 此重载将会从缓存中获取最新的指定数量的缓存消息实体。 + ///
/// - /// This method requires the use of cache, which is not enabled by default; if caching is not enabled, - /// this method will always return an empty collection. Please refer to - /// for more details. + /// 要想通过此方法获取缓存的消息,需要启用缓存功能,否则此方法将始终返回空集合。缓存功能是默认禁用的,要想启用缓存,请参考 + /// 。 /// - /// - /// This method retrieves the message(s) from the local WebSocket cache and does not send any additional - /// request to Kook. This read-only collection may include messages that have been deleted. The - /// maximum number of messages that can be retrieved from this method depends on the - /// set. - /// + ///
+ /// 此方法从本地的内存缓存中获取消息实体,不会向 KOOK 发送额外的 API 请求。所获取的消息也可能是已经被删除的消息。 ///
- /// The number of messages to get. - /// - /// A read-only collection of WebSocket-based messages. - /// + /// 此频道缓存的所有消息。 IReadOnlyCollection GetCachedMessages(int limit = KookConfig.MaxMessagesPerBatch); /// - /// Gets the last N cached messages starting from a certain message in this message channel. + /// 获取此频道缓存的多条消息。 /// + /// 要开始获取消息的参考位置的消息的 ID。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 /// /// - /// This method requires the use of cache, which is not enabled by default; if caching is not enabled, - /// this method will always return an empty collection. Please refer to - /// for more details. + /// 要想通过此方法获取缓存的消息,需要启用缓存功能,否则此方法将始终返回空集合。缓存功能是默认禁用的,要想启用缓存,请参考 + /// 。 /// - /// - /// This method retrieves the message(s) from the local WebSocket cache and does not send any additional - /// request to Kook. This read-only collection may include messages that have been deleted. The - /// maximum number of messages that can be retrieved from this method depends on the - /// set. - /// + ///
+ /// 此方法从本地的内存缓存中获取消息实体,不会向 KOOK 发送额外的 API 请求。所获取的消息也可能是已经被删除的消息。 ///
- /// The message ID to start the fetching from. - /// The direction of which the message should be gotten from. - /// The number of messages to get. - /// - /// A read-only collection of WebSocket-based messages. - /// - IReadOnlyCollection GetCachedMessages(Guid fromMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch); + /// 获取到的多条缓存消息。 + IReadOnlyCollection GetCachedMessages(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch); /// - /// Gets the last N cached messages starting from a certain message in this message channel. + /// 获取此频道缓存的多条消息。 /// + /// 要开始获取消息的参考位置的消息。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 /// /// - /// This method requires the use of cache, which is not enabled by default; if caching is not enabled, - /// this method will always return an empty collection. Please refer to - /// for more details. + /// 要想通过此方法获取缓存的消息,需要启用缓存功能,否则此方法将始终返回空集合。缓存功能是默认禁用的,要想启用缓存,请参考 + /// 。 /// - /// - /// This method retrieves the message(s) from the local WebSocket cache and does not send any additional - /// request to Kook. This read-only collection may include messages that have been deleted. The - /// maximum number of messages that can be retrieved from this method depends on the - /// set. - /// + ///
+ /// 此方法从本地的内存缓存中获取消息实体,不会向 KOOK 发送额外的 API 请求。所获取的消息也可能是已经被删除的消息。 ///
- /// The message to start the fetching from. - /// The direction of which the message should be gotten from. - /// The number of messages to get. - /// - /// A read-only collection of WebSocket-based messages. - /// - IReadOnlyCollection GetCachedMessages(IMessage fromMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch); + /// 获取到的多条缓存消息。 + IReadOnlyCollection GetCachedMessages(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch); } diff --git a/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs index 9b42b9b9..25bf4fdf 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs @@ -1,15 +1,10 @@ namespace Kook.WebSocket; /// -/// Represents a generic WebSocket-based channel that is private to select recipients. +/// 表示一个基于网关的私有频道,只有特定的用户可以访问。 /// public interface ISocketPrivateChannel : IPrivateChannel { - /// - /// Gets the users that can access this channel. - /// - /// - /// A read-only collection of users that can access this channel. - /// + /// new IReadOnlyCollection Recipients { get; } } diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs index b1114fa5..699a4675 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs @@ -6,7 +6,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based category channel. +/// 表示一个基于网关的分组频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketCategoryChannel : SocketGuildChannel, ICategoryChannel @@ -21,12 +21,8 @@ public class SocketCategoryChannel : SocketGuildChannel, ICategoryChannel .ToImmutableArray(); /// - /// Gets the child channels of this category. + /// 获取所有属于此分组频道的所有子频道。 /// - /// - /// A read-only collection of whose - /// matches the identifier of this category channel. - /// public IReadOnlyCollection Channels => [..Guild.Channels.Where(x => x is INestedChannel nestedChannel && nestedChannel.CategoryId == Id)]; diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs index 62d2a285..3fd366ac 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs @@ -4,7 +4,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based channel. +/// 表示一个基于网关的频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public abstract class SocketChannel : SocketEntity, IChannel, IUpdateable @@ -12,8 +12,11 @@ public abstract class SocketChannel : SocketEntity, IChannel, IUpdateable #region SocketChannel /// - /// Gets a collection of users from the WebSocket cache. + /// 获取用户缓存列表中的可以访问此频道的所有用户。 /// + /// + /// 此属性仅会返回缓存中可以访问此频道的所有用户,如果未启用用户列表缓存,或者由于网关事件确实导致本地缓存不同步,此属性所返回的用户列表可能不准确。 + /// public IReadOnlyCollection Users => GetUsersInternal(); internal SocketChannel(KookSocketClient kook, ulong id) @@ -31,12 +34,10 @@ internal SocketChannel(KookSocketClient kook, ulong id) #region User /// - /// Gets a generic user from this channel. + /// 获取此频道中的一个用户。 /// - /// The identifier of the user. - /// - /// A generic WebSocket-based user associated with the identifier. - /// + /// 要获取的用户的 ID。 + /// 如果找到了具有指定 ID 的用户,则返回该用户;否则返回 null public SocketUser? GetUser(ulong id) => GetUserInternal(id); internal abstract SocketUser? GetUserInternal(ulong id); diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs index 085e0ead..943d3e8e 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs @@ -10,7 +10,8 @@ public static IAsyncEnumerable> GetMessagesAsync(I KookSocketClient kook, MessageCache? messages, Guid? referenceMessageId, Direction dir, int limit, CacheMode mode, RequestOptions? options) { - if (dir == Direction.After && referenceMessageId == null) return AsyncEnumerable.Empty>(); + if (dir == Direction.After && referenceMessageId == null) + return AsyncEnumerable.Empty>(); IReadOnlyCollection cachedMessages = GetCachedMessages(channel, kook, messages, referenceMessageId, dir, limit); IAsyncEnumerable> result = diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs index 291519de..8014be7c 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs @@ -1,41 +1,46 @@ using Kook.API; using Kook.Rest; using System.Collections.Immutable; +using System.Diagnostics; namespace Kook.WebSocket; /// -/// Represents a WebSocket-based direct-message channel. +/// 表示一个基于网关的私聊频道。 /// +[DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketDMChannel : SocketChannel, IDMChannel, ISocketPrivateChannel, ISocketMessageChannel { #region SocketDMChannel /// - /// Get the identifier of the DM channel. + /// 获取此私聊频道的唯一标识符。 /// /// - /// This property is the same as . + /// 此属性的值与 相同。 /// public new Guid Id { get; } - /// + /// + /// 获取此私聊频道的聊天代码。 + /// /// - /// This property is the same as . + /// 此属性的值与 相同。 /// public Guid ChatCode => Id; - /// - /// Gets the recipient of the channel. - /// + /// public SocketUser Recipient { get; } /// + /// + /// + /// 私聊消息频道不支持缓存消息,此属性将始终返回空集合。 + /// + /// public IReadOnlyCollection CachedMessages => ImmutableArray.Create(); - /// - /// Gets a collection that is the current logged-in user and the recipient. - /// + /// public new IReadOnlyCollection Users => ImmutableArray.Create(Kook.CurrentUser, Recipient); internal SocketDMChannel(KookSocketClient kook, Guid chatCode, SocketUser recipient) @@ -73,175 +78,159 @@ public Task CloseAsync(RequestOptions? options = null) => #region Messages /// + /// + /// + /// 私聊消息频道不支持缓存消息,此方法将始终返回 null。 + /// + /// public SocketMessage? GetCachedMessage(Guid id) => null; /// - /// Gets the message associated with the given . + /// 从此消息频道获取一条消息。 /// - /// TThe ID of the message. - /// The options to be used when sending the request. - /// - /// The message gotten from either the cache or the download, or null if none is found. - /// + /// 消息的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务结果包含检索到的消息;如果未找到具有指定 ID 的消息,则返回 null public async Task GetMessageAsync(Guid id, RequestOptions? options = null) => await ChannelHelper.GetDirectMessageAsync(this, Kook, id, options).ConfigureAwait(false); /// - /// Gets the last N messages from this message channel. + /// 获取此消息频道中的最新的一些消息。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 public IAsyncEnumerable> GetMessagesAsync( int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => ChannelHelper.GetDirectMessagesAsync(this, Kook, null, Direction.Before, limit, true, options); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The ID of the starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息的 ID。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 public IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => ChannelHelper.GetDirectMessagesAsync(this, Kook, referenceMessageId, dir, limit, true, options); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 public IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => ChannelHelper.GetDirectMessagesAsync(this, Kook, referenceMessage.Id, dir, limit, true, options); /// + /// + /// + /// 私聊消息频道不支持缓存消息,此属性将始终返回空集合。 + /// + /// public IReadOnlyCollection GetCachedMessages(int limit = KookConfig.MaxMessagesPerBatch) => []; /// - public IReadOnlyCollection GetCachedMessages(Guid fromMessageId, + /// + /// + /// 私聊消息频道不支持缓存消息,此属性将始终返回空集合。 + /// + /// + public IReadOnlyCollection GetCachedMessages(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch) => []; /// - public IReadOnlyCollection GetCachedMessages(IMessage fromMessage, - Direction dir, int limit = KookConfig.MaxMessagesPerBatch) => []; - - /// - /// Sends a file to this message channel. - /// /// - /// This method sends a file as if you are uploading a file directly from your Kook client. + /// + /// 私聊消息频道不支持缓存消息,此属性将始终返回空集合。 + /// /// - /// The file path of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + public IReadOnlyCollection GetCachedMessages(IMessage referenceMessage, + Direction dir, int limit = KookConfig.MaxMessagesPerBatch) => []; + + /// public Task> SendFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, path, filename, type, quote, options); - /// - /// Sends a file to this message channel. - /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The stream of the file. - /// The name of the file. - /// The type of the file. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, stream, filename, type, quote, options); - /// - /// Sends a file to this message channel. - /// - /// - /// This method sends a file as if you are uploading a file directly from your Kook client. - /// - /// The attachment containing the file. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendFileAsync(FileAttachment attachment, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, attachment, quote, options); - /// - /// Sends a text message to this message channel. - /// - /// The message to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendTextAsync(string text, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectMessageAsync(this, Kook, MessageType.KMarkdown, text, quote, options); - /// - /// Sends a card message to this message channel. - /// - /// The cards to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendCardsAsync(IEnumerable cards, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectCardsAsync(this, Kook, cards, quote, options); - /// - /// Sends a card message to this message channel. - /// - /// The card to be sent. - /// The message quote to be included. Used to reply to specific messages. - /// 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 identifier and timestamp of the sent message. - /// + /// public Task> SendCardAsync(ICard card, IQuote? quote = null, RequestOptions? options = null) => ChannelHelper.SendDirectCardAsync(this, Kook, card, quote, options); @@ -269,13 +258,7 @@ internal void AddMessage(SocketMessage msg) #region Users - /// - /// Gets a user in this channel from the provided . - /// - /// The identifier of the user. - /// - /// A object that is a recipient of this channel; otherwise null. - /// + /// public new SocketUser? GetUser(ulong id) { if (id == Recipient.Id) return Recipient; @@ -426,8 +409,10 @@ IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mo #endregion /// - /// Returns the recipient user. + /// 获取此参与到此私聊频道的另外一位用户的包含 @ 前缀的用户名及识别号格式化字符串。 /// + /// 一个表示此私聊频道的格式化字符串。 + /// public override string ToString() => $"@{Recipient}"; private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)"; diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs index 4b776a5b..973043c7 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs @@ -6,7 +6,7 @@ namespace Kook.WebSocket; /// -/// Represent a WebSocket-based guild channel. +/// 表示一个基于网关的服务器频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketGuildChannel : SocketChannel, IGuildChannel @@ -16,12 +16,7 @@ public class SocketGuildChannel : SocketChannel, IGuildChannel #region SocketGuildChannel - /// - /// Gets the guild associated with this channel. - /// - /// - /// A guild object that this channel belongs to. - /// + /// public SocketGuild Guild { get; } /// @@ -37,16 +32,14 @@ public class SocketGuildChannel : SocketChannel, IGuildChannel public ulong? CreatorId { get; private set; } /// - /// Gets the creator of this channel. + /// 获取创建此频道的用户。 /// /// - /// This method will try to get the user as a member of this channel. If the user is not a member of this guild, - /// this method will return null. To get the creator under this circumstance, use - /// . + /// 此属性会尝试从缓存的用户列表中获取此频道的创建者。如果用户不是此服务器的成员,或该用户不在本地缓存的用户列表中,则此属性将返回 + /// null。在这种情况下,可以尝试通过 + /// + /// 获取指定的用户信息。 /// - /// - /// A task that represents the asynchronous get operation. The task result contains the creator of this channel. - /// public SocketGuildUser? Creator => CreatorId.HasValue ? GetUser(CreatorId.Value) : null; /// @@ -55,12 +48,7 @@ public class SocketGuildChannel : SocketChannel, IGuildChannel /// public IReadOnlyCollection UserPermissionOverwrites => _userPermissionOverwrites; - /// - /// Gets a collection of users that are able to view the channel. - /// - /// - /// A read-only collection of users that can access the channel (i.e. the users seen in the user list). - /// + /// public new virtual IReadOnlyCollection Users => []; internal SocketGuildChannel(KookSocketClient kook, ulong id, SocketGuild guild) @@ -82,7 +70,6 @@ internal static SocketGuildChannel Create(SocketGuild guild, ClientState state, _ => new SocketGuildChannel(guild.Kook, model.Id, guild) }; - /// internal override void Update(ClientState state, Model model) { Name = model.Name; @@ -116,34 +103,15 @@ public Task ModifyAsync(Action func, RequestOption public Task DeleteAsync(RequestOptions? options = null) => ChannelHelper.DeleteGuildChannelAsync(this, Kook, options); - /// - /// Gets the permission overwrite for a specific user. - /// - /// The user to get the overwrite from. - /// - /// An overwrite object for the targeted user; null if none is set. - /// + /// public virtual OverwritePermissions? GetPermissionOverwrite(IUser user) => _userPermissionOverwrites.FirstOrDefault(x => x.Target.Id == user.Id)?.Permissions; - /// - /// Gets the permission overwrite for a specific role. - /// - /// The role to get the overwrite from. - /// - /// An overwrite object for the targeted role; null if none is set. - /// + /// public virtual OverwritePermissions? GetPermissionOverwrite(IRole role) => _rolePermissionOverwrites.FirstOrDefault(x => x.Target == role.Id)?.Permissions; - /// - /// Adds or updates the permission overwrite for the given user. - /// - /// The user to add the overwrite to. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. - /// + /// public async Task AddPermissionOverwriteAsync(IGuildUser user, RequestOptions? options = null) { UserPermissionOverwrite perms = await ChannelHelper @@ -152,14 +120,7 @@ public async Task AddPermissionOverwriteAsync(IGuildUser user, RequestOptions? o _userPermissionOverwrites = [.._userPermissionOverwrites, perms]; } - /// - /// Adds or updates the permission overwrite for the given role. - /// - /// The role to add the overwrite to. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. - /// + /// public async Task AddPermissionOverwriteAsync(IRole role, RequestOptions? options = null) { RolePermissionOverwrite perms = await ChannelHelper @@ -168,43 +129,21 @@ public async Task AddPermissionOverwriteAsync(IRole role, RequestOptions? option _rolePermissionOverwrites = [.._rolePermissionOverwrites, perms]; } - /// - /// Removes the permission overwrite for the given user, if one exists. - /// - /// The user to remove the overwrite from. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task RemovePermissionOverwriteAsync(IGuildUser user, RequestOptions? options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Kook, user, options).ConfigureAwait(false); RemoveUserPermissionOverwrite(user.Id); } - /// - /// Removes the permission overwrite for the given role, if one exists. - /// - /// The role to remove the overwrite from. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions? options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Kook, role, options).ConfigureAwait(false); RemoveRolePermissionOverwrite(role.Id); } - /// - /// Updates the permission overwrite for the given user, if one exists. - /// - /// The user to modify the overwrite for. - /// A delegate containing the values to modify the permission overwrite with. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions? options = null) { @@ -214,15 +153,7 @@ public async Task ModifyPermissionOverwriteAsync(IGuildUser user, _userPermissionOverwrites = [.._userPermissionOverwrites.Where(x => x.Target.Id != user.Id), perms]; } - /// - /// Updates the permission overwrite for the given role, if one exists. - /// - /// The role to remove the overwrite for. - /// A delegate containing the values to modify the permission overwrite with. - /// The options to be used when sending the request. - /// - /// A task representing the asynchronous operation for removing the specified permissions from the channel. - /// + /// public async Task ModifyPermissionOverwriteAsync(IRole role, Func func, RequestOptions? options = null) { @@ -233,18 +164,13 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, } /// - /// Gets a from this channel. + /// 获取此频道中的一个服务器用户。 /// - /// The user's identifier. - /// A with the provided identifier; null if none is found. + /// 要获取的服务器用户的 ID。 + /// 如果找到了具有指定 ID 的服务器用户,则返回该用户;否则返回 null public new virtual SocketGuildUser? GetUser(ulong id) => null; - /// - /// Gets the name of the channel. - /// - /// - /// A string that resolves to . - /// + /// public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id}, Guild)"; @@ -254,10 +180,8 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, #region SocketChannel - /// internal override SocketUser? GetUserInternal(ulong id) => GetUser(id); - /// internal override IReadOnlyCollection GetUsersInternal() => Users; #endregion @@ -305,17 +229,7 @@ IAsyncEnumerable> IGuildChannel.GetUsersAsync( Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions? options) => Task.FromResult(GetUser(id)); //Overridden in Text/Voice - /// - /// Gets the creator of this channel. - /// - /// - /// This method will try to get the user as a member of this channel. If the user is not a member of this guild, - /// this method will return null. To get the creator under this circumstance, use - /// . - /// - /// - /// A task that represents the asynchronous get operation. The task result contains the creator of this channel. - /// + /// Task IGuildChannel.GetCreatorAsync(CacheMode mode, RequestOptions? options) => Task.FromResult(Creator); diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs index acd58cd8..375c0ea8 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs @@ -6,7 +6,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based channel in a guild that can send and receive messages. +/// 表示服务器中一个基于网关的具有文字聊天能力的频道,可以发送和接收消息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketTextChannel : SocketGuildChannel, ITextChannel, ISocketMessageChannel @@ -25,11 +25,9 @@ public class SocketTextChannel : SocketGuildChannel, ITextChannel, ISocketMessag public ulong? CategoryId { get; private set; } /// - /// Gets the parent (category) of this channel in the guild's channel list. + /// 获取此嵌套频道在服务器频道列表中所属的分组频道的。 /// - /// - /// An representing the parent of this channel; null if none is set. - /// + /// 如果当前频道不属于任何分组频道,则会返回 null public ICategoryChannel? Category => CategoryId.HasValue ? Guild.GetChannel(CategoryId.Value) as ICategoryChannel : null; @@ -44,10 +42,6 @@ public class SocketTextChannel : SocketGuildChannel, ITextChannel, ISocketMessag public string PlainTextMention => MentionUtils.PlainTextMentionChannel(Id); /// - /// - /// This property is only available if the is set to a value greater than zero. - /// - /// public IReadOnlyCollection CachedMessages => _messages?.Messages ?? []; /// @@ -101,18 +95,11 @@ public virtual Task SyncPermissionsAsync(RequestOptions? options = null) => public SocketMessage? GetCachedMessage(Guid id) => _messages?.Get(id); /// - /// Gets a message from this message channel. + /// 从此消息频道获取一条消息。 /// - /// - /// This method follows the same behavior as described in . - /// Please visit its documentation for more details on this method. - /// - /// The identifier of the message. - /// The options to be used when sending the request. - /// - /// A task that represents an asynchronous get operation for retrieving the message. The task result contains - /// the retrieved message; null if no message is found with the specified identifier. - /// + /// 消息的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务结果包含检索到的消息;如果未找到具有指定 ID 的消息,则返回 null public async Task GetMessageAsync(Guid id, RequestOptions? options = null) { IMessage? msg = _messages?.Get(id); @@ -120,58 +107,88 @@ public async Task GetMessageAsync(Guid id, RequestOptions? options = n } /// - /// Gets the last N messages from this message channel. + /// 获取此消息频道中的最新的一些消息。 /// /// - /// This method follows the same behavior as described in - /// . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 public virtual IAsyncEnumerable> GetMessagesAsync( int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => SocketChannelHelper.GetMessagesAsync(this, Kook, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// - /// This method follows the same behavior as described in - /// . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The ID of the starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息的 ID。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 public virtual IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => SocketChannelHelper.GetMessagesAsync(this, Kook, _messages, referenceMessageId, dir, limit, CacheMode.AllowDownload, options); /// - /// Gets a collection of messages in this channel. + /// 获取此消息频道中的一些消息。 /// /// - /// This method follows the same behavior as described in - /// . - /// Please visit its documentation for more details on this method. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取此频道最新的 条消息。此方法会根据 + /// 将请求拆分。换句话说,如果要获取 500 条消息,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
- /// The starting message to get the messages from. - /// The direction of the messages to be gotten from. - /// The numbers of message to be gotten from. - /// The options to be used when sending the request. - /// - /// Paged collection of messages. - /// + /// 要开始获取消息的参考位置的消息。 + /// 要以参考位置为基准,获取消息的方向。 + /// 要获取的消息数量。 + /// 发送请求时要使用的选项。 + /// 分页的消息集合的异步可枚举对象。 public virtual IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => SocketChannelHelper.GetMessagesAsync(this, Kook, _messages, @@ -182,20 +199,20 @@ public IReadOnlyCollection GetCachedMessages(int limit = KookConf SocketChannelHelper.GetCachedMessages(this, Kook, _messages, null, Direction.Before, limit); /// - public IReadOnlyCollection GetCachedMessages(Guid fromMessageId, + public IReadOnlyCollection GetCachedMessages(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch) => - SocketChannelHelper.GetCachedMessages(this, Kook, _messages, fromMessageId, dir, limit); + SocketChannelHelper.GetCachedMessages(this, Kook, _messages, referenceMessageId, dir, limit); /// - public IReadOnlyCollection GetCachedMessages(IMessage fromMessage, + public IReadOnlyCollection GetCachedMessages(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch) => - SocketChannelHelper.GetCachedMessages(this, Kook, _messages, fromMessage.Id, dir, limit); + SocketChannelHelper.GetCachedMessages(this, Kook, _messages, referenceMessage.Id, dir, limit); /// public Task> GetPinnedMessagesAsync(RequestOptions? options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Kook, options); - /// + /// public Task> SendFileAsync(string path, string? filename = null, AttachmentType type = AttachmentType.File, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) @@ -204,28 +221,28 @@ public Task> SendFileAsync(string path, string? fi return ChannelHelper.SendFileAsync(this, Kook, path, name, type, quote, ephemeralUser, options); } - /// + /// public Task> SendFileAsync(Stream stream, string filename, AttachmentType type = AttachmentType.File, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendFileAsync(this, Kook, stream, filename, type, quote, ephemeralUser, options); - /// + /// public Task> SendFileAsync(FileAttachment attachment, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendFileAsync(this, Kook, attachment, quote, ephemeralUser, options); - /// + /// public Task> SendTextAsync(string text, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendMessageAsync(this, Kook, MessageType.KMarkdown, text, quote, ephemeralUser, options); - /// + /// public Task> SendCardsAsync(IEnumerable cards, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendCardsAsync(this, Kook, cards, quote, ephemeralUser, options); - /// + /// public Task> SendCardAsync(ICard card, IQuote? quote = null, IUser? ephemeralUser = null, RequestOptions? options = null) => ChannelHelper.SendCardAsync(this, Kook, card, quote, ephemeralUser, options); diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs index 0bac45e3..0fa225f4 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs @@ -8,7 +8,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based voice channel in a guild. +/// 表示服务器中的一个基于网关的具有语音聊天能力的频道。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketVoiceChannel : SocketTextChannel, IVoiceChannel, ISocketAudioChannel, IDisposable @@ -37,9 +37,7 @@ public class SocketVoiceChannel : SocketTextChannel, IVoiceChannel, ISocketAudio /// public bool HasPassword { get; private set; } - /// - /// Gets the associated with this guild. - /// + /// public IAudioClient? AudioClient => _audioClient; /// @@ -50,21 +48,18 @@ public class SocketVoiceChannel : SocketTextChannel, IVoiceChannel, ISocketAudio ChannelPermission.ViewChannel)).ToImmutableArray(); /// - /// Gets a collection of users that are currently connected to this voice channel. + /// 获取当前连接到此语音频道的所有用户。 /// /// /// - /// This property may not always return all the members that are connected to this voice channel, - /// because uses may connected this voice channel before the bot has connected to the gateway. - /// To ensure accuracy, you may need to enable - /// to fetch the full voice states upon startup, or use - /// on the guild this voice channel belongs to to manually download the users voice states, - /// or use to fetch the connected users from the API. + /// 此属性可能不会始终返回连接到此语音频道的所有成员,因为用户可能在 Bot 连接到网关之前就连接到了此语音频道。 + /// 如需准确获取所有连接到此语音频道的成员,可能需要启用 + /// ,这可以让 Bot + /// 在启动连接到网关时获取完整的语音状态。也可以调用方法 + /// + /// 访问 API 获取连接到此语音频道的用户。 /// /// - /// - /// A read-only collection of users that are currently connected to this voice channel. - /// public IReadOnlyCollection ConnectedUsers => Guild.Users.Where(x => x.VoiceChannel?.Id == Id).ToImmutableArray(); @@ -105,15 +100,7 @@ internal override void Update(ClientState state, Model model) public Task ModifyAsync(Action func, RequestOptions? options = null) => ChannelHelper.ModifyAsync(this, Kook, func, options); - /// - /// Gets a collection of users that are currently connected to this voice channel. - /// - /// 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 a read-only collection of users - /// that are currently connected to this voice channel. - /// + /// public async Task> GetConnectedUsersAsync( CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null) => mode is CacheMode.AllowDownload @@ -125,25 +112,25 @@ mode is CacheMode.AllowDownload #region TextOverrides /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override IAsyncEnumerable> GetMessagesAsync( int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 public override IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions? options = null) => throw new NotSupportedException("Getting messages from a voice channel is not supported."); /// - /// Getting messages from a voice channel is not supported. + /// 不支持在语音频道中获取消息。 Task> ITextChannel.GetPinnedMessagesAsync(RequestOptions? options) => Task.FromException>( new NotSupportedException("Getting messages from a voice channel is not supported.")); @@ -153,7 +140,7 @@ Task> ITextChannel.GetPinnedMessagesAsync(RequestO #region IVoiceChannel /// - async Task> IVoiceChannel.GetConnectedUsersAsync( + async Task> IVoiceChannel.GetConnectedUsersAsync( CacheMode mode, RequestOptions? options) => await GetConnectedUsersAsync(mode, options).ConfigureAwait(false); @@ -301,7 +288,7 @@ void IDisposable.Dispose() Task.FromResult(GetUser(id)); /// - /// + /// IAsyncEnumerable> IGuildChannel.GetUsersAsync( CacheMode mode, RequestOptions? options) => mode == CacheMode.AllowDownload diff --git a/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs b/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs index 02ff5a92..1ba51184 100644 --- a/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs +++ b/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs @@ -17,7 +17,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based guild object. +/// 表示一个基于网关的服务器。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable @@ -40,7 +40,15 @@ public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable /// public ulong OwnerId { get; private set; } - /// Gets the user that owns this guild. + /// + /// 获取此服务器的所有者。 + /// + /// + /// + /// 此属性尝试在缓存的用户列表中获取具有其用户 ID 为 + /// 的用户。如果该用户不在缓存中,则此属性将返回 null。 + /// + /// public SocketGuildUser? Owner => GetUser(OwnerId); /// @@ -93,60 +101,54 @@ public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable public RecommendInfo? RecommendInfo { get; private set; } /// - /// Gets the number of members. + /// 获取此服务器的成员数。 /// /// - /// This property retrieves the number of members returned by Kook. /// - /// - /// Due to how this property is returned by Kook instead of relying on the WebSocket cache, the - /// number here is the most accurate in terms of counting the number of users within this guild. - /// - /// - /// Use this instead of enumerating the count of the - /// collection, as you may see discrepancy - /// between that and this property. - /// + /// 在 属性上计数的结果为所缓存用户的数量, + /// 如果缓存不完整,统计结果可能会与此属性值不一致。 /// + ///
/// - /// Only when is set to true - /// will this property be populated upon startup. Otherwise, this property will be null, - /// and will be populated when is called. + /// 当 true 时。 + /// Bot 启动后会自动下载服务器的所有用户,并设定此属性值。否则,此属性将为 null。调用 + /// + /// 也可以立即下载服务器的所有用户,下载完成后,此属性值将被设定。 /// ///
public int? MemberCount { get; internal set; } - /// Gets the number of members downloaded to the local guild cache. - public int DownloadedMemberCount { get; private set; } + /// + /// 获取此服务器内已缓存的成员数量。 + /// + public int DownloadedMemberCount => _members.Count; - internal bool IsAvailable { get; private set; } + /// + public bool IsAvailable { get; private set; } - /// Indicates whether the client is connected to this guild. + /// + /// 获取此服务器是否已连接至网关。 + /// public bool IsConnected { get; internal set; } - /// Indicates whether the client has all the members downloaded to the local guild cache. + /// + /// 获取是否已下载此服务器的所有成员至缓存。 + /// /// - /// - /// If is null, this property will always return null, - /// which means that the client is unable to determine whether all the members are downloaded or not. - /// + /// 当如法确定是否已下载此服务器的所有成员,或者服务器的成员数量未知时,此属性将返回 null。 /// public bool? HasAllMembers => MemberCount is null ? null : MemberCount <= DownloadedMemberCount; /// public int MaxBitrate => GuildHelper.GetMaxBitrate(this); - /// - /// Gets the associated with this guild. - /// + /// [Obsolete("Use AudioClients instead.")] public IAudioClient? AudioClient => VoiceChannels .FirstOrDefault(x => x.AudioClient is not null)? .AudioClient; - /// - /// Gets a collection of all audio clients in this guild. - /// + /// public IReadOnlyDictionary AudioClients => VoiceChannels .Where(x => x.AudioClient is not null) .ToDictionary(x => x.Id, x => x.AudioClient!); @@ -157,7 +159,7 @@ public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable public ulong MaxUploadLimit => GuildHelper.GetUploadLimit(this); /// - /// Gets the current logged-in user. + /// 获取当前登录的用户。 /// public SocketGuildUser? CurrentUser => Kook.CurrentUser is not null @@ -165,131 +167,82 @@ Kook.CurrentUser is not null ? member : null; - /// - /// Gets the built-in role containing all users in this guild. - /// - /// - /// A role object that represents an @everyone role in this guild. - /// + /// public SocketRole EveryoneRole => GetRole(0) ?? new SocketRole(this, 0); /// - /// Gets a collection of all text channels in this guild. + /// 获取此服务器中所有具有文字聊天能力的频道。 /// - /// - /// A read-only collection of message channels found within this guild. - /// + /// + /// 语音频道也是一种文字频道,此属性本意用于获取所有具有文字聊天能力的频道,通过此方法获取到的文字频道列表中也包含了语音频道。 + /// 如需获取频道的实际类型,请参考 。 + /// public IReadOnlyCollection TextChannels => [..Channels.OfType()]; /// - /// Gets a collection of all voice channels in this guild. + /// 获取此服务器中所有具有语音聊天能力的频道。 /// - /// - /// A read-only collection of voice channels found within this guild. - /// public IReadOnlyCollection VoiceChannels => [..Channels.OfType()]; /// - /// Gets a collection of all stage channels in this guild. + /// 获取此服务器中的所有分组频道。 /// - /// - /// A read-only collection of stage channels found within this guild. - /// - /// - /// Gets a collection of all category channels in this guild. - /// - /// - /// A read-only collection of category channels found within this guild. - /// public IReadOnlyCollection CategoryChannels => [..Channels.OfType()]; /// - /// Gets a collection of all channels in this guild. + /// 获取此服务器的所有频道。 /// - /// - /// A read-only collection of generic channels found within this guild. - /// public IReadOnlyCollection Channels => [.._channels.Values]; /// - /// Gets the default text channel for this guild. + /// 获取此服务器的默认文字频道。 /// - /// - /// This property retrieves default text channel for this guild. - /// - /// - /// A representing the default text channel for this guild. - /// public SocketTextChannel? DefaultChannel => TextChannels .Where(x => CurrentUser?.GetPermissions(x).ViewChannel is true) .FirstOrDefault(c => c.Id == DefaultChannelId); /// - /// Gets the welcome text channel for this guild. + /// 获取此服务器的欢迎通知频道。 /// - /// - /// This property retrieves default text channel for this guild. - /// - /// - /// A representing the default text channel for this guild. - /// public SocketTextChannel? WelcomeChannel => TextChannels .Where(c => CurrentUser?.GetPermissions(c).ViewChannel is true) .FirstOrDefault(c => c.Id == WelcomeChannelId); - /// + /// public IReadOnlyCollection Emotes => [.._emotes.Values]; /// - /// Gets a dictionary of all boost subscriptions for this guild. + /// 获取此服务器内的所有服务器助力信息。 /// - /// - /// A read-only dictionary containing all boost subscription metadata for this guild grouped by users; - /// or null if the boost subscription data has never been cached. - /// /// /// - /// - /// Only when is set to true - /// will this property be populated upon startup. Due to the lack of event support for boost subscriptions, - /// this property will never be updated. The changes of will trigger the update - /// of this property, but KOOK gateway will not publish this event resulting from the changes of total boost subscription - /// count. To fetch the latest boost subscription data, use or - /// upon a to - /// manually download the latest boost subscription data, or . - /// + /// 当 true + /// 时,Bot 启动时会自动下载所有服务器的所有助力信息。否则,此属性将为 null。调用 + /// + /// 也可以立即下载服务器的所有助力信息,下载完成后,此属性值将被设定。 + ///
+ /// 网关不会发布有关此属性值变更的事件,此属性值可能并不准确。要获取准确的服务器订阅信息,请调用 + /// 。 ///
///
- /// - /// - /// public ImmutableDictionary> BoostSubscriptions => _boostSubscriptions.ToImmutableDictionary(); /// - /// Gets a dictionary of all boost subscriptions which have not expired for this guild. + /// 获取此服务器内的所有生效中的服务器助力信息。 /// - /// - /// A read-only dictionary containing all boost subscription metadata which have not expired for this guild grouped by users; - /// or null if the boost subscription data has never been cached. - /// /// /// - /// - /// Only when is set to true - /// will this property be populated upon startup. Due to the lack of event support for boost subscriptions, - /// this property will never be updated. The changes of will trigger the update - /// of this property, but KOOK gateway will not publish this event resulting from the changes of total boost subscription - /// count. To fetch the latest boost subscription data, use or - /// upon a to - /// manually download the latest boost subscription data, or . - /// + /// 当 true + /// 时,Bot 启动时会自动下载所有服务器的所有助力信息。否则,此属性将为 null。调用 + /// + /// 也可以立即下载服务器的所有助力信息,下载完成后,此属性值将被设定。 + ///
+ /// 网关不会发布有关此属性值变更的事件,此属性值可能并不准确。要获取准确的服务器订阅信息,请调用 + /// 。 ///
///
- /// - /// - /// - public ImmutableDictionary> ValidBoostSubscriptions => + public ImmutableDictionary> ActiveBoostSubscriptions => _boostSubscriptions.Select(x => new KeyValuePair>( x.Key, [..x.Value.Where(y => y.IsValid)])) @@ -297,42 +250,19 @@ Kook.CurrentUser is not null .ToImmutableDictionary(); /// - /// Gets a collection of users in this guild. + /// 获取此服务器内缓存的所有用户。 /// /// - /// This property retrieves all users found within this guild. - /// - /// - /// This property may not always return all the members for large guilds (i.e. guilds containing - /// 100+ users). If you are simply looking to get the number of users present in this guild, - /// consider using instead. - /// - /// - /// Otherwise, you may need to enable to fetch - /// the full user list upon startup, or use to manually download - /// the users. - /// - /// + /// 要获取服务器的总成员数量,请访问 。 /// - /// - /// A collection of guild users found within this guild. - /// - /// - /// public IReadOnlyCollection Users => _members.ToReadOnlyCollection(); - /// - /// Gets a collection of all roles in this guild. - /// - /// - /// A read-only collection of roles found within this guild. - /// + /// /// /// - /// Due to the lack of event args which should contains the reordered roles data - /// when roles are reordered, this property may not be completely accurate. - /// To ensure the most accurate results, it is recommended to - /// call before this property is used. + /// 由于 KOOK 不会通过网关发布有关服务器角色重新排序的事件,此属性值可能并不准确。 + /// 要确保获取准确的服务器角色排序信息,请在使用此属性之前调用 + /// 。 /// /// public IReadOnlyCollection Roles => _roles.ToReadOnlyCollection(); @@ -391,7 +321,6 @@ internal void Update(ClientState state, IReadOnlyCollection models) if (_members.TryAdd(member.Id, member)) member.GlobalUser.AddRef(); } - DownloadedMemberCount = _members.Count; MemberCount = _members.Count; } @@ -504,12 +433,7 @@ public Task UpdateAsync(RequestOptions? options = null) => #endregion - /// - /// Gets the name of the guild. - /// - /// - /// A string that resolves to . - /// + /// public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; @@ -535,15 +459,15 @@ public Task + /// public Task> GetBansAsync(RequestOptions? options = null) => GuildHelper.GetBansAsync(this, Kook, options); - /// + /// public Task GetBanAsync(IUser user, RequestOptions? options = null) => GuildHelper.GetBanAsync(this, Kook, user.Id, options); - /// + /// public Task GetBanAsync(ulong userId, RequestOptions? options = null) => GuildHelper.GetBanAsync(this, Kook, userId, options); @@ -568,81 +492,48 @@ public Task RemoveBanAsync(ulong userId, RequestOptions? options = null) => #region Channels /// - /// Gets a channel in this guild. + /// 获取此服务器内的频道。 /// - /// The identifier for the channel. - /// - /// A generic channel associated with the specified ; null if none is found. - /// + /// 要获取的频道的 ID。 + /// 与指定的 关联的频道;如果未找到,则返回 null public SocketGuildChannel? GetChannel(ulong id) => Kook.State.GetChannel(id) as SocketGuildChannel; /// - /// Gets a text channel in this guild. + /// 获取此服务器中所有具有文字聊天能力的频道。 /// - /// The identifier for the text channel. - /// - /// A text channel associated with the specified ; null if none is found. - /// + /// 要获取的频道的 ID。 + /// 与指定的 关联的频道;如果未找到,则返回 null + /// + /// 语音频道也是一种文字频道,此方法本意用于获取具有文字聊天能力的频道。如果通过此方法传入的 ID 对应的频道是语音频道,那么也会返回对应的语音频道实体。 + /// 如需获取频道的实际类型,请参考 。 + /// public SocketTextChannel? GetTextChannel(ulong id) => GetChannel(id) as SocketTextChannel; /// - /// Gets a voice channel in this guild. + /// 获取此服务器内指定具有语音聊天能力的频道。 /// - /// The identifier for the voice channel. - /// - /// A voice channel associated with the specified ; null if none is found. - /// + /// 要获取的频道的 ID。 + /// 一个表示异步获取操作的任务。任务的结果包含与指定的 关联的频道;如果未找到,则返回 null public SocketVoiceChannel? GetVoiceChannel(ulong id) => GetChannel(id) as SocketVoiceChannel; /// - /// Gets a category channel in this guild. + /// 获取此服务器内指定的分组频道 /// - /// The snowflake identifier for the category channel. - /// - /// A category channel associated with the specified ; null if none is found. - /// + /// 要获取的频道的 ID。 + /// 与指定的 关联的频道;如果未找到,则返回 null public SocketCategoryChannel? GetCategoryChannel(ulong id) => GetChannel(id) as SocketCategoryChannel; - /// - /// Creates a new text channel in this guild. - /// - /// The new name for the text channel. - /// The delegate containing the properties to be applied to the channel upon its creation. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// text channel. - /// + /// public Task CreateTextChannelAsync(string name, Action? func = null, RequestOptions? options = null) => GuildHelper.CreateTextChannelAsync(this, Kook, name, func, options); - /// - /// Creates a new voice channel in this guild. - /// - /// 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. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// voice channel. - /// + /// public Task CreateVoiceChannelAsync(string name, Action? func = null, RequestOptions? options = null) => GuildHelper.CreateVoiceChannelAsync(this, Kook, name, func, options); - /// - /// Creates a new channel category in this guild. - /// - /// 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. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// category channel. - /// + /// public Task CreateCategoryChannelAsync(string name, Action? func = null, RequestOptions? options = null) => GuildHelper.CreateCategoryChannelAsync(this, Kook, name, func, options); @@ -683,43 +574,13 @@ internal void PurgeChannelCache(ClientState state) #endregion - // #region Invites - // - // /// - // /// Gets a collection of all invites in this guild. - // /// - // /// The options to be used when sending the request. - // /// - // /// A task that represents the asynchronous get operation. The task result contains a read-only collection of - // /// invite metadata, each representing information for an invite found within this guild. - // /// - // public Task> GetInvitesAsync(RequestOptions? options = null) - // => GuildHelper.GetInvitesAsync(this, Kook, options); - // - // #endregion - #region Roles - /// - /// Gets a role in this guild. - /// - /// The identifier for the role. - /// - /// A role that is associated with the specified ; null if none is found. - /// + /// public SocketRole? GetRole(uint id) => _roles.TryGetValue(id, out SocketRole? value) ? value : null; - /// - /// Creates a new role with the provided name. - /// - /// The new name for the role. - /// The options to be used when sending the request. - /// is null. - /// - /// A task that represents the asynchronous creation operation. The task result contains the newly created - /// role. - /// + /// public Task CreateRoleAsync(string name, RequestOptions? options = null) => GuildHelper.CreateRoleAsync(this, Kook, name, options); @@ -746,19 +607,13 @@ internal SocketRole AddOrUpdateRole(RoleModel model) #region Users /// - /// Gets a user from this guild. + /// 获取此服务器内的用户。 /// /// - /// This method retrieves a user found within this guild. - /// - /// This may return null in the WebSocket implementation due to incomplete user collection in - /// large guilds. - /// + /// 此方法可能返回 null,因为在大型服务器中,用户列表的缓存可能不完整。 /// - /// The identifier of the user. - /// - /// A guild user associated with the specified ; null if none is found. - /// + /// 要获取的用户的 ID。 + /// 与指定的 关联的用户;如果未找到,则返回 null public SocketGuildUser? GetUser(ulong id) => _members.TryGetValue(id, out SocketGuildUser? member) ? member : null; @@ -774,7 +629,6 @@ internal SocketGuildUser AddOrUpdateUser(UserModel model) SocketGuildUser member = SocketGuildUser.Create(this, Kook.State, model); member.GlobalUser.AddRef(); _members[member.Id] = member; - DownloadedMemberCount++; return member; } @@ -790,7 +644,6 @@ internal SocketGuildUser AddOrUpdateUser(MemberModel model) SocketGuildUser member = SocketGuildUser.Create(this, Kook.State, model); member.GlobalUser.AddRef(); _members[member.Id] = member; - DownloadedMemberCount++; return member; } @@ -805,7 +658,6 @@ internal SocketGuildUser AddOrUpdateCurrentUser(RichModel model) member = SocketGuildUser.Create(this, Kook.State, model); member.GlobalUser.AddRef(); _members[member.Id] = member; - DownloadedMemberCount++; } return member; @@ -815,21 +667,20 @@ internal SocketGuildUser AddOrUpdateCurrentUser(RichModel model) { if (!_members.TryRemove(id, out SocketGuildUser? member)) return null; - DownloadedMemberCount--; member.GlobalUser.RemoveRef(Kook); return member; } /// - /// Purges this guild's user cache. + /// 清除此服务器的用户缓存。 /// public void PurgeUserCache() => PurgeUserCache(_ => true); /// - /// Purges this guild's user cache. + /// 清除此服务器的用户缓存。 /// - /// The predicate used to select which users to clear. - public void PurgeUserCache(Func predicate) + /// 要清除的用户的筛选条件。 + public void PurgeUserCache(Predicate predicate) { IEnumerable membersToPurge = Users .Where(x => predicate.Invoke(x) && x.Id != Kook.CurrentUser?.Id); @@ -842,21 +693,13 @@ public void PurgeUserCache(Func predicate) } foreach (SocketGuildUser member in membersToKeep) _members.TryAdd(member.Id, member); - DownloadedMemberCount = _members.Count; } /// - /// Gets a collection of all users in this guild. + /// 获取此服务器内的所有用户。 /// - /// - /// This method retrieves all users found within this guild through REST. - /// Users returned by this method are not cached. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of guild - /// users found within this guild. - /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含此服务器内的所有用户。 public IAsyncEnumerable> GetUsersAsync(RequestOptions? options = null) { if (HasAllMembers is true) @@ -877,20 +720,15 @@ public async Task DownloadBoostSubscriptionsAsync(RequestOptions? options = null await Kook.DownloadBoostSubscriptionsAsync(new[] { this }, options).ConfigureAwait(false); /// - /// Gets a collection of users in this guild that the name or nickname contains the - /// provided string at . + /// 搜索加入到此服务器内匹配指定搜索条件的所有用户。 /// /// - /// The can not be higher than . + /// 此方法使用指定的属性搜索服务器用户。要查看可用的属性,请参考 。 /// - /// A delegate containing the properties to search users with. - /// The maximum number of users to be gotten. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains a collection of guild - /// users that matches the properties with the provided - /// at . - /// + /// 一个包含要搜索的用户属性及排序条件的委托。 + /// 搜索结果的最大数量。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果包含与提供的 中指定的属性匹配的服务器用户集合。 public IAsyncEnumerable> SearchUsersAsync( Action func, int limit = KookConfig.MaxUsersPerBatch, RequestOptions? options = null) => @@ -910,12 +748,10 @@ public Task MoveUsersAsync(IEnumerable users, IVoiceChannel targetCh #region Emotes /// - /// Gets a guild emoji in this guild. + /// 获取此服务器的指定自定义表情。 /// - /// The identifier for the guild emoji. - /// - /// A guild emoji associated with the specified ; null if none is found. - /// + /// 要获取的自定义表情的 ID。 + /// 与指定的 关联的自定义表情;如果未找到,则返回 null public GuildEmote? GetEmote(string id) => _emotes.TryGetValue(id, out GuildEmote? emote) ? emote : null; @@ -942,7 +778,6 @@ public Task CreateEmoteAsync(string name, Image image, RequestOption GuildHelper.CreateEmoteAsync(this, Kook, name, image, options); /// - /// is null. public Task ModifyEmoteNameAsync(GuildEmote emote, string name, RequestOptions? options = null) => GuildHelper.ModifyEmoteNameAsync(this, Kook, emote, name, options); @@ -1029,9 +864,6 @@ internal void ResetAllVoiceStateChannels() #region IGuild - /// - bool IGuild.Available => true; - /// void IDisposable.Dispose() { diff --git a/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs b/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs index 2dd3cbf2..cdc09571 100644 --- a/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs +++ b/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs @@ -5,7 +5,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based invite to a guild. +/// 表示一个基于网关的邀请。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketInvite : SocketEntity, IInvite @@ -13,17 +13,13 @@ public class SocketInvite : SocketEntity, IInvite /// public ulong? ChannelId { get; private set; } - /// - /// Gets the channel where this invite was created. - /// + /// public SocketGuildChannel Channel { get; } /// public ulong? GuildId { get; private set; } - /// - /// Gets the guild where this invite was created. - /// + /// public SocketGuild Guild { get; } /// @@ -47,9 +43,7 @@ public class SocketInvite : SocketEntity, IInvite /// public int InvitedUsersCount { get; private set; } - /// - /// Gets the user that created this invite if available. - /// + /// public SocketGuildUser Inviter { get; private set; } /// @@ -96,12 +90,7 @@ internal void Update(Model model) public Task DeleteAsync(RequestOptions? options = null) => InviteHelper.DeleteAsync(this, Kook, 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})"; diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs index 73d95679..40b03273 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs @@ -5,7 +5,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based message. +/// 表示一个基于网关的消息。 /// public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable { @@ -14,20 +14,10 @@ public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable private readonly List _reactions = []; private ImmutableArray _userMentions = []; - /// - /// Gets the author of this message. - /// - /// - /// A WebSocket-based user object. - /// + /// public SocketUser Author { get; } - /// - /// Gets the source channel of the message. - /// - /// - /// A WebSocket-based message channel. - /// + /// public ISocketMessageChannel Channel { get; } /// @@ -37,10 +27,10 @@ public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable public string Content { get; internal set; } /// - /// Gets the raw content of the message. + /// 获取消息的原始可读文本。 /// /// - /// This property is only available for messages that were received from the gateway. + /// 此属性值仅在从网关接收的消息中可用。 /// public string RawContent { get; internal set; } @@ -53,7 +43,7 @@ public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable /// public DateTimeOffset? EditedTimestamp { get; private set; } - /// + /// public virtual bool IsPinned { get; protected internal set; } /// @@ -65,49 +55,26 @@ public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable /// public MessageType Type { get; private set; } - /// - /// Gets the attachment included in this message. - /// + /// public virtual IReadOnlyCollection Attachments { get; private set; } - /// - /// Returns all cards included in this message. - /// - /// - /// Collection of card objects. - /// + /// public virtual IReadOnlyCollection Cards => []; - /// - /// Returns all embeds included in this message. - /// - /// - /// Collection of embed objects. - /// + /// public virtual IReadOnlyCollection Embeds => []; - /// - /// Gets a collection of the 's on the message. - /// - /// - /// Collection of poke action objects. - /// + /// public virtual IReadOnlyCollection Pokes => []; /// - /// Returns the roles mentioned in this message. + /// 获取此消息中提及的所有角色。 /// - /// - /// Collection of WebSocket-based roles. - /// public virtual IReadOnlyCollection MentionedRoles => []; /// - /// Returns the users mentioned in this message. + /// 获取此消息中提及的所有用户。 /// - /// - /// Collection of WebSocket-based users. - /// public IReadOnlyCollection MentionedUsers => _userMentions; /// @@ -244,7 +211,6 @@ internal virtual void Update(ClientState state, DirectMessageUpdateEvent model) public Task DeleteAsync(RequestOptions? options = null) => MessageHelper.DeleteAsync(this, Kook, options); - internal void AddReaction(SocketReaction reaction) => _reactions.Add(reaction); internal void RemoveReaction(SocketReaction reaction) @@ -299,12 +265,7 @@ public Task> GetReactionUsersAsync(IEmote emote, Requ #endregion - /// - /// Gets the content of the message. - /// - /// - /// Content of the message. - /// + /// public override string ToString() => Content; internal SocketMessage Clone() => (SocketMessage)MemberwiseClone(); diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs index 7bf7566f..180be403 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs @@ -3,7 +3,7 @@ namespace Kook.WebSocket; /// -/// Represents a single WebSocket-based poke action. +/// 表示一个基于网关的 POKE 动作。 /// public class SocketPokeAction : IPokeAction { diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs index ce118cb2..89274ebd 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs @@ -4,65 +4,42 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based reaction. +/// 表示一个基于网关的回应。 /// public class SocketReaction : IReaction { /// - /// Gets the ID of the user who added the reaction. + /// 获取添加此回应的用户的 ID。 /// - /// - /// This property retrieves the identifier of the user responsible for this reaction. This - /// property will always contain the user identifier in event that - /// cannot be retrieved. - /// - /// - /// A user identifier associated with the user. - /// public ulong UserId { get; } /// - /// Gets the user who added the reaction if possible. + /// 获取添加此回应的用户。 /// /// - /// - /// This property attempts to retrieve a WebSocket-cached user that is responsible for this reaction from - /// the client. In other words, when the user is not in the WebSocket cache, this property may not - /// contain a value, leaving the only identifiable information to be - /// . - /// - /// - /// If you wish to obtain an identifiable user object, consider utilizing - /// which will attempt to retrieve the user from REST. - /// + /// 如果要获取的用户实体不存在于缓存中,则此属性将返回 。 /// - /// - /// A user object where possible; a value is not always returned. - /// public IUser? User { get; internal set; } /// - /// Gets the ID of the message that has been reacted to. + /// 获取此回应所对应的消息的 ID。 /// - /// - /// A message Guid associated with the message. - /// public Guid MessageId { get; } /// - /// Gets the message that has been reacted to if possible. + /// 获取此回应所对应的消息。 /// - /// - /// A WebSocket-based message where possible; a value is not always returned. - /// + /// + /// 如果要获取的消息实体不存在于缓存中,则此属性将返回 。 + /// public IMessage? Message { get; internal set; } /// - /// Gets the channel where the reaction takes place in. + /// 获取此回应所在的消息频道。 /// - /// - /// A WebSocket-based message channel. - /// + /// + /// 如果要获取的频道实体不存在于缓存中,则此属性将返回 。 + /// public ISocketMessageChannel? Channel { get; } /// diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs index e0c44065..473b8c6b 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs @@ -4,8 +4,13 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based message sent by the system. +/// 表示一个基于网关的系统消息。 /// +/// +/// +/// KOOK 未统一规范系统消息类型,此接口并未在 之上封装更多的实用功能。 +/// +/// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketSystemMessage : SocketMessage, ISystemMessage { @@ -15,6 +20,7 @@ public class SocketSystemMessage : SocketMessage, ISystemMessage internal SocketSystemMessage(KookSocketClient kook, Guid id, ISocketMessageChannel channel, SocketUser author) : base(kook, id, channel, author, MessageSource.System) { + SystemMessageType = SystemMessageType.Unknown; } internal static new SocketSystemMessage Create(KookSocketClient kook, ClientState state, SocketUser author, diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs index 17473b20..d3ab2343 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs @@ -6,7 +6,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based message sent by a user. +/// 表示一个基于网关的用户消息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketUserMessage : SocketMessage, IUserMessage @@ -25,11 +25,8 @@ public class SocketUserMessage : SocketMessage, IUserMessage public IQuote? Quote { get; private set; } /// - /// Gets the that the message was sent from. + /// 获取此消息所属的服务器。 /// - /// - /// The that the message was sent from. - /// public SocketGuild? Guild { get; private set; } /// @@ -51,7 +48,7 @@ public class SocketUserMessage : SocketMessage, IUserMessage public override IReadOnlyCollection MentionedRoles => _roleMentions; /// - /// Gets a collection of the mentioned channels in the message. + /// 获取此消息中提及的所有频道。 /// public IReadOnlyCollection MentionedChannels => _channelMentions; @@ -393,20 +390,19 @@ internal override void Update(ClientState state, DirectMessageUpdateEvent model) } /// - /// Only the author of a message may modify the message. - /// Message content is too long, length must be less or equal to . public Task ModifyAsync(Action func, RequestOptions? options = null) => MessageHelper.ModifyAsync(this, Kook, func, options); /// - /// Transforms this message's text into a human-readable form by resolving its tags. + /// 转换消息文本中的提及与表情符号为可读形式。 /// - /// The zero-based index at which to begin the resolving for the specified value. - /// Determines how the user tag should be handled. - /// Determines how the channel tag should be handled. - /// Determines how the role tag should be handled. - /// Determines how the @everyone tag should be handled. - /// Determines how the emoji tag should be handled. + /// 指定要开始解析的位置。 + /// 指定用户提及标签的处理方式。 + /// 指定频道提及标签的处理方式。 + /// 指定角色提及标签的处理方式。 + /// 指定全体成员与在线成员提及标签的处理方式。 + /// 指定表情符号标签的处理方式。 + /// 转换后的消息文本。 public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Name, TagHandling emojiHandling = TagHandling.Name) => diff --git a/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs b/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs index fc88dd9f..fc411a87 100644 --- a/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs +++ b/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs @@ -7,19 +7,14 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based role to be given to a guild user. +/// 表示一个基于网关的可授予服务器用户的角色。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketRole : SocketEntity, IRole { #region SocketRole - /// - /// Gets the guild that owns this role. - /// - /// - /// A representing the parent guild of this role. - /// + /// public SocketGuild Guild { get; } /// @@ -50,15 +45,12 @@ public class SocketRole : SocketEntity, IRole public GuildPermissions Permissions { get; private set; } /// - /// Returns a value that determines if the role is an @everyone role. + /// 获取此角色是否为 @全体成员 角色。 /// - /// - /// true if the role is @everyone; otherwise false. - /// public bool IsEveryone => Id == 0; /// - public string KMarkdownMention => IsEveryone ? "@everyone" : MentionUtils.KMarkdownMentionRole(Id); + public string KMarkdownMention => IsEveryone ? MentionUtils.KMarkdownMentionRole("all") : MentionUtils.KMarkdownMentionRole(Id); /// public string PlainTextMention => IsEveryone ? "@全体成员" : MentionUtils.PlainTextMentionRole(Id); @@ -85,8 +77,8 @@ internal void Update(ClientState state, Model model) ColorType = model.ColorType; GradientColor = model.GradientColor; Position = model.Position; - IsHoisted = model.Hoist; - IsMentionable = model.Mentionable; + IsHoisted = model.IsHoisted; + IsMentionable = model.IsMentionable; Permissions = new GuildPermissions(model.Permissions); } @@ -99,18 +91,27 @@ public Task DeleteAsync(RequestOptions? options = null) => RoleHelper.DeleteAsync(this, Kook, options); /// - /// Gets a collection of users with this role. + /// 获取拥有此角色的用户的集合。 /// - /// The options to be used when sending the request. - /// - /// Paged collection of users with this role. - /// /// - /// If the guild this role belongs to does not has all members cached locally - /// by checking , this method will request - /// the data via REST and update the guild users cache, otherwise it will - /// return the cached data. + /// + /// 返回的集合是一个异步可枚举对象;调用 + /// + /// 可以异步枚举所有分页,并将其合并为一个集合。 + /// + ///
+ /// + /// 请勿一次性获取过多消息,这可能会导致抢占式速率限制,甚至触发实际的速率限制,从而导致 Bot 服务暂停。 + /// + ///
+ /// 此方法将尝试获取拥有此角色的所有服务器用户。此方法会根据 + /// 将请求拆分。换句话说,如果存在 500 个用户拥有此角色,而 的常量为 + /// 50,则请求将被拆分为 10 个单独请求,因此异步枚举器会异步枚举返回 10 个响应。 + /// + /// 方法可以展开这 10 个响应返回的集合,并将其合并为一个集合。 ///
+ /// 发送请求时要使用的选项。 + /// 分页的用户集合的异步可枚举对象。 public async IAsyncEnumerable> GetUsersAsync(RequestOptions? options = null) { // From SocketGuild.Users @@ -138,12 +139,7 @@ public async IAsyncEnumerable> GetUsersAsyn #endregion - /// - /// Gets the name of the role. - /// - /// - /// A string that resolves to . - /// + /// public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; diff --git a/src/Kook.Net.WebSocket/Entities/SocketEntity.cs b/src/Kook.Net.WebSocket/Entities/SocketEntity.cs index 28a6405b..3d644bc9 100644 --- a/src/Kook.Net.WebSocket/Entities/SocketEntity.cs +++ b/src/Kook.Net.WebSocket/Entities/SocketEntity.cs @@ -1,18 +1,18 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based entity. +/// 表示一个基于网关的具有唯一标识符的实体。 /// -/// The type of the entity's identifier. -public abstract class SocketEntity : IEntity - where T : IEquatable +/// 唯一标识符的类型。 +public abstract class SocketEntity : IEntity + where TId : IEquatable { internal KookSocketClient Kook { get; } /// - public T Id { get; } + public TId Id { get; } - internal SocketEntity(KookSocketClient kook, T id) + internal SocketEntity(KookSocketClient kook, TId id) { Kook = kook; Id = id; diff --git a/src/Kook.Net.WebSocket/Entities/Users/LiveStreamStatus.cs b/src/Kook.Net.WebSocket/Entities/Users/LiveStreamStatus.cs index 17e7f107..9d994c82 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/LiveStreamStatus.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/LiveStreamStatus.cs @@ -4,73 +4,73 @@ namespace Kook.WebSocket; /// -/// Represents the status of a live stream. +/// 表示一个直播状态。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct LiveStreamStatus { /// - /// Gets the voice channel that the user is currently in; or null if none. + /// 获取用户当前所在的语音频道;如果不在任何频道中则为 null。 /// public SocketVoiceChannel? VoiceChannel { get; private set; } /// - /// Gets whether the stream is live. + /// 获取此直播是否正在进行。 /// public bool IsLive { get; private set; } /// - /// Gets the number of audience members. + /// 获取此直播的观众人数。 /// public int AudienceCount { get; private set; } /// - /// Gets the maximum number of audience members. + /// 获取此直播间可容纳的最大观众人数。 /// public int AudienceLimit { get; private set; } /// - /// Gets the thumbnail of the live stream. + /// 获取此直播的封面缩略图。 /// public string? CoverThumbnail { get; private set; } /// - /// Gets the start time of the live stream. + /// 获取此直播的开始时间。 /// public DateTimeOffset? StartTime { get; private set; } /// - /// Gets the resolution of the live stream. + /// 获取此直播的分辨率。 /// public int? Resolution { get; private set; } /// - /// Gets the frame rate of the live stream. + /// 获取此直播的帧率。 /// public int? FrameRate { get; private set; } /// - /// Gets the tag of the live stream. + /// 获取此直播的标签。 /// public string Tag { get; private set; } = string.Empty; /// - /// Gets the color of the live stream. + /// // TODO: To be documented. /// public AlphaColor Color { get; private set; } /// - /// Gets the image URL of the live stream. + /// 获取此直播间图像的 URL。 /// public string Image { get; private set; } = string.Empty; /// - /// Gets the mode of the live stream. + /// 获取直播间的模式。 /// public int Mode { get; private set; } /// - /// Initializes a new instance of the structure. + /// 初始化 结构的新实例。 /// public LiveStreamStatus() { diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs index 836fad42..1482d9f7 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs @@ -9,7 +9,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based guild user. +/// 表示一个基于网关的服务器用户。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable @@ -20,9 +20,7 @@ public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable internal override SocketGlobalUser GlobalUser { get; } - /// - /// Gets the guild the user is in. - /// + /// public SocketGuild Guild { get; } /// @@ -149,34 +147,23 @@ internal override SocketPresence Presence /// public bool? IsMuted => VoiceState?.IsMuted; - /// - /// Gets the live stream status of the user. - /// + /// public LiveStreamStatus? LiveStreamStatus => VoiceState?.LiveStreamStatus; /// - /// Gets a collection of all boost subscriptions of this user for this guild. + /// 获取此用户在该服务器内的所有服务器助力信息。 /// - /// - /// A read-only collection of boost subscription metadata of this user for this guild; - /// or null if the boost subscription data has never been cached. - /// /// /// - /// - /// Only when is set to true - /// will this property be populated upon startup. Due to the lack of event support for boost subscriptions, - /// this property may be not up-to-date. The changes of will trigger the update - /// of this property, but KOOK gateway will not publish this event resulting from the changes of total boost subscription - /// count. To fetch the latest boost subscription data, use upon - /// or - /// upon a to manually download the latest boost subscription data, - /// or . - /// + /// 当 true + /// 时,Bot 启动时会自动下载所有服务器的所有助力信息。否则,此属性将为 null。调用 + /// + /// 也可以立即下载服务器的所有助力信息,下载完成后,此属性值将被设定。 + ///
+ /// 网关不会发布有关此属性值变更的事件,此属性值可能并不准确。要获取准确的服务器订阅信息,请调用 + /// 。 ///
///
- /// - /// public IReadOnlyCollection BoostSubscriptions => Guild.BoostSubscriptions? .Where(x => x.Key.Id == Id) .SelectMany(x => x.Value) @@ -184,13 +171,12 @@ internal override SocketPresence Presence ?? []; /// - /// Returns a collection of roles that the user possesses. + /// 获取此用户在该服务器内拥有的所有角色。 /// /// /// - /// Due to the lack of events which should be raised when a role is added or removed from a user, - /// this property may not be completely accurate. To ensure the most accurate results, - /// it is recommended to call before this property is used. + /// 由于网关不会发布有关服务器用户角色变更的事件,此属性值可能并不准确。要获取准确的角色信息,请在使用此属性前调用 + /// 。 /// /// public IReadOnlyCollection Roles => _roleIds @@ -198,25 +184,20 @@ internal override SocketPresence Presence .Where(x => x != null) .ToImmutableArray(); + /// /// - /// Returns the voice channel the user is in, or null if none or unknown. + ///
/// - /// If a user connects to a voice channel before the bot has connected to the gateway, - /// this property will be null until - /// or is called. - /// To ensure whether the user is in a voice channel or not, use those methods above, - /// or . + /// 默认情况下,此属性不会返回用户在 Bot 启动前所连接到的语音频道。如需让 Bot 在启动后自动获取所有用户的语音状态,请设置 + /// ,也可以在使用此属性前调用 + /// 或 /// ///
public SocketVoiceChannel? VoiceChannel => VoiceState?.VoiceChannel; /// - /// Gets the voice status of the user if any. + /// 获取此用户的语音状态。 /// - /// - /// A representing the user's voice status; null if the user is neither - /// connected to a voice channel nor is muted or deafened by the guild. - /// public SocketVoiceState? VoiceState => Guild.GetVoiceState(Id); internal SocketGuildUser(SocketGuild guild, SocketGlobalUser globalUser) @@ -274,9 +255,6 @@ internal void Update(ClientState state, RichGuild guildModel) _roleIds = [..guildModel.CurrentUserRoles]; } - /// - /// Updates the nickname of this user. - /// internal void UpdateNickname() { if (Nickname == Username) @@ -329,74 +307,34 @@ public Task KickAsync(RequestOptions? options = null) => UserHelper.KickAsync(this, Kook, options); /// - /// - /// Due to the lack of events which should be raised when a role is added to a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task AddRoleAsync(uint roleId, RequestOptions? options = null) => - AddRolesAsync(new[] { roleId }, options); + AddRolesAsync([roleId], options); /// - /// - /// Due to the lack of events which should be raised when a role is added to a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task AddRoleAsync(IRole role, RequestOptions? options = null) => AddRoleAsync(role.Id, options); /// - /// - /// Due to the lack of events which should be raised when a role is added to a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task AddRolesAsync(IEnumerable roleIds, RequestOptions? options = null) => SocketUserHelper.AddRolesAsync(this, Kook, roleIds, options); /// - /// - /// Due to the lack of events which should be raised when a role is added to a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task AddRolesAsync(IEnumerable roles, RequestOptions? options = null) => AddRolesAsync(roles.Select(x => x.Id), options); /// - /// - /// Due to the lack of events which should be raised when a role is removed from a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task RemoveRoleAsync(uint roleId, RequestOptions? options = null) => - RemoveRolesAsync(new[] { roleId }, options); + RemoveRolesAsync([roleId], options); /// - /// - /// Due to the lack of events which should be raised when a role is removed from a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task RemoveRoleAsync(IRole role, RequestOptions? options = null) => RemoveRoleAsync(role.Id, options); /// - /// - /// Due to the lack of events which should be raised when a role is removed from a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task RemoveRolesAsync(IEnumerable roleIds, RequestOptions? options = null) => SocketUserHelper.RemoveRolesAsync(this, Kook, roleIds, options); /// - /// - /// Due to the lack of events which should be raised when a role is removed from a user, - /// the property will not be updated immediately after - /// calling this method. To update the cached roles of this user, please use . - /// public Task RemoveRolesAsync(IEnumerable roles, RequestOptions? options = null) => RemoveRolesAsync(roles.Select(x => x.Id)); @@ -416,7 +354,7 @@ public Task UnmuteAsync(RequestOptions? options = null) => public Task UndeafenAsync(RequestOptions? options = null) => GuildHelper.UndeafenUserAsync(this, Kook, options); - /// + /// public async Task> GetConnectedVoiceChannelsAsync(RequestOptions? options = null) { IReadOnlyCollection channels = @@ -425,14 +363,7 @@ public async Task> GetConnectedVoiceChan return channels; } - /// - /// Fetches the users data from the REST API to update this object, - /// especially the property. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous reloading operation. - /// + /// public Task UpdateAsync(RequestOptions? options = null) => SocketUserHelper.UpdateAsync(this, Kook, options); @@ -464,6 +395,9 @@ async Task> IGuildUser.GetConnectedVoiceChann /// IVoiceChannel? IVoiceState.VoiceChannel => VoiceChannel; + /// + IReadOnlyCollection IVoiceState.VoiceChannels => VoiceState?.VoiceChannels ?? []; + #endregion private string DebuggerDisplay => diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs index cc5a1094..be7105aa 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs @@ -3,7 +3,7 @@ namespace Kook.WebSocket; /// -/// Represents the WebSocket user's presence status. This may include their online status and their activity. +/// 表示一个基于网关的用户实时状态。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketPresence : IPresence @@ -38,15 +38,6 @@ internal void Update(bool? isOnline, string? activeClient) ActiveClient = ConvertClientType(activeClient); } - /// - /// The client type where a user is active. - /// - /// - /// A string representing the client type. - /// - /// - /// A that this user is active. - /// private static ClientType? ConvertClientType(string? clientType) { if (string.IsNullOrWhiteSpace(clientType)) diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs index 52680db5..6b8763d0 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs @@ -5,7 +5,7 @@ namespace Kook.WebSocket; /// -/// Represents the logged-in WebSocket-based user. +/// 表示一个基于网关的当前登录的用户信息。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketSelfUser : SocketUser, ISelfUser, IUpdateable @@ -142,14 +142,7 @@ internal bool Update(ClientState state, Model model) return hasChanged; } - /// - /// Fetches the users data from the REST API to update this object, - /// especially the property. - /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous reloading operation. - /// + /// public Task UpdateAsync(RequestOptions? options = null) => SocketUserHelper.UpdateAsync(this, Kook, options); diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs index 327ff7af..5cac8870 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs @@ -3,10 +3,10 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based user that is yet to be recognized by the client. +/// 表示一个基于网关的未知用户。 /// /// -/// A user may not be recognized due to the user missing from the cache or failed to be recognized properly. +/// 如果用户未能被识别,或缓存中不存在该用户,则会使用此类型的用户实体设置需要用户实体的属性。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SocketUnknownUser : SocketUser @@ -47,15 +47,12 @@ public class SocketUnknownUser : SocketUser /// public override IReadOnlyCollection Nameplates { get; internal set; } = []; - /// internal override SocketPresence Presence { get => new(); set { } } - /// - /// This field is not supported for an unknown user. internal override SocketGlobalUser GlobalUser => throw new NotSupportedException(); internal SocketUnknownUser(KookSocketClient kook, ulong id) diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs index 73ca8384..a9790bc8 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs @@ -7,7 +7,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based user. +/// 表示一个基于网关的用户。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public abstract class SocketUser : SocketEntity, IUser @@ -70,12 +70,7 @@ public abstract class SocketUser : SocketEntity, IUser /// public ClientType? ActiveClient => Presence?.ActiveClient; - /// - /// Initializes a new WebSocket-based user. - /// - /// The WebSocket client. - /// The identifier of the user. - protected SocketUser(KookSocketClient kook, ulong id) + internal SocketUser(KookSocketClient kook, ulong id) : base(kook, id) { IsSystemUser = Id == KookConfig.SystemMessageAuthorID; @@ -128,15 +123,15 @@ internal virtual void UpdatePresence(bool? isOnline, string? activeClient) Presence.Update(isOnline, activeClient); } - /// + /// public async Task CreateDMChannelAsync(RequestOptions? options = null) => await SocketUserHelper.CreateDMChannelAsync(this, Kook, options).ConfigureAwait(false); - /// + /// public Task GetIntimacyAsync(RequestOptions? options = null) => UserHelper.GetIntimacyAsync(this, Kook, options); - /// + /// public async Task UpdateIntimacyAsync(Action func, RequestOptions? options = null) => await UserHelper.UpdateIntimacyAsync(this, Kook, func, options).ConfigureAwait(false); @@ -157,11 +152,10 @@ public Task RemoveFriendAsync(RequestOptions? options = null) => UserHelper.RemoveFriendAsync(this, Kook, options); /// - /// Gets the full name of the user (e.g. Example#0001). + /// 获取此用户的包含用户名及识别号的格式化字符串。 /// - /// - /// The full name of the user. - /// + /// 一个表示此用户的包含用户名及识别号的格式化字符串。 + /// public override string ToString() => Format.UsernameAndIdentifyNumber(this, Kook.FormatUsersInBidirectionalUnicode); private string DebuggerDisplay => @@ -180,9 +174,5 @@ async Task IUser.CreateDMChannelAsync(RequestOptions? options) => async Task IUser.GetIntimacyAsync(RequestOptions? options) => await GetIntimacyAsync(options).ConfigureAwait(false); - /// - async Task IUser.UpdateIntimacyAsync(Action func, RequestOptions? options) => - await UpdateIntimacyAsync(func, options).ConfigureAwait(false); - #endregion } diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs index a8b2b8be..e205eb3e 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs @@ -1,25 +1,21 @@ using System.Collections.Concurrent; -using System.Collections.Immutable; -using System.Collections.ObjectModel; using System.Diagnostics; namespace Kook.WebSocket; /// -/// Represents a WebSocket user's voice connection status. +/// 表示一个基于网关的用户的语音连接状态。 /// [DebuggerDisplay("{DebuggerDisplay,nq}")] public struct SocketVoiceState : IVoiceState { private readonly ConcurrentDictionary _voiceChannels; - /// - /// Initializes a default with everything set to null or false. - /// + /// public static SocketVoiceState Default => new(); /// - /// Initializes a new with the specified voice channel. + /// 初始化一个 结构的新实例。 /// public SocketVoiceState() { @@ -27,16 +23,15 @@ public SocketVoiceState() } /// - /// Gets the voice channel that the user is currently in; or null if none. + /// 获取用户当前所在的语音频道;如果不在任何频道中则为 null。 /// public SocketVoiceChannel? VoiceChannel => _voiceChannels.Values.FirstOrDefault(); /// - /// Gets a collection of voice channels that the user is connected to. + /// 获取用户连接到的所有语音频道。 /// /// - /// Currently, KOOK only allows a user to be in one voice channel at a time, - /// but allows a Bot user to be in multiple voice channels at a time. + /// 目前,KOOK 仅允许用户同时连接到一个语音频道,但允许 Bot 用户同时连接到多个语音频道。 /// public IReadOnlyCollection VoiceChannels => [.._voiceChannels.Values]; @@ -47,7 +42,7 @@ public SocketVoiceState() public bool? IsDeafened { get; private set; } /// - /// Gets the live stream status of the user. + /// 获取用户的直播状态。 /// public LiveStreamStatus? LiveStreamStatus { get; private set; } @@ -88,11 +83,8 @@ internal void Update(SocketVoiceChannel? voiceChannel, API.Gateway.LiveInfo mode } /// - /// Gets the name of this voice channel. + /// 获取此语音状态所属语音频道的名称。 /// - /// - /// A string that resolves to name of this voice channel; otherwise "Unknown". - /// public override string ToString() => VoiceChannel?.Name ?? "Unknown"; private string DebuggerDisplay => @@ -114,4 +106,7 @@ internal void Update(SocketVoiceChannel? voiceChannel, API.Gateway.LiveInfo mode /// IVoiceChannel? IVoiceState.VoiceChannel => VoiceChannel; + + /// + IReadOnlyCollection IVoiceState.VoiceChannels => VoiceChannels; } diff --git a/src/Kook.Net.WebSocket/GatewayReconnectException.cs b/src/Kook.Net.WebSocket/GatewayReconnectException.cs index 71d1d8c0..e37e87b6 100644 --- a/src/Kook.Net.WebSocket/GatewayReconnectException.cs +++ b/src/Kook.Net.WebSocket/GatewayReconnectException.cs @@ -1,15 +1,14 @@ namespace Kook.WebSocket; /// -/// The exception thrown when the gateway client has been requested to reconnect. +/// 当网关客户端被请求重新连接时引发的异常。 /// public class GatewayReconnectException : Exception { /// - /// Initializes a new instance of the class with the reconnection - /// message. + /// 初始化一个带有重新连接消息的 类的新实例。 /// - /// The reason why the gateway has been requested to reconnect. + /// 包含要求客户端重新连接原因的消息。 public GatewayReconnectException(string message) : base(message) { diff --git a/src/Kook.Net.WebSocket/KookSocketClient.Events.cs b/src/Kook.Net.WebSocket/KookSocketClient.Events.cs index 5931e15f..5f964599 100644 --- a/src/Kook.Net.WebSocket/KookSocketClient.Events.cs +++ b/src/Kook.Net.WebSocket/KookSocketClient.Events.cs @@ -4,7 +4,9 @@ public partial class KookSocketClient { #region General - /// Fired when connected to the Kook gateway. + /// + /// 当连接到 KOOK 网关时引发。 + /// public event Func Connected { add => _connectedEvent.Add(value); @@ -13,7 +15,9 @@ public event Func Connected internal readonly AsyncEvent> _connectedEvent = new(); - /// Fired when disconnected to the Kook gateway. + /// + /// 当与 KOOK 网关断开连接时引发。 + /// public event Func Disconnected { add => _disconnectedEvent.Add(value); @@ -23,15 +27,10 @@ public event Func Disconnected internal readonly AsyncEvent> _disconnectedEvent = new(); /// - /// Fired when guild data has finished downloading. + /// 当此 Bot 准备就绪以供用户代码访问时引发。 /// /// - /// - /// Because guilds may contain a large amount of members, - /// this event will not wait for all users, subscriptions, and voice states - /// to be downloaded. It will only wait for guilds, channels, roles, and - /// emojis to be downloaded. - /// + /// 此事件引发的时机可由 配置指定。 /// public event Func Ready { @@ -41,7 +40,16 @@ public event Func Ready private readonly AsyncEvent> _readyEvent = new(); - /// Fired when a heartbeat is received from the Kook gateway. + /// + /// 当网关延迟已更新时引发。 + /// + /// + /// 事件参数: + /// + /// 参数是更新前的延迟(毫秒)。 + /// 参数是更新后的延迟(毫秒)。 + /// + /// public event Func LatencyUpdated { add => _latencyUpdatedEvent.Add(value); diff --git a/src/Kook.Net.WebSocket/KookSocketClient.cs b/src/Kook.Net.WebSocket/KookSocketClient.cs index 5f26413a..dae9390e 100644 --- a/src/Kook.Net.WebSocket/KookSocketClient.cs +++ b/src/Kook.Net.WebSocket/KookSocketClient.cs @@ -18,7 +18,7 @@ namespace Kook.WebSocket; /// -/// Represents a WebSocket-based KOOK client. +/// 表示一个基于网关的 KOOK 客户端。 /// public partial class KookSocketClient : BaseSocketClient, IKookClient { @@ -76,32 +76,27 @@ public partial class KookSocketClient : BaseSocketClient, IKookClient public override IReadOnlyCollection Guilds => State.Guilds; /// - /// Gets a collection of direct message channels opened in this session. + /// 获取在此会话中存在的所有私聊频道。 /// /// - /// This method returns a collection of currently opened direct message channels. /// - /// This method will not return previously opened DM channels outside of the current session! If you - /// have just started the client, this may return an empty collection. + /// 此属性不会包含在当前会话之外创建的私聊会话的私聊频道实体,如果此 Bot 刚刚启动,此属性可能会返回一个空集合。 /// /// - /// - /// A collection of DM channels that have been opened in this session. - /// public IReadOnlyCollection DMChannels => State.DMChannels.Where(x => x is not null).ToImmutableArray(); /// - /// Initializes a new REST/WebSocket-based Kook client. + /// 初始化一个 类的新实例。 /// public KookSocketClient() : this(new KookSocketConfig()) { } /// - /// Initializes a new REST/WebSocket-based Kook client with the provided configuration. + /// 初始化一个 类的新实例。 /// - /// The configuration to be used with the client. + /// 用于配置此客户端的配置对象。 public KookSocketClient(KookSocketConfig config) : this(config, CreateApiClient(config)) { } @@ -275,14 +270,11 @@ private protected void ResetCounter() public override SocketDMChannel? GetDMChannel(ulong userId) => State.GetDMChannel(userId); /// - /// Gets a generic channel from the cache or does a rest request if unavailable. + /// 获取一个频道。 /// - /// The identifier of the channel. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the channel associated - /// with the identifier; null when the channel cannot be found. - /// + /// 频道的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的频道;若指定 ID 的频道不存在,则为 null public async Task GetChannelAsync(ulong id, RequestOptions? options = null) { if (GetChannel(id) is { } channel) return channel; @@ -290,37 +282,33 @@ public async Task GetChannelAsync(ulong id, RequestOptions? options = } /// - /// Gets a direct message channel from the cache or does a rest request if unavailable. + /// 获取一个私聊频道。 /// - /// The identifier of the channel. - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the channel associated - /// with the identifier; null when the channel cannot be found. - /// + /// 私聊频道的聊天代码。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定聊天代码的私聊频道;若指定聊天代码的私聊频道不存在,则为 null public async Task GetDMChannelAsync(Guid chatCode, RequestOptions? options = null) => await ClientHelper.GetDMChannelAsync(this, chatCode, options).ConfigureAwait(false); /// - /// Gets a collection of direct message channels from the cache or does a rest request if unavailable. + /// 获取当前会话中已创建的所有私聊频道。 /// - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the channel associated - /// with the identifier; null when the channel cannot be found. - /// + /// + /// + /// 此方法不会返回当前会话之外已创建的私聊频道。如果客户端刚刚启动,这可能会返回一个空集合。 + /// + /// + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是当前会话中已创建的所有私聊频道。 public async Task> GetDMChannelsAsync(RequestOptions? options = null) => (await ClientHelper.GetDMChannelsAsync(this, options).ConfigureAwait(false)).ToImmutableArray(); /// - /// Gets a user from the cache or does a rest request if unavailable. + /// 获取一个用户。 /// - /// The identifier of the user (e.g. `168693960628371456`). - /// The options to be used when sending the request. - /// - /// A task that represents the asynchronous get operation. The task result contains the user associated with - /// the identifier; null if the user is not found. - /// + /// 用户的 ID。 + /// 发送请求时要使用的选项。 + /// 一个表示异步获取操作的任务。任务的结果是具有指定 ID 的用户;若指定 ID 的用户不存在,则为 null public async Task GetUserAsync(ulong id, RequestOptions? options = null) { if (GetUser(id) is { } user) return user; @@ -350,13 +338,7 @@ internal SocketGlobalUser GetOrCreateSelfUser(ClientState state, User model) => internal void RemoveUser(ulong id) => State.RemoveUser(id); - /// - /// Downloads all users for the specified guilds. - /// - /// - /// The guilds to download the users for. If null, all available guilds will be downloaded. - /// - /// The options to be used when sending the request. + /// public override async Task DownloadUsersAsync(IEnumerable? guilds = null, RequestOptions? options = null) { if (ConnectionState != ConnectionState.Connected) return; @@ -379,13 +361,7 @@ private async Task ProcessUserDownloadsAsync(IEnumerable guilds, Re } } - /// - /// Downloads all voice states for the specified guilds. - /// - /// - /// The guilds to download the voice states for. If null, all available guilds will be downloaded. - /// - /// The options to be used when sending the request. + /// public override async Task DownloadVoiceStatesAsync(IEnumerable? guilds = null, RequestOptions? options = null) { @@ -426,15 +402,7 @@ private async Task ProcessVoiceStateDownloadsAsync(IEnumerable guil } } - /// - /// Downloads all boost subscriptions for the specified guilds. - /// - /// - /// The guilds to download the boost subscriptions for. If null, all available guilds will be downloaded. - /// To download all boost subscriptions, the current user must has the - /// permission. - /// - /// The options to be used when sending the request. + /// public override async Task DownloadBoostSubscriptionsAsync(IEnumerable? guilds = null, RequestOptions? options = null) { @@ -460,13 +428,6 @@ private async Task ProcessBoostSubscriptionsDownloadsAsync(IEnumerable - /// Processes a message received from the gateway. - /// - /// The type of the gateway socket frame. - /// The sequence number of the message. - /// The payload of the message. - /// Unknown event type. internal virtual async Task ProcessMessageAsync(GatewaySocketFrameType gatewaySocketFrameType, int? sequence, JsonElement payload) { if (sequence.HasValue) diff --git a/src/Kook.Net.WebSocket/KookSocketConfig.cs b/src/Kook.Net.WebSocket/KookSocketConfig.cs index 94c34041..ee356a0b 100644 --- a/src/Kook.Net.WebSocket/KookSocketConfig.cs +++ b/src/Kook.Net.WebSocket/KookSocketConfig.cs @@ -7,15 +7,13 @@ namespace Kook.WebSocket; /// -/// Represents a configuration class for . +/// 表示一个用于 的配置类。 /// /// -/// This configuration, based on , helps determine several key configurations the -/// socket client depend on. For instance, message cache and connection timeout. +/// 此配置基于 ,在与 REST 有关的配置的基础上,定义了有关网关的配置。 /// /// -/// The following config enables the message cache and configures the client to always download user upon guild -/// availability. +/// 以下代码启用了消息缓存,并配置客户端在服务器可用时始终下载用户。 /// /// var config = new KookSocketConfig /// { @@ -28,131 +26,130 @@ namespace Kook.WebSocket; public class KookSocketConfig : KookRestConfig { /// - /// Returns the encoding gateway should use. + /// 获取网关使用的数据格式。 /// public const string GatewayEncoding = "json"; /// - /// Gets or sets the WebSocket host to connect to. If null, the client will use the - /// /gateway endpoint. + /// 获取或设置要连接的网关地址。如果为 null,则客户端将会通过 API 请求获取网关地址。 /// public string? GatewayHost { get; set; } /// - /// Gets or sets the time, in milliseconds, to wait for a connection to complete before aborting. + /// 获取或设置连接到网关时的超时时间间隔(毫秒)。 /// public int ConnectionTimeout { get; set; } = 6000; /// - /// Gets the heartbeat interval of WebSocket connection in milliseconds. + /// 获取网关发送心跳包的时间间隔(毫秒)。 /// public int HeartbeatIntervalMilliseconds { get; internal set; } = 30000; /// - /// Gets the RTCP interval of RTP connection in milliseconds. + /// 获取语音客户端 RTP 连接中发送 RTCP 数据报的时间间隔(毫秒)。 /// public const int RtcpIntervalMilliseconds = 5000; /// - /// Gets or sets the timeout for event handlers, in milliseconds, after which a warning will be logged. - /// Setting this property to nulldisables this check. + /// 获取或设置阻塞网关线程的事件处理程序的超时时间间隔(毫秒),超过此时间间隔的阻塞网关线程的事件处理程序会被日志记录警告。将此属性设置为 null 将禁用此检查。 /// public int? HandlerTimeout { get; set; } = 3000; /// - /// Gets or sets the threshold quantity considered as joining a small number of guilds. + /// 获取或设置被视为加入少量服务器的阈值数量。 /// + /// public uint SmallNumberOfGuildsThreshold { get; set; } = 5; /// - /// Get or set the threshold quantity considered as joining a large number of guilds. + /// 获取或设置被视为加入大量服务器的阈值数量。 /// + /// public uint LargeNumberOfGuildsThreshold { get; set; } = 50; /// - /// Gets or sets the number of messages per channel that should be kept in cache. Setting this to zero - /// disables the message cache entirely. + /// 获取或设置应在缓存中保留的每个频道的消息数量。将此属性设置为零将完全禁用消息缓存。 /// public int MessageCacheSize { get; set; } = 10; /// - /// Gets or sets the provider used to generate new WebSocket connections. + /// 获取或设置用于创建 WebSocket 客户端的委托。 /// public WebSocketProvider WebSocketProvider { get; set; } /// - /// Gets or sets the provider used to generate new UDP sockets. + /// 获取或设置用于创建 UDP 客户端的委托。 /// public UdpSocketProvider UdpSocketProvider { get; set; } /// - /// Gets or sets the startup mode of the socket client. + /// 获取或设置在启动时缓存获取模式。 /// + /// + /// 此属性用于指定客户端在启动时如何缓存基础数据,并影响 事件的引发时机。
+ /// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 + ///
public StartupCacheFetchMode StartupCacheFetchMode { get; set; } = StartupCacheFetchMode.Auto; /// - /// Gets or sets the timeout for the audio client to be considered idle, in milliseconds. + /// 获取或设置音频客户端被视为空闲的超时时间间隔(毫秒)。 /// public int AudioClientIdleTimeout { get; set; } = 15000; /// - /// Gets or sets whether or not all users should be downloaded as guilds come available. + /// 获取或设置是否在服务器可用时始终下载所有用户。 /// /// /// - /// Setting this property to true will cause the client to download all users - /// for all guilds upon startup. - /// Please note that it can be difficult to fill the cache completely on large guilds depending on the - /// traffic. If you are experiencing issues, try setting this to false and manually call - /// on the guilds you want. + /// 对于大型服务器,启用此选项可能会导致性能问题。调用 + /// + /// 可以按需下载服务器用户列表。 /// /// public bool AlwaysDownloadUsers { get; set; } = false; /// - /// Gets or sets whether or not all voice states should be downloaded as guilds come available. + /// 获取或设置是否在服务器可用时始终下载所有语音状态。 /// /// /// - /// Setting this property to true will cause the client to download all voice states - /// for all guilds upon startup. - /// Please note that it can be difficult to fill the cache completely on large guilds depending on the - /// traffic. If you are experiencing issues, try setting this to false and manually call - /// on the guilds you want. + /// 对于大型服务器,启用此选项可能会导致性能问题。调用 + /// + /// 可以按需下载服务器语音状态。 /// /// public bool AlwaysDownloadVoiceStates { get; set; } = false; /// - /// Gets or sets whether or not all boost subscriptions should be downloaded as guilds come available. + /// 获取或设置是否在服务器可用时始终下载所有服务器的所有服务器助力信息。 /// /// /// - /// Setting this property to true will cause the client to download all boost subscriptions - /// for all guilds upon startup and when is triggered with - /// changes occurring to . - /// Please note that it can be difficult to fill the cache completely on large guilds depending on the - /// traffic. If you are experiencing issues, try setting this to false and manually call - /// on the guilds you want. + /// 当此属性为 true 时,客户端将在启动时下载所有服务器的所有服务器助力信息,并在引发 + /// 事件时,当 + /// 发生更改时,也会重新下载所有服务器的所有服务器助力信息。
+ /// 对于大型服务器,启用此选项可能会导致性能问题。调用 + /// + /// 可以按需下载服务器的所有服务器助力信息。 ///
///
public bool AlwaysDownloadBoostSubscriptions { get; set; } = false; /// - /// Gets or sets the maximum number of times to retry fetching joined guild data. + /// 获取或设置获取新加入服务器数据的最大重试次数。 /// /// - /// Due to the KOOK API cannot return the newly joined guilds immediately well, this property is used to - /// control the maximum number of times to retry fetching joined guild data. Each retry will be delayed - /// by milliseconds. Set to 0 or negative value to disable - /// retrying. + /// KOOK API 无法立即返回刚刚新加入的服务器数据,因此此属性用于控制获取加入的服务器数据的最大重试次数。 + /// 每次重试前都会等待 + /// 毫秒。将当前属性设置为 0 或负值以禁用重试。 /// public int MaxJoinedGuildDataFetchingRetryTimes { get; set; } = 10; /// - /// Gets or sets the delay in milliseconds between each retry of fetching joined guild data. + /// 获取或设置获取新加入服务器数据每次重试之前所等待的时间间隔(毫秒)。 /// - /// Value must be at least 0. + /// 时间间隔不能小于 0 + /// public int JoinedGuildDataFetchingRetryDelay { get => _joinedGuildDataFetchingRetryDelay; @@ -166,22 +163,22 @@ public int JoinedGuildDataFetchingRetryDelay private int _joinedGuildDataFetchingRetryDelay = 500; /// - /// Gets or sets whether to update guild role positions via API when fires. + /// 获取或设置是否在引发 事件时通过 API 更新服务器角色位置。 /// public bool AutoUpdateRolePositions { get; set; } = false; /// - /// Gets or sets whether to update guild channels via API when gateway publishes sort_channel events. + /// 获取或设置是否在网关发布 sort_channel 事件时通过 API 更新服务器频道。 /// public bool AutoUpdateChannelPositions { get; set; } = false; /// - /// Gets or sets the provider used to generate new message queues. + /// 获取或设置用于创建消息队列的委托。 /// public MessageQueueProvider MessageQueueProvider { get; set; } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public KookSocketConfig() { diff --git a/src/Kook.Net.WebSocket/KookSocketRestClient.cs b/src/Kook.Net.WebSocket/KookSocketRestClient.cs index 85d24ec1..da72ebba 100644 --- a/src/Kook.Net.WebSocket/KookSocketRestClient.cs +++ b/src/Kook.Net.WebSocket/KookSocketRestClient.cs @@ -3,7 +3,7 @@ namespace Kook.WebSocket; /// -/// Represents an REST-only client that is used in a WebSocket-based client. +/// 表示一个用于网关客户端内的 REST 客户端。 /// public class KookSocketRestClient : KookRestClient { @@ -11,21 +11,16 @@ internal KookSocketRestClient(KookRestConfig config, API.KookRestApiClient api) { } - /// - /// Throws a when trying to log in. - /// - /// The Socket REST wrapper cannot be used to log in or out. + /// + /// 网关客户端内的 REST 客户端无法进行登录或退出登录。 public new Task LoginAsync(TokenType tokenType, string token, bool validateToken = true) => throw new NotSupportedException("The Socket REST wrapper cannot be used to log in or out."); internal override Task LoginInternalAsync(TokenType tokenType, string token, bool validateToken) => throw new NotSupportedException("The Socket REST wrapper cannot be used to log in or out."); - /// - /// Throws a when trying to log out. - /// - /// - /// The Socket REST wrapper cannot be used to log in or out. + /// + /// 网关客户端内的 REST 客户端无法进行登录或退出登录。 public new Task LogoutAsync() => throw new NotSupportedException("The Socket REST wrapper cannot be used to log in or out."); diff --git a/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs b/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs index 6a569671..172bfab7 100644 --- a/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs +++ b/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs @@ -1,11 +1,4 @@ using Kook.Net.Udp; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Serialization; - -#if DEBUG_AUDIO -using System.Diagnostics; -#endif namespace Kook.Audio; diff --git a/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs b/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs index c9a94623..b0fb76a6 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs @@ -42,7 +42,6 @@ private void Dispose(bool disposing) public void Dispose() => Dispose(true); - public async Task StartAsync() { await _lock.WaitAsync(CancellationToken.None).ConfigureAwait(false); diff --git a/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs b/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs index b5868885..af94837e 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs @@ -1,12 +1,14 @@ namespace Kook.Net.Udp; /// -/// Represents a delegate that provides a instance. +/// 表示一个默认的 ,用于创建 +/// 的默认实现的实例。 /// public static class DefaultUdpSocketProvider { /// - /// A delegate that creates a default instance. + /// 获取一个默认的 委托,用于创建 + /// 的默认实现的实例。 /// public static readonly UdpSocketProvider Instance = () => { diff --git a/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs b/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs index 982099ec..858cc2b3 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs @@ -3,27 +3,28 @@ namespace Kook.Net.WebSockets; /// -/// Represents a default that creates instances. +/// 表示一个默认的 ,用于创建 +/// 的默认实现的实例。 /// public static class DefaultWebSocketProvider { /// - /// A delegate that creates a default instance. + /// 获取一个默认的 委托,用于创建 + /// 的默认实现的实例。 /// public static readonly WebSocketProvider Instance = Create(); /// - /// Creates a delegate that creates a new instance. + /// 创建一个新的 委托。 /// - /// The proxy to use. - /// A delegate that creates a new instance. - /// The default WebSocketProvider is not supported on this platform. - public static WebSocketProvider Create(IWebProxy? proxy = null) => + /// 是否使用系统代理。 + /// 一个新的 委托。 + public static WebSocketProvider Create(IWebProxy? useProxy = null) => () => { try { - return new DefaultWebSocketClient(proxy); + return new DefaultWebSocketClient(useProxy); } catch (PlatformNotSupportedException ex) { diff --git a/src/Kook.Net.WebSocket/StartupCacheFetchMode.cs b/src/Kook.Net.WebSocket/StartupCacheFetchMode.cs index 84cda527..24f6abfc 100644 --- a/src/Kook.Net.WebSocket/StartupCacheFetchMode.cs +++ b/src/Kook.Net.WebSocket/StartupCacheFetchMode.cs @@ -1,55 +1,53 @@ namespace Kook.WebSocket; /// -/// Represents the mode in which the socket client fetches the cache when starting up. +/// 表示基于网关的客户端在启动时缓存基础数据的模式。 /// +/// +/// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 +/// public enum StartupCacheFetchMode { /// - /// Automatically selects the best mode based on the number of guilds. + /// 根据服务器数量自动选择最佳模式。 /// /// - /// If the number of guilds reaches value of - /// , - /// the mode will be ; - /// otherwise, if that reaches value of - /// , - /// the mode will be ; - /// otherwise, the mode will be . + /// 如果服务器数量达到了 + /// 的值,模式将为 ;否则,如果达到了 + /// + /// 的值,模式将为 ; + /// 否则,模式将为 。 /// - /// . Auto, /// - /// Fetches the cache synchronously. + /// 同步主动获取。 /// /// - /// When the socket client starts up, it will proactively fetch all the basic data from the KOOK API. - /// The event will be triggered - /// after the data fetching is complete. + /// 当客户端启动时,将主动通过 KOOK API 获取所有服务器基础数据,数据获取完成后引发 + /// 事件。
+ /// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 ///
Synchronous, /// - /// Fetches the cache asynchronously. + /// 异步主动获取。 /// /// - /// When the socket client starts up, it will trigger the - /// event as soon as possible, then start a background task to fetch all the basic data from the KOOK API. - /// If an event related to a guild is received during this period and the basic data for that guild has not - /// yet been fetched, the event handler will fetch the basic data for that server before triggering - /// the event subscribed to by the user code. + /// 当客户端启动时,将尽快引发 事件,然后启动一个后台任务,通过 + /// KOOK API 获取所有服务器基础数据。如果在基础数据获取期间接收到与服务器相关的事件,但该服务器的基础数据尚未获取, + /// 事件处理程序将在引发用户代码订阅的事件之前获取该服务器的基础数据。
+ /// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 ///
Asynchronous, /// - /// Fetches the cache lazily. + /// 被动获取。 /// /// - /// When the socket client starts up, it will trigger the - /// event as soon as possible. When an event related to a guild is received and the basic data for that guild - /// has not yet been fetched, the event handler will fetch the basic data for that server before triggering - /// the event subscribed to by the user code. + /// 当客户端启动时,将尽快引发 + /// 事件。当接收到与服务器相关的事件,但该服务器的基础数据尚未获取时,事件处理程序将在引发用户代码订阅的事件之前获取该服务器的基础数据。
+ /// 缓存基础数据包括服务器基本信息、频道、角色、频道权限重写、当前用户在服务器内的昵称。 ///
Lazy } diff --git a/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookClient.cs b/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookClient.cs index 89f5f23c..adfffa02 100644 --- a/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookClient.cs +++ b/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookClient.cs @@ -5,39 +5,30 @@ namespace Kook.Webhook.AspNet; /// -/// Represents a KOOK webhook client using ASP.NET. +/// 表示一个使用 ASP.NET 的 KOOK Webhook 客户端。 /// public class KookAspNetWebhookClient : KookWebhookClient, IHostedService { - /// - /// Initializes a new instance of the class. - /// - /// The to configure the KOOK ASP.NET webhook client with. internal KookAspNetWebhookClient(IOptions config) : base(config.Value) { } - /// - /// Initializes a new instance of the class. - /// - /// The to configure the KOOK ASP.NET webhook client with. internal KookAspNetWebhookClient(KookAspNetWebhookConfig config) : base(config) { } - /// - /// Gets the configuration used by this client. - /// internal new KookAspNetWebhookConfig BaseConfig => base.BaseConfig as KookAspNetWebhookConfig ?? throw new InvalidOperationException("The base configuration is not a Webhook-based configuration for ASP.NET."); /// + /// KOOK Webhook 客户端不支持手动启动。 public override Task StartAsync() => throw new NotSupportedException("Webhook client does not support starting manually."); /// + /// KOOK Webhook 客户端不支持手动停止。 public override Task StopAsync() => throw new NotSupportedException("Webhook client does not support stopping manually."); diff --git a/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookConfig.cs b/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookConfig.cs index 4d9f356c..e568620f 100644 --- a/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookConfig.cs +++ b/src/Kook.Net.Webhook.AspNet/KookAspNetWebhookConfig.cs @@ -3,32 +3,35 @@ namespace Kook.Webhook.AspNet; /// -/// Represents a KOOK webhook client configuration for ASP.NET. +/// 表示一个用于 的配置类。 /// +/// +/// 此配置基于 ,在与 Webhook 有关的配置的基础上,定义了有关在 ASP.NET 内继承 KOOK Webhook 的配置。 +/// public class KookAspNetWebhookConfig : KookWebhookConfig { /// - /// Gets or sets the token type used to authenticate with the KOOK API. + /// 获取或设置用于验证 KOOK API 的令牌类型。 /// public TokenType? TokenType { get; set; } /// - /// Gets or sets the token used to authenticate with the KOOK API. + /// 获取或设置用于验证 KOOK API 的令牌。 /// public string? Token { get; set; } /// - /// Gets or sets a value indicating whether the token should be validated before logging in. + /// 获取或设置是否在登录前应验证令牌。 /// public bool ValidateToken { get; set; } = true; /// - /// Gets or sets the route endpoint for the webhook. + /// 获取或设置注册到 ASP.NET 的 KOOK Webhook 的路由模式。 /// public string RoutePattern { get; set; } = "kook"; /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public KookAspNetWebhookConfig() : base(DefaultAspNetWebhookProvider.Instance) diff --git a/src/Kook.Net.Webhook.AspNet/KookWebhookClientExtension.cs b/src/Kook.Net.Webhook.AspNet/KookWebhookClientExtension.cs index 970d5243..7173240c 100644 --- a/src/Kook.Net.Webhook.AspNet/KookWebhookClientExtension.cs +++ b/src/Kook.Net.Webhook.AspNet/KookWebhookClientExtension.cs @@ -11,16 +11,16 @@ namespace Kook.Webhook.AspNet; /// -/// Provides extension methods for Kook webhook client. +/// 提供用于与 ASP.NET 集成,注册与配置 的扩展方法。 /// public static class KookWebhookClientExtension { /// - /// Adds a KOOK webhook client to the specified . + /// 向指定的 添加 客户端。 /// - /// The to add the KOOK webhook client to. - /// The to configure the KOOK webhook client with. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK ASP.NET Webhook 客户端的服务集合。 + /// 用于配置 KOOK ASP.NET Webhook 客户端的配置。 + /// 添加了 KOOK ASP.NET Webhook 客户端的服务集合。 public static IServiceCollection AddKookAspNetWebhookClient(this IServiceCollection services, KookAspNetWebhookConfig config) { services.AddSingleton(config); @@ -30,11 +30,11 @@ public static IServiceCollection AddKookAspNetWebhookClient(this IServiceCollect } /// - /// Adds a KOOK webhook client to the specified . + /// 向指定的 添加 客户端。 /// - /// The to add the KOOK webhook client to. - /// The to configure the KOOK webhook client with. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK ASP.NET Webhook 客户端的服务集合。 + /// 用于配置 KOOK ASP.NET Webhook 客户端的配置委托。 + /// 添加了 KOOK ASP.NET Webhook 客户端的服务集合。 public static IServiceCollection AddKookAspNetWebhookClient(this IServiceCollection services, Action configure) { services.AddKookWebhookClient((_, config) => new KookAspNetWebhookClient(config), configure); @@ -44,10 +44,10 @@ public static IServiceCollection AddKookAspNetWebhookClient(this IServiceCollect } /// - /// Adds a KOOK webhook client to the specified . + /// 向指定的 添加 KOOK Webhook 客户端。 /// - /// The to add the KOOK webhook client to. - /// The so that additional calls can be chained. + /// 要向其添加 KOOK ASP.NET Webhook 客户端的服务集合。 + /// 添加了 KOOK ASP.NET Webhook 客户端的服务集合。 public static IServiceCollection AddKookAspNetWebhookClient(this IServiceCollection services) { services.AddKookWebhookClient(provider => @@ -65,11 +65,11 @@ public static IServiceCollection AddKookAspNetWebhookClient(this IServiceCollect } /// - /// Configures the KOOK service to use the ASP.NET webhook client. + /// 配置 KOOK 服务以使用 ASP.NET Webhook 客户端。 /// - /// The KOOK service configurator. - /// The configuration action. - /// The KOOK service configurator. + /// KOOK 服务配置器。 + /// 用于配置 KOOK ASP.NET Webhook 客户端的配置委托。 + /// 配置了 KOOK ASP.NET Webhook 客户端的配置器。 public static IKookClientConfigurator UseAspNetWebhookClient (this IKookClientServiceConfigurator configurator, Action configure) { @@ -83,13 +83,13 @@ public static IKookClientConfigurator - /// Configures the KOOK service to use the ASP.NET webhook client. + /// 配置 KOOK 服务以将 ASP.NET Webhook 客户端包装为 。 /// - /// The KOOK service configurator. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The KOOK service configurator. + /// KOOK 服务配置器。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 配置了 ASP.NET Webhook 客户端的配置器。 [DoesNotReturn] [Obsolete("The KookAspNetWebhookClient itself is a hosted service, configure the token in the KookAspNetWebhookConfig.")] public static IKookClientConfigurator UseHostedClient( @@ -98,13 +98,13 @@ public static IKookClientConfigurator - /// Configures the KOOK service to use the ASP.NET webhook client. + /// 配置 KOOK 服务以将 ASP.NET Webhook 客户端包装为 。 /// - /// The KOOK service configurator. - /// The token type. - /// The token. - /// The value indicating whether to validate the token. - /// The KOOK service configurator. + /// KOOK 服务配置器。 + /// 令牌的类型。 + /// 令牌。 + /// 是否验证令牌。 + /// 配置了 ASP.NET Webhook 客户端的配置器。 [DoesNotReturn] [Obsolete("The KookAspNetWebhookClient itself is a hosted service, configure the token in the KookAspNetWebhookConfig.")] public static IKookClientConfigurator UseHostedClient( @@ -114,11 +114,11 @@ public static IKookClientConfigurator - /// Adds a KOOK webhook endpoint to the specified . + /// 向 添加 KOOK Webhook 路由端点。 /// - /// The to add the KOOK webhook endpoint to. - /// The route pattern to use for the KOOK webhook endpoint. - /// A reference to this instance after the operation has completed. + /// 要向其添加 KOOK Webhook 端点的应用程序构建器。 + /// 用于注册 KOOK Webhook 的路由模式。 + /// 添加了 KOOK Webhook 端点的应用程序构建器。 public static T UseKookEndpoint(this T builder, string? routePattern = null) where T: IHost, IEndpointRouteBuilder { diff --git a/src/Kook.Net.Webhook.AspNet/Net/AspNet/DefaultAspNetWebhookProvider.cs b/src/Kook.Net.Webhook.AspNet/Net/AspNet/DefaultAspNetWebhookProvider.cs index d00f8ac8..db40335a 100644 --- a/src/Kook.Net.Webhook.AspNet/Net/AspNet/DefaultAspNetWebhookProvider.cs +++ b/src/Kook.Net.Webhook.AspNet/Net/AspNet/DefaultAspNetWebhookProvider.cs @@ -1,20 +1,20 @@ namespace Kook.Net.Webhooks.AspNet; /// -/// Represents a default that creates instances. +/// 表示一个默认的使用 ASP.NET 的 ,用于创建 实例。 /// public static class DefaultAspNetWebhookProvider { /// - /// A delegate that creates a default instance. + /// 一个创建默认的使用 ASP.NET 的 实例的委托。 /// public static readonly WebhookProvider Instance = Create(); /// - /// Creates a delegate that creates a new instance. + /// 创建一个新的用于创建默认的使用 ASP.NET 的 实例的委托。 /// - /// A delegate that creates a new instance. - /// The default WebhookProvider is not supported on this platform. + /// 一个用于创建默认的使用 ASP.NET 的 实例的委托。 + /// 当默认的 在当前平台上不受支持时引发。 public static WebhookProvider Create() => () => { diff --git a/src/Kook.Net.Webhook.AspNet/Net/AspNet/IAspNetWebhookClient.cs b/src/Kook.Net.Webhook.AspNet/Net/AspNet/IAspNetWebhookClient.cs index 4f0717e0..f19c1036 100644 --- a/src/Kook.Net.Webhook.AspNet/Net/AspNet/IAspNetWebhookClient.cs +++ b/src/Kook.Net.Webhook.AspNet/Net/AspNet/IAspNetWebhookClient.cs @@ -5,9 +5,9 @@ namespace Kook.Net.Webhooks.AspNet; internal interface IAspNetWebhookClient : IWebhookClient { /// - /// Handles a Kook webhook request. + /// 处理一个 KOOK Webhook 请求。 /// - /// The HTTP context to handle the request with. - /// A task that represents the asynchronous operation. + /// KOOK Webhook 请求的 HTTP 上下文。 + /// 一个表示异步操作的任务。 Task HandleRequestAsync(HttpContext httpContext); } diff --git a/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookClient.cs b/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookClient.cs index 94db9293..69736b2f 100644 --- a/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookClient.cs +++ b/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookClient.cs @@ -3,19 +3,19 @@ namespace Kook.Webhook.HttpListener; /// -/// Represents a KOOK webhook client using HTTP listener. +/// 表示一个使用 HTTP 监听器的 KOOK Webhook 客户端。 /// public class KookHttpListenerWebhookClient : KookWebhookClient { - /// + /// + /// 初始化一个 类的新实例。 + /// + /// 用于配置 KOOK Webhook 客户端的 。 public KookHttpListenerWebhookClient(KookHttpListenerWebhookConfig config) : base(config) { } - /// - /// Gets the configuration used by this client. - /// internal new KookHttpListenerWebhookConfig BaseConfig => base.BaseConfig as KookHttpListenerWebhookConfig ?? throw new InvalidOperationException("The base configuration is not a Webhook-based configuration for HTTP listener."); diff --git a/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookConfig.cs b/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookConfig.cs index 6ecfbfd7..fea1e351 100644 --- a/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookConfig.cs +++ b/src/Kook.Net.Webhook.HttpListener/KookHttpListenerWebhookConfig.cs @@ -3,12 +3,15 @@ namespace Kook.Webhook.HttpListener; /// -/// Represents a KOOK webhook client configuration using HTTP listener. +/// 表示一个用于 的配置类。 /// +/// +/// 此配置基于 ,在与 Webhook 有关的配置的基础上,定义了有关 HTTP 监听器的配置。 +/// public class KookHttpListenerWebhookConfig : KookWebhookConfig { /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// public KookHttpListenerWebhookConfig() : base(DefaultHttpListenerWebhookProvider.Instance) @@ -16,16 +19,19 @@ public KookHttpListenerWebhookConfig() } /// - /// Gets or sets the URI prefixes to listen for incoming webhook requests. + /// 获取或设置用于监听传入 Webhook 请求的 URI 前缀。 /// public IReadOnlyCollection? UriPrefixes { get; set; } /// - /// Gets or sets the interval to wait before restarting the HTTP listener after it has been closed. - /// The same value to Timeout.InfiniteTimeSpan represents that the client will not restart with - /// leaving the application running. Other negative values will cause the client to exit the application. - /// The zero value will cause the client to restart immediately. Any positive value will cause the client - /// to restart after the specified interval. + /// 获取或设置在 HTTP 监听器关闭后等待重新启动的时间间隔。 /// + /// + /// 设置为与 + /// 相等的值表示客户端将在保持应用程序运行的情况下不重新启动;设置为其它任何负值将导致客户端在 HTTP 监听器关闭后退出应用程序;设置为 + /// 将导致客户端在 HTTP + /// 监听器关闭后立即重新启动;设置为任何正值将导致客户端在指定的时间间隔后重新启动。
+ /// 默认值为 5 秒,即在 HTTP 监听器关闭后 5 秒后重新启动。 + ///
public TimeSpan AutoRestartInterval { get; set; } = TimeSpan.FromSeconds(5); } diff --git a/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/DefaultHttpListenerWebhookProvider.cs b/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/DefaultHttpListenerWebhookProvider.cs index 2edb8aac..b2cc84c3 100644 --- a/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/DefaultHttpListenerWebhookProvider.cs +++ b/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/DefaultHttpListenerWebhookProvider.cs @@ -1,20 +1,20 @@ namespace Kook.Net.Webhooks.HttpListener; /// -/// Represents a default that creates instances. +/// 表示一个默认的使用 HTTP 监听器的 ,用于创建 实例。 /// public static class DefaultHttpListenerWebhookProvider { /// - /// A delegate that creates a default instance. + /// 一个创建默认的使用 HTTP 监听器的 实例的委托。 /// public static readonly WebhookProvider Instance = Create(); /// - /// Creates a delegate that creates a new instance. + /// 创建一个新的用于创建默认的使用 HTTP 监听器的 实例的委托。 /// - /// A delegate that creates a new instance. - /// The default WebhookProvider is not supported on this platform. + /// 一个用于创建默认的使用 HTTP 监听器的 实例的委托。 + /// 当默认的 在当前平台上不受支持时引发。 public static WebhookProvider Create() => () => { diff --git a/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/IHttpListenerWebhookClient.cs b/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/IHttpListenerWebhookClient.cs index 25970018..80c585d1 100644 --- a/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/IHttpListenerWebhookClient.cs +++ b/src/Kook.Net.Webhook.HttpListener/Net/HttpListener/IHttpListenerWebhookClient.cs @@ -3,21 +3,21 @@ internal interface IHttpListenerWebhookClient : IWebhookClient { /// - /// Sets the cancellation token for this client. + /// 设置此客户端的取消令牌。 /// - /// The cancellation token to be used. + /// 要设置的取消令牌。 void SetCancellationToken(CancellationToken cancellationToken); /// - /// Connects to the specified host. + /// 连接到主机。 /// - /// - /// A task that represents an asynchronous connect operation. + /// 要监听的 URI 前缀。 + /// 一个表示异步连接操作的任务。 Task StartAsync(IEnumerable uriPrefixes); /// - /// Disconnects from the host. + /// 断开连接。 /// - /// A task that represents an asynchronous disconnect operation. + /// 一个表示异步断开连接操作的任务。 Task StopAsync(); } diff --git a/src/Kook.Net.Webhook/KookWebhookClient.cs b/src/Kook.Net.Webhook/KookWebhookClient.cs index 179c3469..f3898064 100644 --- a/src/Kook.Net.Webhook/KookWebhookClient.cs +++ b/src/Kook.Net.Webhook/KookWebhookClient.cs @@ -10,7 +10,7 @@ namespace Kook.Webhook; /// -/// Represents a KOOK webhook client. +/// 表示一个基于 Webhook 网关的 KOOK 客户端。 /// public abstract class KookWebhookClient : KookSocketClient { @@ -23,9 +23,9 @@ public abstract class KookWebhookClient : KookSocketClient private protected Logger WebhookLogger { get; } /// - /// Initializes a new REST/WebSocket-based Kook client with the provided configuration. + /// 初始化一个 类的新实例。 /// - /// The configuration to be used with the client. + /// Webhook 客户端的配置。 protected KookWebhookClient(KookWebhookConfig config) : this(config, CreateApiClient(config)) { @@ -51,9 +51,6 @@ private protected KookWebhookClient(KookWebhookConfig config, KookWebhookApiClie internal new KookWebhookApiClient ApiClient => base.ApiClient as KookWebhookApiClient ?? throw new InvalidOperationException("The API client is not a Webhook-based client."); - /// - /// Gets the configuration used by this client. - /// internal new KookWebhookConfig BaseConfig => base.BaseConfig as KookWebhookConfig ?? throw new InvalidOperationException("The base configuration is not a Webhook-based configuration."); @@ -153,7 +150,6 @@ internal override void Dispose(bool disposing) base.Dispose(disposing); } - /// internal override async Task ProcessMessageAsync(GatewaySocketFrameType gatewaySocketFrameType, int? sequence, JsonElement payload) { if (gatewaySocketFrameType is GatewaySocketFrameType.Event) diff --git a/src/Kook.Net.Webhook/KookWebhookConfig.cs b/src/Kook.Net.Webhook/KookWebhookConfig.cs index 25e26024..6edc4dfc 100644 --- a/src/Kook.Net.Webhook/KookWebhookConfig.cs +++ b/src/Kook.Net.Webhook/KookWebhookConfig.cs @@ -4,37 +4,40 @@ namespace Kook.Webhook; /// -/// Represents a KOOK webhook client configuration. +/// 表示一个用于 的配置类。 /// +/// +/// 此配置基于 ,在与网关有关的配置的基础上,定义了有关 Webhook 的配置。 +/// public abstract class KookWebhookConfig : KookSocketConfig { /// - /// Gets or sets the verification token used to verify the webhook request. + /// 获取或设置用于验证 Webhook 请求的验证令牌。 /// public string? VerifyToken { get; set; } /// - /// Gets or sets the encryption key used to decrypt the webhook payload. + /// 获取或设置用于解密 Webhook 负载的加密密钥。 /// public string? EncryptKey { get; set; } /// - /// Gets or sets a value indicating whether the client should try to automatically log in. + /// 获取或设置客户端是否尝试自动登录。 /// public bool AutoLogin { get; set; } = true; /// - /// Gets or sets a value indicating whether the client should try to automatically log out. + /// 获取或设置客户端是否尝试自动退出登录。 /// public bool AutoLogout { get; set; } = false; /// - /// Gets or sets the provider used to generate new UDP sockets. + /// 获取或设置用于创建 Webhook 客户端的委托。 /// public WebhookProvider WebhookProvider { get; set; } /// - /// Gets the heartbeat interval of WebSocket connection in milliseconds. + /// 获取或设置网关发送心跳包的时间间隔(毫秒)。 /// public new int HeartbeatIntervalMilliseconds { @@ -43,9 +46,9 @@ public abstract class KookWebhookConfig : KookSocketConfig } /// - /// Initializes a new instance of the class. + /// 初始化一个 类的新实例。 /// - /// The provider used to generate new UDP sockets. + /// 用于创建 Webhook 客户端的委托。 protected KookWebhookConfig(WebhookProvider webhookProvider) { WebhookProvider = webhookProvider; diff --git a/src/Kook.Net.Webhook/Net/Webhook/IWebhookClient.cs b/src/Kook.Net.Webhook/Net/Webhook/IWebhookClient.cs index e65034d5..9c4c1b99 100644 --- a/src/Kook.Net.Webhook/Net/Webhook/IWebhookClient.cs +++ b/src/Kook.Net.Webhook/Net/Webhook/IWebhookClient.cs @@ -1,38 +1,60 @@ namespace Kook.Net.Webhooks; /// -/// Represents a generic WebSocket client. +/// 表示一个通用的基于 Webhook 的网关客户端。 /// public interface IWebhookClient : IDisposable { /// - /// Fired when a binary message is received. + /// 当接收到二进制消息时引发。 /// + /// + /// 事件参数: + /// + /// [] 参数是消息的二进制数据。 + /// 参数是数据的起始索引。 + /// 参数是数据的长度。 + /// + /// 事件返回值:返回一个表示异步操作的任务。任务的结果是一个字符串,表示响应消息。 + /// event Func>? BinaryMessage; /// - /// Fired when a text message is received. + /// 当接收到文本消息时引发。 /// + /// + /// 事件参数: + /// + /// 参数是消息的文本。 + /// + /// 事件返回值:返回一个表示异步操作的任务。任务的结果是一个字符串,表示响应消息。 + /// event Func>? TextMessage; /// - /// Fired when the HttpListener is closed. + /// 当连接关闭时引发。 /// + /// + /// 事件参数: + /// + /// 参数是引发关闭的异常。 + /// + /// event Func? Closed; /// - /// Handles a text message. + /// 处理文本消息。 /// - /// The request body. - /// A task that represents the asynchronous operation. + /// 请求体。 + /// 一个表示异步操作的任务。任务的结果是一个字符串,表示响应消息。 Task HandleTextMessageAsync(string requestBody); /// - /// Handles a binary message. + /// 处理二进制消息。 /// - /// The data. - /// The index. - /// The count. - /// A task that represents the asynchronous operation. + /// 消息的二进制数据。 + /// 数据的起始索引。 + /// 数据的长度。 + /// 一个表示异步操作的任务。任务的结果是一个字符串,表示响应消息。 Task HandleBinaryMessageAsync(byte[] data, int index, int count); } diff --git a/src/Kook.Net.Webhook/Net/Webhook/WebhookProvider.cs b/src/Kook.Net.Webhook/Net/Webhook/WebhookProvider.cs index 88b8fbe9..41ba1a67 100644 --- a/src/Kook.Net.Webhook/Net/Webhook/WebhookProvider.cs +++ b/src/Kook.Net.Webhook/Net/Webhook/WebhookProvider.cs @@ -1,6 +1,6 @@ namespace Kook.Net.Webhooks; /// -/// Represents a delegate that provides a new instance. +/// 表示一个提供新的 实例的委托。 /// public delegate IWebhookClient WebhookProvider(); diff --git a/test/Kook.Net.Tests.Integration.Rest/Fixtures/RestGuildFixture.cs b/test/Kook.Net.Tests.Integration.Rest/Fixtures/RestGuildFixture.cs index 181995a8..06de3ff8 100644 --- a/test/Kook.Net.Tests.Integration.Rest/Fixtures/RestGuildFixture.cs +++ b/test/Kook.Net.Tests.Integration.Rest/Fixtures/RestGuildFixture.cs @@ -1,3 +1,4 @@ +using System; using Kook.Rest; using System.Collections.Generic; using System.Linq; @@ -23,7 +24,6 @@ private async Task InitializeAsync() List guilds = Client.GetGuildsAsync().GetAwaiter().GetResult() .Where(x => x.Name == guildName) .ToList(); - await RemoveUselessTestGuildsAsync(guilds.Skip(1)); // If there is a guild created by this bot, use it if (guilds.Find(x => x.OwnerId == Client.CurrentUser?.Id) is { } guild) @@ -34,24 +34,18 @@ private async Task InitializeAsync() Guild = guilds[0]; // Otherwise, create a new guild else - Guild = await Client.CreateGuildAsync(guildName); + throw new InvalidOperationException("No guild found to use for testing."); await RemoveAllChannelsAsync(); await RemoveAllRolesAsync(); } - private async Task RemoveUselessTestGuildsAsync(IEnumerable guilds) - { - foreach (RestGuild guild in guilds) - await guild.DeleteAsync(); - } - /// /// Removes all channels in the guild. /// private async Task RemoveAllChannelsAsync() { - IReadOnlyCollection channels = Guild.GetChannelsAsync().GetAwaiter().GetResult(); + IReadOnlyCollection channels = await Guild.GetChannelsAsync(); foreach (RestGuildChannel channel in channels.Where(x => x is INestedChannel)) await channel.DeleteAsync(); foreach (RestGuildChannel channel in channels.Where(x => x is ICategoryChannel)) @@ -78,15 +72,4 @@ private async Task RemoveAllRolesAsync() foreach (RestRole role in roles) await role.DeleteAsync(); } - - /// - public override async ValueTask DisposeAsync() - { - if (Guild.OwnerId == Client.CurrentUser?.Id) - await Guild.DeleteAsync(); - await base.DisposeAsync(); - } - - /// - public override void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); } diff --git a/test/Kook.Net.Tests.Integration.Rest/MessageInTextTests.cs b/test/Kook.Net.Tests.Integration.Rest/MessageInTextTests.cs index 06aedadf..5984507a 100644 --- a/test/Kook.Net.Tests.Integration.Rest/MessageInTextTests.cs +++ b/test/Kook.Net.Tests.Integration.Rest/MessageInTextTests.cs @@ -69,7 +69,7 @@ CODE BLOCK ```"; // Due to the client is REST, the channel name will not be parsed. // Hence, the channel name will be displayed as empty string. - string kMarkDownCleanContent = @"TEST KMARKDOWN MESSAGE + string kMarkdownCleanContent = @"TEST KMARKDOWN MESSAGE NOTHING [INLINE LINK](https://kooknet.dev) UNDERLINESPOLIER @@ -93,15 +93,15 @@ CODE BLOCK Assert.NotNull(message); Assert.Equal(MessageType.KMarkdown, message.Type); Assert.Equal(kMarkdownParsedContent, message.Content); - Assert.Equal(kMarkDownCleanContent, message.CleanContent); + Assert.Equal(kMarkdownCleanContent, message.CleanContent); Assert.Equal(selfUser.Id, message.Author.Id); Assert.Equal(MessageSource.Bot, message.Source); Assert.Equal(4, message.Tags.Count); List tags = message.Tags.ToList(); Assert.Equal(_channel.Id, tags.Single(tag => tag.Type == TagType.ChannelMention).Key); Assert.Equal(selfUser.Id, tags.Single(tag => tag.Type == TagType.UserMention).Key); - Assert.Equal(0, tags.Single(tag => tag.Type == TagType.EveryoneMention).Key); - Assert.Equal(0, tags.Single(tag => tag.Type == TagType.HereMention).Key); + Assert.Equal(0U, tags.Single(tag => tag.Type == TagType.EveryoneMention).Key); + Assert.Equal(0U, tags.Single(tag => tag.Type == TagType.HereMention).Key); } finally { diff --git a/test/Kook.Net.Tests.Integration.Rest/MessageInVoiceTests.cs b/test/Kook.Net.Tests.Integration.Rest/MessageInVoiceTests.cs index 7b2bfda2..a8f9d565 100644 --- a/test/Kook.Net.Tests.Integration.Rest/MessageInVoiceTests.cs +++ b/test/Kook.Net.Tests.Integration.Rest/MessageInVoiceTests.cs @@ -69,7 +69,7 @@ CODE BLOCK ```"; // Due to the client is REST, the channel name will not be parsed. // Hence, the channel name will be displayed as empty string. - string kMarkDownCleanContent = @"TEST KMARKDOWN MESSAGE + const string kMarkdownCleanContent = @"TEST KMARKDOWN MESSAGE NOTHING [INLINE LINK](https://kooknet.dev) UNDERLINESPOLIER @@ -93,15 +93,15 @@ CODE BLOCK Assert.NotNull(message); Assert.Equal(MessageType.KMarkdown, message.Type); Assert.Equal(kMarkdownParsedContent, message.Content); - Assert.Equal(kMarkDownCleanContent, message.CleanContent); + Assert.Equal(kMarkdownCleanContent, message.CleanContent); Assert.Equal(selfUser.Id, message.Author.Id); Assert.Equal(MessageSource.Bot, message.Source); Assert.Equal(4, message.Tags.Count); List tags = message.Tags.ToList(); Assert.Equal(_channel.Id, tags.Single(tag => tag.Type == TagType.ChannelMention).Key); Assert.Equal(selfUser.Id, tags.Single(tag => tag.Type == TagType.UserMention).Key); - Assert.Equal(0, tags.Single(tag => tag.Type == TagType.EveryoneMention).Key); - Assert.Equal(0, tags.Single(tag => tag.Type == TagType.HereMention).Key); + Assert.Equal(0U, tags.Single(tag => tag.Type == TagType.EveryoneMention).Key); + Assert.Equal(0U, tags.Single(tag => tag.Type == TagType.HereMention).Key); } finally { diff --git a/test/Kook.Net.Tests.Integration.Rest/RoleTests.cs b/test/Kook.Net.Tests.Integration.Rest/RoleTests.cs index da0fb1f2..162e5d2c 100644 --- a/test/Kook.Net.Tests.Integration.Rest/RoleTests.cs +++ b/test/Kook.Net.Tests.Integration.Rest/RoleTests.cs @@ -43,8 +43,8 @@ public async Task ModifyRoleAsync() await role.ModifyAsync(x => { x.Name = "UPDATED ROLE"; - x.Hoist = true; - x.Mentionable = true; + x.IsHoisted = true; + x.IsMentionable = true; x.Color = Color.Red; x.Permissions = GuildPermissions.All; }); diff --git a/test/Kook.Net.Tests.Integration.Socket/Fixtures/SocketGuildFixture.cs b/test/Kook.Net.Tests.Integration.Socket/Fixtures/SocketGuildFixture.cs index 01bc0d8c..79d18001 100644 --- a/test/Kook.Net.Tests.Integration.Socket/Fixtures/SocketGuildFixture.cs +++ b/test/Kook.Net.Tests.Integration.Socket/Fixtures/SocketGuildFixture.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Kook.WebSocket; @@ -7,8 +8,6 @@ namespace Kook; public class SocketGuildFixture : KookSocketClientFixture { - private readonly TaskCompletionSource _joinedPromise = new(); - public SocketGuild Guild { get; private set; } = null!; public SocketGuildFixture() @@ -35,29 +34,12 @@ private async Task InitializeAsync() Guild = existingGuild; // Otherwise, create a new guild else - { - Client.JoinedGuild += OnJoinedGuild; - await Client.CreateGuildAsync(guildName); - Guild = await _joinedPromise.Task.WithTimeout(); - Client.JoinedGuild -= OnJoinedGuild; - } + throw new InvalidOperationException("No guild found to use for testing."); await RemoveAllChannelsAsync(); await RemoveAllRolesAsync(); } - private Task OnJoinedGuild(SocketGuild guild) - { - _joinedPromise.SetResult(guild); - return Task.CompletedTask; - } - - private async Task RemoveUselessTestGuildsAsync(IEnumerable guilds) - { - foreach (SocketGuild guild in guilds) - await guild.DeleteAsync(); - } - /// /// Removes all channels in the guild. /// @@ -91,15 +73,4 @@ private async Task RemoveAllRolesAsync() foreach (SocketRole role in roles) await role.DeleteAsync(); } - - /// - public override async ValueTask DisposeAsync() - { - if (Guild.OwnerId == Client.CurrentUser?.Id) - await Guild.DeleteAsync(); - await base.DisposeAsync(); - } - - /// - public override void Dispose() => DisposeAsync().AsTask(); } diff --git a/test/Kook.Net.Tests.Integration.Socket/MessageTests.cs b/test/Kook.Net.Tests.Integration.Socket/MessageTests.cs index 607d6ee3..30656636 100644 --- a/test/Kook.Net.Tests.Integration.Socket/MessageTests.cs +++ b/test/Kook.Net.Tests.Integration.Socket/MessageTests.cs @@ -95,7 +95,7 @@ public async Task SendImageAsync() _client.MessageReceived += ClientOnMessageReceived; await using Stream imageStream = await new HttpClient().GetStreamAsync(rawUri); string assetUri = await _client.Rest.CreateAssetAsync(imageStream, filename); - FileAttachment fileAttachment = new(new Uri(assetUri), filename, AttachmentType.Image); + using FileAttachment fileAttachment = new(new Uri(assetUri), filename, AttachmentType.Image); Cacheable cacheableMessage = await _textChannel.SendFileAsync(fileAttachment); // The message content received should be the same as the message sent @@ -135,7 +135,7 @@ public async Task SendFileAsync() byte[] buffer = RandomNumberGenerator.GetBytes(fileSize); using MemoryStream stream = new(buffer); string assetUri = await _client.Rest.CreateAssetAsync(stream, filename); - FileAttachment fileAttachment = new(new Uri(assetUri), filename); + using FileAttachment fileAttachment = new(new Uri(assetUri), filename); Cacheable cacheableMessage = await _textChannel.SendFileAsync(fileAttachment); // The message content received should be the same as the message sent diff --git a/test/Kook.Net.Tests.Unit/EmojiTests.cs b/test/Kook.Net.Tests.Unit/EmojiTests.cs index 4a428777..274822fd 100644 --- a/test/Kook.Net.Tests.Unit/EmojiTests.cs +++ b/test/Kook.Net.Tests.Unit/EmojiTests.cs @@ -50,6 +50,6 @@ public void Test_Emote_Parse(string input, string name, string id, TagMode tagMo public void Test_Invalid_Emote_Parse(string input, TagMode tagMode) { Assert.False(Emote.TryParse(input, out _, tagMode)); - Assert.Throws(() => Emote.Parse(input, tagMode)); + Assert.Throws(() => Emote.Parse(input, tagMode)); } } diff --git a/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs b/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs index 05bbd435..4640517d 100644 --- a/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs +++ b/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs @@ -101,6 +101,9 @@ public Task CreateInviteAsync(int? maxAge = 604800, int? maxUses = null public int UserLimit => throw new NotImplementedException(); + /// + public IAudioClient? AudioClient => throw new NotImplementedException(); + /// public bool? IsVoiceRegionOverwritten => throw new NotImplementedException(); @@ -122,7 +125,7 @@ public Task CreateInviteAsync(int? maxAge = 604800, int? maxUses = null public Task ModifyAsync(Action func, RequestOptions? options = null) => throw new NotImplementedException(); - public Task> GetConnectedUsersAsync( + public Task> GetConnectedUsersAsync( CacheMode mode = CacheMode.AllowDownload, RequestOptions? options = null) => throw new NotImplementedException(); diff --git a/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs b/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs index d07f2d98..cec72b14 100644 --- a/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs +++ b/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs @@ -117,7 +117,7 @@ public void CheckBotTokenValidity(string? token, bool expected) => [InlineData("these chars aren't allowed @U#)*@#!)*", true, 0)] public void DecodeBase64UserId(string? encodedUserId, bool isNull, ulong expectedUserId) { - ulong? result = TokenUtils.DecodeBase64UserId(encodedUserId!); + ulong? result = TokenUtils.DecodeBase64AsNumber(encodedUserId!); if (isNull) Assert.Null(result); else diff --git a/test/Kook.Net.Tests.Unit/TypeReaderTests.cs b/test/Kook.Net.Tests.Unit/TypeReaderTests.cs index c13e7a24..e256d7e7 100644 --- a/test/Kook.Net.Tests.Unit/TypeReaderTests.cs +++ b/test/Kook.Net.Tests.Unit/TypeReaderTests.cs @@ -104,19 +104,19 @@ public async Task TestMultiple() ArgumentType? m = result.BestMatch as ArgumentType; Assert.NotNull(m); - Assert.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, m.ManyInts); + Assert.Equal([1, 2, 3, 4, 5, 6, 7], m.ManyInts); } } [NamedArgumentType] public sealed class ArgumentType { - public required int Foo { get; set; } + public int? Foo { get; set; } [OverrideTypeReader(typeof(CustomTypeReader))] - public required string Bar { get; set; } + public string? Bar { get; set; } - public required IEnumerable ManyInts { get; set; } + public IEnumerable? ManyInts { get; set; } } public sealed class CustomTypeReader : TypeReader diff --git a/test/Kook.Net.Tests.Unit/UrlValidationTests.cs b/test/Kook.Net.Tests.Unit/UrlValidationTests.cs index 1e9259ae..a8ac239d 100644 --- a/test/Kook.Net.Tests.Unit/UrlValidationTests.cs +++ b/test/Kook.Net.Tests.Unit/UrlValidationTests.cs @@ -28,7 +28,6 @@ public void UrlValidation_ValidUrl(string url) public void UrlValidation_EmptyUrl(string? url) => Assert.Throws(() => UrlValidation.Validate(url!)); - [Theory] [InlineData(" ")] [InlineData("kaiheila.net")]