Иконка ресурса

FREE DiscordCore : 3.0.2 3.0.2

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Ext.Discord.Attributes;
using Oxide.Ext.Discord.Builders;
using Oxide.Ext.Discord.Cache;
using Oxide.Ext.Discord.Clients;
using Oxide.Ext.Discord.Connections;
using Oxide.Ext.Discord.Constants;
using Oxide.Ext.Discord.Entities;
using Oxide.Ext.Discord.Extensions;
using Oxide.Ext.Discord.Helpers;
using Oxide.Ext.Discord.Interfaces;
using Oxide.Ext.Discord.Libraries;
using Oxide.Ext.Discord.Logging;
using Oxide.Ext.Discord.Types;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
//DiscordCore created with PluginMerge v(1.0.9.0) by MJSU @ https://github.com/dassjosh/Plugin.Merge
namespace Oxide.Plugins {
    [Info("Discord Core", "MJSU", "3.0.2")]
    [Description("Creates a link between a player and discord")]
    public partial class DiscordCore : CovalencePlugin, IDiscordPlugin, IDiscordLink {
#region Plugins\DiscordCore.Fields.cs
        public DiscordClient Client {
            get;
            set;
        }
        private PluginData _pluginData;
        private PluginConfig _pluginConfig;
        private DiscordUser _bot;
        public DiscordGuild Guild;
        private readonly BotConnection _discordSettings = new() {
            Intents = GatewayIntents.Guilds | GatewayIntents.GuildMembers
        }
        ;
        private readonly DiscordLink _link = GetLibrary<DiscordLink>();
        private readonly DiscordMessageTemplates _templates = GetLibrary<DiscordMessageTemplates>();
        private readonly DiscordPlaceholders _placeholders = GetLibrary<DiscordPlaceholders>();
        private readonly DiscordLocales _lang = GetLibrary<DiscordLocales>();
        private readonly DiscordCommandLocalizations _local = GetLibrary<DiscordCommandLocalizations>();
        private readonly StringBuilder _sb = new();
        private JoinHandler _joinHandler;
        private JoinBanHandler _banHandler;
        private LinkHandler _linkHandler;
        private const string UsePermission = "discordcore.use";
        private static readonly DiscordColor AccentColor = new("de8732");
        private static readonly DiscordColor Success = new("43b581");
        private static readonly DiscordColor Danger = new("f04747");
        private const string PlayerArg = "player";
        private const string UserArg = "user";
        private const string CodeArg = "code";
        private DiscordApplicationCommand _appCommand;
        private string _allowedChannels;
        public static DiscordCore Instance;
#endregion
#region Plugins\DiscordCore.Setup.cs
        // ReSharper disable once UnusedMember.Local
        private void Init() {
            Instance = this;
            _pluginData = Interface.Oxide.DataFileSystem.ReadObject<PluginData>(Name);
            permission.RegisterPermission(UsePermission, this);
            _banHandler = new JoinBanHandler(_pluginConfig.LinkBanSettings);
            _linkHandler = new LinkHandler(_pluginData, _pluginConfig);
            _joinHandler = new JoinHandler(_pluginConfig.LinkSettings, _linkHandler, _banHandler);
            _discordSettings.ApiToken = _pluginConfig.ApiKey;
            _discordSettings.LogLevel = _pluginConfig.ExtensionDebugging;
        }
        protected override void LoadDefaultConfig() {
            PrintWarning("Loading Default Config");
        }
        protected override void LoadConfig() {
            base.LoadConfig();
            Config.Settings.DefaultValueHandling = DefaultValueHandling.Populate;
            _pluginConfig = AdditionalConfig(Config.ReadObject<PluginConfig>());
            Config.WriteObject(_pluginConfig);
        }
        public PluginConfig AdditionalConfig(PluginConfig config) {
            config.LinkSettings = new LinkSettings(config.LinkSettings);
            config.WelcomeMessageSettings = new WelcomeMessageSettings(config.WelcomeMessageSettings);
            config.LinkMessageSettings = new GuildMessageSettings(config.LinkMessageSettings);
            config.PermissionSettings = new LinkPermissionSettings(config.PermissionSettings);
            config.LinkBanSettings = new LinkBanSettings(config.LinkBanSettings);
            return config;
        }
        // ReSharper disable once UnusedMember.Local
        private void OnServerInitialized() {
            RegisterChatLangCommand(nameof(DiscordCoreChatCommand), ServerLang.Commands.DcCommand);
            if (string.IsNullOrEmpty(_pluginConfig.ApiKey)) {
                PrintWarning("Please set the Discord Bot Token in the config and reload the plugin");
                return;
            }
            foreach (DiscordInfo info in _pluginData.PlayerDiscordInfo.Values) {
                if (info.LastOnline == DateTime.MinValue) {
                    info.LastOnline = DateTime.UtcNow;
                }
            }
            _link.AddLinkPlugin(this);
            RegisterPlaceholders();
            ValidateGroups();
            Client.Connect(_discordSettings);
        }
        public void ValidateGroups() {
            foreach (string group in _pluginConfig.PermissionSettings.LinkGroups) {
                if (!permission.GroupExists(group)) {
                    PrintWarning($"`{group}` is set as the link group but group does not exist");
                }
            }
            foreach (string group in _pluginConfig.PermissionSettings.UnlinkGroups) {
                if (!permission.GroupExists(group)) {
                    PrintWarning($"`{group}` is set as the unlink group but group does not exist");
                }
            }
            foreach (string perm in _pluginConfig.PermissionSettings.LinkPermissions) {
                if (!permission.PermissionExists(perm)) {
                    PrintWarning($"`{perm}` is set as the link permission but group does not exist");
                }
            }
            foreach (string perm in _pluginConfig.PermissionSettings.UnlinkPermissions) {
                if (!permission.PermissionExists(perm)) {
                    PrintWarning($"`{perm}` is set as the unlink permission but group does not exist");
                }
            }
        }
        // ReSharper disable once UnusedMember.Local
        private void Unload() {
            SaveData();
            Instance = null;
        }
#endregion
#region Plugins\DiscordCore.Lang.cs
        public void Chat(IPlayer player, string key, PlaceholderData data = null) {
            if (player.IsConnected) {
                player.Reply(string.Format(Lang(ServerLang.Format, player), Lang(key, player, data)));
            }
        }
        public void BroadcastMessage(string key, PlaceholderData data) {
            string message = Lang(key);
            message = _placeholders.ProcessPlaceholders(message, data);
            if (string.IsNullOrEmpty(message)) {
                return;
            }
            message = string.Format(Lang(ServerLang.Format), message);
            server.Broadcast(message);
        }
        public string Lang(string key, IPlayer player = null, PlaceholderData data = null) {
            string message = lang.GetMessage(key, this, player?.Id);
            if (data != null) {
                message = _placeholders.ProcessPlaceholders(message, data);
            }
            return message;
        }
        public void RegisterChatLangCommand(string command, string langKey) {
            HashSet<string> registeredCommands = new();
            foreach (string langType in lang.GetLanguages(this)) {
                Dictionary<string, string> langKeys = lang.GetMessages(langType, this);
                string commandValue;
                if (langKeys.TryGetValue(langKey, out commandValue) && !string.IsNullOrEmpty(commandValue) && registeredCommands.Add(commandValue)) {
                    AddCovalenceCommand(commandValue, command);
                }
            }
        }
        protected override void LoadDefaultMessages() {
            lang.RegisterMessages(new Dictionary<string, string> {
                [ServerLang.Format]
                = $"[#CCCCCC][[{AccentColor.ToHex()}]{Title}[/#]] {{0}}[/#]", [ServerLang.NoPermission] = "You do not have permission to use this command", [ServerLang.Commands.DcCommand] = "dc", [ServerLang.Commands.CodeCommand] = "code", [ServerLang.Commands.UserCommand] = "user", [ServerLang.Commands.LeaveCommand] = "leave", [ServerLang.Commands.AcceptCommand] = "accept", [ServerLang.Commands.DeclineCommand] = "decline", [ServerLang.Commands.LinkCommand] = "link", [ServerLang.Commands.Code.LinkInfo] = $"To complete your activation please open Discord use the following command: [{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Discord.DiscordCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Discord.LinkCommand)} {PlaceholderKeys.LinkCode}[/#].\n", [ServerLang.Commands.Code.LinkServer] = $"In order to use this command you must be in the {DefaultKeys.Guild.Name.Color(AccentColor)} discord server." + $"You can join @ {$" {
                    PlaceholderKeys.InviteUrl
                }
                ".Color(AccentColor)}.\n", [ServerLang.Commands.Code.LinkInGuild] = $"This command can be used in the following guild channels {PlaceholderKeys.CommandChannels}.\n", [ServerLang.Commands.Code.LinkInDm] = $"This command can be used in the following in a direct message to {DefaultKeys.User.Username.Color(AccentColor)} bot", [ServerLang.Commands.User.MatchFound] = $"We found a match by username." + $"We have a sent a discord message to {DefaultKeys.User.Fullname.Color(AccentColor)} to complete the link.\n" + $"If you haven't received a message make sure you allow DM's from {DefaultKeys.Bot.Fullname.Color(AccentColor)}.", [ServerLang.Commands.User.Errors.InvalidSyntax] = "Invalid User Join Syntax.\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.UserCommand)} username[/#] to start the link process by your discord username\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.UserCommand)} userid[/#] to start the link process by your discord user ID", [ServerLang.Commands.User.Errors.UserIdNotFound] = $"Failed to find a discord user in the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord server with user ID {DefaultKeys.Snowflake.Id.Color(Danger)}", [ServerLang.Commands.User.Errors.UserNotFound] = $"Failed to find a any discord users in the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord server with the username {PlaceholderKeys.NotFound.Color(Danger)}", [ServerLang.Commands.User.Errors.MultipleUsersFound] = $"Multiple discord users found in the the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord server matching {PlaceholderKeys.NotFound.Color(Danger)}." + "Please include more of the username and/or the discriminator in your search.", [ServerLang.Commands.User.Errors.SearchError] = "An error occured while trying to search by username." + "Please try a different username or try again later." + "If the issue persists please notify an admin.", [ServerLang.Commands.Leave.Errors.NotLinked] = "We were unable to unlink your account as you do not appear to have been linked.", [ServerLang.Announcements.Link.Command] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has successfully linked their game account with their discord user {DefaultKeys.User.Fullname.Color(AccentColor)}.If you would would like to be linked type /{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} to learn more.", [ServerLang.Announcements.Link.Admin] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has successfully been linked by an admin to discord user {DefaultKeys.User.Fullname.Color(AccentColor)}.", [ServerLang.Announcements.Link.Api] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has successfully linked their game account with their discord user {DefaultKeys.User.Fullname.Color(AccentColor)}.If you would would like to be linked type /{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} to learn more.", [ServerLang.Announcements.Link.GuildRejoin] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has been relinked with discord user {DefaultKeys.User.Fullname.Color(AccentColor)} for rejoining the {DefaultKeys.Guild.Name.Color(AccentColor)} discord server", [ServerLang.Announcements.Link.InactiveRejoin] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has been relinked with discord user {DefaultKeys.User.Fullname.Color(AccentColor)} for rejoining the {DefaultKeys.Server.Name.Color(AccentColor)} game server", [ServerLang.Announcements.Unlink.Command] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has successfully unlinked their game account from their discord user {DefaultKeys.User.Fullname.Color(AccentColor)}.", [ServerLang.Announcements.Unlink.Admin] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has successfully been unlinked by an admin from discord user {DefaultKeys.User.Fullname.Color(AccentColor)}.", [ServerLang.Announcements.Unlink.Api] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has successfully unlinked their game account from their discord user {DefaultKeys.User.Fullname.Color(AccentColor)}.", [ServerLang.Announcements.Unlink.LeftGuild] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has been unlinked from discord user {DefaultKeys.User.Fullname.Color(AccentColor)} they left the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord server", [ServerLang.Announcements.Unlink.Inactive] = $"{DefaultKeys.Player.Name.Color(AccentColor)} has been unlinked from discord user {DefaultKeys.User.Fullname.Color(AccentColor)} because they haven't been active on {DefaultKeys.Server.Name.Color(AccentColor)} game server for {DefaultKeys.Timespan.TotalDays.Color(AccentColor)} days", [ServerLang.Link.Completed.Command] = $"You have successfully linked your player {DefaultKeys.Player.Name.Color(AccentColor)} with discord user {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Link.Completed.Admin] = $"You have been successfully linked by an admin with player {DefaultKeys.Player.Name.Color(AccentColor)} and discord user {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Link.Completed.Api] = $"You have successfully linked your player {DefaultKeys.Player.Name.Color(AccentColor)} with discord user {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Link.Completed.GuildRejoin] = $"Your player {DefaultKeys.Player.Name.Color(AccentColor)} has been relinked with discord user {DefaultKeys.User.Fullname.Color(AccentColor)} because rejoined the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord server", [ServerLang.Link.Completed.InactiveRejoin] = $"Your player {DefaultKeys.Player.Name.Color(AccentColor)} has been relinked with discord user {DefaultKeys.User.Fullname.Color(AccentColor)} because rejoined {DefaultKeys.Server.Name.Color(AccentColor)} server", [ServerLang.Unlink.Completed.Command] = $"You have successfully unlinked your player {DefaultKeys.Player.Name.Color(AccentColor)} from discord user {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Unlink.Completed.Admin] = $"You have been successfully unlinked by an admin from discord user {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Unlink.Completed.Api] = $"You have successfully unlinked your player {DefaultKeys.Player.Name.Color(AccentColor)} from discord user {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Unlink.Completed.LeftGuild] = $"Your player {DefaultKeys.Player.Name.Color(AccentColor)} has been unlinked from discord user {DefaultKeys.User.Fullname.Color(AccentColor)} because you left the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord server", [ServerLang.Link.Declined.JoinWithPlayer] = $"We have declined the discord link between {DefaultKeys.Player.Name.Color(AccentColor)} and {DefaultKeys.User.Fullname.Color(AccentColor)}", [ServerLang.Link.Declined.JoinWithUser] = $"{DefaultKeys.User.Fullname.Color(AccentColor)} has declined your link to {DefaultKeys.Player.Name.Color(AccentColor)}", [ServerLang.Link.Errors.InvalidSyntax] = "Invalid Link Syntax.Please type the command you were given in Discord." + "Command should be in the following format:" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.LinkCommand)} {{code}}[/#] where {{code}} is the code sent to you in Discord.", [ServerLang.Banned.IsUserBanned] = "You have been banned from joining by Discord user due to multiple declined join attempts." + $"Your ban will end in {DefaultKeys.Timespan.Days} days {DefaultKeys.Timespan.Hours} hours {DefaultKeys.Timespan.Minutes} minutes {DefaultKeys.Timespan.Seconds} Seconds.", [ServerLang.Join.ByPlayer] = $"{DefaultKeys.User.Fullname.Color(AccentColor)} is trying to link their Discord account with your game account." + $"If you wish to [{Success.ToHex()}]accept[/#] this link please type [{Success.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.AcceptCommand)}[/#]." + $"If you wish to [{Danger.ToHex()}]decline[/#] this link please type [{Danger.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DeclineCommand)}[/#]", [ServerLang.Discord.DiscordCommand] = "dc", [ServerLang.Discord.LinkCommand] = "link", [ServerLang.Join.Errors.PlayerJoinActivationNotFound] = "There are no pending joins in progress for this game account.Please start the link in Discord and try again.", [ServerLang.Errors.PlayerAlreadyLinked] = $"This player is already linked to Discord user {DefaultKeys.User.Fullname.Color(AccentColor)}." + $"If you wish to link yourself to another account please type [{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.LeaveCommand)}[/#]", [ServerLang.Errors.DiscordAlreadyLinked] = $"This Discord user is already linked to player {DefaultKeys.Player.Name.Color(AccentColor)}." + $"If you wish to link yourself to another account please type [{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.LeaveCommand)}[/#]", [ServerLang.Errors.ActivationNotFound] = $"We failed to find any pending joins with code [{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)}[/#]." + "Please verify the code is correct and try again.", [ServerLang.Errors.MustBeCompletedInDiscord] = "You need to complete the steps provided in Discord since you started the link from the game server.", [ServerLang.Errors.ConsolePlayerNotSupported] = "This command cannot be ran in the server console.", [ServerLang.Commands.HelpMessage] = "Allows players to link their player and discord accounts together." + $"Players must first join the {DefaultKeys.Guild.Name.Color(AccentColor)} Discord @ [{AccentColor.ToHex()}]{PlaceholderKeys.InviteUrl}[/#]\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.CodeCommand)}[/#] to start the link process using a code\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.UserCommand)} username[/#] to start the link process by your discord username\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.UserCommand)} userid[/#] to start the link process by your discord user ID\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)} {DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.LeaveCommand)}[/#] to to unlink yourself from discord\n" + $"[{AccentColor.ToHex()}]/{DefaultKeys.Plugin.Lang.WithFormat(ServerLang.Commands.DcCommand)}[/#] to see this message again",
            }
            , this);
        }
#endregion
#region Plugins\DiscordCore.ChatCommands.cs
        // ReSharper disable once UnusedParameter.Local
        private void DiscordCoreChatCommand(IPlayer player, string cmd, string[] args) {
            if (!player.HasPermission(UsePermission)) {
                Chat(player, ServerLang.NoPermission);
                return;
            }
            if (player.Id == "server_console") {
                Chat(player, ServerLang.Errors.ConsolePlayerNotSupported, GetDefault(player));
                return;
            }
            if (args.Length == 0) {
                DisplayHelp(player);
                return;
            }
            string subCommand = args[0];
            if (subCommand.Equals(Lang(ServerLang.Commands.CodeCommand, player), StringComparison.OrdinalIgnoreCase)) {
                HandleServerCodeJoin(player);
                return;
            }
            if (subCommand.Equals(Lang(ServerLang.Commands.UserCommand, player), StringComparison.OrdinalIgnoreCase)) {
                HandleServerUserJoin(player, args);
                return;
            }
            if (subCommand.Equals(Lang(ServerLang.Commands.LeaveCommand, player), StringComparison.OrdinalIgnoreCase)) {
                HandleServerLeave(player);
                return;
            }
            if (subCommand.Equals(Lang(ServerLang.Commands.AcceptCommand, player), StringComparison.OrdinalIgnoreCase)) {
                HandleUserJoinAccept(player);
                return;
            }
            if (subCommand.Equals(Lang(ServerLang.Commands.DeclineCommand, player), StringComparison.OrdinalIgnoreCase)) {
                HandleUserJoinDecline(player);
                return;
            }
            if (subCommand.Equals(Lang(ServerLang.Commands.LinkCommand, player), StringComparison.OrdinalIgnoreCase)) {
                HandleServerCompleteLink(player, args);
                return;
            }
            DisplayHelp(player);
        }
        public void DisplayHelp(IPlayer player) {
            Chat(player, ServerLang.Commands.HelpMessage, GetDefault(player));
        }
        public void HandleServerCodeJoin(IPlayer player) {
            if (player.IsLinked()) {
                Chat(player, ServerLang.Errors.PlayerAlreadyLinked, GetDefault(player, player.GetDiscordUser()));
                return;
            }
            //Puts("A");
            JoinData join = _joinHandler.CreateActivation(player);
            //Puts("B");
            using (PlaceholderData data = GetDefault(player).AddUser(_bot).Add(PlaceholderDataKeys.Code, join.Code)) {
                data.ManualPool();
                _sb.Clear();
                _sb.Append(LangPlaceholder(ServerLang.Commands.Code.LinkInfo, data));
                _sb.Append(LangPlaceholder(ServerLang.Commands.Code.LinkServer, data));
                if (!string.IsNullOrEmpty(_allowedChannels)) {
                    _sb.Append(LangPlaceholder(ServerLang.Commands.Code.LinkInGuild, data));
                }
                if (_appCommand?.DmPermission is true) {
                    _sb.Append(LangPlaceholder(ServerLang.Commands.Code.LinkInDm, data));
                }
            }
            Chat(player, _sb.ToString());
        }
        public void HandleServerUserJoin(IPlayer player, string[] args) {
            if (player.IsLinked()) {
                Chat(player, ServerLang.Errors.PlayerAlreadyLinked, GetDefault(player, player.GetDiscordUser()));
                return;
            }
            if (_banHandler.IsBanned(player)) {
                Chat(player, ServerLang.Banned.IsUserBanned, GetDefault(player).AddTimeSpan(_banHandler.GetRemainingDuration(player)));
                return;
            }
            if (args.Length < 2) {
                Chat(player, ServerLang.Commands.User.Errors.InvalidSyntax, GetDefault(player));
                return;
            }
            string search = args[1];
            Snowflake id;
            if (Snowflake.TryParse(search, out id)) {
                GuildMember member = Guild.Members[id];
                if (member == null) {
                    Chat(player, ServerLang.Commands.User.Errors.UserIdNotFound, GetDefault(player).AddSnowflake(id));
                    return;
                }
                UserSearchMatchFound(player, member.User);
                return;
            }
            int discriminatorIndex = search.LastIndexOf('#');
            string userName;
            string discriminator;
            if (discriminatorIndex == -1) {
                userName = search;
                discriminator = null;
            }
            else {
                userName = search.Substring(0, discriminatorIndex);
                discriminator = search.Substring(discriminatorIndex, search.Length - discriminatorIndex);
            }
            GuildSearchMembers guildSearch = new() {
                Query = userName, Limit = 1000
            }
            ;
            Guild.SearchMembers(Client, guildSearch).Then(members => {
                HandleChatJoinUserResults(player, members, userName, discriminator);
            }
            ).Catch(error => {
                Chat(player, ServerLang.Commands.User.Errors.SearchError, GetDefault(player));
            }
            );
        }
        public void HandleChatJoinUserResults(IPlayer player, List<GuildMember> members, string userName, string discriminator) {
            if (members.Count == 0) {
                string name = !string.IsNullOrEmpty(discriminator) ? $"{userName}#{discriminator}" : userName;
                Chat(player, ServerLang.Commands.User.Errors.UserNotFound, GetDefault(player).Add(PlaceholderDataKeys.NotFound, name));
                return;
            }
            if (members.Count == 1) {
                UserSearchMatchFound(player, members[0].User);
                return;
            }
            DiscordUser user = null;
            int count = 0;
            for (int index = 0; index < members.Count; index++) {
                GuildMember member = members[index];
                DiscordUser searchUser = member.User;
                if (discriminator == null) {
                    if (searchUser.Username.StartsWith(userName, StringComparison.OrdinalIgnoreCase)) {
                        user = searchUser;
                        count++;
                        if (count > 1) {
                            break;
                        }
                    }
                }
#pragma warning disable CS0618
                else if (searchUser.Username.Equals(userName, StringComparison.OrdinalIgnoreCase) && (searchUser.HasUpdatedUsername || searchUser.Discriminator.Equals(discriminator)))
#pragma warning restore CS0618
                {
                    user = searchUser;
                    break;
                }
            }
            if (user == null || count > 1) {
                string name = !string.IsNullOrEmpty(discriminator) ? $"{userName}#{discriminator}" : userName;
                Chat(player, ServerLang.Commands.User.Errors.MultipleUsersFound, GetDefault(player).Add(PlaceholderDataKeys.NotFound, name));
                return;
            }
            UserSearchMatchFound(player, user);
        }
        public void UserSearchMatchFound(IPlayer player, DiscordUser user) {
            _joinHandler.CreateActivation(player, user, JoinSource.Server);
            using (PlaceholderData data = GetDefault(player, user)) {
                data.ManualPool();
                Chat(player, ServerLang.Commands.User.MatchFound, data);
                SendTemplateMessage(TemplateKeys.Join.CompleteLink, user, player, data);
            }
        }
        public void HandleServerLeave(IPlayer player) {
            DiscordUser user = player.GetDiscordUser();
            if (user == null) {
                Chat(player, ServerLang.Commands.Leave.Errors.NotLinked, GetDefault(player));
                return;
            }
            _linkHandler.HandleUnlink(player, user, UnlinkedReason.Command, null);
        }
        public void HandleUserJoinAccept(IPlayer player) {
            JoinData join = _joinHandler.FindCompletedByPlayer(player);
            if (join == null) {
                Chat(player, ServerLang.Join.Errors.PlayerJoinActivationNotFound, GetDefault(player));
                return;
            }
            if (join.From == JoinSource.Server) {
                Chat(player, ServerLang.Errors.MustBeCompletedInDiscord, GetDefault(player));
                return;
            }
            _joinHandler.CompleteLink(join, null);
        }
        public void HandleUserJoinDecline(IPlayer player) {
            JoinData join = _joinHandler.FindCompletedByPlayer(player);
            if (join == null) {
                Chat(player, ServerLang.Join.Errors.PlayerJoinActivationNotFound, GetDefault(player));
                return;
            }
            _joinHandler.DeclineLink(join, null);
        }
        public void HandleServerCompleteLink(IPlayer player, string[] args) {
            if (player.IsLinked()) {
                Chat(player, ServerLang.Errors.PlayerAlreadyLinked, GetDefault(player, player.GetDiscordUser()));
                return;
            }
            if (args.Length < 2) {
                Chat(player, ServerLang.Link.Errors.InvalidSyntax, GetDefault(player));
                return;
            }
            string code = args[1];
            JoinData join = _joinHandler.FindByCode(code);
            if (join == null) {
                Chat(player, ServerLang.Errors.MustBeCompletedInDiscord, GetDefault(player));
                return;
            }
            if (join.From == JoinSource.Server) {
                Chat(player, ServerLang.Errors.MustBeCompletedInDiscord, GetDefault(player));
                return;
            }
            if (join.Discord.IsLinked()) {
                Chat(player, ServerLang.Errors.DiscordAlreadyLinked, GetDefault(player, join.Discord));
                return;
            }
            join.Player = player;
            _joinHandler.CompleteLink(join, null);
        }
#endregion
#region Plugins\DiscordCore.Hooks.cs
        // ReSharper disable once UnusedMember.Local
        private void OnUserConnected(IPlayer player) {
            _linkHandler.OnUserConnected(player);
        }
#endregion
#region Plugins\DiscordCore.DiscordHooks.cs
        // ReSharper disable once UnusedMember.Local
        [HookMethod(DiscordExtHooks.OnDiscordGatewayReady)]
        private void OnDiscordGatewayReady(GatewayReadyEvent ready) {
            _bot = ready.User;
            DiscordGuild guild = null;
            if (ready.Guilds.Count == 1 && !_pluginConfig.GuildId.IsValid()) {
                guild = ready.Guilds.Values.FirstOrDefault();
            }
            if (guild == null) {
                guild = ready.Guilds[_pluginConfig.GuildId];
                if (guild == null) {
                    PrintError("Failed to find a matching guild for the Discord Server Id." + "Please make sure your guild Id is correct and the bot is in the discord server.");
                    return;
                }
            }
            Guild = guild;
            DiscordApplication app = Client.Bot.Application;
            if (!app.HasApplicationFlag(ApplicationFlags.GatewayGuildMembersLimited) && !app.HasApplicationFlag(ApplicationFlags.GatewayGuildMembers)) {
                PrintError($"You need to enable \"Server Members Intent\" for {Client.Bot.BotUser.Username} @ https://discord.com/developers/applications\n" + $"{Name} will not function correctly until that is fixed.Once updated please reload {Name}.");
                return;
            }
            Puts($"Connected to bot: {_bot.Username}");
        }
        // ReSharper disable once UnusedMember.Local
        [HookMethod(DiscordExtHooks.OnDiscordBotFullyLoaded)]
        private void OnDiscordBotFullyLoaded() {
            RegisterTemplates();
            RegisterUserApplicationCommands();
            RegisterAdminApplicationCommands();
            _linkHandler.ProcessLeaveAndRejoin();
            SetupGuildWelcomeMessage();
            foreach (Snowflake role in _pluginConfig.PermissionSettings.LinkRoles) {
                if (!Guild?.Roles.ContainsKey(role) ?? false) {
                    PrintWarning($"`{role}` is set as the link role but role does not exist");
                }
            }
            foreach (Snowflake role in _pluginConfig.PermissionSettings.UnlinkRoles) {
                if (!Guild?.Roles.ContainsKey(role) ?? false) {
                    PrintWarning($"`{role}` is set as the unlink role but role does not exist");
                }
            }
        }
        // ReSharper disable once UnusedMember.Local
        [HookMethod(DiscordExtHooks.OnDiscordGuildMemberAdded)]
        private void OnDiscordGuildMemberAdded(GuildMemberAddedEvent member, DiscordGuild guild) {
            if (Guild?.Id != guild.Id) {
                return;
            }
            _linkHandler.OnGuildMemberJoin(member.User);
            if (!_pluginConfig.WelcomeMessageSettings.EnableWelcomeMessage || !_pluginConfig.WelcomeMessageSettings.SendOnGuildJoin) {
                return;
            }
            if (member.User.IsLinked()) {
                return;
            }
            SendGlobalTemplateMessage(TemplateKeys.WelcomeMessage.PmWelcomeMessage, member.User);
        }
        // ReSharper disable once UnusedMember.Local
        [HookMethod(DiscordExtHooks.OnDiscordGuildMemberRemoved)]
        private void OnDiscordGuildMemberRemoved(GuildMemberRemovedEvent member, DiscordGuild guild) {
            if (Guild?.Id != guild.Id) {
                return;
            }
            _linkHandler.OnGuildMemberLeft(member.User);
        }
        // ReSharper disable once UnusedMember.Local
        [HookMethod(DiscordExtHooks.OnDiscordGuildMemberRoleAdded)]
        private void OnDiscordGuildMemberRoleAdded(GuildMember member, Snowflake roleId, DiscordGuild guild) {
            if (Guild?.Id != guild.Id) {
                return;
            }
            if (!_pluginConfig.WelcomeMessageSettings.EnableWelcomeMessage || !_pluginConfig.WelcomeMessageSettings.SendOnRoleAdded.Contains(roleId)) {
                return;
            }
            if (member.User.IsLinked()) {
                return;
            }
            SendGlobalTemplateMessage(TemplateKeys.WelcomeMessage.PmWelcomeMessage, member.User);
        }
#endregion
#region Plugins\DiscordCore.UserAppCommands.cs
        public void RegisterUserApplicationCommands() {
            ApplicationCommandBuilder builder = new ApplicationCommandBuilder(UserAppCommands.Command, "Discord Core Commands", ApplicationCommandType.ChatInput).AddDefaultPermissions(PermissionFlags.None);
            AddUserCodeCommand(builder);
            AddUserUserCommand(builder);
            AddUserLeaveCommand(builder);
            AddUserLinkCommand(builder);
            CommandCreate build = builder.Build();
            DiscordCommandLocalization localization = builder.BuildCommandLocalization();
            TemplateKey template = new("User");
            _local.RegisterCommandLocalizationAsync(this, template, localization, new TemplateVersion(1, 0, 0), new TemplateVersion(1, 0, 0)).Then(_ => {
                _local.ApplyCommandLocalizationsAsync(this, build, template).Then(() => {
                    Client.Bot.Application.CreateGlobalCommand(Client, build).Then(command => {
                        _appCommand = command;
                        CreateAllowedChannels(command);
                    }
                    );
                }
                );
            }
            );
        }
        public void AddUserCodeCommand(ApplicationCommandBuilder builder) {
            builder.AddSubCommand(UserAppCommands.CodeCommand, "Start the link between discord and the game server using a link code");
        }
        public void AddUserUserCommand(ApplicationCommandBuilder builder) {
            builder.AddSubCommand(UserAppCommands.UserCommand, "Start the link between discord and the game server by game server player name", sub => {
                sub.AddOption(CommandOptionType.String, PlayerArg, "Player name on the game server", options => options.AutoComplete().Required());
            }
            );
        }
        public void AddUserLeaveCommand(ApplicationCommandBuilder builder) {
            builder.AddSubCommand(UserAppCommands.LeaveCommand, "Unlink your discord and game server accounts");
        }
        public void AddUserLinkCommand(ApplicationCommandBuilder builder) {
            builder.AddSubCommand(UserAppCommands.LinkCommand, "Complete the link using the given link code", sub => {
                sub.AddOption(CommandOptionType.String, CodeArg, "Code to complete the link", options => options.Required().MinLength(_pluginConfig.LinkSettings.LinkCodeLength).MaxLength(_pluginConfig.LinkSettings.LinkCodeLength));
            }
            );
        }
        public void CreateAllowedChannels(DiscordApplicationCommand command) {
            timer.In(1f, () => {
                command.GetPermissions(Client, Guild.Id).Then(CreateAllowedChannels).Catch<ResponseError>(error => {
                    error.SuppressErrorMessage();
                }
                );
            }
            );
        }
        public void CreateAllowedChannels(GuildCommandPermissions permissions) {
            List<string> channels = new();
            for (int index = 0; index < permissions.Permissions.Count; index++) {
                CommandPermissions perm = permissions.Permissions[index];
                if (perm.Type == CommandPermissionType.Channel) {
                    string name = Guild.Channels[perm.Id]?.Name;
                    if (!string.IsNullOrEmpty(name)) {
                        channels.Add(name);
                    }
                }
            }
            _allowedChannels = string.Join(", ", channels);
            _placeholders.RegisterPlaceholder(this, PlaceholderKeys.CommandChannels, _allowedChannels);
        }
        // ReSharper disable once UnusedMember.Local
        // ReSharper disable once UnusedParameter.Local
        [DiscordApplicationCommand(UserAppCommands.Command, UserAppCommands.CodeCommand)]
        private void DiscordCodeCommand(DiscordInteraction interaction, InteractionDataParsed parsed) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user.Player, user));
                return;
            }
            JoinData join = _joinHandler.CreateActivation(user);
            SendTemplateMessage(TemplateKeys.Commands.Code.Success, interaction, GetDefault(user).Add(PlaceholderDataKeys.Code, join.Code));
        }
        // ReSharper disable once UnusedMember.Local
        [DiscordApplicationCommand(UserAppCommands.Command, UserAppCommands.UserCommand)]
        private void DiscordUserCommand(DiscordInteraction interaction, InteractionDataParsed parsed) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user));
                return;
            }
            if (_banHandler.IsBanned(user)) {
                SendTemplateMessage(TemplateKeys.Banned.PlayerBanned, interaction, GetDefault(user).AddTimestamp(_banHandler.GetBannedEndDate(user)));
                return;
            }
            string playerId = parsed.Args.GetString(PlayerArg);
            IPlayer player = covalence.Players.FindPlayerById(playerId);
            if (player == null) {
                SendTemplateMessage(TemplateKeys.Commands.User.Error.PlayerIsInvalid, interaction, GetDefault(user));
                return;
            }
            if (player.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.PlayerAlreadyLinked, interaction, GetDefault(player, user));
                return;
            }
            if (!player.IsConnected) {
                SendTemplateMessage(TemplateKeys.Commands.User.Error.PlayerNotConnected, interaction, GetDefault(player, user));
                return;
            }
            _joinHandler.CreateActivation(player, user, JoinSource.Discord);
            using (PlaceholderData data = GetDefault(player, user)) {
                data.ManualPool();
                Chat(player, ServerLang.Join.ByPlayer, data);
                SendTemplateMessage(TemplateKeys.Commands.User.Success, interaction, data);
            }
        }
        // ReSharper disable once UnusedMember.Local
        [DiscordAutoCompleteCommand(UserAppCommands.Command, PlayerArg, UserAppCommands.UserCommand)]
        private void HandleNameAutoComplete(DiscordInteraction interaction, InteractionDataOption focused) {
            string search = focused.GetString();
            InteractionAutoCompleteBuilder response = interaction.GetAutoCompleteBuilder();
            response.AddAllOnlineFirstPlayers(search, PlayerNameFormatter.ClanName);
            interaction.CreateResponse(Client, response);
        }
        // ReSharper disable once UnusedMember.Local
        // ReSharper disable once UnusedParameter.Local
        [DiscordApplicationCommand(UserAppCommands.Command, UserAppCommands.LeaveCommand)]
        private void DiscordLeaveCommand(DiscordInteraction interaction, InteractionDataParsed parsed) {
            DiscordUser user = interaction.User;
            if (!user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Commands.Leave.Error.UserNotLinked, interaction, GetDefault(user));
                return;
            }
            IPlayer player = user.Player;
            _linkHandler.HandleUnlink(player, user, UnlinkedReason.Command, interaction);
        }
        // ReSharper disable once UnusedMember.Local
        [DiscordApplicationCommand(UserAppCommands.Command, UserAppCommands.LinkCommand)]
        private void DiscordLinkCommand(DiscordInteraction interaction, InteractionDataParsed parsed) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user.Player, user));
                return;
            }
            string code = parsed.Args.GetString(CodeArg);
            JoinData join = _joinHandler.FindByCode(code);
            if (join == null) {
                SendTemplateMessage(TemplateKeys.Errors.CodeActivationNotFound, interaction, GetDefault(user).Add(PlaceholderDataKeys.Code, code));
                return;
            }
            if (join.From == JoinSource.Discord) {
                SendTemplateMessage(TemplateKeys.Errors.MustBeCompletedInServer, interaction, GetDefault(user).Add(PlaceholderDataKeys.Code, code));
                return;
            }
            join.Discord = user;
            _joinHandler.CompleteLink(join, interaction);
        }
