diff --git a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireBotPermissionsAttribute.cs b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireBotPermissionsAttribute.cs
index 9e22d0b02..ead45fc26 100644
--- a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireBotPermissionsAttribute.cs
+++ b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireBotPermissionsAttribute.cs
@@ -1,76 +1,77 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
using DisCatSharp.ApplicationCommands.Context;
+using DisCatSharp.Enums;
namespace DisCatSharp.ApplicationCommands.Attributes;
///
/// Defines that usage of this application command is only possible when the bot is granted a specific permission.
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public sealed class ApplicationCommandRequireBotPermissionsAttribute : SlashCheckBaseAttribute
{
///
/// Gets the permissions required by this attribute.
///
public Permissions Permissions { get; }
///
/// Gets or sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
///
public bool IgnoreDms { get; } = true;
///
/// Defines that usage of this application command is only possible when the bot is granted a specific permission.
///
/// Permissions required to execute this command.
/// Sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
public ApplicationCommandRequireBotPermissionsAttribute(Permissions permissions, bool ignoreDms = true)
{
this.Permissions = permissions;
this.IgnoreDms = ignoreDms;
}
///
/// Runs checks.
///
public override async Task ExecuteChecksAsync(InteractionContext ctx)
{
if (ctx.Guild == null)
return this.IgnoreDms;
var bot = await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id).ConfigureAwait(false);
if (bot == null)
return false;
if (bot.Id == ctx.Guild.OwnerId)
return true;
var pbot = ctx.Channel.PermissionsFor(bot);
return (pbot & Permissions.Administrator) != 0 || (pbot & this.Permissions) == this.Permissions;
}
}
diff --git a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequirePermissionsAttribute.cs b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequirePermissionsAttribute.cs
index cc7e86ae0..d45eb2197 100644
--- a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequirePermissionsAttribute.cs
+++ b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequirePermissionsAttribute.cs
@@ -1,86 +1,87 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
using DisCatSharp.ApplicationCommands.Context;
+using DisCatSharp.Enums;
namespace DisCatSharp.ApplicationCommands.Attributes;
///
/// Defines that usage of this application command is restricted to members with specified permissions. This check also verifies that the bot has the same permissions.
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public sealed class ApplicationCommandRequirePermissionsAttribute : SlashCheckBaseAttribute
{
///
/// Gets the permissions required by this attribute.
///
public Permissions Permissions { get; }
///
/// Gets or sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
///
public bool IgnoreDms { get; } = true;
///
/// Defines that usage of this command is restricted to members with specified permissions. This check also verifies that the bot has the same permissions.
///
/// Permissions required to execute this command.
/// Sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
public ApplicationCommandRequirePermissionsAttribute(Permissions permissions, bool ignoreDms = true)
{
this.Permissions = permissions;
this.IgnoreDms = ignoreDms;
}
///
/// Runs checks.
///
public override async Task ExecuteChecksAsync(InteractionContext ctx)
{
if (ctx.Guild == null)
return this.IgnoreDms;
var usr = ctx.Member;
if (usr == null)
return false;
var pusr = ctx.Channel.PermissionsFor(usr);
var bot = await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id).ConfigureAwait(false);
if (bot == null)
return false;
var pbot = ctx.Channel.PermissionsFor(bot);
var usrok = ctx.Guild.OwnerId == usr.Id;
var botok = ctx.Guild.OwnerId == bot.Id;
if (!usrok)
usrok = (pusr & Permissions.Administrator) != 0 || (pusr & this.Permissions) == this.Permissions;
if (!botok)
botok = (pbot & Permissions.Administrator) != 0 || (pbot & this.Permissions) == this.Permissions;
return usrok && botok;
}
}
diff --git a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireUserPermissionsAttribute.cs b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireUserPermissionsAttribute.cs
index d49ea9372..b3987d5ce 100644
--- a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireUserPermissionsAttribute.cs
+++ b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/RequireUserPermissionsAttribute.cs
@@ -1,78 +1,79 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
using DisCatSharp.ApplicationCommands.Context;
+using DisCatSharp.Enums;
namespace DisCatSharp.ApplicationCommands.Attributes;
///
/// Defines that usage of this application command is restricted to members with specified permissions.
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public sealed class ApplicationCommandRequireUserPermissionsAttribute : SlashCheckBaseAttribute
{
///
/// Gets the permissions required by this attribute.
///
public Permissions Permissions { get; }
///
/// Gets or sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
///
public bool IgnoreDms { get; } = true;
///
/// Defines that usage of this command is restricted to members with specified permissions.
///
/// Permissions required to execute this command.
/// Sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
public ApplicationCommandRequireUserPermissionsAttribute(Permissions permissions, bool ignoreDms = true)
{
this.Permissions = permissions;
this.IgnoreDms = ignoreDms;
}
///
/// Runs checks.
///
public override Task ExecuteChecksAsync(InteractionContext ctx)
{
if (ctx.Guild == null)
return Task.FromResult(this.IgnoreDms);
var usr = ctx.Member;
if (usr == null)
return Task.FromResult(false);
if (usr.Id == ctx.Guild.OwnerId)
return Task.FromResult(true);
var pusr = ctx.Channel.PermissionsFor(usr);
return (pusr & Permissions.Administrator) != 0
? Task.FromResult(true)
: (pusr & this.Permissions) == this.Permissions ? Task.FromResult(true) : Task.FromResult(false);
}
}
diff --git a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandAttribute.cs b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandAttribute.cs
index caf664339..3f4a6f9e3 100644
--- a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandAttribute.cs
+++ b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandAttribute.cs
@@ -1,121 +1,123 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
+using DisCatSharp.Enums;
+
namespace DisCatSharp.ApplicationCommands.Attributes;
///
/// Marks this method as a slash command
///
[AttributeUsage(AttributeTargets.Method)]
public class SlashCommandAttribute : Attribute
{
///
/// Gets the name of this command
///
public string Name { get; set; }
///
/// Gets the description of this command
///
public string Description { get; set; }
///
/// Gets the needed permission of this command
///
public Permissions? DefaultMemberPermissions { get; set; }
///
/// Gets the dm permission of this command
///
public bool? DmPermission { get; set; }
///
/// Gets whether this command is marked as NSFW
///
public bool IsNsfw { get; set; }
///
/// Marks this method as a slash command
///
/// The name of this slash command.
/// The description of this slash command.
/// Whether this command is marked as NSFW.
public SlashCommandAttribute(string name, string description, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = null;
this.DmPermission = null;
this.IsNsfw = isNsfw;
}
///
/// Marks this method as a slash command
///
/// The name of this slash command.
/// The description of this slash command.
/// The default member permissions.
/// Whether this command is marked as NSFW.
public SlashCommandAttribute(string name, string description, long defaultMemberPermissions, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = (Permissions)defaultMemberPermissions;
this.DmPermission = null;
this.IsNsfw = isNsfw;
}
///
/// Marks this method as a slash command
///
/// The name of this slash command.
/// The description of this slash command.
/// The dm permission.
/// Whether this command is marked as NSFW.
public SlashCommandAttribute(string name, string description, bool dmPermission, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = null;
this.DmPermission = dmPermission;
this.IsNsfw = isNsfw;
}
///
/// Marks this method as a slash command
///
/// The name of this slash command.
/// The description of this slash command.
/// The default member permissions.
/// The dm permission.
/// Whether this command is marked as NSFW.
public SlashCommandAttribute(string name, string description, long defaultMemberPermissions, bool dmPermission, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = (Permissions)defaultMemberPermissions;
this.DmPermission = dmPermission;
this.IsNsfw = isNsfw;
}
}
diff --git a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandGroupAttribute.cs b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandGroupAttribute.cs
index 6a717ef4c..e7a1814d2 100644
--- a/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandGroupAttribute.cs
+++ b/DisCatSharp.ApplicationCommands/Attributes/SlashCommand/SlashCommandGroupAttribute.cs
@@ -1,121 +1,123 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
+using DisCatSharp.Enums;
+
namespace DisCatSharp.ApplicationCommands.Attributes;
///
/// Marks this class a slash command group
///
[AttributeUsage(AttributeTargets.Class)]
public class SlashCommandGroupAttribute : Attribute
{
///
/// Gets the name of this slash command group
///
public string Name { get; set; }
///
/// Gets the description of this slash command group
///
public string Description { get; set; }
///
/// Gets the needed permission of this slash command group
///
public Permissions? DefaultMemberPermissions { get; set; }
///
/// Gets the dm permission of this slash command group
///
public bool? DmPermission { get; set; }
///
/// Gets whether this command is marked as NSFW
///
public bool IsNsfw { get; set; }
///
/// Marks this class as a slash command group
///
/// The name of this slash command group.
/// The description of this slash command group.
/// Whether this command is marked as NSFW.
public SlashCommandGroupAttribute(string name, string description, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = null;
this.DmPermission = null;
this.IsNsfw = isNsfw;
}
///
/// Marks this method as a slash command group
///
/// The name of this slash command.
/// The description of this slash command.
/// The default member permissions.
/// Whether this command is marked as NSFW.
public SlashCommandGroupAttribute(string name, string description, long defaultMemberPermissions, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = (Permissions)defaultMemberPermissions;
this.DmPermission = null;
this.IsNsfw = isNsfw;
}
///
/// Marks this method as a slash command group
///
/// The name of this slash command.
/// The description of this slash command.
/// The dm permission.
/// Whether this command is marked as NSFW.
public SlashCommandGroupAttribute(string name, string description, bool dmPermission, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = null;
this.DmPermission = dmPermission;
this.IsNsfw = isNsfw;
}
///
/// Marks this method as a slash command group
///
/// The name of this slash command.
/// The description of this slash command.
/// The default member permissions.
/// The dm permission.
/// Whether this command is marked as NSFW.
public SlashCommandGroupAttribute(string name, string description, long defaultMemberPermissions, bool dmPermission, bool isNsfw = false)
{
this.Name = name.ToLower();
this.Description = description;
this.DefaultMemberPermissions = (Permissions)defaultMemberPermissions;
this.DmPermission = dmPermission;
this.IsNsfw = isNsfw;
}
}
diff --git a/DisCatSharp.ApplicationCommands/Context/AutocompleteContext.cs b/DisCatSharp.ApplicationCommands/Context/AutocompleteContext.cs
index d2031c841..7a118a3d1 100644
--- a/DisCatSharp.ApplicationCommands/Context/AutocompleteContext.cs
+++ b/DisCatSharp.ApplicationCommands/Context/AutocompleteContext.cs
@@ -1,104 +1,105 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using Microsoft.Extensions.DependencyInjection;
namespace DisCatSharp.ApplicationCommands.Context;
///
/// Represents a context for an autocomplete interaction.
///
public class AutocompleteContext
{
///
/// The interaction created.
///
public DiscordInteraction Interaction { get; internal set; }
///
/// Gets the client for this interaction.
///
public DiscordClient Client { get; internal set; }
///
/// Gets the guild this interaction was executed in.
///
public DiscordGuild Guild { get; internal set; }
///
/// Gets the channel this interaction was executed in.
///
public DiscordChannel Channel { get; internal set; }
///
/// Gets the user which executed this interaction.
///
public DiscordUser User { get; internal set; }
///
/// Gets the member which executed this interaction, or null if the command is in a DM.
///
public DiscordMember Member
=> this.User is DiscordMember member ? member : null;
///
/// Gets the invoking user locale.
///
public string Locale { get; internal set; }
///
/// Gets the guild locale if applicable.
///
public string GuildLocale { get; internal set; }
///
/// Gets the applications permissions.
///
public Permissions AppPermissions { get; internal set; }
///
/// Gets the slash command module this interaction was created in.
///
public ApplicationCommandsExtension ApplicationCommandsExtension { get; internal set; }
///
/// Gets the service provider.
/// This allows passing data around without resorting to static members.
/// Defaults to an empty service provider.
///
public IServiceProvider Services { get; internal set; } = new ServiceCollection().BuildServiceProvider(true);
///
/// The options already provided.
///
public IReadOnlyList Options { get; internal set; }
///
/// The option to autocomplete.
///
public DiscordInteractionDataOption FocusedOption { get; internal set; }
}
diff --git a/DisCatSharp.CommandsNext/Attributes/RequireBotPermissionsAttribute.cs b/DisCatSharp.CommandsNext/Attributes/RequireBotPermissionsAttribute.cs
index b50236dee..5d560528b 100644
--- a/DisCatSharp.CommandsNext/Attributes/RequireBotPermissionsAttribute.cs
+++ b/DisCatSharp.CommandsNext/Attributes/RequireBotPermissionsAttribute.cs
@@ -1,76 +1,78 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
+using DisCatSharp.Enums;
+
namespace DisCatSharp.CommandsNext.Attributes;
///
/// Defines that usage of this command is only possible when the bot is granted a specific permission.
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public sealed class RequireBotPermissionsAttribute : CheckBaseAttribute
{
///
/// Gets the permissions required by this attribute.
///
public Permissions Permissions { get; }
///
/// Gets or sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
///
public bool IgnoreDms { get; } = true;
///
/// Defines that usage of this command is only possible when the bot is granted a specific permission.
///
/// Permissions required to execute this command.
/// Sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
public RequireBotPermissionsAttribute(Permissions permissions, bool ignoreDms = true)
{
this.Permissions = permissions;
this.IgnoreDms = ignoreDms;
}
///
/// Executes the a check.
///
/// The command context.
/// If true, help - returns true.
public override async Task ExecuteCheckAsync(CommandContext ctx, bool help)
{
if (ctx.Guild == null)
return this.IgnoreDms;
var bot = await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id).ConfigureAwait(false);
if (bot == null)
return false;
if (bot.Id == ctx.Guild.OwnerId)
return true;
var pbot = ctx.Channel.PermissionsFor(bot);
return (pbot & Permissions.Administrator) != 0 || (pbot & this.Permissions) == this.Permissions;
}
}
diff --git a/DisCatSharp.CommandsNext/Attributes/RequirePermissionsAttribute.cs b/DisCatSharp.CommandsNext/Attributes/RequirePermissionsAttribute.cs
index 483cabf7a..9362133f6 100644
--- a/DisCatSharp.CommandsNext/Attributes/RequirePermissionsAttribute.cs
+++ b/DisCatSharp.CommandsNext/Attributes/RequirePermissionsAttribute.cs
@@ -1,86 +1,88 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
+using DisCatSharp.Enums;
+
namespace DisCatSharp.CommandsNext.Attributes;
///
/// Defines that usage of this command is restricted to members with specified permissions. This check also verifies that the bot has the same permissions.
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public sealed class RequirePermissionsAttribute : CheckBaseAttribute
{
///
/// Gets the permissions required by this attribute.
///
public Permissions Permissions { get; }
///
/// Gets or sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
///
public bool IgnoreDms { get; } = true;
///
/// Defines that usage of this command is restricted to members with specified permissions. This check also verifies that the bot has the same permissions.
///
/// Permissions required to execute this command.
/// Sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
public RequirePermissionsAttribute(Permissions permissions, bool ignoreDms = true)
{
this.Permissions = permissions;
this.IgnoreDms = ignoreDms;
}
///
/// Executes the a check.
///
/// The command context.
/// If true, help - returns true.
public override async Task ExecuteCheckAsync(CommandContext ctx, bool help)
{
if (ctx.Guild == null)
return this.IgnoreDms;
var usr = ctx.Member;
if (usr == null)
return false;
var pusr = ctx.Channel.PermissionsFor(usr);
var bot = await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id).ConfigureAwait(false);
if (bot == null)
return false;
var pbot = ctx.Channel.PermissionsFor(bot);
var usrok = ctx.Guild.OwnerId == usr.Id;
var botok = ctx.Guild.OwnerId == bot.Id;
if (!usrok)
usrok = (pusr & Permissions.Administrator) != 0 || (pusr & this.Permissions) == this.Permissions;
if (!botok)
botok = (pbot & Permissions.Administrator) != 0 || (pbot & this.Permissions) == this.Permissions;
return usrok && botok;
}
}
diff --git a/DisCatSharp.CommandsNext/Attributes/RequireUserPermissionsAttribute.cs b/DisCatSharp.CommandsNext/Attributes/RequireUserPermissionsAttribute.cs
index 3c0cbc620..afd4d4ca4 100644
--- a/DisCatSharp.CommandsNext/Attributes/RequireUserPermissionsAttribute.cs
+++ b/DisCatSharp.CommandsNext/Attributes/RequireUserPermissionsAttribute.cs
@@ -1,80 +1,82 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
+using DisCatSharp.Enums;
+
namespace DisCatSharp.CommandsNext.Attributes;
///
/// Defines that usage of this command is restricted to members with specified permissions.
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public sealed class RequireUserPermissionsAttribute : CheckBaseAttribute
{
///
/// Gets the permissions required by this attribute.
///
public Permissions Permissions { get; }
///
/// Gets or sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
///
public bool IgnoreDms { get; } = true;
///
/// Defines that usage of this command is restricted to members with specified permissions.
///
/// Permissions required to execute this command.
/// Sets this check's behaviour in DMs. True means the check will always pass in DMs, whereas false means that it will always fail.
public RequireUserPermissionsAttribute(Permissions permissions, bool ignoreDms = true)
{
this.Permissions = permissions;
this.IgnoreDms = ignoreDms;
}
///
/// Executes the a check.
///
/// The command context.
/// If true, help - returns true.
public override Task ExecuteCheckAsync(CommandContext ctx, bool help)
{
if (ctx.Guild == null)
return Task.FromResult(this.IgnoreDms);
var usr = ctx.Member;
if (usr == null)
return Task.FromResult(false);
if (usr.Id == ctx.Guild.OwnerId)
return Task.FromResult(true);
var pusr = ctx.Channel.PermissionsFor(usr);
if ((pusr & Permissions.Administrator) != 0)
return Task.FromResult(true);
return (pusr & this.Permissions) == this.Permissions ? Task.FromResult(true) : Task.FromResult(false);
}
}
diff --git a/DisCatSharp.Configuration.Tests/ConfigurationExtensionTests.cs b/DisCatSharp.Configuration.Tests/ConfigurationExtensionTests.cs
index bfdc19779..52b1768ad 100644
--- a/DisCatSharp.Configuration.Tests/ConfigurationExtensionTests.cs
+++ b/DisCatSharp.Configuration.Tests/ConfigurationExtensionTests.cs
@@ -1,336 +1,337 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using DisCatSharp.Configuration.Models;
+using DisCatSharp.Enums;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Xunit;
namespace DisCatSharp.Configuration.Tests;
public class ConfigurationExtensionTests
{
#region Test Classes
class SampleClass
{
public int Amount { get; set; }
public string? Email { get; set; }
}
class ClassWithArray
{
public int[] Values { get; set; } = { 1, 2, 3, 4, 5 };
public string[] Strings { get; set; } = { "1", "2", "3", "4", "5" };
}
class ClassWithEnumerable
{
public IEnumerable Values { get; set; } = new[] { 1, 2, 3, 4, 5 };
public IEnumerable Strings { get; set; } = new[] { "1", "2", "3", "4", "5" };
}
class ClassWithList
{
public List Strings { get; set; } = new()
{
"1",
"2",
"3",
"4",
"5"
};
public List Values { get; set; } = new()
{
1,
2,
3,
4,
5
};
}
class SampleClass2
{
public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(7);
public string Name { get; set; } = "Sample";
public string ConstructorValue { get; }
public SampleClass2(string value)
{
this.ConstructorValue = value;
}
}
#endregion
private IConfiguration EnumerableTestConfiguration() =>
new ConfigurationBuilder()
.AddJsonFile("enumerable-test.json")
.Build();
private IConfiguration HasSectionWithSuffixConfiguration() =>
new ConfigurationBuilder()
.AddJsonFile("section-with-suffix.json")
.Build();
private IConfiguration HasSectionNoSuffixConfiguration() =>
new ConfigurationBuilder()
.AddJsonFile("section-no-suffix.json")
.Build();
private IConfiguration BasicDiscordConfiguration() => new ConfigurationBuilder()
.AddJsonFile("default-discord.json")
.Build();
private IConfiguration DiscordIntentsConfig() => new ConfigurationBuilder()
.AddJsonFile("intents-discord.json")
.Build();
private IConfiguration DiscordHaphazardConfig() => new ConfigurationBuilder()
.AddJsonFile("haphazard-discord.json")
.Build();
private IConfiguration SampleConfig() => new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
{ "Sample:Amount", "200" },
{ "Sample:Email", "test@gmail.com" }
})
.Build();
private IConfiguration SampleClass2Configuration_Default() => new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
{"Random:Stuff", "Meow"},
{"SampleClass2:Name", "Purfection"}
})
.Build();
private IConfiguration SampleClass2Configuration_Change() => new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
{ "SampleClass:Timeout", "01:30:00" }, { "SampleClass:NotValid", "Something" }
})
.Build();
private IConfiguration SampleClass2EnumerableTest() => new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
{ "SampleClass:EnumerableTest", "[\"10\",\"20\",\"30\"]" }
})
.Build();
private IConfiguration SampleClass2ArrayTest() => new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
{ "SampleClass:ArrayTest", "[\"10\",\"20\",\"30\"]" }
})
.Build();
private IConfiguration SampleClass2ListTest() => new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
{ "SampleClass:ListTest", "[\"10\",\"20\",\"30\"]" }
})
.Build();
[Fact]
public void TestExtractDiscordConfig_Intents()
{
var source = this.DiscordIntentsConfig();
var config = source.ExtractConfig("Discord");
var expected = DiscordIntents.GuildEmojisAndStickers | DiscordIntents.GuildMembers |
DiscordIntents.GuildInvites | DiscordIntents.GuildMessageReactions;
Assert.Equal(expected, config.Intents);
}
[Fact]
public void TestExtractDiscordConfig_Haphazard()
{
var source = this.DiscordHaphazardConfig();
var config = source.ExtractConfig("Discord");
var expectedIntents = DiscordIntents.GuildEmojisAndStickers | DiscordIntents.GuildMembers |
DiscordIntents.Guilds;
Assert.Equal(expectedIntents, config.Intents);
Assert.True(config.MobileStatus);
Assert.Equal(1000, config.LargeThreshold);
Assert.Equal(TimeSpan.FromHours(10), config.HttpTimeout);
}
[Fact]
public void TestExtractDiscordConfig_Default()
{
var source = this.BasicDiscordConfiguration();
var config = source.ExtractConfig("Discord");
Assert.Equal("1234567890", config.Token);
Assert.Equal(TokenType.Bot, config.TokenType);
Assert.Equal(LogLevel.Information, config.MinimumLogLevel);
Assert.True(config.UseRelativeRatelimit);
Assert.Equal("yyyy-MM-dd HH:mm:ss zzz", config.LogTimestampFormat);
Assert.Equal(250, config.LargeThreshold);
Assert.True(config.AutoReconnect);
Assert.Equal(123123, config.ShardId);
Assert.Equal(GatewayCompressionLevel.Stream, config.GatewayCompressionLevel);
Assert.Equal(1024, config.MessageCacheSize);
Assert.Equal(TimeSpan.FromSeconds(20), config.HttpTimeout);
Assert.False(config.ReconnectIndefinitely);
Assert.True(config.AlwaysCacheMembers);
Assert.Equal(DiscordIntents.AllUnprivileged, config.Intents);
Assert.False(config.MobileStatus);
Assert.False(config.UseCanary);
Assert.False(config.AutoRefreshChannelCache);
}
[Fact]
public void TestSection()
{
var source = this.SampleConfig();
var config = source.ExtractConfig("Sample", null);
Assert.Equal(200, config.Amount);
Assert.Equal("test@gmail.com", config.Email);
}
[Fact]
public void TestExtractConfig_V2_Default()
{
var source = this.SampleClass2Configuration_Default();
var config = (SampleClass2) source.ExtractConfig("SampleClass", () => new SampleClass2("Test"), null);
Assert.Equal(TimeSpan.FromMinutes(7), config.Timeout);
Assert.Equal("Test", config.ConstructorValue);
Assert.Equal("Sample", config.Name);
}
[Fact]
public void TestExtractConfig_V2_Change()
{
var source = this.SampleClass2Configuration_Change();
var config = (SampleClass2) source.ExtractConfig("SampleClass", () => new SampleClass2("Test123"), null);
var span = new TimeSpan(0, 1, 30, 0);
Assert.Equal(span, config.Timeout);
Assert.Equal("Test123", config.ConstructorValue);
Assert.Equal("Sample", config.Name);
}
[Fact]
public void TestExtractConfig_V3_Default()
{
var source = this.SampleClass2Configuration_Default();
var config =
(SampleClass2)new ConfigSection(ref source, "SampleClass", null).ExtractConfig(() =>
new SampleClass2("Meow"));
Assert.Equal("Meow", config.ConstructorValue);
Assert.Equal(TimeSpan.FromMinutes(7), config.Timeout);
Assert.Equal("Sample", config.Name);
}
[Fact]
public void TestExtractConfig_V3_Change()
{
var source = this.SampleClass2Configuration_Change();
var config =
(SampleClass2)new ConfigSection(ref source, "SampleClass", null).ExtractConfig(() =>
new SampleClass2("Meow"));
Assert.Equal("Meow", config.ConstructorValue);
var span = new TimeSpan(0, 1, 30, 0);
Assert.Equal(span, config.Timeout);
Assert.Equal("Sample", config.Name);
}
[Fact]
public void TestExtractConfig_Enumerable()
{
var source = this.EnumerableTestConfiguration();
var config =
(ClassWithEnumerable)new ConfigSection(ref source, "ClassWithEnumerable", null).ExtractConfig(() =>
new ClassWithEnumerable());
Assert.NotNull(config.Values);
Assert.Equal(3, config.Values.Count());
Assert.NotNull(config.Strings);
Assert.Equal(3, config.Values.Count());
}
[Fact]
public void TestExtractConfig_Array()
{
var source = this.EnumerableTestConfiguration();
var config =
(ClassWithArray)new ConfigSection(ref source, "ClassWithArray", null).ExtractConfig(() =>
new ClassWithArray());
Assert.NotNull(config.Values);
Assert.Equal(3, config.Values.Length);
Assert.NotNull(config.Strings);
Assert.Equal(3, config.Values.Length);
}
[Fact]
public void TestExtractConfig_List()
{
var source = this.EnumerableTestConfiguration();
var config =
(ClassWithList)new ConfigSection(ref source, "ClassWithList", null).ExtractConfig(() =>
new ClassWithList());
Assert.NotNull(config.Values);
Assert.Equal(3, config.Values.Count);
Assert.NotNull(config.Strings);
Assert.Equal(3, config.Values.Count);
}
[Fact]
public void TestHasSectionWithSuffix()
{
var source = this.HasSectionWithSuffixConfiguration();
Assert.True(source.HasSection("DiscordConfiguration"));
Assert.False(source.HasSection("Discord"));
#pragma warning disable 8625
Assert.False(source.HasSection("DiscordConfiguration", null));
#pragma warning restore 8625
}
[Fact]
public void TestHasSectionNoSuffix()
{
var source = this.HasSectionNoSuffixConfiguration();
Assert.True(source.HasSection("Discord"));
Assert.False(source.HasSection("DiscordConfiguration"));
#pragma warning disable 8625
Assert.False(source.HasSection("Discord", null));
#pragma warning restore 8625
}
}
diff --git a/DisCatSharp.Interactivity/EventHandling/Components/ComponentEventWaiter.cs b/DisCatSharp.Interactivity/EventHandling/Components/ComponentEventWaiter.cs
index d7a7b654d..cf3c66b56 100644
--- a/DisCatSharp.Interactivity/EventHandling/Components/ComponentEventWaiter.cs
+++ b/DisCatSharp.Interactivity/EventHandling/Components/ComponentEventWaiter.cs
@@ -1,151 +1,152 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ConcurrentCollections;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using DisCatSharp.Interactivity.Enums;
using Microsoft.Extensions.Logging;
namespace DisCatSharp.Interactivity.EventHandling;
///
/// A component-based version of
///
internal class ComponentEventWaiter : IDisposable
{
private readonly DiscordClient _client;
private readonly ConcurrentHashSet _matchRequests = new();
private readonly ConcurrentHashSet _collectRequests = new();
private readonly DiscordFollowupMessageBuilder _message;
private readonly InteractivityConfiguration _config;
///
/// Initializes a new instance of the class.
///
/// The client.
/// The config.
public ComponentEventWaiter(DiscordClient client, InteractivityConfiguration config)
{
this._client = client;
this._client.ComponentInteractionCreated += this.Handle;
this._config = config;
this._message = new DiscordFollowupMessageBuilder { Content = config.ResponseMessage ?? "This message was not meant for you.", IsEphemeral = true };
}
///
/// Waits for a specified 's predicate to be fulfilled.
///
/// The request to wait for.
/// The returned args, or null if it timed out.
public async Task WaitForMatchAsync(ComponentMatchRequest request)
{
this._matchRequests.Add(request);
try
{
return await request.Tcs.Task.ConfigureAwait(false);
}
catch (Exception e)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityWaitError, e, "An exception was thrown while waiting for components.");
return null;
}
finally
{
this._matchRequests.TryRemove(request);
}
}
///
/// Collects reactions and returns the result when the 's cancellation token is canceled.
///
/// The request to wait on.
/// The result from request's predicate over the period of time leading up to the token's cancellation.
public async Task> CollectMatchesAsync(ComponentCollectRequest request)
{
this._collectRequests.Add(request);
try
{
await request.Tcs.Task.ConfigureAwait(false);
}
catch (Exception e)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityCollectorError, e, "There was an error while collecting component event args.");
}
finally
{
this._collectRequests.TryRemove(request);
}
return request.Collected.ToArray();
}
///
/// Handles the waiter.
///
/// The client.
/// The args.
private async Task Handle(DiscordClient _, ComponentInteractionCreateEventArgs args)
{
foreach (var mreq in this._matchRequests)
{
if (mreq.Message == args.Message && mreq.IsMatch(args))
mreq.Tcs.TrySetResult(args);
else if (this._config.ResponseBehavior is InteractionResponseBehavior.Respond)
await args.Interaction.CreateFollowupMessageAsync(this._message).ConfigureAwait(false);
}
foreach (var creq in this._collectRequests)
{
if (creq.Message == args.Message && creq.IsMatch(args))
{
await args.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate).ConfigureAwait(false);
if (creq.IsMatch(args))
creq.Collected.Add(args);
else if (this._config.ResponseBehavior is InteractionResponseBehavior.Respond)
await args.Interaction.CreateFollowupMessageAsync(this._message).ConfigureAwait(false);
}
}
}
///
/// Disposes the waiter.
///
public void Dispose()
{
this._matchRequests.Clear();
this._collectRequests.Clear();
this._client.ComponentInteractionCreated -= this.Handle;
}
}
diff --git a/DisCatSharp.Interactivity/EventHandling/Components/ComponentPaginator.cs b/DisCatSharp.Interactivity/EventHandling/Components/ComponentPaginator.cs
index 1f8798141..cb53a053b 100644
--- a/DisCatSharp.Interactivity/EventHandling/Components/ComponentPaginator.cs
+++ b/DisCatSharp.Interactivity/EventHandling/Components/ComponentPaginator.cs
@@ -1,182 +1,183 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using DisCatSharp.Interactivity.Enums;
using Microsoft.Extensions.Logging;
namespace DisCatSharp.Interactivity.EventHandling;
///
/// The component paginator.
///
internal class ComponentPaginator : IPaginator
{
private readonly DiscordClient _client;
private readonly InteractivityConfiguration _config;
private readonly DiscordMessageBuilder _builder = new();
private readonly Dictionary _requests = new();
///
/// Initializes a new instance of the class.
///
/// The client.
/// The config.
public ComponentPaginator(DiscordClient client, InteractivityConfiguration config)
{
this._client = client;
this._client.ComponentInteractionCreated += this.Handle;
this._config = config;
}
///
/// Does the pagination async.
///
/// The request.
public async Task DoPaginationAsync(IPaginationRequest request)
{
var id = (await request.GetMessageAsync().ConfigureAwait(false)).Id;
this._requests.Add(id, request);
try
{
var tcs = await request.GetTaskCompletionSourceAsync().ConfigureAwait(false);
await tcs.Task.ConfigureAwait(false);
}
catch (Exception ex)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityPaginationError, ex, "There was an exception while paginating.");
}
finally
{
this._requests.Remove(id);
try
{
await request.DoCleanupAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityPaginationError, ex, "There was an exception while cleaning up pagination.");
}
}
}
///
/// Disposes the paginator.
///
public void Dispose() => this._client.ComponentInteractionCreated -= this.Handle;
///
/// Handles the pagination event.
///
/// The client.
/// The event arguments.
private async Task Handle(DiscordClient _, ComponentInteractionCreateEventArgs e)
{
if (e.Interaction.Type == InteractionType.ModalSubmit)
return;
if (!this._requests.TryGetValue(e.Message.Id, out var req))
return;
if (this._config.AckPaginationButtons)
{
e.Handled = true;
await e.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate).ConfigureAwait(false);
}
if (await req.GetUserAsync().ConfigureAwait(false) != e.User)
{
if (this._config.ResponseBehavior is InteractionResponseBehavior.Respond)
await e.Interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder { Content = this._config.ResponseMessage, IsEphemeral = true }).ConfigureAwait(false);
return;
}
if (req is InteractionPaginationRequest ipr)
ipr.RegenerateCts(e.Interaction); // Necessary to ensure we don't prematurely yeet the CTS //
await this.HandlePaginationAsync(req, e).ConfigureAwait(false);
}
///
/// Handles the pagination async.
///
/// The request.
/// The arguments.
private async Task HandlePaginationAsync(IPaginationRequest request, ComponentInteractionCreateEventArgs args)
{
var buttons = this._config.PaginationButtons;
var msg = await request.GetMessageAsync().ConfigureAwait(false);
var id = args.Id;
var tcs = await request.GetTaskCompletionSourceAsync().ConfigureAwait(false);
#pragma warning disable CS8846 // The switch expression does not handle all possible values of its input type (it is not exhaustive).
var paginationTask = id switch
#pragma warning restore CS8846 // The switch expression does not handle all possible values of its input type (it is not exhaustive).
{
_ when id == buttons.SkipLeft.CustomId => request.SkipLeftAsync(),
_ when id == buttons.SkipRight.CustomId => request.SkipRightAsync(),
_ when id == buttons.Stop.CustomId => Task.FromResult(tcs.TrySetResult(true)),
_ when id == buttons.Left.CustomId => request.PreviousPageAsync(),
_ when id == buttons.Right.CustomId => request.NextPageAsync(),
};
await paginationTask.ConfigureAwait(false);
if (id == buttons.Stop.CustomId)
return;
var page = await request.GetPageAsync().ConfigureAwait(false);
var bts = await request.GetButtonsAsync().ConfigureAwait(false);
if (request is InteractionPaginationRequest ipr)
{
var builder = new DiscordWebhookBuilder()
.WithContent(page.Content)
.AddEmbed(page.Embed)
.AddComponents(bts);
await args.Interaction.EditOriginalResponseAsync(builder).ConfigureAwait(false);
return;
}
this._builder.Clear();
this._builder
.WithContent(page.Content)
.AddEmbed(page.Embed)
.AddComponents(bts);
await this._builder.ModifyAsync(msg).ConfigureAwait(false);
}
}
diff --git a/DisCatSharp.Interactivity/EventHandling/Paginator.cs b/DisCatSharp.Interactivity/EventHandling/Paginator.cs
index a34233022..41386de81 100644
--- a/DisCatSharp.Interactivity/EventHandling/Paginator.cs
+++ b/DisCatSharp.Interactivity/EventHandling/Paginator.cs
@@ -1,304 +1,305 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Threading.Tasks;
using ConcurrentCollections;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using DisCatSharp.Interactivity.Enums;
using Microsoft.Extensions.Logging;
namespace DisCatSharp.Interactivity.EventHandling;
///
/// The paginator.
///
internal class Paginator : IPaginator
{
DiscordClient _client;
ConcurrentHashSet _requests;
///
/// Creates a new EventWaiter object.
///
/// Discord client
public Paginator(DiscordClient client)
{
this._client = client;
this._requests = new ConcurrentHashSet();
this._client.MessageReactionAdded += this.HandleReactionAdd;
this._client.MessageReactionRemoved += this.HandleReactionRemove;
this._client.MessageReactionsCleared += this.HandleReactionClear;
}
///
/// Dos the pagination async.
///
/// The request.
public async Task DoPaginationAsync(IPaginationRequest request)
{
await this.ResetReactionsAsync(request).ConfigureAwait(false);
this._requests.Add(request);
try
{
var tcs = await request.GetTaskCompletionSourceAsync().ConfigureAwait(false);
await tcs.Task.ConfigureAwait(false);
}
catch (Exception ex)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityPaginationError, ex, "Exception occurred while paginating");
}
finally
{
this._requests.TryRemove(request);
try
{
await request.DoCleanupAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityPaginationError, ex, "Exception occurred while paginating");
}
}
}
///
/// Handles the reaction add.
///
/// The client.
/// The event's arguments.
private Task HandleReactionAdd(DiscordClient client, MessageReactionAddEventArgs eventArgs)
{
if (this._requests.Count == 0)
return Task.CompletedTask;
_ = Task.Run(async () =>
{
foreach (var req in this._requests)
{
var emojis = await req.GetEmojisAsync().ConfigureAwait(false);
var msg = await req.GetMessageAsync().ConfigureAwait(false);
var usr = await req.GetUserAsync().ConfigureAwait(false);
if (msg.Id == eventArgs.Message.Id)
{
if (eventArgs.User.Id == usr.Id)
{
if (req.PageCount > 1 &&
(eventArgs.Emoji == emojis.Left ||
eventArgs.Emoji == emojis.SkipLeft ||
eventArgs.Emoji == emojis.Right ||
eventArgs.Emoji == emojis.SkipRight ||
eventArgs.Emoji == emojis.Stop))
{
await this.PaginateAsync(req, eventArgs.Emoji).ConfigureAwait(false);
}
else if (eventArgs.Emoji == emojis.Stop &&
req is PaginationRequest paginationRequest &&
paginationRequest.PaginationDeletion == PaginationDeletion.DeleteMessage)
{
await this.PaginateAsync(req, eventArgs.Emoji).ConfigureAwait(false);
}
else
{
await msg.DeleteReactionAsync(eventArgs.Emoji, eventArgs.User).ConfigureAwait(false);
}
}
else if (eventArgs.User.Id != this._client.CurrentUser.Id)
{
if (eventArgs.Emoji != emojis.Left &&
eventArgs.Emoji != emojis.SkipLeft &&
eventArgs.Emoji != emojis.Right &&
eventArgs.Emoji != emojis.SkipRight &&
eventArgs.Emoji != emojis.Stop)
{
await msg.DeleteReactionAsync(eventArgs.Emoji, eventArgs.User).ConfigureAwait(false);
}
}
}
}
});
return Task.CompletedTask;
}
///
/// Handles the reaction remove.
///
/// The client.
/// The event's arguments.
private Task HandleReactionRemove(DiscordClient client, MessageReactionRemoveEventArgs eventArgs)
{
if (this._requests.Count == 0)
return Task.CompletedTask;
_ = Task.Run(async () =>
{
foreach (var req in this._requests)
{
var emojis = await req.GetEmojisAsync().ConfigureAwait(false);
var msg = await req.GetMessageAsync().ConfigureAwait(false);
var usr = await req.GetUserAsync().ConfigureAwait(false);
if (msg.Id == eventArgs.Message.Id)
{
if (eventArgs.User.Id == usr.Id)
{
if (req.PageCount > 1 &&
(eventArgs.Emoji == emojis.Left ||
eventArgs.Emoji == emojis.SkipLeft ||
eventArgs.Emoji == emojis.Right ||
eventArgs.Emoji == emojis.SkipRight ||
eventArgs.Emoji == emojis.Stop))
{
await this.PaginateAsync(req, eventArgs.Emoji).ConfigureAwait(false);
}
else if (eventArgs.Emoji == emojis.Stop &&
req is PaginationRequest paginationRequest &&
paginationRequest.PaginationDeletion == PaginationDeletion.DeleteMessage)
{
await this.PaginateAsync(req, eventArgs.Emoji).ConfigureAwait(false);
}
}
}
}
});
return Task.CompletedTask;
}
///
/// Handles the reaction clear.
///
/// The client.
/// The eventArgs.
private Task HandleReactionClear(DiscordClient client, MessageReactionsClearEventArgs eventArgs)
{
if (this._requests.Count == 0)
return Task.CompletedTask;
_ = Task.Run(async () =>
{
foreach (var req in this._requests)
{
var msg = await req.GetMessageAsync().ConfigureAwait(false);
if (msg.Id == eventArgs.Message.Id)
{
await this.ResetReactionsAsync(req).ConfigureAwait(false);
}
}
});
return Task.CompletedTask;
}
///
/// Resets the reactions async.
///
/// The p.
private async Task ResetReactionsAsync(IPaginationRequest p)
{
var msg = await p.GetMessageAsync().ConfigureAwait(false);
var emojis = await p.GetEmojisAsync().ConfigureAwait(false);
var chn = msg.Channel;
var gld = chn?.Guild;
var mbr = gld?.CurrentMember;
if (mbr != null && (chn.PermissionsFor(mbr) & Permissions.ManageMessages) != 0)
await msg.DeleteAllReactionsAsync("Pagination").ConfigureAwait(false);
if (p.PageCount > 1)
{
if (emojis.SkipLeft != null)
await msg.CreateReactionAsync(emojis.SkipLeft).ConfigureAwait(false);
if (emojis.Left != null)
await msg.CreateReactionAsync(emojis.Left).ConfigureAwait(false);
if (emojis.Right != null)
await msg.CreateReactionAsync(emojis.Right).ConfigureAwait(false);
if (emojis.SkipRight != null)
await msg.CreateReactionAsync(emojis.SkipRight).ConfigureAwait(false);
if (emojis.Stop != null)
await msg.CreateReactionAsync(emojis.Stop).ConfigureAwait(false);
}
else if (emojis.Stop != null && p is PaginationRequest paginationRequest && paginationRequest.PaginationDeletion == PaginationDeletion.DeleteMessage)
{
await msg.CreateReactionAsync(emojis.Stop).ConfigureAwait(false);
}
}
///
/// Paginates the async.
///
/// The p.
/// The emoji.
private async Task PaginateAsync(IPaginationRequest p, DiscordEmoji emoji)
{
var emojis = await p.GetEmojisAsync().ConfigureAwait(false);
var msg = await p.GetMessageAsync().ConfigureAwait(false);
if (emoji == emojis.SkipLeft)
await p.SkipLeftAsync().ConfigureAwait(false);
else if (emoji == emojis.Left)
await p.PreviousPageAsync().ConfigureAwait(false);
else if (emoji == emojis.Right)
await p.NextPageAsync().ConfigureAwait(false);
else if (emoji == emojis.SkipRight)
await p.SkipRightAsync().ConfigureAwait(false);
else if (emoji == emojis.Stop)
{
var tcs = await p.GetTaskCompletionSourceAsync().ConfigureAwait(false);
tcs.TrySetResult(true);
return;
}
var page = await p.GetPageAsync().ConfigureAwait(false);
var builder = new DiscordMessageBuilder()
.WithContent(page.Content)
.WithEmbed(page.Embed);
await builder.ModifyAsync(msg).ConfigureAwait(false);
}
~Paginator()
{
this.Dispose();
}
///
/// Disposes this EventWaiter
///
public void Dispose()
{
this._client.MessageReactionAdded -= this.HandleReactionAdd;
this._client.MessageReactionRemoved -= this.HandleReactionRemove;
this._client.MessageReactionsCleared -= this.HandleReactionClear;
this._client = null;
this._requests.Clear();
this._requests = null;
}
}
diff --git a/DisCatSharp.Interactivity/EventHandling/Poller.cs b/DisCatSharp.Interactivity/EventHandling/Poller.cs
index 976508d4d..5c3fc35de 100644
--- a/DisCatSharp.Interactivity/EventHandling/Poller.cs
+++ b/DisCatSharp.Interactivity/EventHandling/Poller.cs
@@ -1,176 +1,177 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ConcurrentCollections;
+using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using Microsoft.Extensions.Logging;
namespace DisCatSharp.Interactivity.EventHandling;
///
/// The poller.
///
internal class Poller
{
DiscordClient _client;
ConcurrentHashSet _requests;
///
/// Creates a new EventWaiter object.
///
/// Your DiscordClient
public Poller(DiscordClient client)
{
this._client = client;
this._requests = new ConcurrentHashSet();
this._client.MessageReactionAdded += this.HandleReactionAdd;
this._client.MessageReactionRemoved += this.HandleReactionRemove;
this._client.MessageReactionsCleared += this.HandleReactionClear;
}
///
/// Dos the poll async.
///
/// The request.
/// A Task.
public async Task> DoPollAsync(PollRequest request)
{
ReadOnlyCollection result = null;
this._requests.Add(request);
try
{
await request.Tcs.Task.ConfigureAwait(false);
}
catch (Exception ex)
{
this._client.Logger.LogError(InteractivityEvents.InteractivityPollError, ex, "Exception occurred while polling");
}
finally
{
result = new ReadOnlyCollection(new HashSet(request.Collected).ToList());
request.Dispose();
this._requests.TryRemove(request);
}
return result;
}
///
/// Handles the reaction add.
///
/// The client.
/// The event's arguments.
/// A Task.
private Task HandleReactionAdd(DiscordClient client, MessageReactionAddEventArgs eventArgs)
{
if (this._requests.Count == 0)
return Task.CompletedTask;
_ = Task.Run(async () =>
{
foreach (var req in this._requests)
{
// match message
if (req.Message.Id == eventArgs.Message.Id && req.Message.ChannelId == eventArgs.Channel.Id)
{
if (req.Emojis.Contains(eventArgs.Emoji) && !req.Collected.Any(x => x.Voted.Contains(eventArgs.User)))
{
if (eventArgs.User.Id != this._client.CurrentUser.Id)
req.AddReaction(eventArgs.Emoji, eventArgs.User);
}
else
{
var member = await eventArgs.Channel.Guild.GetMemberAsync(client.CurrentUser.Id).ConfigureAwait(false);
if (eventArgs.Channel.PermissionsFor(member).HasPermission(Permissions.ManageMessages))
await eventArgs.Message.DeleteReactionAsync(eventArgs.Emoji, eventArgs.User).ConfigureAwait(false);
}
}
}
});
return Task.CompletedTask;
}
///
/// Handles the reaction remove.
///
/// The client.
/// The event's arguments.
/// A Task.
private Task HandleReactionRemove(DiscordClient client, MessageReactionRemoveEventArgs eventArgs)
{
foreach (var req in this._requests)
{
// match message
if (req.Message.Id == eventArgs.Message.Id && req.Message.ChannelId == eventArgs.Channel.Id)
{
if (eventArgs.User.Id != this._client.CurrentUser.Id)
req.RemoveReaction(eventArgs.Emoji, eventArgs.User);
}
}
return Task.CompletedTask;
}
///
/// Handles the reaction clear.
///
/// The client.
/// The event's arguments.
/// A Task.
private Task HandleReactionClear(DiscordClient client, MessageReactionsClearEventArgs eventArgs)
{
foreach (var req in this._requests)
{
// match message
if (req.Message.Id == eventArgs.Message.Id && req.Message.ChannelId == eventArgs.Channel.Id)
{
req.ClearCollected();
}
}
return Task.CompletedTask;
}
~Poller()
{
this.Dispose();
}
///
/// Disposes this EventWaiter
///
public void Dispose()
{
this._client.MessageReactionAdded -= this.HandleReactionAdd;
this._client.MessageReactionRemoved -= this.HandleReactionRemove;
this._client.MessageReactionsCleared -= this.HandleReactionClear;
this._client = null;
this._requests.Clear();
this._requests = null;
}
}
diff --git a/DisCatSharp.Interactivity/Extensions/InteractionExtensions.cs b/DisCatSharp.Interactivity/Extensions/InteractionExtensions.cs
index a6de60d97..dc5e5b3ca 100644
--- a/DisCatSharp.Interactivity/Extensions/InteractionExtensions.cs
+++ b/DisCatSharp.Interactivity/Extensions/InteractionExtensions.cs
@@ -1,120 +1,121 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using DisCatSharp.Interactivity.Enums;
using DisCatSharp.Interactivity.EventHandling;
namespace DisCatSharp.Interactivity.Extensions;
///
/// The interaction extensions.
///
public static class InteractionExtensions
{
///
/// Sends a paginated message in response to an interaction.
///
/// Pass the interaction directly. Interactivity will ACK it.
///
///
/// The interaction to create a response to.
/// Whether the interaction was deferred.
/// Whether the response should be ephemeral.
/// The user to listen for button presses from.
/// The pages to paginate.
/// Optional: custom buttons
/// Pagination behaviour.
/// Deletion behaviour
/// A custom cancellation token that can be cancelled at any point.
public static Task SendPaginatedResponseAsync(this DiscordInteraction interaction, bool deferred, bool ephemeral, DiscordUser user, IEnumerable pages, PaginationButtons buttons = null, PaginationBehaviour? behaviour = default, ButtonPaginationBehavior? deletion = default, CancellationToken token = default)
=> MessageExtensions.GetInteractivity(interaction.Message).SendPaginatedResponseAsync(interaction, deferred, ephemeral, user, pages, buttons, behaviour, deletion, token);
///
/// Sends multiple modals to the user with a prompt to open the next one.
///
/// The interaction to create a response to.
/// The modal pages.
/// A custom timeout. (Default: 15 minutes)
/// A read-only dictionary with the customid of the components as the key.
/// Is thrown when no modals are defined.
/// Is thrown when interactivity is not enabled for the client/shard.
public static async Task CreatePaginatedModalResponseAsync(this DiscordInteraction interaction, IReadOnlyList modals, TimeSpan? timeOutOverride = null)
{
if (modals is null || modals.Count == 0)
throw new ArgumentException("You have to set at least one page");
var client = (DiscordClient)interaction.Discord;
var interactivity = client.GetInteractivity() ?? throw new InvalidOperationException($"Interactivity is not enabled for this {(client.IsShard ? "shard" : "client")}.");
timeOutOverride ??= TimeSpan.FromMinutes(15);
Dictionary caughtResponses = new();
var previousInteraction = interaction;
foreach (var b in modals)
{
var modal = b.Modal.WithCustomId(Guid.NewGuid().ToString());
if (previousInteraction.Type is InteractionType.Ping or InteractionType.ModalSubmit)
{
await previousInteraction.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, b.OpenMessage.AddComponents(b.OpenButton));
var originalResponse = await previousInteraction.GetOriginalResponseAsync();
var modalOpen = await interactivity.WaitForButtonAsync(originalResponse, new List { b.OpenButton }, timeOutOverride);
if (modalOpen.TimedOut)
{
_ = previousInteraction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(b.OpenMessage.Content).AddComponents(b.OpenButton.Disable()));
return new PaginatedModalResponse { TimedOut = true };
}
await modalOpen.Result.Interaction.CreateInteractionModalResponseAsync(modal);
}
else
{
await previousInteraction.CreateInteractionModalResponseAsync(modal);
}
_ = previousInteraction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent(b.OpenMessage.Content).AddComponents(b.OpenButton.Disable()));
var modalResult = await interactivity.WaitForModalAsync(modal.CustomId, timeOutOverride);
if (modalResult.TimedOut)
return new PaginatedModalResponse { TimedOut = true };
foreach (var submissions in modalResult.Result.Interaction.Data.Components)
caughtResponses.Add(submissions.CustomId, submissions.Value);
previousInteraction = modalResult.Result.Interaction;
}
await previousInteraction.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral());
return new PaginatedModalResponse { TimedOut = false, Responses = caughtResponses, Interaction = previousInteraction };
}
}
diff --git a/DisCatSharp/Clients/DiscordClient.Dispatch.cs b/DisCatSharp/Clients/DiscordClient.Dispatch.cs
index 09d0bd65b..2f16c21fd 100644
--- a/DisCatSharp/Clients/DiscordClient.Dispatch.cs
+++ b/DisCatSharp/Clients/DiscordClient.Dispatch.cs
@@ -1,3427 +1,3431 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DisCatSharp.Common;
using DisCatSharp.Entities;
using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using DisCatSharp.Exceptions;
using DisCatSharp.Net.Abstractions;
using DisCatSharp.Net.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DisCatSharp;
///
/// Represents a discord Logger.ent.L
///
public sealed partial class DiscordClient
{
#region Private Fields
private string _resumeGatewayUrl;
private string _sessionId;
private bool _guildDownloadCompleted;
private readonly Dictionary> _tempTimers = new();
///
/// Represents a timeout handler.
///
internal class TimeoutHandler
{
///
/// Gets the member.
///
internal readonly DiscordMember Member;
///
/// Gets the guild.
///
internal readonly DiscordGuild Guild;
///
/// Gets the old timeout value.
///
internal DateTime? TimeoutUntilOld;
///
/// Gets the new timeout value.
///
internal DateTime? TimeoutUntilNew;
///
/// Constructs a new .
///
/// The affected member.
/// The affected guild.
/// The old timeout value.
/// The new timeout value.
internal TimeoutHandler(DiscordMember mbr, DiscordGuild guild, DateTime? too, DateTime? ton)
{
this.Guild = guild;
this.Member = mbr;
this.TimeoutUntilOld = too;
this.TimeoutUntilNew = ton;
}
}
#endregion
#region Dispatch Handler
///
/// Handles the dispatch payloads.
///
/// The payload.
internal async Task HandleDispatchAsync(GatewayPayload payload)
{
if (payload.Data is not JObject dat)
{
this.Logger.LogWarning(LoggerEvents.WebSocketReceive, "Invalid payload body (this message is probably safe to ignore); opcode: {0} event: {1}; payload: {2}", payload.OpCode, payload.EventName, payload.Data);
return;
}
await this._payloadReceived.InvokeAsync(this, new PayloadReceivedEventArgs(this.ServiceProvider)
{
EventName = payload.EventName,
PayloadObject = dat
}).ConfigureAwait(false);
#region Default objects
DiscordChannel chn;
ulong gid;
ulong cid;
ulong uid;
DiscordStageInstance stg = default;
DiscordIntegration itg = default;
DiscordThreadChannel trd = default;
DiscordThreadChannelMember trdm = default;
DiscordScheduledEvent gse = default;
TransportUser usr = default;
TransportMember mbr = default;
TransportUser refUsr = default;
TransportMember refMbr = default;
JToken rawMbr = default;
var rawRefMsg = dat["referenced_message"];
#endregion
switch (payload.EventName.ToLowerInvariant())
{
#region Gateway Status
case "ready":
var glds = (JArray)dat["guilds"];
await this.OnReadyEventAsync(dat.ToObject(), glds).ConfigureAwait(false);
break;
case "resumed":
await this.OnResumedAsync().ConfigureAwait(false);
break;
#endregion
#region Channel
case "channel_create":
chn = dat.ToObject();
await this.OnChannelCreateEventAsync(chn).ConfigureAwait(false);
break;
case "channel_update":
await this.OnChannelUpdateEventAsync(dat.ToObject()).ConfigureAwait(false);
break;
case "channel_delete":
chn = dat.ToObject();
await this.OnChannelDeleteEventAsync(chn.IsPrivate ? dat.ToObject() : chn).ConfigureAwait(false);
break;
case "channel_pins_update":
cid = (ulong)dat["channel_id"];
var ts = (string)dat["last_pin_timestamp"];
await this.OnChannelPinsUpdateAsync((ulong?)dat["guild_id"], cid, ts != null ? DateTimeOffset.Parse(ts, CultureInfo.InvariantCulture) : default(DateTimeOffset?)).ConfigureAwait(false);
break;
#endregion
#region Guild
case "guild_create":
await this.OnGuildCreateEventAsync(dat.ToDiscordObject(), (JArray)dat["members"], dat["presences"].ToDiscordObject>()).ConfigureAwait(false);
break;
case "guild_update":
await this.OnGuildUpdateEventAsync(dat.ToDiscordObject(), (JArray)dat["members"]).ConfigureAwait(false);
break;
case "guild_delete":
await this.OnGuildDeleteEventAsync(dat.ToDiscordObject()).ConfigureAwait(false);
break;
case "guild_sync":
gid = (ulong)dat["id"];
await this.OnGuildSyncEventAsync(this.GuildsInternal[gid], (bool)dat["large"], (JArray)dat["members"], dat["presences"].ToDiscordObject>()).ConfigureAwait(false);
break;
case "guild_emojis_update":
gid = (ulong)dat["guild_id"];
var ems = dat["emojis"].ToObject>();
await this.OnGuildEmojisUpdateEventAsync(this.GuildsInternal[gid], ems).ConfigureAwait(false);
break;
case "guild_stickers_update":
gid = (ulong)dat["guild_id"];
var strs = dat["stickers"].ToDiscordObject>();
await this.OnStickersUpdatedAsync(strs, gid).ConfigureAwait(false);
break;
case "guild_integrations_update":
gid = (ulong)dat["guild_id"];
// discord fires this event inconsistently if the current user leaves a guild.
if (!this.GuildsInternal.ContainsKey(gid))
return;
await this.OnGuildIntegrationsUpdateEventAsync(this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_join_request_create":
break;
case "guild_join_request_update":
break;
case "guild_join_request_delete":
break;
#endregion
#region Guild Ban
case "guild_ban_add":
usr = dat["user"].ToObject();
gid = (ulong)dat["guild_id"];
await this.OnGuildBanAddEventAsync(usr, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_ban_remove":
usr = dat["user"].ToObject();
gid = (ulong)dat["guild_id"];
await this.OnGuildBanRemoveEventAsync(usr, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
#endregion
#region Guild Event
case "guild_scheduled_event_create":
gse = dat.ToObject();
gid = (ulong)dat["guild_id"];
await this.OnGuildScheduledEventCreateEventAsync(gse, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_scheduled_event_update":
gse = dat.ToObject();
gid = (ulong)dat["guild_id"];
await this.OnGuildScheduledEventUpdateEventAsync(gse, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_scheduled_event_delete":
gse = dat.ToObject();
gid = (ulong)dat["guild_id"];
await this.OnGuildScheduledEventDeleteEventAsync(gse, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_scheduled_event_user_add":
gid = (ulong)dat["guild_id"];
uid = (ulong)dat["user_id"];
await this.OnGuildScheduledEventUserAddedEventAsync((ulong)dat["guild_scheduled_event_id"], uid, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_scheduled_event_user_remove":
gid = (ulong)dat["guild_id"];
uid = (ulong)dat["user_id"];
await this.OnGuildScheduledEventUserRemovedEventAsync((ulong)dat["guild_scheduled_event_id"], uid, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
#endregion
#region Guild Integration
case "integration_create":
gid = (ulong)dat["guild_id"];
itg = dat.ToObject();
// discord fires this event inconsistently if the current user leaves a guild.
if (!this.GuildsInternal.ContainsKey(gid))
return;
await this.OnGuildIntegrationCreateEventAsync(this.GuildsInternal[gid], itg).ConfigureAwait(false);
break;
case "integration_update":
gid = (ulong)dat["guild_id"];
itg = dat.ToObject();
// discord fires this event inconsistently if the current user leaves a guild.
if (!this.GuildsInternal.ContainsKey(gid))
return;
await this.OnGuildIntegrationUpdateEventAsync(this.GuildsInternal[gid], itg).ConfigureAwait(false);
break;
case "integration_delete":
gid = (ulong)dat["guild_id"];
// discord fires this event inconsistently if the current user leaves a guild.
if (!this.GuildsInternal.ContainsKey(gid))
return;
await this.OnGuildIntegrationDeleteEventAsync(this.GuildsInternal[gid], (ulong)dat["id"], (ulong?)dat["application_id"]).ConfigureAwait(false);
break;
#endregion
#region Guild Member
case "guild_member_add":
gid = (ulong)dat["guild_id"];
await this.OnGuildMemberAddEventAsync(dat.ToObject(), this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_member_remove":
gid = (ulong)dat["guild_id"];
usr = dat["user"].ToObject();
if (!this.GuildsInternal.ContainsKey(gid))
{
// discord fires this event inconsistently if the current user leaves a guild.
if (usr.Id != this.CurrentUser.Id)
this.Logger.LogError(LoggerEvents.WebSocketReceive, "Could not find {0} in guild cache", gid);
return;
}
await this.OnGuildMemberRemoveEventAsync(usr, this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_member_update":
gid = (ulong)dat["guild_id"];
await this.OnGuildMemberUpdateEventAsync(dat.ToDiscordObject(), this.GuildsInternal[gid], dat["roles"].ToObject>(), (string)dat["nick"], (bool?)dat["pending"]).ConfigureAwait(false);
break;
case "guild_members_chunk":
await this.OnGuildMembersChunkEventAsync(dat).ConfigureAwait(false);
break;
#endregion
#region Guild Role
case "guild_role_create":
gid = (ulong)dat["guild_id"];
await this.OnGuildRoleCreateEventAsync(dat["role"].ToObject(), this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_role_update":
gid = (ulong)dat["guild_id"];
await this.OnGuildRoleUpdateEventAsync(dat["role"].ToObject(), this.GuildsInternal[gid]).ConfigureAwait(false);
break;
case "guild_role_delete":
gid = (ulong)dat["guild_id"];
await this.OnGuildRoleDeleteEventAsync((ulong)dat["role_id"], this.GuildsInternal[gid]).ConfigureAwait(false);
break;
#endregion
#region Invite
case "invite_create":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnInviteCreateEventAsync(cid, gid, dat.ToObject()).ConfigureAwait(false);
break;
case "invite_delete":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnInviteDeleteEventAsync(cid, gid, dat).ConfigureAwait(false);
break;
#endregion
#region Message
case "message_ack":
cid = (ulong)dat["channel_id"];
var mid = (ulong)dat["message_id"];
await this.OnMessageAckEventAsync(this.InternalGetCachedChannel(cid), mid).ConfigureAwait(false);
break;
case "message_create":
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject();
if (rawRefMsg != null && rawRefMsg.HasValues)
{
if (rawRefMsg.SelectToken("author") != null)
{
refUsr = rawRefMsg.SelectToken("author").ToObject();
}
if (rawRefMsg.SelectToken("member") != null)
{
refMbr = rawRefMsg.SelectToken("member").ToObject();
}
}
await this.OnMessageCreateEventAsync(dat.ToDiscordObject(), dat["author"].ToObject(), mbr, refUsr, refMbr).ConfigureAwait(false);
break;
case "message_update":
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject();
if (rawRefMsg != null && rawRefMsg.HasValues)
{
if (rawRefMsg.SelectToken("author") != null)
{
refUsr = rawRefMsg.SelectToken("author").ToObject();
}
if (rawRefMsg.SelectToken("member") != null)
{
refMbr = rawRefMsg.SelectToken("member").ToObject();
}
}
await this.OnMessageUpdateEventAsync(dat.ToDiscordObject(), dat["author"]?.ToObject(), mbr, refUsr, refMbr).ConfigureAwait(false);
break;
// delete event does *not* include message object
case "message_delete":
await this.OnMessageDeleteEventAsync((ulong)dat["id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "message_delete_bulk":
await this.OnMessageBulkDeleteEventAsync(dat["ids"].ToObject(), (ulong)dat["channel_id"], (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
#endregion
#region Message Reaction
case "message_reaction_add":
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject();
await this.OnMessageReactionAddAsync((ulong)dat["user_id"], (ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"], mbr, dat["emoji"].ToObject()).ConfigureAwait(false);
break;
case "message_reaction_remove":
await this.OnMessageReactionRemoveAsync((ulong)dat["user_id"], (ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"], dat["emoji"].ToObject()).ConfigureAwait(false);
break;
case "message_reaction_remove_all":
await this.OnMessageReactionRemoveAllAsync((ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "message_reaction_remove_emoji":
await this.OnMessageReactionRemoveEmojiAsync((ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong)dat["guild_id"], dat["emoji"]).ConfigureAwait(false);
break;
#endregion
#region Stage Instance
case "stage_instance_create":
stg = dat.ToObject();
await this.OnStageInstanceCreateEventAsync(stg).ConfigureAwait(false);
break;
case "stage_instance_update":
stg = dat.ToObject();
await this.OnStageInstanceUpdateEventAsync(stg).ConfigureAwait(false);
break;
case "stage_instance_delete":
stg = dat.ToObject();
await this.OnStageInstanceDeleteEventAsync(stg).ConfigureAwait(false);
break;
#endregion
#region Thread
case "thread_create":
trd = dat.ToObject();
await this.OnThreadCreateEventAsync(trd).ConfigureAwait(false);
break;
case "thread_update":
trd = dat.ToObject();
await this.OnThreadUpdateEventAsync(trd).ConfigureAwait(false);
break;
case "thread_delete":
trd = dat.ToObject();
await this.OnThreadDeleteEventAsync(trd).ConfigureAwait(false);
break;
case "thread_list_sync":
gid = (ulong)dat["guild_id"]; //get guild
await this.OnThreadListSyncEventAsync(this.GuildsInternal[gid], dat["channel_ids"].ToObject>(), dat["threads"].ToObject>(), dat["members"].ToObject>()).ConfigureAwait(false);
break;
case "thread_member_update":
trdm = dat.ToObject();
await this.OnThreadMemberUpdateEventAsync(trdm).ConfigureAwait(false);
break;
case "thread_members_update":
gid = (ulong)dat["guild_id"];
await this.OnThreadMembersUpdateEventAsync(this.GuildsInternal[gid], (ulong)dat["id"], (JArray)dat["added_members"], (JArray)dat["removed_member_ids"], (int)dat["member_count"]).ConfigureAwait(false);
break;
#endregion
#region Activities
case "embedded_activity_update":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnEmbeddedActivityUpdateAsync((JObject)dat["embedded_activity"], this.GuildsInternal[gid], cid, (JArray)dat["users"], (ulong)dat["embedded_activity"]["application_id"]).ConfigureAwait(false);
break;
#endregion
#region User/Presence Update
case "presence_update":
await this.OnPresenceUpdateEventAsync(dat, (JObject)dat["user"]).ConfigureAwait(false);
break;
case "user_settings_update":
await this.OnUserSettingsUpdateEventAsync(dat.ToObject()).ConfigureAwait(false);
break;
case "user_update":
await this.OnUserUpdateEventAsync(dat.ToObject()).ConfigureAwait(false);
break;
#endregion
#region Voice
case "voice_state_update":
await this.OnVoiceStateUpdateEventAsync(dat).ConfigureAwait(false);
break;
case "voice_server_update":
gid = (ulong)dat["guild_id"];
await this.OnVoiceServerUpdateEventAsync((string)dat["endpoint"], (string)dat["token"], this.GuildsInternal[gid]).ConfigureAwait(false);
break;
#endregion
#region Interaction/Integration/Application
case "interaction_create":
rawMbr = dat["member"];
if (rawMbr != null)
{
mbr = dat["member"].ToObject();
usr = mbr.User;
}
else
{
usr = dat["user"].ToObject();
}
cid = (ulong)dat["channel_id"];
// Console.WriteLine(dat.ToString()); // Get raw interaction payload.
await this.OnInteractionCreateAsync((ulong?)dat["guild_id"], cid, usr, mbr, dat.ToDiscordObject(), dat.ToString()).ConfigureAwait(false);
break;
case "application_command_create":
await this.OnApplicationCommandCreateAsync(dat.ToObject(), (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "application_command_update":
await this.OnApplicationCommandUpdateAsync(dat.ToObject(), (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "application_command_delete":
await this.OnApplicationCommandDeleteAsync(dat.ToObject(), (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "guild_application_command_counts_update":
var counts = dat["application_command_counts"];
await this.OnGuildApplicationCommandCountsUpdateAsync((int)counts["1"], (int)counts["2"], (int)counts["3"], (ulong)dat["guild_id"]).ConfigureAwait(false);
break;
case "guild_application_command_index_update":
// TODO: Implement.
break;
case "application_command_permissions_update":
var aid = (ulong)dat["application_id"];
if (aid != this.CurrentApplication.Id)
return;
var pms = dat["permissions"].ToObject>();
gid = (ulong)dat["guild_id"];
await this.OnApplicationCommandPermissionsUpdateAsync(pms, (ulong)dat["id"], gid, aid).ConfigureAwait(false);
break;
#endregion
#region Misc
case "gift_code_update": //Not supposed to be dispatched to bots
break;
case "typing_start":
cid = (ulong)dat["channel_id"];
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject();
await this.OnTypingStartEventAsync((ulong)dat["user_id"], cid, this.InternalGetCachedChannel(cid), (ulong?)dat["guild_id"], Utilities.GetDateTimeOffset((long)dat["timestamp"]), mbr).ConfigureAwait(false);
break;
case "webhooks_update":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnWebhooksUpdateAsync(this.GuildsInternal[gid].GetChannel(cid), this.GuildsInternal[gid]).ConfigureAwait(false);
break;
default:
await this.OnUnknownEventAsync(payload).ConfigureAwait(false);
this.Logger.LogWarning(LoggerEvents.WebSocketReceive, "Unknown event: {0}\npayload: {1}", payload.EventName, payload.Data);
break;
#endregion
}
}
#endregion
#region Events
#region Gateway
///
/// Handles the ready event.
///
/// The ready payload.
/// The raw guilds.
internal async Task OnReadyEventAsync(ReadyPayload ready, JArray rawGuilds)
{
//ready.CurrentUser.Discord = this;
var rusr = ready.CurrentUser;
this.CurrentUser.Username = rusr.Username;
this.CurrentUser.Discriminator = rusr.Discriminator;
this.CurrentUser.AvatarHash = rusr.AvatarHash;
this.CurrentUser.MfaEnabled = rusr.MfaEnabled;
this.CurrentUser.Verified = rusr.Verified;
this.CurrentUser.IsBot = rusr.IsBot;
this.CurrentUser.Flags = rusr.Flags;
this.GatewayVersion = ready.GatewayVersion;
this._sessionId = ready.SessionId;
this._resumeGatewayUrl = ready.ResumeGatewayUrl;
var rawGuildIndex = rawGuilds.ToDictionary(xt => (ulong)xt["id"], xt => (JObject)xt);
this.GuildsInternal.Clear();
foreach (var guild in ready.Guilds)
{
guild.Discord = this;
guild.ChannelsInternal ??= new ConcurrentDictionary();
foreach (var xc in guild.Channels.Values)
{
xc.GuildId = guild.Id;
xc.Initialize(this);
}
guild.RolesInternal ??= new ConcurrentDictionary();
foreach (var xr in guild.Roles.Values)
{
xr.Discord = this;
xr.GuildId = guild.Id;
}
var rawGuild = rawGuildIndex[guild.Id];
var rawMembers = (JArray)rawGuild["members"];
if (guild.MembersInternal != null)
guild.MembersInternal.Clear();
else
guild.MembersInternal = new ConcurrentDictionary();
if (rawMembers != null)
{
foreach (var xj in rawMembers)
{
var xtm = xj.ToObject();
var xu = new DiscordUser(xtm.User) { Discord = this };
xu = this.UserCache.AddOrUpdate(xtm.User.Id, xu, (id, old) =>
{
old.Username = xu.Username;
old.Discriminator = xu.Discriminator;
old.AvatarHash = xu.AvatarHash;
return old;
});
guild.MembersInternal[xtm.User.Id] = new DiscordMember(xtm) { Discord = this, GuildId = guild.Id };
}
}
guild.EmojisInternal ??= new ConcurrentDictionary();
foreach (var xe in guild.Emojis.Values)
xe.Discord = this;
guild.StickersInternal ??= new ConcurrentDictionary();
foreach (var xs in guild.Stickers.Values)
xs.Discord = this;
guild.VoiceStatesInternal ??= new ConcurrentDictionary();
foreach (var xvs in guild.VoiceStates.Values)
xvs.Discord = this;
guild.ThreadsInternal ??= new ConcurrentDictionary();
foreach (var xt in guild.ThreadsInternal.Values)
xt.Discord = this;
guild.StageInstancesInternal ??= new ConcurrentDictionary();
foreach (var xsi in guild.StageInstancesInternal.Values)
xsi.Discord = this;
guild.ScheduledEventsInternal ??= new ConcurrentDictionary();
foreach (var xse in guild.ScheduledEventsInternal.Values)
xse.Discord = this;
this.GuildsInternal[guild.Id] = guild;
}
await this._ready.InvokeAsync(this, new ReadyEventArgs(this.ServiceProvider)).ConfigureAwait(false);
}
///
/// Handles the resumed event.
///
internal Task OnResumedAsync()
{
this.Logger.LogInformation(LoggerEvents.SessionUpdate, "Session resumed");
return this._resumed.InvokeAsync(this, new ReadyEventArgs(this.ServiceProvider));
}
#endregion
#region Channel
///
/// Handles the channel create event.
///
/// The channel.
internal async Task OnChannelCreateEventAsync(DiscordChannel channel)
{
channel.Initialize(this);
this.GuildsInternal[channel.GuildId.Value].ChannelsInternal[channel.Id] = channel;
/*if (this.Configuration.AutoRefreshChannelCache)
{
await this.RefreshChannelsAsync(channel.Guild.Id);
}*/
await this._channelCreated.InvokeAsync(this, new ChannelCreateEventArgs(this.ServiceProvider) { Channel = channel, Guild = channel.Guild }).ConfigureAwait(false);
}
///
/// Handles the channel update event.
///
/// The channel.
internal async Task OnChannelUpdateEventAsync(DiscordChannel channel)
{
if (channel == null)
return;
channel.Discord = this;
var gld = channel.Guild;
var channelNew = this.InternalGetCachedChannel(channel.Id);
DiscordChannel channelOld = null;
if (channelNew != null)
{
channelOld = new DiscordChannel
{
Bitrate = channelNew.Bitrate,
Discord = this,
GuildId = channelNew.GuildId,
Id = channelNew.Id,
LastMessageId = channelNew.LastMessageId,
Name = channelNew.Name,
PermissionOverwritesInternal = new List(channelNew.PermissionOverwritesInternal),
Position = channelNew.Position,
Topic = channelNew.Topic,
Type = channelNew.Type,
UserLimit = channelNew.UserLimit,
ParentId = channelNew.ParentId,
IsNsfw = channelNew.IsNsfw,
PerUserRateLimit = channelNew.PerUserRateLimit,
RtcRegionId = channelNew.RtcRegionId,
QualityMode = channelNew.QualityMode,
DefaultAutoArchiveDuration = channelNew.DefaultAutoArchiveDuration,
};
channelNew.Bitrate = channel.Bitrate;
channelNew.Name = channel.Name;
channelNew.Position = channel.Position;
channelNew.Topic = channel.Topic;
channelNew.UserLimit = channel.UserLimit;
channelNew.ParentId = channel.ParentId;
channelNew.IsNsfw = channel.IsNsfw;
channelNew.PerUserRateLimit = channel.PerUserRateLimit;
channelNew.Type = channel.Type;
channelNew.RtcRegionId = channel.RtcRegionId;
channelNew.QualityMode = channel.QualityMode;
channelNew.DefaultAutoArchiveDuration = channel.DefaultAutoArchiveDuration;
channelNew.PermissionOverwritesInternal.Clear();
channel.Initialize(this);
channelNew.PermissionOverwritesInternal.AddRange(channel.PermissionOverwritesInternal);
if (channel.Type == ChannelType.Forum)
{
channelOld.PostCreateUserRateLimit = channelNew.PostCreateUserRateLimit;
channelOld.InternalAvailableTags = channelNew.InternalAvailableTags;
channelOld.Template = channelNew.Template;
channelOld.DefaultReactionEmoji = channelNew.DefaultReactionEmoji;
+ channelOld.DefaultSortOrder = channelNew.DefaultSortOrder;
channelNew.PostCreateUserRateLimit = channel.PostCreateUserRateLimit;
channelNew.Template = channel.Template;
channelNew.DefaultReactionEmoji = channel.DefaultReactionEmoji;
+ channelNew.DefaultSortOrder = channel.DefaultSortOrder;
if (channelNew.InternalAvailableTags != null && channelNew.InternalAvailableTags.Any())
channelNew.InternalAvailableTags.Clear();
if (channel.InternalAvailableTags != null && channel.InternalAvailableTags.Any())
channelNew.InternalAvailableTags.AddRange(channel.InternalAvailableTags);
}
else
{
channelOld.PostCreateUserRateLimit = null;
channelOld.InternalAvailableTags = null;
channelOld.Template = null;
channelOld.DefaultReactionEmoji = null;
+ channelOld.DefaultSortOrder = null;
channelNew.PostCreateUserRateLimit = null;
+ channelNew.InternalAvailableTags = null;
channelNew.Template = null;
channelNew.DefaultReactionEmoji = null;
- channelNew.InternalAvailableTags = null;
+ channelNew.DefaultSortOrder = null;
}
channelOld.Initialize(this);
channelNew.Initialize(this);
if (this.Configuration.AutoRefreshChannelCache && gld != null)
{
await this.RefreshChannelsAsync(channel.Guild.Id);
}
}
else if (gld != null)
{
gld.ChannelsInternal[channel.Id] = channel;
if (this.Configuration.AutoRefreshChannelCache)
{
await this.RefreshChannelsAsync(channel.Guild.Id);
}
}
await this._channelUpdated.InvokeAsync(this, new ChannelUpdateEventArgs(this.ServiceProvider) { ChannelAfter = channelNew, Guild = gld, ChannelBefore = channelOld }).ConfigureAwait(false);
}
///
/// Handles the channel delete event.
///
/// The channel.
internal async Task OnChannelDeleteEventAsync(DiscordChannel channel)
{
if (channel == null)
return;
channel.Discord = this;
//if (channel.IsPrivate)
if (channel.Type == ChannelType.Group || channel.Type == ChannelType.Private)
{
var dmChannel = channel as DiscordDmChannel;
await this._dmChannelDeleted.InvokeAsync(this, new DmChannelDeleteEventArgs(this.ServiceProvider) { Channel = dmChannel }).ConfigureAwait(false);
}
else
{
var gld = channel.Guild;
if (gld.ChannelsInternal.TryRemove(channel.Id, out var cachedChannel)) channel = cachedChannel;
if (this.Configuration.AutoRefreshChannelCache)
{
await this.RefreshChannelsAsync(channel.Guild.Id);
}
await this._channelDeleted.InvokeAsync(this, new ChannelDeleteEventArgs(this.ServiceProvider) { Channel = channel, Guild = gld }).ConfigureAwait(false);
}
}
///
/// Refreshes the channels.
///
/// The guild id.
internal async Task RefreshChannelsAsync(ulong guildId)
{
var guild = this.InternalGetCachedGuild(guildId);
var channels = await this.ApiClient.GetGuildChannelsAsync(guildId);
guild.ChannelsInternal.Clear();
foreach (var channel in channels.ToList())
{
channel.Initialize(this);
guild.ChannelsInternal[channel.Id] = channel;
}
}
///
/// Handles the channel pins update event.
///
/// The optional guild id.
/// The channel id.
/// The optional last pin timestamp.
internal async Task OnChannelPinsUpdateAsync(ulong? guildId, ulong channelId, DateTimeOffset? lastPinTimestamp)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
var ea = new ChannelPinsUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
Channel = channel,
LastPinTimestamp = lastPinTimestamp
};
await this._channelPinsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Guild
///
/// Handles the guild create event.
///
/// The guild.
/// The raw members.
/// The presences.
internal async Task OnGuildCreateEventAsync(DiscordGuild guild, JArray rawMembers, IEnumerable presences)
{
if (presences != null)
{
foreach (var xp in presences)
{
xp.Discord = this;
xp.GuildId = guild.Id;
xp.Activity = new DiscordActivity(xp.RawActivity);
if (xp.RawActivities != null)
{
xp.InternalActivities = xp.RawActivities
.Select(x => new DiscordActivity(x)).ToArray();
}
this.PresencesInternal[xp.InternalUser.Id] = xp;
}
}
var exists = this.GuildsInternal.TryGetValue(guild.Id, out var foundGuild);
guild.Discord = this;
guild.IsUnavailable = false;
var eventGuild = guild;
if (exists)
guild = foundGuild;
guild.ChannelsInternal ??= new ConcurrentDictionary();
guild.ThreadsInternal ??= new ConcurrentDictionary();
guild.RolesInternal ??= new ConcurrentDictionary();
guild.ThreadsInternal ??= new ConcurrentDictionary();
guild.StickersInternal ??= new ConcurrentDictionary();
guild.EmojisInternal ??= new ConcurrentDictionary();
guild.VoiceStatesInternal ??= new ConcurrentDictionary();
guild.MembersInternal ??= new ConcurrentDictionary();
guild.ScheduledEventsInternal ??= new ConcurrentDictionary();
this.UpdateCachedGuild(eventGuild, rawMembers);
guild.JoinedAt = eventGuild.JoinedAt;
guild.IsLarge = eventGuild.IsLarge;
guild.MemberCount = Math.Max(eventGuild.MemberCount, guild.MembersInternal.Count);
guild.IsUnavailable = eventGuild.IsUnavailable;
guild.PremiumSubscriptionCount = eventGuild.PremiumSubscriptionCount;
guild.PremiumTier = eventGuild.PremiumTier;
guild.BannerHash = eventGuild.BannerHash;
guild.VanityUrlCode = eventGuild.VanityUrlCode;
guild.Description = eventGuild.Description;
guild.IsNsfw = eventGuild.IsNsfw;
foreach (var kvp in eventGuild.VoiceStatesInternal) guild.VoiceStatesInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.ChannelsInternal) guild.ChannelsInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.RolesInternal) guild.RolesInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.EmojisInternal) guild.EmojisInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.ThreadsInternal) guild.ThreadsInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.StickersInternal) guild.StickersInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.StageInstancesInternal) guild.StageInstancesInternal[kvp.Key] = kvp.Value;
foreach (var kvp in eventGuild.ScheduledEventsInternal) guild.ScheduledEventsInternal[kvp.Key] = kvp.Value;
foreach (var xc in guild.ChannelsInternal.Values)
{
xc.GuildId = guild.Id;
xc.Initialize(this);
}
foreach (var xt in guild.ThreadsInternal.Values)
{
xt.GuildId = guild.Id;
xt.Discord = this;
}
foreach (var xe in guild.EmojisInternal.Values)
xe.Discord = this;
foreach (var xs in guild.StickersInternal.Values)
xs.Discord = this;
foreach (var xvs in guild.VoiceStatesInternal.Values)
xvs.Discord = this;
foreach (var xsi in guild.StageInstancesInternal.Values)
{
xsi.Discord = this;
xsi.GuildId = guild.Id;
}
foreach (var xr in guild.RolesInternal.Values)
{
xr.Discord = this;
xr.GuildId = guild.Id;
}
foreach (var xse in guild.ScheduledEventsInternal.Values)
{
xse.Discord = this;
xse.GuildId = guild.Id;
if (xse.Creator != null)
xse.Creator.Discord = this;
}
var old = Volatile.Read(ref this._guildDownloadCompleted);
var dcompl = this.GuildsInternal.Values.All(xg => !xg.IsUnavailable);
Volatile.Write(ref this._guildDownloadCompleted, dcompl);
if (exists)
await this._guildAvailable.InvokeAsync(this, new GuildCreateEventArgs(this.ServiceProvider) { Guild = guild }).ConfigureAwait(false);
else
await this._guildCreated.InvokeAsync(this, new GuildCreateEventArgs(this.ServiceProvider) { Guild = guild }).ConfigureAwait(false);
if (dcompl && !old)
await this._guildDownloadCompletedEv.InvokeAsync(this, new GuildDownloadCompletedEventArgs(this.Guilds, this.ServiceProvider)).ConfigureAwait(false);
}
///
/// Handles the guild update event.
///
/// The guild.
/// The raw members.
internal async Task OnGuildUpdateEventAsync(DiscordGuild guild, JArray rawMembers)
{
DiscordGuild oldGuild;
if (!this.GuildsInternal.ContainsKey(guild.Id))
{
this.GuildsInternal[guild.Id] = guild;
oldGuild = null;
}
else
{
var gld = this.GuildsInternal[guild.Id];
oldGuild = new DiscordGuild
{
Discord = gld.Discord,
Name = gld.Name,
AfkChannelId = gld.AfkChannelId,
AfkTimeout = gld.AfkTimeout,
ApplicationId = gld.ApplicationId,
DefaultMessageNotifications = gld.DefaultMessageNotifications,
ExplicitContentFilter = gld.ExplicitContentFilter,
RawFeatures = gld.RawFeatures,
IconHash = gld.IconHash,
Id = gld.Id,
IsLarge = gld.IsLarge,
IsSynced = gld.IsSynced,
IsUnavailable = gld.IsUnavailable,
JoinedAt = gld.JoinedAt,
MemberCount = gld.MemberCount,
MaxMembers = gld.MaxMembers,
MaxPresences = gld.MaxPresences,
ApproximateMemberCount = gld.ApproximateMemberCount,
ApproximatePresenceCount = gld.ApproximatePresenceCount,
MaxVideoChannelUsers = gld.MaxVideoChannelUsers,
DiscoverySplashHash = gld.DiscoverySplashHash,
PreferredLocale = gld.PreferredLocale,
MfaLevel = gld.MfaLevel,
OwnerId = gld.OwnerId,
SplashHash = gld.SplashHash,
SystemChannelId = gld.SystemChannelId,
SystemChannelFlags = gld.SystemChannelFlags,
Description = gld.Description,
WidgetEnabled = gld.WidgetEnabled,
WidgetChannelId = gld.WidgetChannelId,
VerificationLevel = gld.VerificationLevel,
RulesChannelId = gld.RulesChannelId,
PublicUpdatesChannelId = gld.PublicUpdatesChannelId,
VoiceRegionId = gld.VoiceRegionId,
IsNsfw = gld.IsNsfw,
PremiumProgressBarEnabled = gld.PremiumProgressBarEnabled,
PremiumSubscriptionCount = gld.PremiumSubscriptionCount,
PremiumTier = gld.PremiumTier,
ChannelsInternal = new ConcurrentDictionary(),
ThreadsInternal = new ConcurrentDictionary(),
EmojisInternal = new ConcurrentDictionary(),
StickersInternal = new ConcurrentDictionary(),
MembersInternal = new ConcurrentDictionary(),
RolesInternal = new ConcurrentDictionary(),
StageInstancesInternal = new ConcurrentDictionary(),
VoiceStatesInternal = new ConcurrentDictionary(),
ScheduledEventsInternal = new ConcurrentDictionary()
};
foreach (var kvp in gld.ChannelsInternal) oldGuild.ChannelsInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.ThreadsInternal) oldGuild.ThreadsInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.EmojisInternal) oldGuild.EmojisInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.StickersInternal) oldGuild.StickersInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.RolesInternal) oldGuild.RolesInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.VoiceStatesInternal) oldGuild.VoiceStatesInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.MembersInternal) oldGuild.MembersInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.StageInstancesInternal) oldGuild.StageInstancesInternal[kvp.Key] = kvp.Value;
foreach (var kvp in gld.ScheduledEventsInternal) oldGuild.ScheduledEventsInternal[kvp.Key] = kvp.Value;
}
guild.Discord = this;
guild.IsUnavailable = false;
var eventGuild = guild;
guild = this.GuildsInternal[eventGuild.Id];
guild.ChannelsInternal ??= new ConcurrentDictionary();
guild.ThreadsInternal ??= new ConcurrentDictionary();
guild.RolesInternal ??= new ConcurrentDictionary();
guild.EmojisInternal ??= new ConcurrentDictionary();
guild.StickersInternal ??= new ConcurrentDictionary();
guild.VoiceStatesInternal ??= new ConcurrentDictionary();
guild.StageInstancesInternal ??= new ConcurrentDictionary();
guild.MembersInternal ??= new ConcurrentDictionary();
guild.ScheduledEventsInternal ??= new ConcurrentDictionary();
this.UpdateCachedGuild(eventGuild, rawMembers);
foreach (var xc in guild.ChannelsInternal.Values)
{
xc.GuildId = guild.Id;
xc.Initialize(this);
}
foreach (var xc in guild.ThreadsInternal.Values)
{
xc.GuildId = guild.Id;
xc.Discord = this;
}
foreach (var xe in guild.EmojisInternal.Values)
xe.Discord = this;
foreach (var xs in guild.StickersInternal.Values)
xs.Discord = this;
foreach (var xvs in guild.VoiceStatesInternal.Values)
xvs.Discord = this;
foreach (var xr in guild.RolesInternal.Values)
{
xr.Discord = this;
xr.GuildId = guild.Id;
}
foreach (var xsi in guild.StageInstancesInternal.Values)
{
xsi.Discord = this;
xsi.GuildId = guild.Id;
}
foreach (var xse in guild.ScheduledEventsInternal.Values)
{
xse.Discord = this;
xse.GuildId = guild.Id;
if (xse.Creator != null)
xse.Creator.Discord = this;
}
await this._guildUpdated.InvokeAsync(this, new GuildUpdateEventArgs(this.ServiceProvider) { GuildBefore = oldGuild, GuildAfter = guild }).ConfigureAwait(false);
}
///
/// Handles the guild delete event.
///
/// The guild.
internal async Task OnGuildDeleteEventAsync(DiscordGuild guild)
{
if (guild.IsUnavailable)
{
if (!this.GuildsInternal.TryGetValue(guild.Id, out var gld))
return;
gld.IsUnavailable = true;
await this._guildUnavailable.InvokeAsync(this, new GuildDeleteEventArgs(this.ServiceProvider) { Guild = guild, Unavailable = true }).ConfigureAwait(false);
}
else
{
if (!this.GuildsInternal.TryRemove(guild.Id, out var gld))
return;
await this._guildDeleted.InvokeAsync(this, new GuildDeleteEventArgs(this.ServiceProvider) { Guild = gld }).ConfigureAwait(false);
}
}
///
/// Handles the guild sync event.
///
/// The guild.
/// Whether the guild is a large guild..
/// The raw members.
/// The presences.
internal async Task OnGuildSyncEventAsync(DiscordGuild guild, bool isLarge, JArray rawMembers, IEnumerable presences)
{
presences = presences.Select(xp => { xp.Discord = this; xp.Activity = new DiscordActivity(xp.RawActivity); return xp; });
foreach (var xp in presences)
this.PresencesInternal[xp.InternalUser.Id] = xp;
guild.IsSynced = true;
guild.IsLarge = isLarge;
this.UpdateCachedGuild(guild, rawMembers);
await this._guildAvailable.InvokeAsync(this, new GuildCreateEventArgs(this.ServiceProvider) { Guild = guild }).ConfigureAwait(false);
}
///
/// Handles the guild emojis update event.
///
/// The guild.
/// The new emojis.
internal async Task OnGuildEmojisUpdateEventAsync(DiscordGuild guild, IEnumerable newEmojis)
{
var oldEmojis = new ConcurrentDictionary(guild.EmojisInternal);
guild.EmojisInternal.Clear();
foreach (var emoji in newEmojis)
{
emoji.Discord = this;
guild.EmojisInternal[emoji.Id] = emoji;
}
var ea = new GuildEmojisUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
EmojisAfter = guild.Emojis,
EmojisBefore = new ReadOnlyConcurrentDictionary(oldEmojis)
};
await this._guildEmojisUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the stickers updated.
///
/// The new stickers.
/// The guild id.
internal async Task OnStickersUpdatedAsync(IEnumerable newStickers, ulong guildId)
{
var guild = this.InternalGetCachedGuild(guildId);
var oldStickers = new ConcurrentDictionary(guild.StickersInternal);
guild.StickersInternal.Clear();
foreach (var nst in newStickers)
{
if (nst.User is not null)
{
nst.User.Discord = this;
this.UserCache.AddOrUpdate(nst.User.Id, nst.User, (old, @new) => @new);
}
nst.Discord = this;
guild.StickersInternal[nst.Id] = nst;
}
var sea = new GuildStickersUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
StickersBefore = oldStickers,
StickersAfter = guild.Stickers
};
await this._guildStickersUpdated.InvokeAsync(this, sea).ConfigureAwait(false);
}
#endregion
#region Guild Ban
///
/// Handles the guild ban add event.
///
/// The transport user.
/// The guild.
internal async Task OnGuildBanAddEventAsync(TransportUser user, DiscordGuild guild)
{
var usr = new DiscordUser(user) { Discord = this };
usr = this.UserCache.AddOrUpdate(user.Id, usr, (id, old) =>
{
old.Username = usr.Username;
old.Discriminator = usr.Discriminator;
old.AvatarHash = usr.AvatarHash;
return old;
});
if (!guild.Members.TryGetValue(user.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, GuildId = guild.Id };
var ea = new GuildBanAddEventArgs(this.ServiceProvider)
{
Guild = guild,
Member = mbr
};
await this._guildBanAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild ban remove event.
///
/// The transport user.
/// The guild.
internal async Task OnGuildBanRemoveEventAsync(TransportUser user, DiscordGuild guild)
{
var usr = new DiscordUser(user) { Discord = this };
usr = this.UserCache.AddOrUpdate(user.Id, usr, (id, old) =>
{
old.Username = usr.Username;
old.Discriminator = usr.Discriminator;
old.AvatarHash = usr.AvatarHash;
return old;
});
if (!guild.Members.TryGetValue(user.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, GuildId = guild.Id };
var ea = new GuildBanRemoveEventArgs(this.ServiceProvider)
{
Guild = guild,
Member = mbr
};
await this._guildBanRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Guild Scheduled Event
///
/// Handles the scheduled event create event.
///
/// The created event.
/// The guild.
internal async Task OnGuildScheduledEventCreateEventAsync(DiscordScheduledEvent scheduledEvent, DiscordGuild guild)
{
scheduledEvent.Discord = this;
guild.ScheduledEventsInternal.AddOrUpdate(scheduledEvent.Id, scheduledEvent, (old, newScheduledEvent) => newScheduledEvent);
if (scheduledEvent.Creator != null)
{
scheduledEvent.Creator.Discord = this;
this.UserCache.AddOrUpdate(scheduledEvent.Creator.Id, scheduledEvent.Creator, (id, old) =>
{
old.Username = scheduledEvent.Creator.Username;
old.Discriminator = scheduledEvent.Creator.Discriminator;
old.AvatarHash = scheduledEvent.Creator.AvatarHash;
old.Flags = scheduledEvent.Creator.Flags;
return old;
});
}
await this._guildScheduledEventCreated.InvokeAsync(this, new GuildScheduledEventCreateEventArgs(this.ServiceProvider) { ScheduledEvent = scheduledEvent, Guild = scheduledEvent.Guild }).ConfigureAwait(false);
}
///
/// Handles the scheduled event update event.
///
/// The updated event.
/// The guild.
internal async Task OnGuildScheduledEventUpdateEventAsync(DiscordScheduledEvent scheduledEvent, DiscordGuild guild)
{
if (guild == null)
return;
DiscordScheduledEvent oldEvent;
if (!guild.ScheduledEventsInternal.ContainsKey(scheduledEvent.Id))
{
oldEvent = null;
}
else
{
var ev = guild.ScheduledEventsInternal[scheduledEvent.Id];
oldEvent = new DiscordScheduledEvent
{
Id = ev.Id,
ChannelId = ev.ChannelId,
EntityId = ev.EntityId,
EntityMetadata = ev.EntityMetadata,
CreatorId = ev.CreatorId,
Creator = ev.Creator,
Discord = this,
Description = ev.Description,
EntityType = ev.EntityType,
ScheduledStartTimeRaw = ev.ScheduledStartTimeRaw,
ScheduledEndTimeRaw = ev.ScheduledEndTimeRaw,
GuildId = ev.GuildId,
Status = ev.Status,
Name = ev.Name,
UserCount = ev.UserCount,
CoverImageHash = ev.CoverImageHash
};
}
if (scheduledEvent.Creator != null)
{
scheduledEvent.Creator.Discord = this;
this.UserCache.AddOrUpdate(scheduledEvent.Creator.Id, scheduledEvent.Creator, (id, old) =>
{
old.Username = scheduledEvent.Creator.Username;
old.Discriminator = scheduledEvent.Creator.Discriminator;
old.AvatarHash = scheduledEvent.Creator.AvatarHash;
old.Flags = scheduledEvent.Creator.Flags;
return old;
});
}
if (scheduledEvent.Status == ScheduledEventStatus.Completed)
{
guild.ScheduledEventsInternal.TryRemove(scheduledEvent.Id, out var deletedEvent);
await this._guildScheduledEventDeleted.InvokeAsync(this, new GuildScheduledEventDeleteEventArgs(this.ServiceProvider) { ScheduledEvent = scheduledEvent, Guild = guild, Reason = ScheduledEventStatus.Completed }).ConfigureAwait(false);
}
else if (scheduledEvent.Status == ScheduledEventStatus.Canceled)
{
guild.ScheduledEventsInternal.TryRemove(scheduledEvent.Id, out var deletedEvent);
scheduledEvent.Status = ScheduledEventStatus.Canceled;
await this._guildScheduledEventDeleted.InvokeAsync(this, new GuildScheduledEventDeleteEventArgs(this.ServiceProvider) { ScheduledEvent = scheduledEvent, Guild = guild, Reason = ScheduledEventStatus.Canceled }).ConfigureAwait(false);
}
else
{
this.UpdateScheduledEvent(scheduledEvent, guild);
await this._guildScheduledEventUpdated.InvokeAsync(this, new GuildScheduledEventUpdateEventArgs(this.ServiceProvider) { ScheduledEventBefore = oldEvent, ScheduledEventAfter = scheduledEvent, Guild = guild }).ConfigureAwait(false);
}
}
///
/// Handles the scheduled event delete event.
///
/// The deleted event.
/// The guild.
internal async Task OnGuildScheduledEventDeleteEventAsync(DiscordScheduledEvent scheduledEvent, DiscordGuild guild)
{
scheduledEvent.Discord = this;
if (scheduledEvent.Status == ScheduledEventStatus.Scheduled)
scheduledEvent.Status = ScheduledEventStatus.Canceled;
if (scheduledEvent.Creator != null)
{
scheduledEvent.Creator.Discord = this;
this.UserCache.AddOrUpdate(scheduledEvent.Creator.Id, scheduledEvent.Creator, (id, old) =>
{
old.Username = scheduledEvent.Creator.Username;
old.Discriminator = scheduledEvent.Creator.Discriminator;
old.AvatarHash = scheduledEvent.Creator.AvatarHash;
old.Flags = scheduledEvent.Creator.Flags;
return old;
});
}
await this._guildScheduledEventDeleted.InvokeAsync(this, new GuildScheduledEventDeleteEventArgs(this.ServiceProvider) { ScheduledEvent = scheduledEvent, Guild = scheduledEvent.Guild, Reason = scheduledEvent.Status }).ConfigureAwait(false);
guild.ScheduledEventsInternal.TryRemove(scheduledEvent.Id, out var deletedEvent);
}
///
/// Handles the scheduled event user add event.
/// The event.
/// The added user id.
/// The guild.
///
internal async Task OnGuildScheduledEventUserAddedEventAsync(ulong guildScheduledEventId, ulong userId, DiscordGuild guild)
{
var scheduledEvent = this.InternalGetCachedScheduledEvent(guildScheduledEventId) ?? this.UpdateScheduledEvent(new DiscordScheduledEvent
{
Id = guildScheduledEventId,
GuildId = guild.Id,
Discord = this,
UserCount = 0
}, guild);
scheduledEvent.UserCount++;
scheduledEvent.Discord = this;
guild.Discord = this;
var user = this.GetUserAsync(userId, true).Result;
user.Discord = this;
var member = guild.Members.TryGetValue(userId, out var mem) ? mem : guild.GetMemberAsync(userId).Result;
member.Discord = this;
await this._guildScheduledEventUserAdded.InvokeAsync(this, new GuildScheduledEventUserAddEventArgs(this.ServiceProvider) { ScheduledEvent = scheduledEvent, Guild = guild, User = user, Member = member }).ConfigureAwait(false);
}
///
/// Handles the scheduled event user remove event.
/// The event.
/// The removed user id.
/// The guild.
///
internal async Task OnGuildScheduledEventUserRemovedEventAsync(ulong guildScheduledEventId, ulong userId, DiscordGuild guild)
{
var scheduledEvent = this.InternalGetCachedScheduledEvent(guildScheduledEventId) ?? this.UpdateScheduledEvent(new DiscordScheduledEvent
{
Id = guildScheduledEventId,
GuildId = guild.Id,
Discord = this,
UserCount = 0
}, guild);
scheduledEvent.UserCount = scheduledEvent.UserCount == 0 ? 0 : scheduledEvent.UserCount - 1;
scheduledEvent.Discord = this;
guild.Discord = this;
var user = this.GetUserAsync(userId, true).Result;
user.Discord = this;
var member = guild.Members.TryGetValue(userId, out var mem) ? mem : guild.GetMemberAsync(userId).Result;
member.Discord = this;
await this._guildScheduledEventUserRemoved.InvokeAsync(this, new GuildScheduledEventUserRemoveEventArgs(this.ServiceProvider) { ScheduledEvent = scheduledEvent, Guild = guild, User = user, Member = member }).ConfigureAwait(false);
}
#endregion
#region Guild Integration
///
/// Handles the guild integration create event.
///
/// The guild.
/// The integration.
internal async Task OnGuildIntegrationCreateEventAsync(DiscordGuild guild, DiscordIntegration integration)
{
integration.Discord = this;
await this._guildIntegrationCreated.InvokeAsync(this, new GuildIntegrationCreateEventArgs(this.ServiceProvider) { Integration = integration, Guild = guild }).ConfigureAwait(false);
}
///
/// Handles the guild integration update event.
///
/// The guild.
/// The integration.
internal async Task OnGuildIntegrationUpdateEventAsync(DiscordGuild guild, DiscordIntegration integration)
{
integration.Discord = this;
await this._guildIntegrationUpdated.InvokeAsync(this, new GuildIntegrationUpdateEventArgs(this.ServiceProvider) { Integration = integration, Guild = guild }).ConfigureAwait(false);
}
///
/// Handles the guild integrations update event.
///
/// The guild.
internal async Task OnGuildIntegrationsUpdateEventAsync(DiscordGuild guild)
{
var ea = new GuildIntegrationsUpdateEventArgs(this.ServiceProvider)
{
Guild = guild
};
await this._guildIntegrationsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild integration delete event.
///
/// The guild.
/// The integration id.
/// The optional application id.
internal async Task OnGuildIntegrationDeleteEventAsync(DiscordGuild guild, ulong integrationId, ulong? applicationId)
=> await this._guildIntegrationDeleted.InvokeAsync(this, new GuildIntegrationDeleteEventArgs(this.ServiceProvider) { Guild = guild, IntegrationId = integrationId, ApplicationId = applicationId }).ConfigureAwait(false);
#endregion
#region Guild Member
///
/// Handles the guild member add event.
///
/// The transport member.
/// The guild.
internal async Task OnGuildMemberAddEventAsync(TransportMember member, DiscordGuild guild)
{
var usr = new DiscordUser(member.User) { Discord = this };
usr = this.UserCache.AddOrUpdate(member.User.Id, usr, (id, old) =>
{
old.Username = usr.Username;
old.Discriminator = usr.Discriminator;
old.AvatarHash = usr.AvatarHash;
return old;
});
var mbr = new DiscordMember(member)
{
Discord = this,
GuildId = guild.Id
};
guild.MembersInternal[mbr.Id] = mbr;
guild.MemberCount++;
var ea = new GuildMemberAddEventArgs(this.ServiceProvider)
{
Guild = guild,
Member = mbr
};
await this._guildMemberAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild member remove event.
///
/// The transport user.
/// The guild.
internal async Task OnGuildMemberRemoveEventAsync(TransportUser user, DiscordGuild guild)
{
var usr = new DiscordUser(user);
if (!guild.MembersInternal.TryRemove(user.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, GuildId = guild.Id };
guild.MemberCount--;
_ = this.UserCache.AddOrUpdate(user.Id, usr, (old, @new) => @new);
var ea = new GuildMemberRemoveEventArgs(this.ServiceProvider)
{
Guild = guild,
Member = mbr
};
await this._guildMemberRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild member update event.
///
/// The transport member.
/// The guild.
/// The roles.
/// The nick.
/// Whether the member is pending.
internal async Task OnGuildMemberUpdateEventAsync(TransportMember member, DiscordGuild guild, IEnumerable roles, string nick, bool? pending)
{
var usr = new DiscordUser(member.User) { Discord = this };
usr = this.UserCache.AddOrUpdate(usr.Id, usr, (id, old) =>
{
old.Username = usr.Username;
old.Discriminator = usr.Discriminator;
old.AvatarHash = usr.AvatarHash;
return old;
});
if (!guild.Members.TryGetValue(member.User.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, GuildId = guild.Id };
var old = mbr;
var gAvOld = old.GuildAvatarHash;
var avOld = old.AvatarHash;
var nickOld = mbr.Nickname;
var pendingOld = mbr.IsPending;
var rolesOld = new ReadOnlyCollection(new List(mbr.Roles));
var cduOld = mbr.CommunicationDisabledUntil;
mbr.MemberFlags = member.MemberFlags;
mbr.AvatarHashInternal = member.AvatarHash;
mbr.GuildAvatarHash = member.GuildAvatarHash;
mbr.Nickname = nick;
mbr.GuildPronouns = member.GuildPronouns;
mbr.IsPending = pending;
mbr.CommunicationDisabledUntil = member.CommunicationDisabledUntil;
mbr.RoleIdsInternal.Clear();
mbr.RoleIdsInternal.AddRange(roles);
guild.MembersInternal.AddOrUpdate(member.User.Id, mbr, (id, oldMbr) => oldMbr);
var timeoutUntil = member.CommunicationDisabledUntil;
/*this.Logger.LogTrace($"Timeout:\nBefore - {cduOld}\nAfter - {timeoutUntil}");
if ((timeoutUntil.HasValue && cduOld.HasValue) || (timeoutUntil == null && cduOld.HasValue) || (timeoutUntil.HasValue && cduOld == null))
{
// We are going to add a scheduled timer to assure that we get a auditlog entry.
var id = $"tt-{mbr.Id}-{guild.Id}-{DateTime.Now.ToLongTimeString()}";
this._tempTimers.Add(
id,
new(
new TimeoutHandler(
mbr,
guild,
cduOld,
timeoutUntil
),
new Timer(
this.TimeoutTimer,
id,
2000,
Timeout.Infinite
)
)
);
this.Logger.LogTrace("Scheduling timeout event.");
return;
}*/
//this.Logger.LogTrace("No timeout detected. Continuing on normal operation.");
var eargs = new GuildMemberUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
Member = mbr,
NicknameAfter = mbr.Nickname,
RolesAfter = new ReadOnlyCollection(new List(mbr.Roles)),
PendingAfter = mbr.IsPending,
TimeoutAfter = mbr.CommunicationDisabledUntil,
AvatarHashAfter = mbr.AvatarHash,
GuildAvatarHashAfter = mbr.GuildAvatarHash,
NicknameBefore = nickOld,
RolesBefore = rolesOld,
PendingBefore = pendingOld,
TimeoutBefore = cduOld,
AvatarHashBefore = avOld,
GuildAvatarHashBefore = gAvOld
};
await this._guildMemberUpdated.InvokeAsync(this, eargs).ConfigureAwait(false);
}
///
/// Handles timeout events.
///
/// Internally used as uid for the timer data.
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "")]
private async void TimeoutTimer(object state)
{
var tid = (string)state;
var data = this._tempTimers.First(x=> x.Key == tid).Value.Key;
var timer = this._tempTimers.First(x=> x.Key == tid).Value.Value;
IReadOnlyList auditlog = null;
DiscordAuditLogMemberUpdateEntry filtered = null;
try
{
auditlog = await data.Guild.GetAuditLogsAsync(10, null, AuditLogActionType.MemberUpdate);
var preFiltered = auditlog.Select(x => x as DiscordAuditLogMemberUpdateEntry).Where(x => x.Target.Id == data.Member.Id);
filtered = preFiltered.First();
}
catch (UnauthorizedException) { }
catch (Exception)
{
this.Logger.LogTrace("Failing timeout event.");
await timer.DisposeAsync();
this._tempTimers.Remove(tid);
return;
}
var actor = filtered?.UserResponsible as DiscordMember;
this.Logger.LogTrace("Trying to execute timeout event.");
if (data.TimeoutUntilOld.HasValue && data.TimeoutUntilNew.HasValue)
{
// A timeout was updated.
if (filtered != null && auditlog == null)
{
this.Logger.LogTrace("Re-scheduling timeout event.");
timer.Change(2000, Timeout.Infinite);
return;
}
var ea = new GuildMemberTimeoutUpdateEventArgs(this.ServiceProvider)
{
Guild = data.Guild,
Target = data.Member,
TimeoutBefore = data.TimeoutUntilOld.Value,
TimeoutAfter = data.TimeoutUntilNew.Value,
Actor = actor,
AuditLogId = filtered?.Id,
AuditLogReason = filtered?.Reason
};
await this._guildMemberTimeoutChanged.InvokeAsync(this, ea).ConfigureAwait(false);
}
else if (!data.TimeoutUntilOld.HasValue && data.TimeoutUntilNew.HasValue)
{
// A timeout was added.
if (filtered != null && auditlog == null)
{
this.Logger.LogTrace("Re-scheduling timeout event.");
timer.Change(2000, Timeout.Infinite);
return;
}
var ea = new GuildMemberTimeoutAddEventArgs(this.ServiceProvider)
{
Guild = data.Guild,
Target = data.Member,
Timeout = data.TimeoutUntilNew.Value,
Actor = actor,
AuditLogId = filtered?.Id,
AuditLogReason = filtered?.Reason
};
await this._guildMemberTimeoutAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
else if (data.TimeoutUntilOld.HasValue && !data.TimeoutUntilNew.HasValue)
{
// A timeout was removed.
if (filtered != null && auditlog == null)
{
this.Logger.LogTrace("Re-scheduling timeout event.");
timer.Change(2000, Timeout.Infinite);
return;
}
var ea = new GuildMemberTimeoutRemoveEventArgs(this.ServiceProvider)
{
Guild = data.Guild,
Target = data.Member,
TimeoutBefore = data.TimeoutUntilOld.Value,
Actor = actor,
AuditLogId = filtered?.Id,
AuditLogReason = filtered?.Reason
};
await this._guildMemberTimeoutRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
// Ending timer because it worked.
this.Logger.LogTrace("Removing timeout event.");
await timer.DisposeAsync();
this._tempTimers.Remove(tid);
}
///
/// Handles the guild members chunk event.
///
/// The raw chunk data.
internal async Task OnGuildMembersChunkEventAsync(JObject dat)
{
var guild = this.Guilds[(ulong)dat["guild_id"]];
var chunkIndex = (int)dat["chunk_index"];
var chunkCount = (int)dat["chunk_count"];
var nonce = (string)dat["nonce"];
var mbrs = new HashSet();
var pres = new HashSet();
var members = dat["members"].ToObject();
foreach (var member in members)
{
var mbr = new DiscordMember(member) { Discord = this, GuildId = guild.Id };
if (!this.UserCache.ContainsKey(mbr.Id))
this.UserCache[mbr.Id] = new DiscordUser(member.User) { Discord = this };
guild.MembersInternal[mbr.Id] = mbr;
mbrs.Add(mbr);
}
guild.MemberCount = guild.MembersInternal.Count;
var ea = new GuildMembersChunkEventArgs(this.ServiceProvider)
{
Guild = guild,
Members = new ReadOnlySet(mbrs),
ChunkIndex = chunkIndex,
ChunkCount = chunkCount,
Nonce = nonce,
};
if (dat["presences"] != null)
{
var presences = dat["presences"].ToObject();
var presCount = presences.Length;
foreach (var presence in presences)
{
presence.Discord = this;
presence.Activity = new DiscordActivity(presence.RawActivity);
if (presence.RawActivities != null)
{
presence.InternalActivities = presence.RawActivities
.Select(x => new DiscordActivity(x)).ToArray();
}
pres.Add(presence);
}
ea.Presences = new ReadOnlySet(pres);
}
if (dat["not_found"] != null)
{
var nf = dat["not_found"].ToObject>();
ea.NotFound = new ReadOnlySet(nf);
}
await this._guildMembersChunked.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Guild Role
///
/// Handles the guild role create event.
///
/// The role.
/// The guild.
internal async Task OnGuildRoleCreateEventAsync(DiscordRole role, DiscordGuild guild)
{
role.Discord = this;
role.GuildId = guild.Id;
guild.RolesInternal[role.Id] = role;
var ea = new GuildRoleCreateEventArgs(this.ServiceProvider)
{
Guild = guild,
Role = role
};
await this._guildRoleCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild role update event.
///
/// The role.
/// The guild.
internal async Task OnGuildRoleUpdateEventAsync(DiscordRole role, DiscordGuild guild)
{
var newRole = guild.GetRole(role.Id);
var oldRole = new DiscordRole
{
GuildId = guild.Id,
ColorInternal = newRole.ColorInternal,
Discord = this,
IsHoisted = newRole.IsHoisted,
Id = newRole.Id,
IsManaged = newRole.IsManaged,
IsMentionable = newRole.IsMentionable,
Name = newRole.Name,
Permissions = newRole.Permissions,
Position = newRole.Position,
IconHash = newRole.IconHash,
Tags = newRole.Tags ?? null,
UnicodeEmojiString = newRole.UnicodeEmojiString
};
newRole.GuildId = guild.Id;
newRole.ColorInternal = role.ColorInternal;
newRole.IsHoisted = role.IsHoisted;
newRole.IsManaged = role.IsManaged;
newRole.IsMentionable = role.IsMentionable;
newRole.Name = role.Name;
newRole.Permissions = role.Permissions;
newRole.Position = role.Position;
newRole.IconHash = role.IconHash;
newRole.Tags = role.Tags ?? null;
newRole.UnicodeEmojiString = role.UnicodeEmojiString;
var ea = new GuildRoleUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
RoleAfter = newRole,
RoleBefore = oldRole
};
await this._guildRoleUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild role delete event.
///
/// The role id.
/// The guild.
internal async Task OnGuildRoleDeleteEventAsync(ulong roleId, DiscordGuild guild)
{
if (!guild.RolesInternal.TryRemove(roleId, out var role))
this.Logger.LogWarning($"Attempted to delete a nonexistent role ({roleId}) from guild ({guild}).");
var ea = new GuildRoleDeleteEventArgs(this.ServiceProvider)
{
Guild = guild,
Role = role
};
await this._guildRoleDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Invite
///
/// Handles the invite create event.
///
/// The channel id.
/// The guild id.
/// The invite.
internal async Task OnInviteCreateEventAsync(ulong channelId, ulong guildId, DiscordInvite invite)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId);
invite.Discord = this;
if (invite.Inviter is not null)
{
invite.Inviter.Discord = this;
this.UserCache.AddOrUpdate(invite.Inviter.Id, invite.Inviter, (old, @new) => @new);
}
guild.Invites[invite.Code] = invite;
var ea = new InviteCreateEventArgs(this.ServiceProvider)
{
Channel = channel,
Guild = guild,
Invite = invite
};
await this._inviteCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the invite delete event.
///
/// The channel id.
/// The guild id.
/// The raw invite.
internal async Task OnInviteDeleteEventAsync(ulong channelId, ulong guildId, JToken dat)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId);
if (!guild.Invites.TryRemove(dat["code"].ToString(), out var invite))
{
invite = dat.ToObject();
invite.Discord = this;
}
invite.IsRevoked = true;
var ea = new InviteDeleteEventArgs(this.ServiceProvider)
{
Channel = channel,
Guild = guild,
Invite = invite
};
await this._inviteDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Message
///
/// Handles the message acknowledge event.
///
/// The channel.
/// The message id.
internal async Task OnMessageAckEventAsync(DiscordChannel chn, ulong messageId)
{
if (this.MessageCache == null || !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == chn.Id, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = chn.Id,
Discord = this,
};
}
await this._messageAcknowledged.InvokeAsync(this, new MessageAcknowledgeEventArgs(this.ServiceProvider) { Message = msg }).ConfigureAwait(false);
}
///
/// Handles the message create event.
///
/// The message.
/// The transport user (author).
/// The transport member.
/// The reference transport user (author).
/// The reference transport member.
internal async Task OnMessageCreateEventAsync(DiscordMessage message, TransportUser author, TransportMember member, TransportUser referenceAuthor, TransportMember referenceMember)
{
message.Discord = this;
this.PopulateMessageReactionsAndCache(message, author, member);
message.PopulateMentions();
if (message.Channel == null && message.ChannelId == default)
this.Logger.LogWarning(LoggerEvents.WebSocketReceive, "Channel which the last message belongs to is not in cache - cache state might be invalid!");
if (message.ReferencedMessage != null)
{
message.ReferencedMessage.Discord = this;
this.PopulateMessageReactionsAndCache(message.ReferencedMessage, referenceAuthor, referenceMember);
message.ReferencedMessage.PopulateMentions();
}
foreach (var sticker in message.Stickers)
sticker.Discord = this;
var ea = new MessageCreateEventArgs(this.ServiceProvider)
{
Message = message,
MentionedUsers = new ReadOnlyCollection(message.MentionedUsersInternal),
MentionedRoles = message.MentionedRolesInternal != null ? new ReadOnlyCollection(message.MentionedRolesInternal) : null,
MentionedChannels = message.MentionedChannelsInternal != null ? new ReadOnlyCollection(message.MentionedChannelsInternal) : null
};
await this._messageCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the message update event.
///
/// The message.
/// The transport user (author).
/// The transport member.
/// The reference transport user (author).
/// The reference transport member.
internal async Task OnMessageUpdateEventAsync(DiscordMessage message, TransportUser author, TransportMember member, TransportUser referenceAuthor, TransportMember referenceMember)
{
DiscordGuild guild;
message.Discord = this;
var eventMessage = message;
DiscordMessage oldmsg = null;
if (this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == eventMessage.Id && xm.ChannelId == eventMessage.ChannelId, out message))
{
message = eventMessage;
this.PopulateMessageReactionsAndCache(message, author, member);
guild = message.Channel?.Guild;
if (message.ReferencedMessage != null)
{
message.ReferencedMessage.Discord = this;
this.PopulateMessageReactionsAndCache(message.ReferencedMessage, referenceAuthor, referenceMember);
message.ReferencedMessage.PopulateMentions();
}
}
else
{
oldmsg = new DiscordMessage(message);
guild = message.Channel?.Guild;
message.EditedTimestampRaw = eventMessage.EditedTimestampRaw;
if (eventMessage.Content != null)
message.Content = eventMessage.Content;
message.EmbedsInternal.Clear();
message.EmbedsInternal.AddRange(eventMessage.EmbedsInternal);
message.Pinned = eventMessage.Pinned;
message.IsTts = eventMessage.IsTts;
}
message.PopulateMentions();
var ea = new MessageUpdateEventArgs(this.ServiceProvider)
{
Message = message,
MessageBefore = oldmsg,
MentionedUsers = new ReadOnlyCollection(message.MentionedUsersInternal),
MentionedRoles = message.MentionedRolesInternal != null ? new ReadOnlyCollection(message.MentionedRolesInternal) : null,
MentionedChannels = message.MentionedChannelsInternal != null ? new ReadOnlyCollection(message.MentionedChannelsInternal) : null
};
await this._messageUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the message delete event.
///
/// The message id.
/// The channel id.
/// The optional guild id.
internal async Task OnMessageDeleteEventAsync(ulong messageId, ulong channelId, ulong? guildId)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
var guild = this.InternalGetCachedGuild(guildId);
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this,
};
}
if (this.Configuration.MessageCacheSize > 0)
this.MessageCache?.Remove(xm => xm.Id == msg.Id && xm.ChannelId == channelId);
var ea = new MessageDeleteEventArgs(this.ServiceProvider)
{
Channel = channel,
Message = msg,
Guild = guild
};
await this._messageDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the message bulk delete event.
///
/// The message ids.
/// The channel id.
/// The optional guild id.
internal async Task OnMessageBulkDeleteEventAsync(ulong[] messageIds, ulong channelId, ulong? guildId)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
var msgs = new List(messageIds.Length);
foreach (var messageId in messageIds)
{
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this,
};
}
if (this.Configuration.MessageCacheSize > 0)
this.MessageCache?.Remove(xm => xm.Id == msg.Id && xm.ChannelId == channelId);
msgs.Add(msg);
}
var guild = this.InternalGetCachedGuild(guildId);
var ea = new MessageBulkDeleteEventArgs(this.ServiceProvider)
{
Channel = channel,
Messages = new ReadOnlyCollection(msgs),
Guild = guild
};
await this._messagesBulkDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Message Reaction
///
/// Handles the message reaction add event.
///
/// The user id.
/// The message id.
/// The channel id.
/// The optional guild id.
/// The transport member.
/// The emoji.
internal async Task OnMessageReactionAddAsync(ulong userId, ulong messageId, ulong channelId, ulong? guildId, TransportMember mbr, DiscordEmoji emoji)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
var guild = this.InternalGetCachedGuild(guildId);
emoji.Discord = this;
var usr = this.UpdateUser(new DiscordUser { Id = userId, Discord = this }, guildId, guild, mbr);
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this,
ReactionsInternal = new List()
};
}
var react = msg.ReactionsInternal.FirstOrDefault(xr => xr.Emoji == emoji);
if (react == null)
{
msg.ReactionsInternal.Add(react = new DiscordReaction
{
Count = 1,
Emoji = emoji,
IsMe = this.CurrentUser.Id == userId
});
}
else
{
react.Count++;
react.IsMe |= this.CurrentUser.Id == userId;
}
var ea = new MessageReactionAddEventArgs(this.ServiceProvider)
{
Message = msg,
User = usr,
Guild = guild,
Emoji = emoji
};
await this._messageReactionAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the message reaction remove event.
///
/// The user id.
/// The message id.
/// The channel id.
/// The guild id.
/// The emoji.
internal async Task OnMessageReactionRemoveAsync(ulong userId, ulong messageId, ulong channelId, ulong? guildId, DiscordEmoji emoji)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
emoji.Discord = this;
if (!this.UserCache.TryGetValue(userId, out var usr))
usr = new DiscordUser { Id = userId, Discord = this };
if (channel?.Guild != null)
usr = channel.Guild.Members.TryGetValue(userId, out var member)
? member
: new DiscordMember(usr) { Discord = this, GuildId = channel.GuildId.Value };
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this
};
}
var react = msg.ReactionsInternal?.FirstOrDefault(xr => xr.Emoji == emoji);
if (react != null)
{
react.Count--;
react.IsMe &= this.CurrentUser.Id != userId;
if (msg.ReactionsInternal != null && react.Count <= 0) // shit happens
msg.ReactionsInternal.RemoveFirst(x => x.Emoji == emoji);
}
var guild = this.InternalGetCachedGuild(guildId);
var ea = new MessageReactionRemoveEventArgs(this.ServiceProvider)
{
Message = msg,
User = usr,
Guild = guild,
Emoji = emoji
};
await this._messageReactionRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the message reaction remove event.
/// Fired when all message reactions were removed.
///
/// The message id.
/// The channel id.
/// The optional guild id.
internal async Task OnMessageReactionRemoveAllAsync(ulong messageId, ulong channelId, ulong? guildId)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this
};
}
msg.ReactionsInternal?.Clear();
var guild = this.InternalGetCachedGuild(guildId);
var ea = new MessageReactionsClearEventArgs(this.ServiceProvider)
{
Message = msg
};
await this._messageReactionsCleared.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the message reaction remove event.
/// Fired when a emoji got removed.
///
/// The message id.
/// The channel id.
/// The guild id.
/// The raw discord emoji.
internal async Task OnMessageReactionRemoveEmojiAsync(ulong messageId, ulong channelId, ulong guildId, JToken dat)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this
};
}
var partialEmoji = dat.ToObject();
if (!guild.EmojisInternal.TryGetValue(partialEmoji.Id, out var emoji))
{
emoji = partialEmoji;
emoji.Discord = this;
}
msg.ReactionsInternal?.RemoveAll(r => r.Emoji.Equals(emoji));
var ea = new MessageReactionRemoveEmojiEventArgs(this.ServiceProvider)
{
Channel = channel,
Guild = guild,
Message = msg,
Emoji = emoji
};
await this._messageReactionRemovedEmoji.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Stage Instance
///
/// Handles the stage instance create event.
///
/// The created stage instance.
internal async Task OnStageInstanceCreateEventAsync(DiscordStageInstance stage)
{
stage.Discord = this;
var guild = this.InternalGetCachedGuild(stage.GuildId);
guild.StageInstancesInternal[stage.Id] = stage;
await this._stageInstanceCreated.InvokeAsync(this, new StageInstanceCreateEventArgs(this.ServiceProvider) { StageInstance = stage, Guild = stage.Guild }).ConfigureAwait(false);
}
///
/// Handles the stage instance update event.
///
/// The updated stage instance.
internal async Task OnStageInstanceUpdateEventAsync(DiscordStageInstance stage)
{
stage.Discord = this;
var guild = this.InternalGetCachedGuild(stage.GuildId);
guild.StageInstancesInternal[stage.Id] = stage;
await this._stageInstanceUpdated.InvokeAsync(this, new StageInstanceUpdateEventArgs(this.ServiceProvider) { StageInstance = stage, Guild = stage.Guild }).ConfigureAwait(false);
}
///
/// Handles the stage instance delete event.
///
/// The deleted stage instance.
internal async Task OnStageInstanceDeleteEventAsync(DiscordStageInstance stage)
{
stage.Discord = this;
var guild = this.InternalGetCachedGuild(stage.GuildId);
guild.StageInstancesInternal[stage.Id] = stage;
await this._stageInstanceDeleted.InvokeAsync(this, new StageInstanceDeleteEventArgs(this.ServiceProvider) { StageInstance = stage, Guild = stage.Guild }).ConfigureAwait(false);
}
#endregion
#region Thread
///
/// Handles the thread create event.
///
/// The created thread.
internal async Task OnThreadCreateEventAsync(DiscordThreadChannel thread)
{
thread.Discord = this;
this.InternalGetCachedGuild(thread.GuildId).ThreadsInternal.AddOrUpdate(thread.Id, thread, (oldThread, newThread) => newThread);
await this._threadCreated.InvokeAsync(this, new ThreadCreateEventArgs(this.ServiceProvider) { Thread = thread, Guild = thread.Guild, Parent = thread.Parent }).ConfigureAwait(false);
}
///
/// Handles the thread update event.
///
/// The updated thread.
internal async Task OnThreadUpdateEventAsync(DiscordThreadChannel thread)
{
if (thread == null)
return;
thread.Discord = this;
var guild = thread.Guild;
var threadNew = this.InternalGetCachedThread(thread.Id);
DiscordThreadChannel threadOld = null;
ThreadUpdateEventArgs updateEvent;
if (threadNew != null)
{
threadOld = new DiscordThreadChannel
{
Discord = this,
Type = threadNew.Type,
ThreadMetadata = thread.ThreadMetadata,
ThreadMembersInternal = threadNew.ThreadMembersInternal,
ParentId = thread.ParentId,
OwnerId = thread.OwnerId,
Name = thread.Name,
LastMessageId = threadNew.LastMessageId,
MessageCount = thread.MessageCount,
MemberCount = thread.MemberCount,
GuildId = thread.GuildId,
LastPinTimestampRaw = threadNew.LastPinTimestampRaw,
PerUserRateLimit = threadNew.PerUserRateLimit,
CurrentMember = threadNew.CurrentMember,
TotalMessagesSent = threadNew.TotalMessagesSent
};
if (this.Guilds != null)
{
if (thread.ParentId.HasValue && this.InternalGetCachedChannel(thread.ParentId.Value).Type == ChannelType.Forum)
{
threadOld.AppliedTagIdsInternal = threadNew.AppliedTagIdsInternal;
threadNew.AppliedTagIdsInternal = thread.AppliedTagIdsInternal;
}
else
{
threadOld.AppliedTagIdsInternal = null;
threadNew.AppliedTagIdsInternal = null;
}
} else
{
threadOld.AppliedTagIdsInternal = threadNew.AppliedTagIdsInternal;
threadNew.AppliedTagIdsInternal = thread.AppliedTagIdsInternal;
}
threadNew.ThreadMetadata = thread.ThreadMetadata;
threadNew.ParentId = thread.ParentId;
threadNew.OwnerId = thread.OwnerId;
threadNew.Name = thread.Name;
threadNew.LastMessageId = thread.LastMessageId.HasValue ? thread.LastMessageId : threadOld.LastMessageId;
threadNew.MessageCount = thread.MessageCount;
threadNew.MemberCount = thread.MemberCount;
threadNew.GuildId = thread.GuildId;
threadNew.Discord = this;
threadNew.TotalMessagesSent = thread.TotalMessagesSent;
updateEvent = new ThreadUpdateEventArgs(this.ServiceProvider)
{
ThreadAfter = thread,
ThreadBefore = threadOld,
Guild = thread.Guild,
Parent = thread.Parent
};
}
else
{
updateEvent = new ThreadUpdateEventArgs(this.ServiceProvider)
{
ThreadAfter = thread,
Guild = thread.Guild,
Parent = thread.Parent
};
guild.ThreadsInternal[thread.Id] = thread;
}
await this._threadUpdated.InvokeAsync(this, updateEvent).ConfigureAwait(false);
}
///
/// Handles the thread delete event.
///
/// The deleted thread.
internal async Task OnThreadDeleteEventAsync(DiscordThreadChannel thread)
{
if (thread == null)
return;
thread.Discord = this;
var gld = thread.Guild;
if (gld.ThreadsInternal.TryRemove(thread.Id, out var cachedThread))
thread = cachedThread;
await this._threadDeleted.InvokeAsync(this, new ThreadDeleteEventArgs(this.ServiceProvider) { Thread = thread, Guild = thread.Guild, Parent = thread.Parent, Type = thread.Type }).ConfigureAwait(false);
}
///
/// Handles the thread list sync event.
///
/// The synced guild.
/// The synced channel ids.
/// The synced threads.
/// The synced thread members.
internal async Task OnThreadListSyncEventAsync(DiscordGuild guild, IReadOnlyList channelIds, IReadOnlyList threads, IReadOnlyList members)
{
guild.Discord = this;
var channels = channelIds.Select(x => guild.GetChannel(x.Value)); //getting channel objects
foreach (var chan in channels)
{
chan.Discord = this;
}
_ = threads.Select(x => x.Discord = this);
await this._threadListSynced.InvokeAsync(this, new ThreadListSyncEventArgs(this.ServiceProvider) { Guild = guild, Channels = channels.ToList().AsReadOnly(), Threads = threads, Members = members.ToList().AsReadOnly() }).ConfigureAwait(false);
}
///
/// Handles the thread member update event.
///
/// The updated member.
internal async Task OnThreadMemberUpdateEventAsync(DiscordThreadChannelMember member)
{
member.Discord = this;
var thread = this.InternalGetCachedThread(member.Id);
if (thread == null)
{
var tempThread = await this.ApiClient.GetThreadAsync(member.Id);
thread = this.GuildsInternal[member.GuildId].ThreadsInternal.AddOrUpdate(member.Id, tempThread, (old, newThread) => newThread);
}
thread.CurrentMember = member;
thread.Guild.ThreadsInternal.AddOrUpdate(member.Id, thread, (oldThread, newThread) => newThread);
await this._threadMemberUpdated.InvokeAsync(this, new ThreadMemberUpdateEventArgs(this.ServiceProvider) { ThreadMember = member, Thread = thread }).ConfigureAwait(false);
}
///
/// Handles the thread members update event.
///
/// The target guild.
/// The thread id of the target thread this update belongs to.
/// The added members.
/// The ids of the removed members.
/// The new member count.
internal async Task OnThreadMembersUpdateEventAsync(DiscordGuild guild, ulong threadId, JArray membersAdded, JArray membersRemoved, int memberCount)
{
var thread = this.InternalGetCachedThread(threadId);
if (thread == null)
{
var tempThread = await this.ApiClient.GetThreadAsync(threadId);
thread = guild.ThreadsInternal.AddOrUpdate(threadId, tempThread, (old, newThread) => newThread);
}
thread.Discord = this;
guild.Discord = this;
List addedMembers = new();
List removedMemberIds = new();
if (membersAdded != null)
{
foreach (var xj in membersAdded)
{
var xtm = xj.ToDiscordObject();
xtm.Discord = this;
xtm.GuildId = guild.Id;
if (xtm != null)
addedMembers.Add(xtm);
if (xtm.Id == this.CurrentUser.Id)
thread.CurrentMember = xtm;
}
}
var removedMembers = new List();
if (membersRemoved != null)
{
foreach (var removedId in membersRemoved)
{
removedMembers.Add(guild.MembersInternal.TryGetValue((ulong)removedId, out var member) ? member : new DiscordMember { Id = (ulong)removedId, GuildId = guild.Id, Discord = this });
}
}
if (removedMemberIds.Contains(this.CurrentUser.Id)) //indicates the bot was removed from the thread
thread.CurrentMember = null;
thread.MemberCount = memberCount;
var threadMembersUpdateArg = new ThreadMembersUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
Thread = thread,
AddedMembers = addedMembers,
RemovedMembers = removedMembers,
MemberCount = memberCount
};
await this._threadMembersUpdated.InvokeAsync(this, threadMembersUpdateArg).ConfigureAwait(false);
}
#endregion
#region Activities
///
/// Dispatches the event.
///
/// The transport activity.
/// The guild.
/// The channel id.
/// The users in the activity.
/// The application id.
internal async Task OnEmbeddedActivityUpdateAsync(JObject trActivity, DiscordGuild guild, ulong channelId, JArray jUsers, ulong appId)
=> await Task.Delay(20);
/*{
try
{
var users = j_users?.ToObject>();
DiscordActivity old = null;
var uid = $"{guild.Id}_{channel_id}_{app_id}";
if (this._embeddedActivities.TryGetValue(uid, out var activity))
{
old = new DiscordActivity(activity);
DiscordJson.PopulateObject(tr_activity, activity);
}
else
{
activity = tr_activity.ToObject();
this._embeddedActivities[uid] = activity;
}
var activity_users = new List();
var channel = this.InternalGetCachedChannel(channel_id) ?? await this.ApiClient.GetChannelAsync(channel_id);
if (users != null)
{
foreach (var user in users)
{
var activity_user = guild._members.TryGetValue(user, out var member) ? member : new DiscordMember { Id = user, _guild_id = guild.Id, Discord = this };
activity_users.Add(activity_user);
}
}
else
activity_users = null;
var ea = new EmbeddedActivityUpdateEventArgs(this.ServiceProvider)
{
Guild = guild,
Users = activity_users,
Channel = channel
};
await this._embeddedActivityUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
} catch (Exception ex)
{
this.Logger.LogError(ex, ex.Message);
}
}*/
#endregion
#region User/Presence Update
///
/// Handles the presence update event.
///
/// The raw presence.
/// The raw user.
internal async Task OnPresenceUpdateEventAsync(JObject rawPresence, JObject rawUser)
{
var uid = (ulong)rawUser["id"];
DiscordPresence old = null;
if (this.PresencesInternal.TryGetValue(uid, out var presence))
{
old = new DiscordPresence(presence);
DiscordJson.PopulateObject(rawPresence, presence);
}
else
{
presence = rawPresence.ToObject();
presence.Discord = this;
presence.Activity = new DiscordActivity(presence.RawActivity);
this.PresencesInternal[presence.InternalUser.Id] = presence;
}
// reuse arrays / avoid linq (this is a hot zone)
if (presence.Activities == null || rawPresence["activities"] == null)
{
presence.InternalActivities = Array.Empty();
}
else
{
if (presence.InternalActivities.Length != presence.RawActivities.Length)
presence.InternalActivities = new DiscordActivity[presence.RawActivities.Length];
for (var i = 0; i < presence.InternalActivities.Length; i++)
presence.InternalActivities[i] = new DiscordActivity(presence.RawActivities[i]);
if (presence.InternalActivities.Length > 0)
{
presence.RawActivity = presence.RawActivities[0];
if (presence.Activity != null)
presence.Activity.UpdateWith(presence.RawActivity);
else
presence.Activity = new DiscordActivity(presence.RawActivity);
}
}
if (this.UserCache.TryGetValue(uid, out var usr))
{
if (old != null)
{
old.InternalUser.Username = usr.Username;
old.InternalUser.Discriminator = usr.Discriminator;
old.InternalUser.AvatarHash = usr.AvatarHash;
}
if (rawUser["username"] is object)
usr.Username = (string)rawUser["username"];
if (rawUser["discriminator"] is object)
usr.Discriminator = (string)rawUser["discriminator"];
if (rawUser["avatar"] is object)
usr.AvatarHash = (string)rawUser["avatar"];
presence.InternalUser.Username = usr.Username;
presence.InternalUser.Discriminator = usr.Discriminator;
presence.InternalUser.AvatarHash = usr.AvatarHash;
}
var usrafter = usr ?? new DiscordUser(presence.InternalUser);
var ea = new PresenceUpdateEventArgs(this.ServiceProvider)
{
Status = presence.Status,
Activity = presence.Activity,
User = usr,
PresenceBefore = old,
PresenceAfter = presence,
UserBefore = old != null ? new DiscordUser(old.InternalUser) : usrafter,
UserAfter = usrafter
};
await this._presenceUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the user settings update event.
///
/// The transport user.
internal async Task OnUserSettingsUpdateEventAsync(TransportUser user)
{
var usr = new DiscordUser(user) { Discord = this };
var ea = new UserSettingsUpdateEventArgs(this.ServiceProvider)
{
User = usr
};
await this._userSettingsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the user update event.
///
/// The transport user.
internal async Task OnUserUpdateEventAsync(TransportUser user)
{
var usrOld = new DiscordUser
{
AvatarHash = this.CurrentUser.AvatarHash,
Discord = this,
Discriminator = this.CurrentUser.Discriminator,
Email = this.CurrentUser.Email,
Id = this.CurrentUser.Id,
IsBot = this.CurrentUser.IsBot,
MfaEnabled = this.CurrentUser.MfaEnabled,
Username = this.CurrentUser.Username,
Verified = this.CurrentUser.Verified
};
this.CurrentUser.AvatarHash = user.AvatarHash;
this.CurrentUser.Discriminator = user.Discriminator;
this.CurrentUser.Email = user.Email;
this.CurrentUser.Id = user.Id;
this.CurrentUser.IsBot = user.IsBot;
this.CurrentUser.MfaEnabled = user.MfaEnabled;
this.CurrentUser.Username = user.Username;
this.CurrentUser.Verified = user.Verified;
var ea = new UserUpdateEventArgs(this.ServiceProvider)
{
UserAfter = this.CurrentUser,
UserBefore = usrOld
};
await this._userUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Voice
///
/// Handles the voice state update event.
///
/// The raw voice state update object.
internal async Task OnVoiceStateUpdateEventAsync(JObject raw)
{
var gid = (ulong)raw["guild_id"];
var uid = (ulong)raw["user_id"];
var gld = this.GuildsInternal[gid];
var vstateNew = raw.ToObject();
vstateNew.Discord = this;
gld.VoiceStatesInternal.TryRemove(uid, out var vstateOld);
if (vstateNew.Channel != null)
{
gld.VoiceStatesInternal[vstateNew.UserId] = vstateNew;
}
if (gld.MembersInternal.TryGetValue(uid, out var mbr))
{
mbr.IsMuted = vstateNew.IsServerMuted;
mbr.IsDeafened = vstateNew.IsServerDeafened;
}
else
{
var transportMbr = vstateNew.TransportMember;
this.UpdateUser(new DiscordUser(transportMbr.User) { Discord = this }, gid, gld, transportMbr);
}
var ea = new VoiceStateUpdateEventArgs(this.ServiceProvider)
{
Guild = vstateNew.Guild,
Channel = vstateNew.Channel,
User = vstateNew.User,
SessionId = vstateNew.SessionId,
Before = vstateOld,
After = vstateNew
};
await this._voiceStateUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the voice server update event.
///
/// The new endpoint.
/// The new token.
/// The guild.
internal async Task OnVoiceServerUpdateEventAsync(string endpoint, string token, DiscordGuild guild)
{
var ea = new VoiceServerUpdateEventArgs(this.ServiceProvider)
{
Endpoint = endpoint,
VoiceToken = token,
Guild = guild
};
await this._voiceServerUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Commands
///
/// Handles the application command create event.
///
/// The application command.
/// The optional guild id.
internal async Task OnApplicationCommandCreateAsync(DiscordApplicationCommand cmd, ulong? guildId)
{
cmd.Discord = this;
var guild = this.InternalGetCachedGuild(guildId);
if (guild == null && guildId.HasValue)
{
guild = new DiscordGuild
{
Id = guildId.Value,
Discord = this
};
}
var ea = new ApplicationCommandEventArgs(this.ServiceProvider)
{
Guild = guild,
Command = cmd
};
await this._applicationCommandCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the application command update event.
///
/// The application command.
/// The optional guild id.
internal async Task OnApplicationCommandUpdateAsync(DiscordApplicationCommand cmd, ulong? guildId)
{
cmd.Discord = this;
var guild = this.InternalGetCachedGuild(guildId);
if (guild == null && guildId.HasValue)
{
guild = new DiscordGuild
{
Id = guildId.Value,
Discord = this
};
}
var ea = new ApplicationCommandEventArgs(this.ServiceProvider)
{
Guild = guild,
Command = cmd
};
await this._applicationCommandUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the application command delete event.
///
/// The application command.
/// The optional guild id.
internal async Task OnApplicationCommandDeleteAsync(DiscordApplicationCommand cmd, ulong? guildId)
{
cmd.Discord = this;
var guild = this.InternalGetCachedGuild(guildId);
if (guild == null && guildId.HasValue)
{
guild = new DiscordGuild
{
Id = guildId.Value,
Discord = this
};
}
var ea = new ApplicationCommandEventArgs(this.ServiceProvider)
{
Guild = guild,
Command = cmd
};
await this._applicationCommandDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the guild application command counts update event.
///
/// The count.
/// The count.
/// The count.
/// The guild id.
/// Count of application commands.
internal async Task OnGuildApplicationCommandCountsUpdateAsync(int chatInputCommandCount, int userContextMenuCommandCount, int messageContextMenuCount, ulong guildId)
{
var guild = this.InternalGetCachedGuild(guildId);
if (guild == null)
{
guild = new DiscordGuild
{
Id = guildId,
Discord = this
};
}
var ea = new GuildApplicationCommandCountEventArgs(this.ServiceProvider)
{
SlashCommands = chatInputCommandCount,
UserContextMenuCommands = userContextMenuCommandCount,
MessageContextMenuCommands = messageContextMenuCount,
Guild = guild
};
await this._guildApplicationCommandCountUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the application command permissions update event.
///
/// The new permissions.
/// The command id.
/// The guild id.
/// The application id.
internal async Task OnApplicationCommandPermissionsUpdateAsync(IEnumerable perms, ulong channelId, ulong guildId, ulong applicationId)
{
if (applicationId != this.CurrentApplication.Id)
return;
var guild = this.InternalGetCachedGuild(guildId);
DiscordApplicationCommand cmd;
try
{
cmd = await this.GetGuildApplicationCommandAsync(guildId, channelId);
}
catch (NotFoundException)
{
cmd = await this.GetGlobalApplicationCommandAsync(channelId);
}
if (guild == null)
{
guild = new DiscordGuild
{
Id = guildId,
Discord = this
};
}
var ea = new ApplicationCommandPermissionsUpdateEventArgs(this.ServiceProvider)
{
Permissions = perms.ToList(),
Command = cmd,
ApplicationId = applicationId,
Guild = guild
};
await this._applicationCommandPermissionsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Interaction
///
/// Handles the interaction create event.
///
/// The guild id.
/// The channel id.
/// The transport user.
/// The transport member.
/// The interaction.
/// Debug.
internal async Task OnInteractionCreateAsync(ulong? guildId, ulong channelId, TransportUser user, TransportMember member, DiscordInteraction interaction, string rawInteraction)
{
this.Logger.LogTrace("Interaction from {guild} on shard {shard}", guildId.HasValue ? guildId.Value : "dm", this.ShardId);
this.Logger.LogTrace("Interaction: {interaction}", rawInteraction);
var usr = new DiscordUser(user) { Discord = this };
interaction.ChannelId = channelId;
interaction.GuildId = guildId;
interaction.Discord = this;
interaction.Data.Discord = this;
if (member != null)
{
usr = new DiscordMember(member) { GuildId = guildId.Value, Discord = this };
this.UpdateUser(usr, guildId, interaction.Guild, member);
}
else
{
this.UserCache.AddOrUpdate(usr.Id, usr, (old, @new) => @new);
}
interaction.User = usr;
var resolved = interaction.Data.Resolved;
if (resolved != null)
{
if (resolved.Users != null)
{
foreach (var c in resolved.Users)
{
c.Value.Discord = this;
this.UserCache.AddOrUpdate(c.Value.Id, c.Value, (old, @new) => @new);
}
}
if (resolved.Members != null)
{
foreach (var c in resolved.Members)
{
c.Value.Discord = this;
c.Value.Id = c.Key;
c.Value.GuildId = guildId.Value;
c.Value.User.Discord = this;
this.UserCache.AddOrUpdate(c.Value.User.Id, c.Value.User, (old, @new) => @new);
}
}
if (resolved.Channels != null)
{
foreach (var c in resolved.Channels)
{
c.Value.Discord = this;
if (guildId.HasValue)
{
c.Value.GuildId = guildId.Value;
try
{
if (this.Guilds.TryGetValue(guildId.Value, out var guild))
if (guild.ChannelsInternal.TryGetValue(c.Key, out var channel) && channel.PermissionOverwritesInternal != null && channel.PermissionOverwritesInternal.Any())
c.Value.PermissionOverwritesInternal = channel.PermissionOverwritesInternal;
}
catch (Exception) { }
}
}
}
if (resolved.Roles != null)
{
foreach (var c in resolved.Roles)
{
c.Value.Discord = this;
if (guildId.HasValue)
c.Value.GuildId = guildId.Value;
}
}
if (resolved.Messages != null)
{
foreach (var m in resolved.Messages)
{
m.Value.Discord = this;
if (guildId.HasValue)
m.Value.GuildId = guildId.Value;
}
}
if (resolved.Attachments != null)
foreach (var a in resolved.Attachments)
a.Value.Discord = this;
}
if (interaction.Type is InteractionType.Component || interaction.Type is InteractionType.ModalSubmit)
{
if (interaction.Message != null)
{
interaction.Message.Discord = this;
interaction.Message.ChannelId = interaction.ChannelId;
}
var cea = new ComponentInteractionCreateEventArgs(this.ServiceProvider)
{
Message = interaction.Message,
Interaction = interaction
};
await this._componentInteractionCreated.InvokeAsync(this, cea).ConfigureAwait(false);
}
else
{
if (interaction.Data.Target.HasValue) // Context-Menu. //
{
var targetId = interaction.Data.Target.Value;
DiscordUser targetUser = null;
DiscordMember targetMember = null;
DiscordMessage targetMessage = null;
interaction.Data.Resolved.Messages?.TryGetValue(targetId, out targetMessage);
interaction.Data.Resolved.Members?.TryGetValue(targetId, out targetMember);
interaction.Data.Resolved.Users?.TryGetValue(targetId, out targetUser);
var ea = new ContextMenuInteractionCreateEventArgs(this.ServiceProvider)
{
Interaction = interaction,
TargetUser = targetMember ?? targetUser,
TargetMessage = targetMessage,
Type = interaction.Data.Type
};
await this._contextMenuInteractionCreated.InvokeAsync(this, ea);
}
else
{
var ea = new InteractionCreateEventArgs(this.ServiceProvider)
{
Interaction = interaction
};
await this._interactionCreated.InvokeAsync(this, ea);
}
}
}
#endregion
#region Misc
///
/// Handles the typing start event.
///
/// The user id.
/// The channel id.
/// The channel.
/// The optional guild id.
/// The time when the user started typing.
/// The transport member.
internal async Task OnTypingStartEventAsync(ulong userId, ulong channelId, DiscordChannel channel, ulong? guildId, DateTimeOffset started, TransportMember mbr)
{
if (channel == null)
{
channel = new DiscordChannel
{
Discord = this,
Id = channelId,
GuildId = guildId ?? default,
};
}
var guild = this.InternalGetCachedGuild(guildId);
var usr = this.UpdateUser(new DiscordUser { Id = userId, Discord = this }, guildId, guild, mbr);
var ea = new TypingStartEventArgs(this.ServiceProvider)
{
Channel = channel,
User = usr,
Guild = guild,
StartedAt = started
};
await this._typingStarted.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles the webhooks update.
///
/// The channel.
/// The guild.
internal async Task OnWebhooksUpdateAsync(DiscordChannel channel, DiscordGuild guild)
{
var ea = new WebhooksUpdateEventArgs(this.ServiceProvider)
{
Channel = channel,
Guild = guild
};
await this._webhooksUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
///
/// Handles all unknown events.
///
/// The payload.
internal async Task OnUnknownEventAsync(GatewayPayload payload)
{
var ea = new UnknownEventArgs(this.ServiceProvider) { EventName = payload.EventName, Json = (payload.Data as JObject)?.ToString() };
await this._unknownEvent.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#endregion
}
diff --git a/DisCatSharp/Clients/DiscordClient.WebSocket.cs b/DisCatSharp/Clients/DiscordClient.WebSocket.cs
index 491e548b0..b54008221 100644
--- a/DisCatSharp/Clients/DiscordClient.WebSocket.cs
+++ b/DisCatSharp/Clients/DiscordClient.WebSocket.cs
@@ -1,591 +1,592 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using DisCatSharp.EventArgs;
using DisCatSharp.Net.Abstractions;
using DisCatSharp.Net.WebSocket;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DisCatSharp;
///
/// Represents a discord websocket client.
///
public sealed partial class DiscordClient
{
#region Private Fields
private int _heartbeatInterval;
private DateTimeOffset _lastHeartbeat;
private Task _heartbeatTask;
internal static DateTimeOffset DiscordEpoch = new(2015, 1, 1, 0, 0, 0, TimeSpan.Zero);
private int _skippedHeartbeats;
private long _lastSequence;
internal IWebSocketClient WebSocketClient;
private PayloadDecompressor _payloadDecompressor;
private CancellationTokenSource _cancelTokenSource;
private CancellationToken _cancelToken;
#endregion
#region Connection Semaphore
///
/// Gets the socket locks.
///
private static ConcurrentDictionary s_socketLocks { get; } = new();
///
/// Gets the session lock.
///
private readonly ManualResetEventSlim _sessionLock = new(true);
#endregion
#region Internal Connection Methods
///
/// Reconnects the websocket client.
///
/// Whether to start a new session.
/// The reconnect code.
/// The reconnect message.
private Task InternalReconnectAsync(bool startNewSession = false, int code = 1000, string message = "")
{
if (startNewSession)
this._sessionId = null;
_ = this.WebSocketClient.DisconnectAsync(code, message);
return Task.CompletedTask;
}
///
/// Connects the websocket client.
///
internal async Task InternalConnectAsync()
{
SocketLock socketLock = null;
try
{
if (this.GatewayInfo == null)
await this.InternalUpdateGatewayAsync().ConfigureAwait(false);
await this.InitializeAsync().ConfigureAwait(false);
socketLock = this.GetSocketLock();
await socketLock.LockAsync().ConfigureAwait(false);
}
catch
{
socketLock?.UnlockAfter(TimeSpan.Zero);
throw;
}
if (!this.Presences.ContainsKey(this.CurrentUser.Id))
{
this.PresencesInternal[this.CurrentUser.Id] = new DiscordPresence
{
Discord = this,
RawActivity = new TransportActivity(),
Activity = new DiscordActivity(),
Status = UserStatus.Online,
InternalUser = new TransportUser
{
Id = this.CurrentUser.Id,
Username = this.CurrentUser.Username,
Discriminator = this.CurrentUser.Discriminator,
AvatarHash = this.CurrentUser.AvatarHash
}
};
}
else
{
var pr = this.PresencesInternal[this.CurrentUser.Id];
pr.RawActivity = new TransportActivity();
pr.Activity = new DiscordActivity();
pr.Status = UserStatus.Online;
}
Volatile.Write(ref this._skippedHeartbeats, 0);
this.WebSocketClient = this.Configuration.WebSocketClientFactory(this.Configuration.Proxy, this.ServiceProvider);
this._payloadDecompressor = this.Configuration.GatewayCompressionLevel != GatewayCompressionLevel.None
? new PayloadDecompressor(this.Configuration.GatewayCompressionLevel)
: null;
this._cancelTokenSource = new CancellationTokenSource();
this._cancelToken = this._cancelTokenSource.Token;
this.WebSocketClient.Connected += SocketOnConnect;
this.WebSocketClient.Disconnected += SocketOnDisconnect;
this.WebSocketClient.MessageReceived += SocketOnMessage;
this.WebSocketClient.ExceptionThrown += SocketOnException;
var gwuri = new QueryUriBuilder(this.GatewayUri)
.AddParameter("v", this.Configuration.ApiVersion)
.AddParameter("encoding", "json");
if (this.Configuration.GatewayCompressionLevel == GatewayCompressionLevel.Stream)
gwuri.AddParameter("compress", "zlib-stream");
this.Logger.LogDebug(LoggerEvents.Startup, "Connecting to {gw}", this.GatewayUri.AbsoluteUri);
await this.WebSocketClient.ConnectAsync(gwuri.Build()).ConfigureAwait(false);
Task SocketOnConnect(IWebSocketClient sender, SocketEventArgs e)
=> this._socketOpened.InvokeAsync(this, e);
async Task SocketOnMessage(IWebSocketClient sender, SocketMessageEventArgs e)
{
string msg = null;
if (e is SocketTextMessageEventArgs etext)
{
msg = etext.Message;
}
else if (e is SocketBinaryMessageEventArgs ebin)
{
using var ms = new MemoryStream();
if (!this._payloadDecompressor.TryDecompress(new ArraySegment(ebin.Message), ms))
{
this.Logger.LogError(LoggerEvents.WebSocketReceiveFailure, "Payload decompression failed");
return;
}
ms.Position = 0;
using var sr = new StreamReader(ms, Utilities.UTF8);
msg = await sr.ReadToEndAsync().ConfigureAwait(false);
}
try
{
this.Logger.LogTrace(LoggerEvents.GatewayWsRx, msg);
await this.HandleSocketMessageAsync(msg).ConfigureAwait(false);
}
catch (Exception ex)
{
this.Logger.LogError(LoggerEvents.WebSocketReceiveFailure, ex, "Socket handler suppressed an exception");
}
}
Task SocketOnException(IWebSocketClient sender, SocketErrorEventArgs e)
=> this._socketErrored.InvokeAsync(this, e);
async Task SocketOnDisconnect(IWebSocketClient sender, SocketCloseEventArgs e)
{
// release session and connection
this._connectionLock.Set();
this._sessionLock.Set();
if (!this._disposed)
this._cancelTokenSource.Cancel();
this.Logger.LogDebug(LoggerEvents.ConnectionClose, "Connection closed ({0}, '{1}')", e.CloseCode, e.CloseMessage);
await this._socketClosed.InvokeAsync(this, e).ConfigureAwait(false);
if (this.Configuration.AutoReconnect && (e.CloseCode < 4001 || e.CloseCode >= 5000))
{
this.Logger.LogCritical(LoggerEvents.ConnectionClose, "Connection terminated ({0}, '{1}'), reconnecting", e.CloseCode, e.CloseMessage);
if (this._status == null)
await this.ConnectAsync().ConfigureAwait(false);
else
if (this._status.IdleSince.HasValue)
await this.ConnectAsync(this._status.ActivityInternal, this._status.Status, Utilities.GetDateTimeOffsetFromMilliseconds(this._status.IdleSince.Value)).ConfigureAwait(false);
else
await this.ConnectAsync(this._status.ActivityInternal, this._status.Status).ConfigureAwait(false);
}
else
{
this.Logger.LogCritical(LoggerEvents.ConnectionClose, "Connection terminated ({0}, '{1}')", e.CloseCode, e.CloseMessage);
}
}
}
#endregion
#region WebSocket (Events)
///
/// Handles the socket message.
///
/// The data.
internal async Task HandleSocketMessageAsync(string data)
{
var payload = JsonConvert.DeserializeObject(data);
this._lastSequence = payload.Sequence ?? this._lastSequence;
switch (payload.OpCode)
{
case GatewayOpCode.Dispatch:
await this.HandleDispatchAsync(payload).ConfigureAwait(false);
break;
case GatewayOpCode.Heartbeat:
await this.OnHeartbeatAsync((long)payload.Data).ConfigureAwait(false);
break;
case GatewayOpCode.Reconnect:
await this.OnReconnectAsync().ConfigureAwait(false);
break;
case GatewayOpCode.InvalidSession:
await this.OnInvalidateSessionAsync((bool)payload.Data).ConfigureAwait(false);
break;
case GatewayOpCode.Hello:
await this.OnHelloAsync((payload.Data as JObject).ToObject()).ConfigureAwait(false);
break;
case GatewayOpCode.HeartbeatAck:
await this.OnHeartbeatAckAsync().ConfigureAwait(false);
break;
default:
this.Logger.LogWarning(LoggerEvents.WebSocketReceive, "Unknown Discord opcode: {0}\nPayload: {1}", payload.OpCode, payload.Data);
break;
}
}
///
/// Handles the heartbeat.
///
/// The sequence.
internal async Task OnHeartbeatAsync(long seq)
{
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received HEARTBEAT (OP1)");
await this.SendHeartbeatAsync(seq).ConfigureAwait(false);
}
///
/// Handles the reconnect event.
///
internal async Task OnReconnectAsync()
{
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received RECONNECT (OP7)");
await this.InternalReconnectAsync(code: 4000, message: "OP7 acknowledged").ConfigureAwait(false);
}
///
/// Handles the invalidate session event
///
/// Unknown. Please fill documentation.
internal async Task OnInvalidateSessionAsync(bool data)
{
// begin a session if one is not open already
if (this._sessionLock.Wait(0))
this._sessionLock.Reset();
// we are sending a fresh resume/identify, so lock the socket
var socketLock = this.GetSocketLock();
await socketLock.LockAsync().ConfigureAwait(false);
socketLock.UnlockAfter(TimeSpan.FromSeconds(5));
if (data)
{
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received INVALID_SESSION (OP9, true)");
await Task.Delay(6000).ConfigureAwait(false);
await this.SendResumeAsync().ConfigureAwait(false);
}
else
{
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received INVALID_SESSION (OP9, false)");
this._sessionId = null;
await this.SendIdentifyAsync(this._status).ConfigureAwait(false);
}
}
///
/// Handles the hello event.
///
/// The gateway hello payload.
internal async Task OnHelloAsync(GatewayHello hello)
{
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received HELLO (OP10)");
if (this._sessionLock.Wait(0))
{
this._sessionLock.Reset();
this.GetSocketLock().UnlockAfter(TimeSpan.FromSeconds(5));
}
else
{
this.Logger.LogWarning(LoggerEvents.SessionUpdate, "Attempt to start a session while another session is active");
return;
}
Interlocked.CompareExchange(ref this._skippedHeartbeats, 0, 0);
this._heartbeatInterval = hello.HeartbeatInterval;
this._heartbeatTask = Task.Run(this.HeartbeatLoopAsync, this._cancelToken);
if (string.IsNullOrEmpty(this._sessionId))
await this.SendIdentifyAsync(this._status).ConfigureAwait(false);
else
await this.SendResumeAsync().ConfigureAwait(false);
}
///
/// Handles the heartbeat acknowledge event.
///
internal async Task OnHeartbeatAckAsync()
{
Interlocked.Decrement(ref this._skippedHeartbeats);
var ping = (int)(DateTime.Now - this._lastHeartbeat).TotalMilliseconds;
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received HEARTBEAT_ACK (OP11, {0}ms)", ping);
Volatile.Write(ref this._ping, ping);
var args = new HeartbeatEventArgs(this.ServiceProvider)
{
Ping = this.Ping,
Timestamp = DateTimeOffset.Now
};
await this._heartbeated.InvokeAsync(this, args).ConfigureAwait(false);
}
///
/// Handles the heartbeat loop.
///
internal async Task HeartbeatLoopAsync()
{
this.Logger.LogDebug(LoggerEvents.Heartbeat, "Heartbeat task started");
var token = this._cancelToken;
try
{
while (true)
{
await this.SendHeartbeatAsync(this._lastSequence).ConfigureAwait(false);
await Task.Delay(this._heartbeatInterval, token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
}
}
catch (OperationCanceledException) { }
}
#endregion
#region Internal Gateway Methods
///
/// Updates the status.
///
/// The activity.
/// The optional user status.
/// Since when is the client performing the specified activity.
internal async Task InternalUpdateStatusAsync(DiscordActivity activity, UserStatus? userStatus, DateTimeOffset? idleSince)
{
if (activity != null && activity.Name != null && activity.Name.Length > 128)
throw new Exception("Game name can't be longer than 128 characters!");
var sinceUnix = idleSince != null ? (long?)Utilities.GetUnixTime(idleSince.Value) : null;
var act = activity ?? new DiscordActivity();
var status = new StatusUpdate
{
Activity = new TransportActivity(act),
IdleSince = sinceUnix,
IsAfk = idleSince != null,
Status = userStatus ?? UserStatus.Online
};
// Solution to have status persist between sessions
this._status = status;
var statusUpdate = new GatewayPayload
{
OpCode = GatewayOpCode.StatusUpdate,
Data = status
};
var statusstr = JsonConvert.SerializeObject(statusUpdate);
await this.WsSendAsync(statusstr).ConfigureAwait(false);
if (!this.PresencesInternal.ContainsKey(this.CurrentUser.Id))
{
this.PresencesInternal[this.CurrentUser.Id] = new DiscordPresence
{
Discord = this,
Activity = act,
Status = userStatus ?? UserStatus.Online,
InternalUser = new TransportUser { Id = this.CurrentUser.Id }
};
}
else
{
var pr = this.PresencesInternal[this.CurrentUser.Id];
pr.Activity = act;
pr.Status = userStatus ?? pr.Status;
}
}
///
/// Sends the heartbeat.
///
/// The sequenze.
internal async Task SendHeartbeatAsync(long seq)
{
var moreThan5 = Volatile.Read(ref this._skippedHeartbeats) > 5;
var guildsComp = Volatile.Read(ref this._guildDownloadCompleted);
if (guildsComp && moreThan5)
{
this.Logger.LogCritical(LoggerEvents.HeartbeatFailure, "Server failed to acknowledge more than 5 heartbeats - connection is zombie");
var args = new ZombiedEventArgs(this.ServiceProvider)
{
Failures = Volatile.Read(ref this._skippedHeartbeats),
GuildDownloadCompleted = true
};
await this._zombied.InvokeAsync(this, args).ConfigureAwait(false);
await this.InternalReconnectAsync(code: 4001, message: "Too many heartbeats missed").ConfigureAwait(false);
return;
}
else if (!guildsComp && moreThan5)
{
var args = new ZombiedEventArgs(this.ServiceProvider)
{
Failures = Volatile.Read(ref this._skippedHeartbeats),
GuildDownloadCompleted = false
};
await this._zombied.InvokeAsync(this, args).ConfigureAwait(false);
this.Logger.LogWarning(LoggerEvents.HeartbeatFailure, "Server failed to acknowledge more than 5 heartbeats, but the guild download is still running - check your connection speed");
}
Volatile.Write(ref this._lastSequence, seq);
this.Logger.LogTrace(LoggerEvents.Heartbeat, "Sending heartbeat");
var heartbeat = new GatewayPayload
{
OpCode = GatewayOpCode.Heartbeat,
Data = seq
};
var heartbeatStr = JsonConvert.SerializeObject(heartbeat);
await this.WsSendAsync(heartbeatStr).ConfigureAwait(false);
this._lastHeartbeat = DateTimeOffset.Now;
Interlocked.Increment(ref this._skippedHeartbeats);
}
///
/// Sends the identify payload.
///
/// The status update payload.
internal async Task SendIdentifyAsync(StatusUpdate status)
{
var identify = new GatewayIdentify
{
Token = Utilities.GetFormattedToken(this),
Compress = this.Configuration.GatewayCompressionLevel == GatewayCompressionLevel.Payload,
LargeThreshold = this.Configuration.LargeThreshold,
ShardInfo = new ShardInfo
{
ShardId = this.Configuration.ShardId,
ShardCount = this.Configuration.ShardCount
},
Presence = status,
Intents = this.Configuration.Intents,
Discord = this
};
var payload = new GatewayPayload
{
OpCode = GatewayOpCode.Identify,
Data = identify
};
var payloadstr = JsonConvert.SerializeObject(payload);
await this.WsSendAsync(payloadstr).ConfigureAwait(false);
this.Logger.LogDebug(LoggerEvents.Intents, "Registered gateway intents ({0})", this.Configuration.Intents);
}
///
/// Sends the resume payload.
///
internal async Task SendResumeAsync()
{
var resume = new GatewayResume
{
Token = Utilities.GetFormattedToken(this),
SessionId = this._sessionId,
SequenceNumber = Volatile.Read(ref this._lastSequence)
};
var resumePayload = new GatewayPayload
{
OpCode = GatewayOpCode.Resume,
Data = resume
};
var resumestr = JsonConvert.SerializeObject(resumePayload);
this.GatewayUri = new Uri(this._resumeGatewayUrl);
this.Logger.LogDebug(LoggerEvents.ConnectionClose, "Request to resume via {gw}", this.GatewayUri.AbsoluteUri);
await this.WsSendAsync(resumestr).ConfigureAwait(false);
}
///
/// Internals the update gateway async.
///
/// A Task.
internal async Task InternalUpdateGatewayAsync()
{
var info = await this.GetGatewayInfoAsync().ConfigureAwait(false);
this.GatewayInfo = info;
this.GatewayUri = new Uri(info.Url);
}
///
/// Sends a websocket message.
///
/// The payload to send.
internal async Task WsSendAsync(string payload)
{
this.Logger.LogTrace(LoggerEvents.GatewayWsTx, payload);
await this.WebSocketClient.SendMessageAsync(payload).ConfigureAwait(false);
}
#endregion
#region Semaphore Methods
///
/// Gets the socket lock.
///
/// The added socket lock.
private SocketLock GetSocketLock()
=> s_socketLocks.GetOrAdd(this.CurrentApplication.Id, appId => new SocketLock(appId, this.GatewayInfo.SessionBucket.MaxConcurrency));
#endregion
}
diff --git a/DisCatSharp/DiscordConfiguration.cs b/DisCatSharp/DiscordConfiguration.cs
index 58c670f55..c58c67d2d 100644
--- a/DisCatSharp/DiscordConfiguration.cs
+++ b/DisCatSharp/DiscordConfiguration.cs
@@ -1,290 +1,291 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Net;
using DisCatSharp.Entities;
+using DisCatSharp.Enums;
using DisCatSharp.Net.Udp;
using DisCatSharp.Net.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DisCatSharp;
///
/// Represents configuration for and .
///
public sealed class DiscordConfiguration
{
///
/// Sets the token used to identify the client.
///
public string Token
{
internal get => this._token;
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException(nameof(value), "Token cannot be null, empty, or all whitespace.");
this._token = value.Trim();
}
}
private string _token = "";
///
/// Sets the type of the token used to identify the client.
/// Defaults to .
///
public TokenType TokenType { internal get; set; } = TokenType.Bot;
///
/// Sets the minimum logging level for messages.
/// Typically, the default value of is ok for most uses.
///
public LogLevel MinimumLogLevel { internal get; set; } = LogLevel.Information;
///
/// Overwrites the api version.
/// Defaults to 10.
///
public string ApiVersion { internal get; set; } = "10";
///
/// Sets whether to rely on Discord for NTP (Network Time Protocol) synchronization with the "X-Ratelimit-Reset-After" header.
/// If the system clock is unsynced, setting this to true will ensure ratelimits are synced with Discord and reduce the risk of hitting one.
/// This should only be set to false if the system clock is synced with NTP.
/// Defaults to true.
///
public bool UseRelativeRatelimit { internal get; set; } = true;
///
/// Allows you to overwrite the time format used by the internal debug logger.
/// Only applicable when is set left at default value. Defaults to ISO 8601-like format.
///
public string LogTimestampFormat { internal get; set; } = "yyyy-MM-dd HH:mm:ss zzz";
///
/// Sets the member count threshold at which guilds are considered large.
/// Defaults to 250.
///
public int LargeThreshold { internal get; set; } = 250;
///
/// Sets whether to automatically reconnect in case a connection is lost.
/// Defaults to true.
///
public bool AutoReconnect { internal get; set; } = true;
///
/// Sets the ID of the shard to connect to.
/// If not sharding, or sharding automatically, this value should be left with the default value of 0.
///
public int ShardId { internal get; set; }
///
/// Sets the total number of shards the bot is on. If not sharding, this value should be left with a default value of 1.
/// If sharding automatically, this value will indicate how many shards to boot. If left default for automatic sharding, the client will determine the shard count automatically.
///
public int ShardCount { internal get; set; } = 1;
///
/// Sets the level of compression for WebSocket traffic.
/// Disabling this option will increase the amount of traffic sent via WebSocket. Setting will enable compression for READY and GUILD_CREATE payloads. Setting will enable compression for the entire WebSocket stream, drastically reducing amount of traffic.
/// Defaults to .
///
public GatewayCompressionLevel GatewayCompressionLevel { internal get; set; } = GatewayCompressionLevel.Stream;
///
/// Sets the size of the global message cache.
/// Setting this to 0 will disable message caching entirely. Defaults to 1024.
///
public int MessageCacheSize { internal get; set; } = 1024;
///
/// Sets the proxy to use for HTTP and WebSocket connections to Discord.
/// Defaults to null.
///
public IWebProxy Proxy { internal get; set; }
///
/// Sets the timeout for HTTP requests.
/// Set to to disable timeouts.
/// Defaults to 20 seconds.
///
public TimeSpan HttpTimeout { internal get; set; } = TimeSpan.FromSeconds(20);
///
/// Defines that the client should attempt to reconnect indefinitely.
/// This is typically a very bad idea to set to true, as it will swallow all connection errors.
/// Defaults to false.
///
public bool ReconnectIndefinitely { internal get; set; }
///
/// Sets whether the client should attempt to cache members if exclusively using unprivileged intents.
///
/// This will only take effect if there are no or
/// intents specified. Otherwise, this will always be overwritten to true.
///
/// Defaults to true.
///
public bool AlwaysCacheMembers { internal get; set; } = true;
///
/// Sets the gateway intents for this client.
/// If set, the client will only receive events that they specify with intents.
/// Defaults to .
///
public DiscordIntents Intents { internal get; set; } = DiscordIntents.AllUnprivileged;
///
/// Sets the factory method used to create instances of WebSocket clients.
/// Use and equivalents on other implementations to switch out client implementations.
/// Defaults to .
///
public WebSocketClientFactoryDelegate WebSocketClientFactory
{
internal get => this._webSocketClientFactory;
set
{
if (value == null)
throw new InvalidOperationException("You need to supply a valid WebSocket client factory method.");
this._webSocketClientFactory = value;
}
}
private WebSocketClientFactoryDelegate _webSocketClientFactory = WebSocketClient.CreateNew;
///
/// Sets the factory method used to create instances of UDP clients.
/// Use and equivalents on other implementations to switch out client implementations.
/// Defaults to .
///
public UdpClientFactoryDelegate UdpClientFactory
{
internal get => this._udpClientFactory;
set => this._udpClientFactory = value ?? throw new InvalidOperationException("You need to supply a valid UDP client factory method.");
}
private UdpClientFactoryDelegate _udpClientFactory = DcsUdpClient.CreateNew;
///
/// Sets the logger implementation to use.
/// To create your own logger, implement the instance.
/// Defaults to built-in implementation.
///
public ILoggerFactory LoggerFactory { internal get; set; }
///
/// Sets if the bot's status should show the mobile icon.
/// Defaults to false.
///
public bool MobileStatus { internal get; set; }
///
/// Whether to use canary. has to be false.
/// Defaults to false.
///
public bool UseCanary { internal get; set; }
///
/// Whether to use ptb. has to be false.
/// Defaults to false.
///
public bool UsePtb { internal get; set; }
///
/// Refresh full guild channel cache.
/// Defaults to false.
///
public bool AutoRefreshChannelCache { internal get; set; }
///
/// Do not use, this is meant for DisCatSharp Devs.
/// Defaults to null.
///
public string Override { internal get; set; }
///
/// Sets your preferred API language. See for valid locales.
///
public string Locale { internal get; set; } = DiscordLocales.AMERICAN_ENGLISH;
///
/// Sets the service provider.
/// This allows passing data around without resorting to static members.
/// Defaults to an empty service provider.
///
public IServiceProvider ServiceProvider { internal get; set; } = new ServiceCollection().BuildServiceProvider(true);
///
/// Creates a new configuration with default values.
///
public DiscordConfiguration()
{ }
///
/// Utilized via Dependency Injection Pipeline
///
///
[ActivatorUtilitiesConstructor]
public DiscordConfiguration(IServiceProvider provider)
{
this.ServiceProvider = provider;
}
///
/// Creates a clone of another discord configuration.
///
/// Client configuration to clone.
public DiscordConfiguration(DiscordConfiguration other)
{
this.Token = other.Token;
this.TokenType = other.TokenType;
this.MinimumLogLevel = other.MinimumLogLevel;
this.UseRelativeRatelimit = other.UseRelativeRatelimit;
this.LogTimestampFormat = other.LogTimestampFormat;
this.LargeThreshold = other.LargeThreshold;
this.AutoReconnect = other.AutoReconnect;
this.ShardId = other.ShardId;
this.ShardCount = other.ShardCount;
this.GatewayCompressionLevel = other.GatewayCompressionLevel;
this.MessageCacheSize = other.MessageCacheSize;
this.WebSocketClientFactory = other.WebSocketClientFactory;
this.UdpClientFactory = other.UdpClientFactory;
this.Proxy = other.Proxy;
this.HttpTimeout = other.HttpTimeout;
this.ReconnectIndefinitely = other.ReconnectIndefinitely;
this.Intents = other.Intents;
this.LoggerFactory = other.LoggerFactory;
this.MobileStatus = other.MobileStatus;
this.UseCanary = other.UseCanary;
this.UsePtb = other.UsePtb;
this.AutoRefreshChannelCache = other.AutoRefreshChannelCache;
this.ApiVersion = other.ApiVersion;
this.ServiceProvider = other.ServiceProvider;
this.Override = other.Override;
this.Locale = other.Locale;
}
}
diff --git a/DisCatSharp/Entities/Application/DiscordApplicationCommandPermission.cs b/DisCatSharp/Entities/Application/DiscordApplicationCommandPermission.cs
index 302081065..746e3f1b0 100644
--- a/DisCatSharp/Entities/Application/DiscordApplicationCommandPermission.cs
+++ b/DisCatSharp/Entities/Application/DiscordApplicationCommandPermission.cs
@@ -1,109 +1,111 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
+using DisCatSharp.Enums;
+
using Newtonsoft.Json;
namespace DisCatSharp.Entities;
///
/// Represents a application command permission.
///
public sealed class DiscordApplicationCommandPermission : SnowflakeObject, IEquatable
{
///
/// Gets the id of the role or user.
///
[JsonProperty("id")]
public new ulong Id { get; set; }
///
/// Gets the application command permission type.
///
[JsonProperty("type")]
public ApplicationCommandPermissionType Type { get; set; }
///
/// Gets the permission .
///
[JsonProperty("permission")]
public bool Permission { get; set; }
///
/// Initializes a new instance of the class.
///
internal DiscordApplicationCommandPermission() { }
///
/// Initializes a new instance of the class.
///
/// The Id of the role or user for this permission.
/// Defines whether the permission effects a user or role.
/// The permission for this command. True allows the subject to use the command, false does not allow the subject to use the command.
public DiscordApplicationCommandPermission(ulong id, ApplicationCommandPermissionType type, bool permission)
{
this.Id = id;
this.Type = type;
this.Permission = permission;
}
///
/// Checks whether this object is equal to another object.
///
/// The command to compare to.
/// Whether the command is equal to this .
public bool Equals(DiscordApplicationCommandPermission other)
=> this.Id == other.Id;
///
/// Determines if two objects are equal.
///
/// The first command object.
/// The second command object.
/// Whether the two objects are equal.
public static bool operator ==(DiscordApplicationCommandPermission e1, DiscordApplicationCommandPermission e2)
=> e1.Equals(e2);
///
/// Determines if two objects are not equal.
///
/// The first command object.
/// The second command object.
/// Whether the two objects are not equal.
public static bool operator !=(DiscordApplicationCommandPermission e1, DiscordApplicationCommandPermission e2)
=> !(e1 == e2);
///
/// Determines if a is equal to the current .
///
/// The object to compare to.
/// Whether the two objects are not equal.
public override bool Equals(object other) => other is DiscordApplicationCommandPermission dacp && this.Equals(dacp);
///
/// Gets the hash code for this .
///
/// The hash code for this .
public override int GetHashCode()
=> this.Id.GetHashCode();
}
diff --git a/DisCatSharp/Entities/Application/DiscordApplicationInstallParams.cs b/DisCatSharp/Entities/Application/DiscordApplicationInstallParams.cs
index 31b835994..e240a6158 100644
--- a/DisCatSharp/Entities/Application/DiscordApplicationInstallParams.cs
+++ b/DisCatSharp/Entities/Application/DiscordApplicationInstallParams.cs
@@ -1,50 +1,52 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System.Collections.Generic;
+using DisCatSharp.Enums;
+
using Newtonsoft.Json;
namespace DisCatSharp.Entities;
///
/// The application install params.
///
public sealed class DiscordApplicationInstallParams
{
///
/// Gets the scopes.
///
[JsonProperty("scopes", NullValueHandling = NullValueHandling.Ignore)]
public IReadOnlyList Scopes { get; internal set; }
///
/// Gets or sets the permissions.
///
[JsonProperty("permissions", NullValueHandling = NullValueHandling.Ignore)]
public Permissions? Permissions { get; internal set; }
///
/// Initializes a new instance of the class.
///
internal DiscordApplicationInstallParams() { }
}
diff --git a/DisCatSharp/Entities/Channel/DiscordChannel.cs b/DisCatSharp/Entities/Channel/DiscordChannel.cs
index aea3d05d5..ec3f23caf 100644
--- a/DisCatSharp/Entities/Channel/DiscordChannel.cs
+++ b/DisCatSharp/Entities/Channel/DiscordChannel.cs
@@ -1,1420 +1,1424 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DisCatSharp.Enums;
+using DisCatSharp.Exceptions;
using DisCatSharp.Net.Abstractions;
using DisCatSharp.Net.Models;
using Newtonsoft.Json;
namespace DisCatSharp.Entities;
///
/// Represents a discord channel.
///
public class DiscordChannel : SnowflakeObject, IEquatable
{
///
/// Gets ID of the guild to which this channel belongs.
///
[JsonProperty("guild_id", NullValueHandling = NullValueHandling.Ignore)]
public ulong? GuildId { get; internal set; }
///
/// Gets ID of the category that contains this channel.
///
[JsonProperty("parent_id", NullValueHandling = NullValueHandling.Include)]
public ulong? ParentId { get; internal set; }
///
/// Gets the category that contains this channel.
///
[JsonIgnore]
public DiscordChannel Parent
=> this.ParentId.HasValue ? this.Guild.GetChannel(this.ParentId.Value) : null;
///
/// Gets the name of this channel.
///
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; internal set; }
///
/// Gets the type of this channel.
///
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public ChannelType Type { get; internal set; }
///
/// Gets the template for new posts in this channel.
/// Applicable if forum channel.
///
[JsonProperty("template", NullValueHandling = NullValueHandling.Ignore)]
public string Template { get; internal set; }
///
/// Gets the position of this channel.
///
[JsonProperty("position", NullValueHandling = NullValueHandling.Ignore)]
public int Position { get; internal set; }
///
/// Gets the flags of this channel.
///
[JsonProperty("flags", NullValueHandling = NullValueHandling.Ignore)]
public ChannelFlags Flags { get; internal set; }
///
/// Gets the maximum available position to move the channel to.
/// This can contain outdated information.
///
public int GetMaxPosition()
{
var channels = this.Guild.Channels.Values;
return this.ParentId != null
? this.Type == ChannelType.Text || this.Type == ChannelType.News
? channels.Where(xc => xc.ParentId == this.ParentId && (xc.Type == ChannelType.Text || xc.Type == ChannelType.News)).OrderBy(xc => xc.Position).Last().Position
: this.Type == ChannelType.Voice || this.Type == ChannelType.Stage
? channels.Where(xc => xc.ParentId == this.ParentId && (xc.Type == ChannelType.Voice || xc.Type == ChannelType.Stage)).OrderBy(xc => xc.Position).Last().Position
: channels.Where(xc => xc.ParentId == this.ParentId && xc.Type == this.Type).OrderBy(xc => xc.Position).Last().Position
: channels.Where(xc => xc.ParentId == null && xc.Type == this.Type).OrderBy(xc => xc.Position).Last().Position;
}
///
/// Gets the minimum available position to move the channel to.
///
public int GetMinPosition()
{
var channels = this.Guild.Channels.Values;
return this.ParentId != null
? this.Type == ChannelType.Text || this.Type == ChannelType.News
? channels.Where(xc => xc.ParentId == this.ParentId && (xc.Type == ChannelType.Text || xc.Type == ChannelType.News)).OrderBy(xc => xc.Position).First().Position
: this.Type == ChannelType.Voice || this.Type == ChannelType.Stage
? channels.Where(xc => xc.ParentId == this.ParentId && (xc.Type == ChannelType.Voice || xc.Type == ChannelType.Stage)).OrderBy(xc => xc.Position).First().Position
: channels.Where(xc => xc.ParentId == this.ParentId && xc.Type == this.Type).OrderBy(xc => xc.Position).First().Position
: channels.Where(xc => xc.ParentId == null && xc.Type == this.Type).OrderBy(xc => xc.Position).First().Position;
}
///
/// Gets whether this channel is a DM channel.
///
[JsonIgnore]
public bool IsPrivate
=> this.Type is ChannelType.Private or ChannelType.Group;
///
/// Gets whether this channel is a channel category.
///
[JsonIgnore]
public bool IsCategory
=> this.Type == ChannelType.Category;
///
/// Gets whether this channel is a stage channel.
///
[JsonIgnore]
public bool IsStage
=> this.Type == ChannelType.Stage;
///
/// Gets the guild to which this channel belongs.
///
[JsonIgnore]
public DiscordGuild Guild
=> this.GuildId.HasValue && this.Discord.Guilds.TryGetValue(this.GuildId.Value, out var guild) ? guild : null;
///
/// Gets a collection of permission overwrites for this channel.
///
[JsonIgnore]
public IReadOnlyList PermissionOverwrites
=> this._permissionOverwritesLazy.Value;
[JsonProperty("permission_overwrites", NullValueHandling = NullValueHandling.Ignore)]
internal List PermissionOverwritesInternal = new();
[JsonIgnore]
private readonly Lazy> _permissionOverwritesLazy;
///
/// Gets the channel's topic. This is applicable to text channels only.
///
[JsonProperty("topic", NullValueHandling = NullValueHandling.Ignore)]
public string Topic { get; internal set; }
///
/// Gets the ID of the last message sent in this channel. This is applicable to text channels only.
///
[JsonProperty("last_message_id", NullValueHandling = NullValueHandling.Ignore)]
public ulong? LastMessageId { get; internal set; }
///
/// Gets this channel's bitrate. This is applicable to voice channels only.
///
[JsonProperty("bitrate", NullValueHandling = NullValueHandling.Ignore)]
public int? Bitrate { get; internal set; }
///
/// Gets this channel's user limit. This is applicable to voice channels only.
///
[JsonProperty("user_limit", NullValueHandling = NullValueHandling.Ignore)]
public int? UserLimit { get; internal set; }
///
/// Gets the slow mode delay configured for this channel.
/// All bots, as well as users with or permissions in the channel are exempt from slow mode.
///
[JsonProperty("rate_limit_per_user", NullValueHandling = NullValueHandling.Ignore)]
public int? PerUserRateLimit { get; internal set; }
///
/// Gets the slow mode delay configured for this channel for post creations.
/// All bots, as well as users with or permissions in the channel are exempt from slow mode.
///
[JsonProperty("default_thread_rate_limit_per_user", NullValueHandling = NullValueHandling.Ignore)]
public int? PostCreateUserRateLimit { get; internal set; }
///
/// Gets this channel's video quality mode. This is applicable to voice channels only.
///
[JsonProperty("video_quality_mode", NullValueHandling = NullValueHandling.Ignore)]
public VideoQualityMode? QualityMode { get; internal set; }
///
/// List of available tags for forum posts.
///
[JsonIgnore]
public IReadOnlyList AvailableTags => this.InternalAvailableTags;
///
/// List of available tags for forum posts.
///
[JsonProperty("available_tags", NullValueHandling = NullValueHandling.Ignore)]
internal List InternalAvailableTags { get; set; } = new();
///
/// List of available tags for forum posts.
///
[JsonProperty("default_reaction_emoji", NullValueHandling = NullValueHandling.Ignore)]
public ForumReactionEmoji DefaultReactionEmoji { get; internal set; }
+ [JsonProperty("default_sort_order", NullValueHandling = NullValueHandling.Include)]
+ public ForumPostSortOrder? DefaultSortOrder { get; internal set; }
+
///
/// Gets when the last pinned message was pinned.
///
[JsonIgnore]
public DateTimeOffset? LastPinTimestamp
=> !string.IsNullOrWhiteSpace(this.LastPinTimestampRaw) && DateTimeOffset.TryParse(this.LastPinTimestampRaw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dto) ?
dto : null;
///
/// Gets when the last pinned message was pinned as raw string.
///
[JsonProperty("last_pin_timestamp", NullValueHandling = NullValueHandling.Ignore)]
internal string LastPinTimestampRaw { get; set; }
///
/// Gets this channel's default duration for newly created threads, in minutes, to automatically archive the thread after recent activity.
///
[JsonProperty("default_auto_archive_duration", NullValueHandling = NullValueHandling.Ignore)]
public ThreadAutoArchiveDuration? DefaultAutoArchiveDuration { get; internal set; }
///
/// Gets this channel's mention string.
///
[JsonIgnore]
public string Mention
=> Formatter.Mention(this);
///
/// Gets this channel's children. This applies only to channel categories.
///
[JsonIgnore]
public IReadOnlyList Children =>
!this.IsCategory
? throw new ArgumentException("Only channel categories contain children.")
: this.Guild.ChannelsInternal.Values.Where(e => e.ParentId == this.Id).ToList();
///
/// Gets the list of members currently in the channel (if voice channel), or members who can see the channel (otherwise).
///
[JsonIgnore]
public virtual IReadOnlyList Users =>
this.Guild == null
? throw new InvalidOperationException("Cannot query users outside of guild channels.")
: this.IsVoiceJoinable()
? this.Guild.Members.Values.Where(x => x.VoiceState?.ChannelId == this.Id).ToList()
: this.Guild.Members.Values.Where(x => (this.PermissionsFor(x) & Permissions.AccessChannels) == Permissions.AccessChannels).ToList();
///
/// Gets whether this channel is an NSFW channel.
///
[JsonProperty("nsfw")]
public bool IsNsfw { get; internal set; }
///
/// Gets this channel's region id (if voice channel).
///
[JsonProperty("rtc_region", NullValueHandling = NullValueHandling.Ignore)]
internal string RtcRegionId { get; set; }
///
/// Gets this channel's region override (if voice channel).
///
[JsonIgnore]
public DiscordVoiceRegion RtcRegion
=> this.RtcRegionId != null ? this.Discord.VoiceRegions[this.RtcRegionId] : null;
///
/// Only sent on the resolved channels of interaction responses for application commands.
/// Gets the permissions of the user in this channel who invoked the command.
///
[JsonProperty("permissions", NullValueHandling = NullValueHandling.Ignore)]
public Permissions? UserPermissions { get; internal set; }
///
/// Initializes a new instance of the class.
///
internal DiscordChannel()
{
this._permissionOverwritesLazy = new Lazy>(() => new ReadOnlyCollection(this.PermissionOverwritesInternal));
}
#region Methods
///
/// Sends a message to this channel.
///
/// Content of the message to send.
/// The sent message.
/// Thrown when the client does not have the permission if TTS is true and if TTS is true.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task SendMessageAsync(string content) =>
!this.IsWritable()
? throw new ArgumentException("Cannot send a text message to a non-text channel.")
: this.Discord.ApiClient.CreateMessageAsync(this.Id, content, null, sticker: null, replyMessageId: null, mentionReply: false, failOnInvalidReply: false);
///
/// Sends a message to this channel.
///
/// Embed to attach to the message.
/// The sent message.
/// Thrown when the client does not have the permission and if TTS is true.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task SendMessageAsync(DiscordEmbed embed) =>
!this.IsWritable()
? throw new ArgumentException("Cannot send a text message to a non-text channel.")
: this.Discord.ApiClient.CreateMessageAsync(this.Id, null, embed != null ? new[] { embed } : null, sticker: null, replyMessageId: null, mentionReply: false, failOnInvalidReply: false);
///
/// Sends a message to this channel.
///
/// Embed to attach to the message.
/// Content of the message to send.
/// The sent message.
/// Thrown when the client does not have the permission if TTS is true and if TTS is true.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task SendMessageAsync(string content, DiscordEmbed embed) =>
!this.IsWritable()
? throw new ArgumentException("Cannot send a text message to a non-text channel.")
: this.Discord.ApiClient.CreateMessageAsync(this.Id, content, embed != null ? new[] { embed } : null, sticker: null, replyMessageId: null, mentionReply: false, failOnInvalidReply: false);
///
/// Sends a message to this channel.
///
/// The builder with all the items to send.
/// The sent message.
/// Thrown when the client does not have the permission TTS is true and if TTS is true.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task SendMessageAsync(DiscordMessageBuilder builder)
=> this.Discord.ApiClient.CreateMessageAsync(this.Id, builder);
///
/// Sends a message to this channel.
///
/// The builder with all the items to send.
/// The sent message.
/// Thrown when the client does not have the permission TTS is true and if TTS is true.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task SendMessageAsync(Action action)
{
var builder = new DiscordMessageBuilder();
action(builder);
return !this.IsWritable()
? throw new ArgumentException("Cannot send a text message to a non-text channel.")
: this.Discord.ApiClient.CreateMessageAsync(this.Id, builder);
}
///
/// Deletes a guild channel
///
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task DeleteAsync(string reason = null)
=> this.Discord.ApiClient.DeleteChannelAsync(this.Id, reason);
///
/// Clones this channel. This operation will create a channel with identical settings to this one. Note that this will not copy messages.
///
/// Reason for audit logs.
/// Newly-created channel.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task CloneAsync(string reason = null)
{
if (this.Guild == null)
throw new InvalidOperationException("Non-guild channels cannot be cloned.");
var ovrs = new List();
foreach (var ovr in this.PermissionOverwritesInternal)
ovrs.Add(await new DiscordOverwriteBuilder().FromAsync(ovr).ConfigureAwait(false));
// TODO: Add forum tags option missing?
var bitrate = this.Bitrate;
var userLimit = this.UserLimit;
Optional perUserRateLimit = this.PerUserRateLimit;
if (!this.IsVoiceJoinable())
{
bitrate = null;
userLimit = null;
}
if (this.Type == ChannelType.Stage)
{
userLimit = null;
}
if (!this.IsWritable())
{
perUserRateLimit = Optional.None;
}
- return await this.Guild.CreateChannelAsync(this.Name, this.Type, this.Parent, this.Topic, bitrate, userLimit, ovrs, this.IsNsfw, perUserRateLimit, this.QualityMode, this.DefaultAutoArchiveDuration, reason).ConfigureAwait(false);
+ return await this.Guild.CreateChannelAsync(this.Name, this.Type, this.Parent, this.Topic, bitrate, userLimit, ovrs, this.IsNsfw, perUserRateLimit, this.QualityMode, this.DefaultAutoArchiveDuration, this.Flags, reason).ConfigureAwait(false);
}
///
/// Returns a specific message
///
/// The id of the message
/// Whether to bypass the message cache
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task GetMessageAsync(ulong id, bool bypassCache = false) =>
this.Discord.Configuration.MessageCacheSize > 0
&& !bypassCache
&& this.Discord is DiscordClient dc
&& dc.MessageCache != null
&& dc.MessageCache.TryGet(xm => xm.Id == id && xm.ChannelId == this.Id, out var msg)
? msg
: await this.Discord.ApiClient.GetMessageAsync(this.Id, id).ConfigureAwait(false);
///
/// Modifies the current channel.
///
/// Action to perform on this channel
/// Thrown when the client does not have the .
/// Thrown when the client does not have the correct for modifying the .
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task ModifyAsync(Action action)
{
if (this.Type == ChannelType.Forum)
throw new NotSupportedException("Cannot execute this request on a forum channel.");
var mdl = new ChannelEditModel();
action(mdl);
if (mdl.DefaultAutoArchiveDuration.HasValue)
if (!Utilities.CheckThreadAutoArchiveDurationFeature(this.Guild, mdl.DefaultAutoArchiveDuration.Value))
throw new NotSupportedException($"Cannot modify DefaultAutoArchiveDuration. Guild needs boost tier {(mdl.DefaultAutoArchiveDuration.Value == ThreadAutoArchiveDuration.ThreeDays ? "one" : "two")}.");
return this.Discord.ApiClient.ModifyChannelAsync(this.Id, mdl.Name, mdl.Position, mdl.Topic, mdl.Nsfw,
mdl.Parent.Map(p => p?.Id), mdl.Bitrate, mdl.UserLimit, mdl.PerUserRateLimit, mdl.RtcRegion.Map(r => r?.Id),
- mdl.QualityMode, mdl.DefaultAutoArchiveDuration, mdl.Type, mdl.PermissionOverwrites, mdl.AuditLogReason);
+ mdl.QualityMode, mdl.DefaultAutoArchiveDuration, mdl.Type, mdl.PermissionOverwrites, mdl.Flags, mdl.AuditLogReason);
}
///
/// Modifies the current forum channel.
///
/// Action to perform on this channel
/// Thrown when the client does not have the .
/// Thrown when the client does not have the correct for modifying the .
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task ModifyForumAsync(Action action)
{
if (this.Type != ChannelType.Forum)
throw new NotSupportedException("Cannot execute this request on a non-forum channel.");
var mdl = new ForumChannelEditModel();
action(mdl);
if (mdl.DefaultAutoArchiveDuration.HasValue)
if (!Utilities.CheckThreadAutoArchiveDurationFeature(this.Guild, mdl.DefaultAutoArchiveDuration.Value))
throw new NotSupportedException($"Cannot modify DefaultAutoArchiveDuration. Guild needs boost tier {(mdl.DefaultAutoArchiveDuration.Value == ThreadAutoArchiveDuration.ThreeDays ? "one" : "two")}.");
return this.Discord.ApiClient.ModifyForumChannelAsync(this.Id, mdl.Name, mdl.Position, mdl.Topic, mdl.Template, mdl.Nsfw,
mdl.Parent.Map(p => p?.Id), mdl.DefaultReactionEmoji, mdl.PerUserRateLimit, mdl.PostCreateUserRateLimit,
- mdl.DefaultAutoArchiveDuration, mdl.PermissionOverwrites, mdl.AuditLogReason);
+ mdl.DefaultSortOrder, mdl.DefaultAutoArchiveDuration, mdl.PermissionOverwrites, mdl.Flags, mdl.AuditLogReason);
}
///
/// Updates the channel position when it doesn't have a category.
///
/// Use for moving to other categories.
/// Use to move out of a category.
/// Use for moving within a category.
///
/// Position the channel should be moved to.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task ModifyPositionAsync(int position, string reason = null)
{
if (this.Guild == null)
throw new ArgumentException("Cannot modify order of non-guild channels.");
if (!this.IsMovable())
throw new NotSupportedException("You can't move this type of channel in categories.");
if (this.ParentId != null)
throw new ArgumentException("Cannot modify order of channels within a category. Use ModifyPositionInCategoryAsync instead.");
var pmds = this.Guild.ChannelsInternal.Values.Where(xc => xc.Type == this.Type).OrderBy(xc => xc.Position)
.Select(x => new RestGuildChannelReorderPayload
{
ChannelId = x.Id,
Position = x.Id == this.Id ? position : x.Position >= position ? x.Position + 1 : x.Position
});
return this.Discord.ApiClient.ModifyGuildChannelPositionAsync(this.Guild.Id, pmds, reason);
}
///
/// Updates the channel position within it's own category.
///
/// Use for moving to other categories.
/// Use to move out of a category.
/// Use to move channels outside a category.
///
/// The position.
/// The reason.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
/// Thrown when is out of range.
/// Thrown when function is called on a channel without a parent channel.
public async Task ModifyPositionInCategoryAsync(int position, string reason = null)
{
if (!this.IsMovableInParent())
throw new NotSupportedException("You can't move this type of channel in categories.");
var isUp = position > this.Position;
var channels = await this.InternalRefreshChannelsAsync();
var chns = this.ParentId != null
? this.Type == ChannelType.Text || this.Type == ChannelType.News
? channels.Where(xc => xc.ParentId == this.ParentId && (xc.Type == ChannelType.Text || xc.Type == ChannelType.News))
: this.Type == ChannelType.Voice || this.Type == ChannelType.Stage
? channels.Where(xc => xc.ParentId == this.ParentId && (xc.Type == ChannelType.Voice || xc.Type == ChannelType.Stage))
: channels.Where(xc => xc.ParentId == this.ParentId && xc.Type == this.Type)
: this.Type == ChannelType.Text || this.Type == ChannelType.News
? channels.Where(xc => xc.ParentId == null && (xc.Type == ChannelType.Text || xc.Type == ChannelType.News))
: this.Type == ChannelType.Voice || this.Type == ChannelType.Stage
? channels.Where(xc => xc.ParentId == null && (xc.Type == ChannelType.Voice || xc.Type == ChannelType.Stage))
: channels.Where(xc => xc.ParentId == null && xc.Type == this.Type);
var ochns = chns.OrderBy(xc => xc.Position).ToArray();
var min = ochns.First().Position;
var max = ochns.Last().Position;
if (position > max || position < min)
throw new IndexOutOfRangeException($"Position is not in range. {position} is {(position > max ? "greater then the maximal" : "lower then the minimal")} position.");
var pmds = ochns.Select(x =>
new RestGuildChannelReorderPayload
{
ChannelId = x.Id,
Position = x.Id == this.Id
? position
: isUp
? x.Position <= position && x.Position > this.Position ? x.Position - 1 : x.Position
: x.Position >= position && x.Position < this.Position ? x.Position + 1 : x.Position
}
);
await this.Discord.ApiClient.ModifyGuildChannelPositionAsync(this.Guild.Id, pmds, reason).ConfigureAwait(false);
}
///
/// Internally refreshes the channel list.
///
private async Task> InternalRefreshChannelsAsync()
{
await this.RefreshPositionsAsync();
return this.Guild.Channels.Values.ToList().AsReadOnly();
}
internal void Initialize(BaseDiscordClient client)
{
this.Discord = client;
foreach (var xo in this.PermissionOverwritesInternal)
{
xo.Discord = this.Discord;
xo.ChannelId = this.Id;
}
if (this.InternalAvailableTags != null)
{
foreach (var xo in this.InternalAvailableTags)
{
xo.Discord = this.Discord;
xo.ChannelId = this.Id;
}
}
}
///
/// Refreshes the positions.
///
public async Task RefreshPositionsAsync()
{
var channels = await this.Discord.ApiClient.GetGuildChannelsAsync(this.Guild.Id);
this.Guild.ChannelsInternal.Clear();
foreach (var channel in channels.ToList())
{
channel.Initialize(this.Discord);
this.Guild.ChannelsInternal[channel.Id] = channel;
}
}
///
/// Updates the channel position within it's own category.
/// Valid modes: '+' or 'down' to move a channel down | '-' or 'up' to move a channel up.
///
/// Use for moving to other categories.
/// Use to move out of a category.
/// Use to move channels outside a category.
///
/// The mode. Valid: '+' or 'down' to move a channel down | '-' or 'up' to move a channel up
/// The position.
/// The reason.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
/// Thrown when is out of range.
/// Thrown when function is called on a channel without a parent channel, a wrong mode is given or given position is zero.
public Task ModifyPositionInCategorySmartAsync(string mode, int position, string reason = null)
{
if (!this.IsMovableInParent())
throw new NotSupportedException("You can't move this type of channel in categories.");
if (mode != "+" && mode != "-" && mode != "down" && mode != "up")
throw new ArgumentException("Error with the selected mode: Valid is '+' or 'down' to move a channel down and '-' or 'up' to move a channel up");
var positive = mode == "+" || mode == "positive" || mode == "down";
var negative = mode == "-" || mode == "negative" || mode == "up";
return positive
? position < this.GetMaxPosition()
? this.ModifyPositionInCategoryAsync(this.Position + position, reason)
: throw new IndexOutOfRangeException($"Position is not in range of category.")
: negative
? position > this.GetMinPosition()
? this.ModifyPositionInCategoryAsync(this.Position - position, reason)
: throw new IndexOutOfRangeException($"Position is not in range of category.")
: throw new ArgumentException("You can only modify with +X or -X. 0 is not valid.");
}
///
/// Updates the channel parent, moving the channel to the bottom of the new category.
///
/// New parent for channel. Use to remove from parent.
/// Sync permissions with parent. Defaults to null.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task ModifyParentAsync(DiscordChannel newParent, bool? lockPermissions = null, string reason = null)
{
if (this.Guild == null)
throw new ArgumentException("Cannot modify parent of non-guild channels.");
if (!this.IsMovableInParent())
throw new NotSupportedException("You can't move this type of channel in categories.");
if (newParent.Type is not ChannelType.Category)
throw new ArgumentException("Only category type channels can be parents.");
var position = this.Guild.ChannelsInternal.Values.Where(xc => xc.Type == this.Type && xc.ParentId == newParent.Id) // gets list same type channels in parent
.Select(xc => xc.Position).DefaultIfEmpty(-1).Max() + 1; // returns highest position of list +1, default val: 0
var pmds = this.Guild.ChannelsInternal.Values.Where(xc => xc.Type == this.Type)
.OrderBy(xc => xc.Position)
.Select(x =>
{
var pmd = new RestGuildChannelNewParentPayload
{
ChannelId = x.Id,
Position = x.Position >= position ? x.Position + 1 : x.Position,
};
if (x.Id == this.Id)
{
pmd.Position = position;
pmd.ParentId = newParent?.Id;
pmd.LockPermissions = lockPermissions;
}
return pmd;
});
return this.Discord.ApiClient.ModifyGuildChannelParentAsync(this.Guild.Id, pmds, reason);
}
///
/// Moves the channel out of a category.
///
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task RemoveParentAsync(string reason = null)
{
if (this.Guild == null)
throw new ArgumentException("Cannot modify parent of non-guild channels.");
if (!this.IsMovableInParent())
throw new NotSupportedException("You can't move this type of channel in categories.");
var pmds = this.Guild.ChannelsInternal.Values.Where(xc => xc.Type == this.Type)
.OrderBy(xc => xc.Position)
.Select(x =>
{
var pmd = new RestGuildChannelNoParentPayload { ChannelId = x.Id };
if (x.Id == this.Id)
{
pmd.Position = 1;
pmd.ParentId = null;
}
else
{
pmd.Position = x.Position < this.Position ? x.Position + 1 : x.Position;
}
return pmd;
});
return this.Discord.ApiClient.DetachGuildChannelParentAsync(this.Guild.Id, pmds, reason);
}
///
/// Returns a list of messages before a certain message.
/// The amount of messages to fetch.
/// Message to fetch before from.
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task> GetMessagesBeforeAsync(ulong before, int limit = 100)
=> this.GetMessagesInternalAsync(limit, before, null, null);
///
/// Returns a list of messages after a certain message.
/// The amount of messages to fetch.
/// Message to fetch after from.
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task> GetMessagesAfterAsync(ulong after, int limit = 100)
=> this.GetMessagesInternalAsync(limit, null, after, null);
///
/// Returns a list of messages around a certain message.
/// The amount of messages to fetch.
/// Message to fetch around from.
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task> GetMessagesAroundAsync(ulong around, int limit = 100)
=> this.GetMessagesInternalAsync(limit, null, null, around);
///
/// Returns a list of messages from the last message in the channel.
/// The amount of messages to fetch.
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task> GetMessagesAsync(int limit = 100) =>
this.GetMessagesInternalAsync(limit, null, null, null);
///
/// Returns a list of messages
///
/// How many messages should be returned.
/// Get messages before snowflake.
/// Get messages after snowflake.
/// Get messages around snowflake.
private async Task> GetMessagesInternalAsync(int limit = 100, ulong? before = null, ulong? after = null, ulong? around = null)
{
if (!this.IsWritable())
throw new ArgumentException("Cannot get the messages of a non-text channel.");
if (limit < 0)
throw new ArgumentException("Cannot get a negative number of messages.");
if (limit == 0)
return Array.Empty();
//return this.Discord.ApiClient.GetChannelMessagesAsync(this.Id, limit, before, after, around);
if (limit > 100 && around != null)
throw new InvalidOperationException("Cannot get more than 100 messages around the specified ID.");
var msgs = new List(limit);
var remaining = limit;
ulong? last = null;
var isAfter = after != null;
int lastCount;
do
{
var fetchSize = remaining > 100 ? 100 : remaining;
var fetch = await this.Discord.ApiClient.GetChannelMessagesAsync(this.Id, fetchSize, !isAfter ? last ?? before : null, isAfter ? last ?? after : null, around).ConfigureAwait(false);
lastCount = fetch.Count;
remaining -= lastCount;
if (!isAfter)
{
msgs.AddRange(fetch);
last = fetch.LastOrDefault()?.Id;
}
else
{
msgs.InsertRange(0, fetch);
last = fetch.FirstOrDefault()?.Id;
}
}
while (remaining > 0 && lastCount > 0);
return new ReadOnlyCollection(msgs);
}
///
/// Deletes multiple messages if they are less than 14 days old. If they are older, none of the messages will be deleted and you will receive a error.
///
/// A collection of messages to delete.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task DeleteMessagesAsync(IEnumerable messages, string reason = null)
{
// don't enumerate more than once
var msgs = messages.Where(x => x.Channel.Id == this.Id).Select(x => x.Id).ToArray();
if (messages == null || !msgs.Any())
throw new ArgumentException("You need to specify at least one message to delete.");
if (msgs.Length < 2)
{
await this.Discord.ApiClient.DeleteMessageAsync(this.Id, msgs.Single(), reason).ConfigureAwait(false);
return;
}
for (var i = 0; i < msgs.Length; i += 100)
await this.Discord.ApiClient.DeleteMessagesAsync(this.Id, msgs.Skip(i).Take(100), reason).ConfigureAwait(false);
}
///
/// Deletes a message
///
/// The message to be deleted.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task DeleteMessageAsync(DiscordMessage message, string reason = null)
=> this.Discord.ApiClient.DeleteMessageAsync(this.Id, message.Id, reason);
///
/// Returns a list of invite objects
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task> GetInvitesAsync() =>
this.Guild == null
? throw new ArgumentException("Cannot get the invites of a channel that does not belong to a guild.")
: this.Discord.ApiClient.GetChannelInvitesAsync(this.Id);
///
/// Create a new invite object
///
/// Duration of invite in seconds before expiry, or 0 for never. Defaults to 86400.
/// Max number of uses or 0 for unlimited. Defaults to 0
/// Whether this invite should be temporary. Defaults to false.
/// Whether this invite should be unique. Defaults to false.
/// The target type. Defaults to null.
/// The target activity. Defaults to null.
/// The target user id. Defaults to null.
/// The audit log reason.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task CreateInviteAsync(int maxAge = 86400, int maxUses = 0, bool temporary = false, bool unique = false, TargetType? targetType = null, TargetActivity? targetApplication = null, ulong? targetUser = null, string reason = null)
=> this.Discord.ApiClient.CreateChannelInviteAsync(this.Id, maxAge, maxUses, targetType, targetApplication, targetUser, temporary, unique, reason);
#region Stage
///
/// Opens a stage.
///
/// Topic of the stage.
/// Whether @everyone should be notified.
/// Privacy level of the stage (Defaults to .
/// Audit log reason.
/// Stage instance
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task OpenStageAsync(string topic, bool sendStartNotification = false, StagePrivacyLevel privacyLevel = StagePrivacyLevel.GuildOnly, string reason = null)
=> await this.Discord.ApiClient.CreateStageInstanceAsync(this.Id, topic, sendStartNotification, privacyLevel, reason);
///
/// Modifies a stage topic.
///
/// New topic of the stage.
/// New privacy level of the stage.
/// Audit log reason.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task ModifyStageAsync(Optional topic, Optional privacyLevel, string reason = null)
=> await this.Discord.ApiClient.ModifyStageInstanceAsync(this.Id, topic, privacyLevel, reason);
///
/// Closes a stage.
///
/// Audit log reason.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task CloseStageAsync(string reason = null)
=> await this.Discord.ApiClient.DeleteStageInstanceAsync(this.Id, reason);
///
/// Gets a stage.
///
/// The requested stage.
/// Thrown when the client does not have the or permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task GetStageAsync()
=> await this.Discord.ApiClient.GetStageInstanceAsync(this.Id);
#endregion
#region Scheduled Events
///
/// Creates a scheduled event based on the channel type.
///
/// The name.
/// The scheduled start time.
/// The description.
/// The cover image.
/// The reason.
/// A scheduled event.
/// Thrown when the resource does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task CreateScheduledEventAsync(string name, DateTimeOffset scheduledStartTime, string description = null, Optional coverImage = default, string reason = null)
{
if (!this.IsVoiceJoinable())
throw new NotSupportedException("Cannot create a scheduled event for this type of channel. Channel type must be either voice or stage.");
var type = this.Type == ChannelType.Voice ? ScheduledEventEntityType.Voice : ScheduledEventEntityType.StageInstance;
return await this.Guild.CreateScheduledEventAsync(name, scheduledStartTime, null, this, null, description, type, coverImage, reason);
}
#endregion
#region Threads
///
/// Creates a thread.
/// Depending on whether it is created inside an or an it is either an or an .
/// Depending on whether the is set to it is either an or an (default).
///
/// The name of the thread.
/// till it gets archived. Defaults to .
/// Can be either an , or an .
/// The per user ratelimit, aka slowdown.
/// Audit log reason.
/// The created thread.
/// Thrown when the client does not have the or or if creating a private thread the permission.
/// Thrown when the guild hasn't enabled threads atm.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
/// Thrown when the cannot be modified. This happens, when the guild hasn't reached a certain boost . Or if is not enabled for guild. This happens, if the guild does not have
public async Task CreateThreadAsync(string name, ThreadAutoArchiveDuration autoArchiveDuration = ThreadAutoArchiveDuration.OneHour, ChannelType type = ChannelType.PublicThread, int? rateLimitPerUser = null, string reason = null) =>
type != ChannelType.NewsThread && type != ChannelType.PublicThread && type != ChannelType.PrivateThread
? throw new NotSupportedException("Wrong thread type given.")
: !this.IsThreadHolder()
? throw new NotSupportedException("Parent channel can't have threads.")
: type == ChannelType.PrivateThread
? Utilities.CheckThreadPrivateFeature(this.Guild)
? Utilities.CheckThreadAutoArchiveDurationFeature(this.Guild, autoArchiveDuration)
? await this.Discord.ApiClient.CreateThreadAsync(this.Id, null, name, autoArchiveDuration, type, rateLimitPerUser, isForum: false, reason: reason)
: throw new NotSupportedException($"Cannot modify ThreadAutoArchiveDuration. Guild needs boost tier {(autoArchiveDuration == ThreadAutoArchiveDuration.ThreeDays ? "one" : "two")}.")
: throw new NotSupportedException($"Cannot create a private thread. Guild needs to be boost tier two.")
: Utilities.CheckThreadAutoArchiveDurationFeature(this.Guild, autoArchiveDuration)
? await this.Discord.ApiClient.CreateThreadAsync(this.Id, null, name, autoArchiveDuration, this.Type == ChannelType.News ? ChannelType.NewsThread : ChannelType.PublicThread, rateLimitPerUser, isForum: false, reason: reason)
: throw new NotSupportedException($"Cannot modify ThreadAutoArchiveDuration. Guild needs boost tier {(autoArchiveDuration == ThreadAutoArchiveDuration.ThreeDays ? "one" : "two")}.");
///
/// Creates a forum post.
///
/// The name of the post.
/// The message of the post.
/// The per user ratelimit, aka slowdown.
/// The tags to add on creation.
/// Audit log reason.
/// The created thread.
/// Thrown when the client does not have the permission.
/// Thrown when the guild hasn't enabled threads atm.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task CreatePostAsync(string name, DiscordMessageBuilder builder, int? rateLimitPerUser = null, IEnumerable? tags = null, string reason = null)
{
if (this.Type != ChannelType.Forum)
throw new NotSupportedException("Parent channel must be forum.");
else
return await this.Discord.ApiClient.CreateThreadAsync(this.Id, null, name, null, null, rateLimitPerUser, tags, builder, true, reason);
}
///
/// Gets joined archived private threads. Can contain more threads.
/// If the result's value 'HasMore' is true, you need to recall this function to get older threads.
///
/// Get threads created before this thread id.
/// Defines the limit of returned .
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task GetJoinedPrivateArchivedThreadsAsync(ulong? before, int? limit)
=> await this.Discord.ApiClient.GetJoinedPrivateArchivedThreadsAsync(this.Id, before, limit);
///
/// Gets archived public threads. Can contain more threads.
/// If the result's value 'HasMore' is true, you need to recall this function to get older threads.
///
/// Get threads created before this thread id.
/// Defines the limit of returned .
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task GetPublicArchivedThreadsAsync(ulong? before, int? limit)
=> await this.Discord.ApiClient.GetPublicArchivedThreadsAsync(this.Id, before, limit);
///
/// Gets archived private threads. Can contain more threads.
/// If the result's value 'HasMore' is true, you need to recall this function to get older threads.
///
/// Get threads created before this thread id.
/// Defines the limit of returned .
/// Thrown when the client does not have the or permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task GetPrivateArchivedThreadsAsync(ulong? before, int? limit)
=> await this.Discord.ApiClient.GetPrivateArchivedThreadsAsync(this.Id, before, limit);
///
/// Gets a forum channel tag.
///
/// The id of the tag to get.
public ForumPostTag GetForumPostTag(ulong id)
{
var tag = this.InternalAvailableTags.First(x => x.Id == id);
tag.Discord = this.Discord;
tag.ChannelId = this.Id;
return tag;
}
///
/// Creates a forum channel tag.
///
/// The name of the tag.
/// The emoji of the tag. Has to be either a of the current guild or a .
/// Whether only moderators should be able to apply this tag.
/// The audit log reason.
/// Thrown when the client does not have the permission.
/// Thrown when the tag does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task CreateForumPostTagAsync(string name, DiscordEmoji emoji, bool moderated = false, string reason = null)
=> await this.Discord.ApiClient.CreateForumTagAsync(this.Id, name, emoji, moderated, reason);
///
/// Deletes a forum channel tag.
///
/// The id of the tag to delete.
/// The audit log reason.
/// Thrown when the client does not have the permission.
/// Thrown when the tag does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task DeleteForumPostTag(ulong id, string reason = null)
=> this.Discord.ApiClient.DeleteForumTagAsync(id, this.Id, reason);
#endregion
///
/// Adds a channel permission overwrite for specified role.
///
/// The role to have the permission added.
/// The permissions to allow.
/// The permissions to deny.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task AddOverwriteAsync(DiscordRole role, Permissions allow = Permissions.None, Permissions deny = Permissions.None, string reason = null)
=> this.Discord.ApiClient.EditChannelPermissionsAsync(this.Id, role.Id, allow, deny, "role", reason);
///
/// Adds a channel permission overwrite for specified member.
///
/// The member to have the permission added.
/// The permissions to allow.
/// The permissions to deny.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task AddOverwriteAsync(DiscordMember member, Permissions allow = Permissions.None, Permissions deny = Permissions.None, string reason = null)
=> this.Discord.ApiClient.EditChannelPermissionsAsync(this.Id, member.Id, allow, deny, "member", reason);
///
/// Deletes a channel permission overwrite for specified member.
///
/// The member to have the permission deleted.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task DeleteOverwriteAsync(DiscordMember member, string reason = null)
=> this.Discord.ApiClient.DeleteChannelPermissionAsync(this.Id, member.Id, reason);
///
/// Deletes a channel permission overwrite for specified role.
///
/// The role to have the permission deleted.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task DeleteOverwriteAsync(DiscordRole role, string reason = null)
=> this.Discord.ApiClient.DeleteChannelPermissionAsync(this.Id, role.Id, reason);
///
/// Post a typing indicator.
///
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task TriggerTypingAsync() =>
!this.IsWritable()
? throw new ArgumentException("Cannot start typing in a non-text channel.")
: this.Discord.ApiClient.TriggerTypingAsync(this.Id);
///
/// Returns all pinned messages.
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public Task> GetPinnedMessagesAsync() =>
!this.IsWritable()
? throw new ArgumentException("A non-text channel does not have pinned messages.")
: this.Discord.ApiClient.GetPinnedMessagesAsync(this.Id);
///
/// Create a new webhook.
///
/// The name of the webhook.
/// The image for the default webhook avatar.
/// Reason for audit logs.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task CreateWebhookAsync(string name, Optional avatar = default, string reason = null)
=> await this.Discord.ApiClient.CreateWebhookAsync(this.IsThread() ? this.ParentId!.Value : this.Id, name,
ImageTool.Base64FromStream(avatar), reason).ConfigureAwait(false);
///
/// Returns a list of webhooks.
///
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exist.
/// Thrown when Discord is unable to process the request.
public Task> GetWebhooksAsync()
=> this.Discord.ApiClient.GetChannelWebhooksAsync(this.IsThread() ? this.ParentId!.Value : this.Id);
///
/// Moves a member to this voice channel.
///
/// The member to be moved.
/// Thrown when the client does not have the permission.
/// Thrown when the channel does not exists or if the Member does not exists.
/// Thrown when an invalid parameter was provided.
/// Thrown when Discord is unable to process the request.
public async Task PlaceMemberAsync(DiscordMember member)
{
if (!this.IsVoiceJoinable())
throw new ArgumentException("Cannot place a member in a non-voice channel.");
await this.Discord.ApiClient.ModifyGuildMemberAsync(this.Guild.Id, member.Id, default, default, default,
default, this.Id, null).ConfigureAwait(false);
}
///
/// Follows a news channel.
///
/// Channel to crosspost messages to.
/// Thrown when trying to follow a non-news channel.
/// Thrown when the current user doesn't have on the target channel.
public Task FollowAsync(DiscordChannel targetChannel) =>
this.Type != ChannelType.News
? throw new ArgumentException("Cannot follow a non-news channel.")
: this.Discord.ApiClient.FollowChannelAsync(this.Id, targetChannel.Id);
///
/// Publishes a message in a news channel to following channels.
///
/// Message to publish.
/// Thrown when the message has already been crossposted.
///
/// Thrown when the current user doesn't have and/or
///
public Task CrosspostMessageAsync(DiscordMessage message) =>
(message.Flags & MessageFlags.Crossposted) == MessageFlags.Crossposted
? throw new ArgumentException("Message is already crossposted.")
: this.Discord.ApiClient.CrosspostMessageAsync(this.Id, message.Id);
///
/// Updates the current user's suppress state in this channel, if stage channel.
///
/// Toggles the suppress state.
/// Sets the time the user requested to speak.
/// Thrown when the channel is not a stage channel.
public async Task UpdateCurrentUserVoiceStateAsync(bool? suppress, DateTimeOffset? requestToSpeakTimestamp = null)
{
if (this.Type != ChannelType.Stage)
throw new ArgumentException("Voice state can only be updated in a stage channel.");
await this.Discord.ApiClient.UpdateCurrentUserVoiceStateAsync(this.GuildId.Value, this.Id, suppress, requestToSpeakTimestamp).ConfigureAwait(false);
}
///
/// Calculates permissions for a given member.
///
/// Member to calculate permissions for.
/// Calculated permissions for a given member.
public Permissions PermissionsFor(DiscordMember mbr)
{
// user > role > everyone
// allow > deny > undefined
// =>
// user allow > user deny > role allow > role deny > everyone allow > everyone deny
if (this.IsPrivate || this.Guild == null)
return Permissions.None;
if (this.Guild.OwnerId == mbr.Id)
return PermissionMethods.FullPerms;
Permissions perms;
// assign @everyone permissions
var everyoneRole = this.Guild.EveryoneRole;
perms = everyoneRole.Permissions;
// roles that member is in
var mbRoles = mbr.Roles.Where(xr => xr.Id != everyoneRole.Id);
// assign permissions from member's roles (in order)
perms |= mbRoles.Aggregate(Permissions.None, (c, role) => c | role.Permissions);
// Administrator grants all permissions and cannot be overridden
if ((perms & Permissions.Administrator) == Permissions.Administrator)
return PermissionMethods.FullPerms;
// channel overrides for roles that member is in
var mbRoleOverrides = mbRoles
.Select(xr => this.PermissionOverwritesInternal.FirstOrDefault(xo => xo.Id == xr.Id))
.Where(xo => xo != null)
.ToList();
// assign channel permission overwrites for @everyone pseudo-role
var everyoneOverwrites = this.PermissionOverwritesInternal.FirstOrDefault(xo => xo.Id == everyoneRole.Id);
if (everyoneOverwrites != null)
{
perms &= ~everyoneOverwrites.Denied;
perms |= everyoneOverwrites.Allowed;
}
// assign channel permission overwrites for member's roles (explicit deny)
perms &= ~mbRoleOverrides.Aggregate(Permissions.None, (c, overs) => c | overs.Denied);
// assign channel permission overwrites for member's roles (explicit allow)
perms |= mbRoleOverrides.Aggregate(Permissions.None, (c, overs) => c | overs.Allowed);
// channel overrides for just this member
var mbOverrides = this.PermissionOverwritesInternal.FirstOrDefault(xo => xo.Id == mbr.Id);
if (mbOverrides == null) return perms;
// assign channel permission overwrites for just this member
perms &= ~mbOverrides.Denied;
perms |= mbOverrides.Allowed;
return perms;
}
///
/// Returns a string representation of this channel.
///
/// String representation of this channel.
public override string ToString() =>
this.Type == ChannelType.Category
? $"Channel Category {this.Name} ({this.Id})"
: this.Type == ChannelType.Text || this.Type == ChannelType.News || this.IsThread()
? $"Channel #{this.Name} ({this.Id})"
: this.IsVoiceJoinable()
? $"Channel #!{this.Name} ({this.Id})"
: !string.IsNullOrWhiteSpace(this.Name) ? $"Channel {this.Name} ({this.Id})" : $"Channel {this.Id}";
#endregion
///
/// Checks whether this is equal to another object.
///
/// Object to compare to.
/// Whether the object is equal to this .
public override bool Equals(object obj)
=> this.Equals(obj as DiscordChannel);
///
/// Checks whether this is equal to another .
///
/// to compare to.
/// Whether the is equal to this .
public bool Equals(DiscordChannel e)
=> e is not null && (ReferenceEquals(this, e) || this.Id == e.Id);
///
/// Gets the hash code for this .
///
/// The hash code for this .
public override int GetHashCode()
=> this.Id.GetHashCode();
///
/// Gets whether the two objects are equal.
///
/// First channel to compare.
/// Second channel to compare.
/// Whether the two channels are equal.
public static bool operator ==(DiscordChannel e1, DiscordChannel e2)
{
var o1 = e1 as object;
var o2 = e2 as object;
return (o1 != null || o2 == null) && (o1 == null || o2 != null) && ((o1 == null && o2 == null) || e1.Id == e2.Id);
}
///
/// Gets whether the two objects are not equal.
///
/// First channel to compare.
/// Second channel to compare.
/// Whether the two channels are not equal.
public static bool operator !=(DiscordChannel e1, DiscordChannel e2)
=> !(e1 == e2);
}
diff --git a/DisCatSharp/Entities/Channel/DiscordGuildDirectoryEntry.cs b/DisCatSharp/Entities/Channel/DiscordGuildDirectoryEntry.cs
index 37129df4b..ce04c1f56 100644
--- a/DisCatSharp/Entities/Channel/DiscordGuildDirectoryEntry.cs
+++ b/DisCatSharp/Entities/Channel/DiscordGuildDirectoryEntry.cs
@@ -1,102 +1,104 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
+using DisCatSharp.Enums;
+
using Newtonsoft.Json;
namespace DisCatSharp.Entities;
///
/// Represents a discord guild directory channel.
///
public class DiscordGuildDirectoryEntry : DiscordChannel, IEquatable
{
///
/// Gets the description of the directory entry.
///
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; internal set; }
///
/// Gets the primary category of the directory entry.
///
[JsonProperty("primary_category_id", NullValueHandling = NullValueHandling.Ignore)]
public DirectoryCategory PrimaryCategory { get; internal set; }
///
/// Initializes a new instance of the class.
///
internal DiscordGuildDirectoryEntry()
{ }
#region Methods
#endregion
///
/// Checks whether this is equal to another object.
///
/// Object to compare to.
/// Whether the object is equal to this .
public override bool Equals(object obj)
=> this.Equals(obj as DiscordGuildDirectoryEntry);
///
/// Checks whether this is equal to another .
///
/// to compare to.
/// Whether the is equal to this .
public bool Equals(DiscordGuildDirectoryEntry e)
=> e is not null && (ReferenceEquals(this, e) || this.Id == e.Id);
///
/// Gets the hash code for this .
///
/// The hash code for this .
public override int GetHashCode()
=> this.Id.GetHashCode();
///
/// Gets whether the two objects are equal.
///
/// First channel to compare.
/// Second channel to compare.
/// Whether the two channels are equal.
public static bool operator ==(DiscordGuildDirectoryEntry e1, DiscordGuildDirectoryEntry e2)
{
var o1 = e1 as object;
var o2 = e2 as object;
return (o1 != null || o2 == null) && (o1 == null || o2 != null) && ((o1 == null && o2 == null) || e1.Id == e2.Id);
}
///
/// Gets whether the two objects are not equal.
///
/// First channel to compare.
/// Second channel to compare.
/// Whether the two channels are not equal.
public static bool operator !=(DiscordGuildDirectoryEntry e1, DiscordGuildDirectoryEntry e2)
=> !(e1 == e2);
}
diff --git a/DisCatSharp/Entities/Guild/DiscordGuild.cs b/DisCatSharp/Entities/Guild/DiscordGuild.cs
index 4f7c0173e..c23de73f1 100644
--- a/DisCatSharp/Entities/Guild/DiscordGuild.cs
+++ b/DisCatSharp/Entities/Guild/DiscordGuild.cs
@@ -1,2027 +1,2028 @@
// This file is part of the DisCatSharp project, based off DSharpPlus.
//
// Copyright (c) 2021-2022 AITSYS
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DisCatSharp.Enums;
+using DisCatSharp.Exceptions;
using DisCatSharp.Net;
using DisCatSharp.Net.Abstractions;
using DisCatSharp.Net.Models;
using DisCatSharp.Net.Serialization;
using Newtonsoft.Json;
namespace DisCatSharp.Entities;
///
/// Represents a Discord guild.
///
public partial class DiscordGuild : SnowflakeObject, IEquatable
{
///
/// Gets the guild's name.
///
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; internal set; }
///
/// Gets the guild icon's hash.
///
[JsonProperty("icon", NullValueHandling = NullValueHandling.Ignore)]
public string IconHash { get; internal set; }
///
/// Gets the guild icon's url.
///
[JsonIgnore]
public string IconUrl
=> !string.IsNullOrWhiteSpace(this.IconHash) ? $"{DiscordDomain.GetDomain(CoreDomain.DiscordCdn).Url}{Endpoints.ICONS}/{this.Id.ToString(CultureInfo.InvariantCulture)}/{this.IconHash}.{(this.IconHash.StartsWith("a_") ? "gif" : "png")}?size=1024" : null;
///
/// Gets the guild splash's hash.
///
[JsonProperty("splash", NullValueHandling = NullValueHandling.Ignore)]
public string SplashHash { get; internal set; }
///
/// Gets the guild splash's url.
///
[JsonIgnore]
public string SplashUrl
=> !string.IsNullOrWhiteSpace(this.SplashHash) ? $"{DiscordDomain.GetDomain(CoreDomain.DiscordCdn).Url}{Endpoints.SPLASHES}/{this.Id.ToString(CultureInfo.InvariantCulture)}/{this.SplashHash}.png?size=1024" : null;
///
/// Gets the guild discovery splash's hash.
///
[JsonProperty("discovery_splash", NullValueHandling = NullValueHandling.Ignore)]
public string DiscoverySplashHash { get; internal set; }
///
/// Gets the guild discovery splash's url.
///
[JsonIgnore]
public string DiscoverySplashUrl
=> !string.IsNullOrWhiteSpace(this.DiscoverySplashHash) ? $"{DiscordDomain.GetDomain(CoreDomain.DiscordCdn).Url}{Endpoints.GUILD_DISCOVERY_SPLASHES}/{this.Id.ToString(CultureInfo.InvariantCulture)}/{this.DiscoverySplashHash}.png?size=1024" : null;
///
/// Gets the preferred locale of this guild.
/// This is used for server discovery, interactions and notices from Discord. Defaults to en-US.
///
[JsonProperty("preferred_locale", NullValueHandling = NullValueHandling.Ignore)]
public string PreferredLocale { get; internal set; }
///
/// Gets the ID of the guild's owner.
///
[JsonProperty("owner_id", NullValueHandling = NullValueHandling.Ignore)]
public ulong OwnerId { get; internal set; }
///
/// Gets the guild's owner.
///
[JsonIgnore]
public DiscordMember Owner
=> this.Members.TryGetValue(this.OwnerId, out var owner)
? owner
: this.Discord.ApiClient.GetGuildMemberAsync(this.Id, this.OwnerId).ConfigureAwait(false).GetAwaiter().GetResult();
///
/// Gets permissions for the user in the guild (does not include channel overrides)
///
[JsonProperty("permissions", NullValueHandling = NullValueHandling.Ignore)]
public Permissions? Permissions { get; set; }
///
/// Gets the guild's voice region ID.
///
[JsonProperty("region", NullValueHandling = NullValueHandling.Ignore)]
internal string VoiceRegionId { get; set; }
///
/// Gets the guild's voice region.
///
[JsonIgnore]
public DiscordVoiceRegion VoiceRegion
=> this.Discord.VoiceRegions[this.VoiceRegionId];
///
/// Gets the guild's AFK voice channel ID.
///
[JsonProperty("afk_channel_id", NullValueHandling = NullValueHandling.Ignore)]
internal ulong AfkChannelId { get; set; }
///
/// Gets the guild's AFK voice channel.
///
[JsonIgnore]
public DiscordChannel AfkChannel
=> this.GetChannel(this.AfkChannelId);
///
/// List of .
/// Null if DisCatSharp.ApplicationCommands is not used or no guild commands are registered.
///
[JsonIgnore]
public ReadOnlyCollection RegisteredApplicationCommands
=> new(this.InternalRegisteredApplicationCommands);
[JsonIgnore]
internal List InternalRegisteredApplicationCommands { get; set; } = null;
///
/// Gets the guild's AFK timeout.
///
[JsonProperty("afk_timeout", NullValueHandling = NullValueHandling.Ignore)]
public int AfkTimeout { get; internal set; }
///
/// Gets the guild's verification level.
///
[JsonProperty("verification_level", NullValueHandling = NullValueHandling.Ignore)]
public VerificationLevel VerificationLevel { get; internal set; }
///
/// Gets the guild's default notification settings.
///
[JsonProperty("default_message_notifications", NullValueHandling = NullValueHandling.Ignore)]
public DefaultMessageNotifications DefaultMessageNotifications { get; internal set; }
///
/// Gets the guild's explicit content filter settings.
///
[JsonProperty("explicit_content_filter")]
public ExplicitContentFilter ExplicitContentFilter { get; internal set; }
///
/// Gets the guild's nsfw level.
///
[JsonProperty("nsfw_level")]
public NsfwLevel NsfwLevel { get; internal set; }
///
/// Gets the system channel id.
///
[JsonProperty("system_channel_id", NullValueHandling = NullValueHandling.Include)]
internal ulong? SystemChannelId { get; set; }
///
/// Gets the channel where system messages (such as boost and welcome messages) are sent.
///
[JsonIgnore]
public DiscordChannel SystemChannel => this.SystemChannelId.HasValue
? this.GetChannel(this.SystemChannelId.Value)
: null;
///
/// Gets the settings for this guild's system channel.
///
[JsonProperty("system_channel_flags")]
public SystemChannelFlags SystemChannelFlags { get; internal set; }
///
/// Gets whether this guild's widget is enabled.
///
[JsonProperty("widget_enabled", NullValueHandling = NullValueHandling.Ignore)]
public bool? WidgetEnabled { get; internal set; }
///
/// Gets the widget channel id.
///
[JsonProperty("widget_channel_id", NullValueHandling = NullValueHandling.Ignore)]
internal ulong? WidgetChannelId { get; set; }
///
/// Gets the widget channel for this guild.
///
[JsonIgnore]
public DiscordChannel WidgetChannel => this.WidgetChannelId.HasValue
? this.GetChannel(this.WidgetChannelId.Value)
: null;
///
/// Gets the rules channel id.
///
[JsonProperty("rules_channel_id")]
internal ulong? RulesChannelId { get; set; }
///
/// Gets the rules channel for this guild.
/// This is only available if the guild is considered "discoverable".
///
[JsonIgnore]
public DiscordChannel RulesChannel => this.RulesChannelId.HasValue
? this.GetChannel(this.RulesChannelId.Value)
: null;
///
/// Gets the public updates channel id.
///
[JsonProperty("public_updates_channel_id")]
internal ulong? PublicUpdatesChannelId { get; set; }
///
/// Gets the public updates channel (where admins and moderators receive messages from Discord) for this guild.
/// This is only available if the guild is considered "discoverable".
///
[JsonIgnore]
public DiscordChannel PublicUpdatesChannel => this.PublicUpdatesChannelId.HasValue
? this.GetChannel(this.PublicUpdatesChannelId.Value)
: null;
///
/// Gets the application id of this guild if it is bot created.
///
[JsonProperty("application_id")]
public ulong? ApplicationId { get; internal set; }
///
/// Gets a collection of this guild's roles.
///
[JsonIgnore]
public IReadOnlyDictionary Roles => new ReadOnlyConcurrentDictionary(this.RolesInternal);
[JsonProperty("roles", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary RolesInternal;
///
/// Gets a collection of this guild's stickers.
///
[JsonIgnore]
public IReadOnlyDictionary Stickers => new ReadOnlyConcurrentDictionary(this.StickersInternal);
[JsonProperty("stickers", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary StickersInternal;
///