public static async Task <IGuild> ModifyGuildAsync(this IRestClient client, Snowflake guildId, Action <ModifyGuildActionProperties> action, IRestRequestOptions options = null) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var properties = new ModifyGuildActionProperties(); action(properties); var content = new ModifyGuildJsonRestRequestContent { Name = properties.Name, VerificationLevel = properties.VerificationLevel, DefaultMessageNotifications = properties.NotificationLevel, ExplicitContentFilter = properties.ContentFilterLevel, AfkChannelId = properties.AfkChannelId, AfkTimeout = properties.AfkTimeout, Icon = properties.Icon, OwnerId = properties.OwnerId, Splash = properties.Splash, DiscoverySplash = properties.DiscoverySplash, Banner = properties.Banner, SystemChannelId = properties.SystemChannelId, SystemChannelFlags = properties.SystemChannelFlags, RulesChannelId = properties.RulesChannelId, PublicUpdatesChannelId = properties.PublicUpdatesChannelId, PreferredLocale = Optional.Convert(properties.PreferredLocale, x => x.Name), Features = Optional.Convert(properties.Features, x => x.ToArray()), Description = properties.Description }; var model = await client.ApiClient.ModifyGuildAsync(guildId, content, options).ConfigureAwait(false); return(new TransientGuild(client, model)); }
public virtual void Update(MessageJsonModel model) { if (_transientAuthor != null) { if (model.Member.HasValue) { model.Member.Value.User = model.Author; _transientAuthor = new TransientMember(Client, GuildId.Value, model.Member.Value); } else { _transientAuthor = new TransientUser(Client, model.Author); } } Content = model.Content; MentionedUsers = model.Mentions.ToReadOnlyList(Client, (x, client) => { var user = client.GetUser(x.Id); if (user != null) { return(user); } return(new TransientUser(client, x) as IUser); }); Reactions = Optional.Convert(model.Reactions, x => x.ToReadOnlyDictionary(x => Emoji.Create(x.Emoji), x => new Reaction(x))); }
public static CreateApplicationCommandJsonRestRequestContent ToContent(this LocalApplicationCommand command, IJsonSerializer serializer) { Guard.IsNotNull(command); var content = new CreateApplicationCommandJsonRestRequestContent { Name = command.Name.Value, DefaultPermission = command.IsEnabledByDefault }; if (command is LocalSlashCommand slashCommand) { content.Type = ApplicationCommandType.Slash; content.Description = slashCommand.Description; content.Options = Optional.Convert(slashCommand.Options, options => options?.Select(option => option?.ToModel(serializer)).ToArray()); } else if (command is LocalUserContextMenuCommand) { content.Type = ApplicationCommandType.User; } else if (command is LocalMessageContextMenuCommand) { content.Type = ApplicationCommandType.Message; } return(content); }
internal static AuditLogChange <T> Convert(AuditLogChangeJsonModel model) { var oldValue = Optional.Convert(model.OldValue, model => model.ToType <T>()); var newValue = Optional.Convert(model.NewValue, model => model.ToType <T>()); return(new(oldValue, newValue)); }
public static async Task <IUserMessage> ModifyMessageAsync(this IRestClient client, Snowflake channelId, Snowflake messageId, Action <ModifyMessageActionProperties> action, IRestRequestOptions options = null) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var properties = new ModifyMessageActionProperties(); action(properties); var content = new ModifyMessageJsonRestRequestContent { Content = properties.Content, Embeds = Optional.Convert(properties.Embeds, models => models.Select(x => { x.Validate(); return(x.ToModel()); }).ToArray()), Flags = properties.Flags, AllowedMentions = Optional.Convert(properties.AllowedMentions, x => x.ToModel()), Attachments = Optional.Convert(properties.AttachmentIds, x => x.Select(x => new AttachmentJsonModel { Id = x }).ToArray()), Components = Optional.Convert(properties.Components, models => models.Select(x => { x.Validate(); return(x.ToModel()); }).ToArray()), StickerIds = Optional.Convert(properties.StickerIds, x => x.ToArray()) }; var model = await client.ApiClient.ModifyMessageAsync(channelId, messageId, content, options).ConfigureAwait(false); return(new TransientUserMessage(client, model)); }
internal static Task <ChannelJsonModel> InternalModifyChannelAsync <T>(this IRestClient client, Snowflake channelId, Action <T> action, IRestRequestOptions options = null) where T : ModifyGuildChannelActionProperties { if (action == null) { throw new ArgumentNullException(nameof(action)); } // Can't use the new() generic constraint because the constructors are internal. // Can't use the generic CreateInstance either *because*. var properties = (T)Activator.CreateInstance(typeof(T), true); action(properties); var content = new ModifyChannelJsonRestRequestContent { Name = properties.Name, Position = properties.Position, PermissionOverwrites = Optional.Convert(properties.Overwrites, x => x.Select(x => x.ToModel()).ToArray()) }; if (properties is ModifyNestableChannelActionProperties nestableProperties) { content.ParentId = nestableProperties.CategoryId; if (nestableProperties is ModifyMessageGuildChannelActionProperties messageGuildChannelProperties) { content.RateLimitPerUser = Optional.Convert(messageGuildChannelProperties.Slowmode, x => (int)x.TotalSeconds); if (nestableProperties is ModifyTextChannelActionProperties textProperties) { content.Topic = textProperties.Topic; content.Nsfw = textProperties.IsNsfw; } else if (nestableProperties is ModifyThreadChannelActionProperties threadProperties) { content.Archived = threadProperties.IsArchived; content.AutoArchiveDuration = Optional.Convert(threadProperties.AutomaticArchiveDuration, x => (int)x.TotalMinutes); content.Locked = threadProperties.IsLocked; } } else if (nestableProperties is ModifyVoiceChannelActionProperties voiceProperties) { content.Bitrate = voiceProperties.Bitrate; content.UserLimit = voiceProperties.MemberLimit; content.RtcRegion = voiceProperties.Region; } } else if (properties is ModifyCategoryChannelActionProperties categoryProperties) { // No extra properties for category channels. } else { throw new ArgumentException($"Unknown channel action properties provided ({properties.GetType()})."); } return(client.ApiClient.ModifyChannelAsync(channelId, content, options)); }
internal static Task <ChannelJsonModel> InternalCreateGuildChannelAsync <T>(this IRestClient client, Snowflake guildId, string name, Action <T> action, IRestRequestOptions options = null, CancellationToken cancellationToken = default) where T : CreateGuildChannelActionProperties { // Can't use the new() generic constraint because the constructors are internal. // Can't use the generic CreateInstance either *because*. var properties = (T)Activator.CreateInstance(typeof(T), true); action?.Invoke(properties); var content = new CreateGuildChannelJsonRestRequestContent(name) { Position = properties.Position, PermissionOverwrites = Optional.Convert(properties.Overwrites, x => x.Select(x => x.ToModel()).ToArray()) }; if (properties is CreateNestedChannelActionProperties nestedProperties) { content.ParentId = nestedProperties.CategoryId; if (properties is CreateTextChannelActionProperties textProperties) { if (textProperties.Topic.HasValue && textProperties.Topic.Value != null && textProperties.Topic.Value.Length > 1024) { throw new ArgumentOutOfRangeException(nameof(CreateTextChannelActionProperties.Topic)); } content.Type = ChannelType.Text; content.Topic = textProperties.Topic; content.RateLimitPerUser = Optional.Convert(textProperties.Slowmode, x => (int)x.TotalSeconds); content.Nsfw = textProperties.IsNsfw; } else if (properties is CreateVoiceChannelActionProperties voiceProperties) { content.Type = ChannelType.Voice; content.Bitrate = voiceProperties.Bitrate; content.UserLimit = voiceProperties.MemberLimit; content.RtcRegion = voiceProperties.Region; } else { throw new ArgumentException($"Unknown channel action properties provided ({properties.GetType()})."); } } else if (properties is CreateCategoryChannelActionProperties categoryProperties) { content.Type = ChannelType.Category; // No extra properties for category channels. } else { throw new ArgumentException($"Unknown channel action properties provided ({properties.GetType()})."); } return(client.ApiClient.CreateGuildChannelAsync(guildId, content, options, cancellationToken)); }
public static CreateInitialInteractionResponseJsonRestRequestContent ToContent(this ILocalInteractionResponse response, IJsonSerializer serializer, out IList <LocalAttachment> attachments) { Guard.IsNotNull(response); var content = new CreateInitialInteractionResponseJsonRestRequestContent { Type = response.Type }; attachments = Array.Empty <LocalAttachment>(); if (response is LocalInteractionAutoCompleteResponse autoCompleteResponse) { content.Data = new InteractionCallbackAutoCompleteDataJsonModel { Choices = Optional.Convert(autoCompleteResponse.Choices, choices => choices?.Select(choice => choice.ToModel(serializer)).ToArray()) }; } else if (response is LocalInteractionMessageResponse messageResponse) { if (content.Type is not InteractionResponseType.MessageUpdate) { messageResponse.Validate(); content.Data = new InteractionCallbackMessageDataJsonModel { Tts = Optional.Conditional(messageResponse.IsTextToSpeech, true), Content = Optional.FromNullable(messageResponse.Content), Embeds = Optional.Conditional(messageResponse.Embeds.Count != 0, x => x.Select(x => x.ToModel()).ToArray(), messageResponse.Embeds), AllowedMentions = Optional.FromNullable(messageResponse.AllowedMentions.ToModel()), Components = Optional.Conditional(messageResponse.Components.Count != 0, x => x.Select(x => x.ToModel()).ToArray(), messageResponse.Components), Flags = Optional.Conditional(messageResponse.Flags != MessageFlag.None, messageResponse.Flags) }; } else { // TODO: make properties properly optional via different LocalInteractionResponse types? content.Data = new InteractionCallbackMessageDataJsonModel { //Tts = messageResponse.IsTextToSpeech, Content = messageResponse.Content, Embeds = messageResponse.Embeds.Select(x => x.ToModel()).ToArray(), AllowedMentions = messageResponse.AllowedMentions?.ToModel(), Components = messageResponse.Components.Select(x => x.ToModel()).ToArray(), Flags = messageResponse.Flags }; } attachments = messageResponse.Attachments; }
private static async Task <IUserMessage> InternalModifyInteractionResponseAsync(this IRestClient client, Snowflake applicationId, string interactionToken, Snowflake?messageId, Action <ModifyWebhookMessageActionProperties> action, IRestRequestOptions options, CancellationToken cancellationToken) { var properties = new ModifyWebhookMessageActionProperties(); action.Invoke(properties); var messageContent = new ModifyWebhookMessageJsonRestRequestContent { Content = properties.Content, Embeds = Optional.Convert(properties.Embeds, x => x.Select(x => { x.Validate(); return(x.ToModel()); }).ToArray()), AllowedMentions = Optional.Convert(properties.AllowedMentions, x => x.ToModel()), Attachments = Optional.Convert(properties.AttachmentIds, x => x.Select(x => new AttachmentJsonModel { Id = x }).ToArray()), Components = Optional.Convert(properties.Components, x => x.Select(x => { x.Validate(); return(x.ToModel()); }).ToArray()) }; Task <MessageJsonModel> task; if (properties.Attachments.HasValue) { // If there is an attachment, we must send it via multipart HTTP content. // Our `messageContent` will be serialized into a "payload_json" form data field. var content = new MultipartJsonPayloadRestRequestContent <ModifyWebhookMessageJsonRestRequestContent>(messageContent, properties.Attachments.Value); task = messageId == null ? client.ApiClient.ModifyInitialInteractionResponseAsync(applicationId, interactionToken, content, options, cancellationToken) : client.ApiClient.ModifyFollowupInteractionResponseAsync(applicationId, interactionToken, messageId.Value, content, options, cancellationToken); } else { task = messageId == null ? client.ApiClient.ModifyInitialInteractionResponseAsync(applicationId, interactionToken, messageContent, options, cancellationToken) : client.ApiClient.ModifyFollowupInteractionResponseAsync(applicationId, interactionToken, messageId.Value, messageContent, options, cancellationToken); } var model = await task.ConfigureAwait(false); return(new TransientUserMessage(client, model)); }
public void Update(GuildJsonModel model) { Name = model.Name; IconHash = model.Icon; SplashHash = model.Splash; if (model.DiscoverySplash.HasValue) { DiscoverySplashHash = model.DiscoverySplash.Value; } OwnerId = model.OwnerId; VoiceRegion = model.Region; AfkChannelId = model.AfkChannelId; AfkTimeout = TimeSpan.FromSeconds(model.AfkTimeout); if (model.WidgetEnabled.HasValue) { IsWidgetEnabled = model.WidgetEnabled.Value; } if (model.WidgetChannelId.HasValue) { WidgetChannelId = model.WidgetChannelId.Value; } VerificationLevel = model.VerificationLevel; NotificationLevel = model.DefaultMessageNotifications; ContentFilterLevel = model.ExplicitContentFilter; SetEmojis(model.Emojis); Features = model.Features; MfaLevel = model.MfaLevel; SystemChannelId = model.SystemChannelId; SystemChannelFlags = model.SystemChannelFlags; RulesChannelId = model.RulesChannelId; MaxPresenceCount = Optional.Convert(model.MaxPresences, x => x ?? Discord.Constants.DefaultMaxGuildPresenceCount).GetValueOrNullable(); MaxMemberCount = model.MaxMembers.GetValueOrNullable(); VanityUrlCode = model.VanityUrlCode; Description = model.Description; BannerHash = model.Banner; BoostTier = model.PremiumTier; BoostingMemberCount = model.PremiumSubscriptionCount.GetValueOrNullable(); PreferredLocale = Discord.Internal.GetLocale(model.PreferredLocale); PublicUpdatesChannelId = model.PublicUpdatesChannelId; MaxVideoMemberCount = model.MaxVideoChannelUsers.GetValueOrNullable(); }
public override void Update(MessageJsonModel model) { base.Update(model); EditedAt = model.EditedTimestamp; IsPinned = model.Pinned; MentionsEveryone = model.MentionEveryone; MentionedRoleIds = model.MentionRoles.ReadOnly(); Attachments = model.Attachments.ToReadOnlyList(model => new TransientAttachment(model)); Embeds = model.Embeds.ToReadOnlyList(model => new TransientEmbed(model)); Activity = Optional.ConvertOrDefault(model.Activity, model => new TransientMessageActivity(model)); Application = Optional.ConvertOrDefault(model.Application, model => new TransientMessageApplication(model)); Reference = Optional.ConvertOrDefault(model.MessageReference, model => new TransientMessageReference(model)); ReferencedMessage = Optional.Convert(model.ReferencedMessage, model => new TransientUserMessage(Client, model) as IUserMessage); Components = Optional.ConvertOrDefault(model.Components, (models, client) => models.ToReadOnlyList(client, (model, client) => new TransientRowComponent(client, model) as IRowComponent), Client) ?? Array.Empty <IRowComponent>(); Stickers = Optional.ConvertOrDefault(model.StickerItems, models => models.ToReadOnlyList(model => new TransientMessageSticker(model) as IMessageSticker), Array.Empty <IMessageSticker>()); }
public static ModifyApplicationCommandJsonRestRequestContent ToContent(this Action <ModifyApplicationCommandActionProperties> action, IJsonSerializer serializer) { Guard.IsNotNull(action); var properties = new ModifyApplicationCommandActionProperties(); action(properties); var content = new ModifyApplicationCommandJsonRestRequestContent { Name = properties.Name, Description = properties.Description, DefaultPermission = properties.IsEnabledByDefault, Options = Optional.Convert(properties.Options, options => options?.Select(option => option?.ToModel(serializer)).ToArray()) }; return(content); }
public static ApplicationCommandOptionJsonModel ToModel(this LocalSlashCommandOption option, IJsonSerializer serializer) { Guard.IsNotNull(option); OptionalGuard.HasValue(option.Type); OptionalGuard.HasValue(option.Name); OptionalGuard.HasValue(option.Description); return(new ApplicationCommandOptionJsonModel { Type = option.Type.Value, Name = option.Name.Value, Description = option.Description.Value, Required = option.IsRequired, Choices = Optional.Convert(option.Choices, choices => choices?.Select(choice => choice?.ToModel(serializer)).ToArray()), Options = Optional.Convert(option.Options, options => options?.Select(option => option?.ToModel(serializer)).ToArray()), ChannelTypes = Optional.Convert(option.ChannelTypes, channelTypes => channelTypes?.ToArray()) }); }
public static async Task <IUserMessage> ModifyMessageAsync(this IRestClient client, Snowflake channelId, Snowflake messageId, Action <ModifyMessageActionProperties> action, IRestRequestOptions options = null, CancellationToken cancellationToken = default) { Guard.IsNotNull(action); var properties = new ModifyMessageActionProperties(); action(properties); var messageContent = new ModifyMessageJsonRestRequestContent { Content = properties.Content, Embeds = Optional.Convert(properties.Embeds, models => models.Select(x => { x.Validate(); return(x.ToModel()); }).ToArray()), Flags = properties.Flags, AllowedMentions = Optional.Convert(properties.AllowedMentions, x => x.ToModel()), Attachments = Optional.Convert(properties.AttachmentIds, x => x.Select(x => new AttachmentJsonModel { Id = x }).ToArray()), Components = Optional.Convert(properties.Components, models => models.Select(x => { x.Validate(); return(x.ToModel()); }).ToArray()), StickerIds = Optional.Convert(properties.StickerIds, x => x.ToArray()) }; Task <MessageJsonModel> task; LocalAttachment[] attachments; if (properties.Attachments.TryGetValue(out var attachmentsEnumerable) && (attachments = attachmentsEnumerable.GetArray()).Length != 0) { // If there are attachments, we must send them via multipart HTTP content. // Our `messageContent` will be serialized into a "payload_json" form data field. var content = new MultipartJsonPayloadRestRequestContent <ModifyMessageJsonRestRequestContent>(messageContent, attachments); task = client.ApiClient.ModifyMessageAsync(channelId, messageId, content, options, cancellationToken); }
public override void Update(MessageJsonModel model) { base.Update(model); EditedAt = model.EditedTimestamp; IsPinned = model.Pinned; MentionsEveryone = model.MentionEveryone; MentionedRoleIds = model.MentionRoles.ReadOnly(); Attachments = model.Attachments.ToReadOnlyList(x => new Attachment(x)); Embeds = model.Embeds.ToReadOnlyList(x => new Embed(x)); Activity = Optional.ConvertOrDefault(model.Activity, x => new MessageActivity(x)); Application = Optional.ConvertOrDefault(model.Application, x => new MessageApplication(x)); Reference = Optional.ConvertOrDefault(model.MessageReference, x => new MessageReference(x)); Flags = model.Flags.GetValueOrDefault(); Stickers = Optional.ConvertOrDefault(model.Stickers, x => x.ToReadOnlyList(y => new Sticker(y)), Array.Empty <Sticker>()); if (model.Type == MessageType.Reply || model.ReferencedMessage.GetValueOrDefault() != null) { // Fix for Discord always sending an empty property. ReferencedMessage = Optional.Convert(model.ReferencedMessage, x => new TransientUserMessage(Client, x) as IUserMessage); } }
public static ModifyMemberJsonRestRequestContent ToContent(this Action <ModifyMemberActionProperties> action, out Optional <string> nick) { Guard.IsNotNull(action); var properties = new ModifyMemberActionProperties(); action(properties); nick = properties.Nick; var content = new ModifyMemberJsonRestRequestContent { Nick = properties.Nick, Roles = Optional.Convert(properties.RoleIds, x => x.ToArray()), ChannelId = properties.VoiceChannelId, Mute = properties.Mute, Deaf = properties.Deaf, CommunicationDisabledUntil = properties.TimedOutUntil }; return(content); }
public static ModifyRoleJsonRestRequestContent ToContent(this Action <ModifyRoleActionProperties> action, out Optional <int> position) { Guard.IsNotNull(action); var properties = new ModifyRoleActionProperties(); action(properties); var content = new ModifyRoleJsonRestRequestContent { Name = properties.Name, Permissions = Optional.Convert(properties.Permissions, permissions => permissions.RawValue), Color = Optional.Convert(properties.Color, color => color?.RawValue ?? 0), Hoist = properties.IsHoisted, Icon = properties.Icon, Mentionable = properties.IsMentionable, UnicodeEmoji = Optional.Convert(properties.UnicodeEmoji, emoji => emoji.Name) }; position = properties.Position; return(content); }
public TransientMemberRolesUpdatedAuditLog(IClient client, Snowflake guildId, AuditLogJsonModel auditLogJsonModel, AuditLogEntryJsonModel model) : base(client, guildId, auditLogJsonModel, model) { for (var i = 0; i < model.Changes.Value.Length; i++) { var change = model.Changes.Value[i]; switch (change.Key) { case "$add": { RolesGranted = Optional.Convert(change.NewValue, x => { var models = x.ToType <RoleJsonModel[]>(); return(models.ToReadOnlyDictionary(x => x.Id, x => x.Name)); }); break; } case "$remove": { RolesRevoked = Optional.Convert(change.NewValue, x => { var models = x.ToType <RoleJsonModel[]>(); return(models.ToReadOnlyDictionary(x => x.Id, x => x.Name)); }); break; } default: { client.Logger.LogDebug("Unknown key {0} for {1}", change.Key, this); break; } } } }
public void Update(MessageUpdateJsonModel model) { if (model.Author.HasValue) { if (_transientAuthor != null) { if (model.Member.HasValue) { model.Member.Value.User = model.Author; _transientAuthor = new TransientMember(Client, GuildId.Value, model.Member.Value); } else { _transientAuthor = new TransientUser(Client, model.Author.Value); } } } if (model.Content.HasValue) { Content = model.Content.Value; } if (model.Mentions.HasValue) { MentionedUsers = model.Mentions.Value.ToReadOnlyList(Client, (x, client) => { var user = client.GetUser(x.Id); if (user != null) { return(user); } return(new TransientUser(client, x) as IUser); }); } if (model.Reactions.HasValue) { Reactions = Optional.Convert(model.Reactions, x => x.ToReadOnlyDictionary(x => Emoji.Create(x.Emoji), x => new MessageReaction(x))); } if (model.EditedTimestamp.HasValue) { EditedAt = model.EditedTimestamp.Value; } if (model.Pinned.HasValue) { IsPinned = model.Pinned.Value; } if (model.MentionEveryone.HasValue) { MentionsEveryone = model.MentionEveryone.Value; } if (model.MentionRoles.HasValue) { MentionedRoleIds = model.MentionRoles.Value.ReadOnly(); } if (model.Attachments.HasValue) { Attachments = model.Attachments.Value.ToReadOnlyList(x => new Attachment(x)); } if (model.Embeds.HasValue) { Embeds = model.Embeds.Value.ToReadOnlyList(x => new Embed(x)); } if (model.Activity.HasValue) { Activity = Optional.ConvertOrDefault(model.Activity, x => new MessageActivity(x)); } if (model.Application.HasValue) { Application = Optional.ConvertOrDefault(model.Application, x => new MessageApplication(x)); } if (model.MessageReference.HasValue) { Reference = Optional.ConvertOrDefault(model.MessageReference, x => new MessageReference(x)); } if (model.Flags.HasValue) { Flags = model.Flags.Value; } if (model.ReferencedMessage.HasValue) { ReferencedMessage = Optional.Convert(model.ReferencedMessage, x => new TransientUserMessage(Client, x) as IUserMessage); } if (model.Components.HasValue) { Components = Optional.ConvertOrDefault(model.Components, (models, client) => models.ToReadOnlyList(client, (model, client) => TransientComponent.Create(client, model)), Client) ?? Array.Empty <IComponent>(); } if (model.StickerItems.HasValue) { Stickers = Optional.ConvertOrDefault(model.StickerItems, x => x.ToReadOnlyList(y => new MessageSticker(y)), Array.Empty <MessageSticker>()); } }
public void Update(MessageReactionRemoveEmojiJsonModel model) { Reactions = Optional.Convert(Reactions, reactions => reactions.Where(kvp => !model.Emoji.Equals(kvp.Key)).ToReadOnlyDictionary(kvp => kvp.Key, kvp => kvp.Value)); }
public void Update(MessageReactionRemoveEmojiJsonModel model) { var emoji = Emoji.Create(model.Emoji); Reactions = Optional.Convert(Reactions, x => x.Where(x => !x.Key.Equals(emoji)).ToReadOnlyDictionary(x => x.Key, x => x.Value)); }