#endregion
#region Plugins\DiscordCore.MessageComponentCommands.cs
        private const string WelcomeMessageLinkAccountsButtonId = nameof(DiscordCore) + "_PmLinkAccounts";
        private const string GuildWelcomeMessageLinkAccountsButtonId = nameof(DiscordCore) + "_GuildLinkAccounts";
        private const string AcceptLinkButtonId = nameof(DiscordCore) + "_AcceptLink";
        private const string DeclineLinkButtonId = nameof(DiscordCore) + "_DeclineLink";
        // ReSharper disable once UnusedMember.Local
        [DiscordMessageComponentCommand(WelcomeMessageLinkAccountsButtonId)]
        private void HandleWelcomeMessageLinkAccounts(DiscordInteraction interaction) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user.Player, user));
                return;
            }
            JoinData join = _joinHandler.CreateActivation(user);
            SendTemplateMessage(TemplateKeys.Link.WelcomeMessage.DmLinkAccounts, interaction, GetDefault(user).Add(PlaceholderDataKeys.Code, join.Code));
        }
        // ReSharper disable once UnusedMember.Local
        [DiscordMessageComponentCommand(GuildWelcomeMessageLinkAccountsButtonId)]
        private void HandleGuildWelcomeMessageLinkAccounts(DiscordInteraction interaction) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user.Player, user));
                return;
            }
            JoinData join = _joinHandler.CreateActivation(user);
            SendTemplateMessage(TemplateKeys.Link.WelcomeMessage.GuildLinkAccounts, interaction, GetDefault(user).Add(PlaceholderDataKeys.Code, join.Code));
        }
        // ReSharper disable once UnusedMember.Local
        [DiscordMessageComponentCommand(AcceptLinkButtonId)]
        private void HandleAcceptLinkButton(DiscordInteraction interaction) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user.Player, user));
                return;
            }
            JoinData join = _joinHandler.FindCompletedByUser(user);
            if (join == null) {
                SendTemplateMessage(TemplateKeys.Errors.LookupActivationNotFound, interaction, GetDefault(user));
                return;
            }
            _joinHandler.CompleteLink(join, interaction);
        }
        // ReSharper disable once UnusedMember.Local
        [DiscordMessageComponentCommand(DeclineLinkButtonId)]
        private void HandleDeclineLinkButton(DiscordInteraction interaction) {
            DiscordUser user = interaction.User;
            if (user.IsLinked()) {
                SendTemplateMessage(TemplateKeys.Errors.UserAlreadyLinked, interaction, GetDefault(user.Player, user));
                return;
            }
            JoinData join = _joinHandler.FindCompletedByUser(user);
            if (join == null) {
                SendTemplateMessage(TemplateKeys.Errors.LookupActivationNotFound, interaction, GetDefault(user));
                return;
            }
            _joinHandler.DeclineLink(join, interaction);
        }
#endregion
#region Plugins\DiscordCore.AdminAppCommands.cs
        public void RegisterAdminApplicationCommands() {
            ApplicationCommandBuilder builder = new ApplicationCommandBuilder(AdminAppCommands.Command, "Discord Core Admin Commands", ApplicationCommandType.ChatInput).AddDefaultPermissions(PermissionFlags.None);
            builder.AllowInDirectMessages(false);
            AddAdminLinkCommand(builder);

// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху