/// <summary>
        /// Returns the command prefix for the current guild message is sent in
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetGuildCommandPrefix(SocketCommandContext context)
        {
            //Find guild id
            var chnl    = context.Channel as SocketGuildChannel;
            var guildId = chnl.Guild.Id;

            //Just in case the file is null
            if (GuildPrefixDictionary == null || GuildPrefixDictionary.GuildPrefixes == null)
            {
                GuildPrefixDictionary = new CommandPrefix {
                    GuildPrefixes = new Dictionary <ulong, string>()
                };
                GuildPrefixDictionary.GuildPrefixes.Add(guildId, ".d");

                //Write new dictionary to file
                string newJson = JsonConvert.SerializeObject(GuildPrefixDictionary);
                CoreMethod.WriteStringToFile(newJson, true, CoreMethod.GetFileLocation("GuildCommandPrefix.json"));
            }

            //Look for guild prefix, in event guild does not have one, use default
            if (!GuildPrefixDictionary.GuildPrefixes.TryGetValue(guildId, out var i))
            {
                GuildPrefixDictionary.GuildPrefixes.Add(guildId, ".d");

                //Write new dictionary to file
                string newJson = JsonConvert.SerializeObject(GuildPrefixDictionary);
                CoreMethod.WriteStringToFile(newJson, true, CoreMethod.GetFileLocation("GuildCommandPrefix.json"));
            }

            return(GuildPrefixDictionary.GuildPrefixes[guildId]);
        }
Example #2
0
 /// <summary>
 /// Returns whether or not the text is formatted as a command.
 /// </summary>
 /// <param name="text">The message text.</param>
 /// <returns>Whether or not the text is formatted as a command.</returns>
 public static bool IsCommand(string text)
 {
     if (text.Length <= CommandPrefix.Length)
     {
         return(false);
     }
     if (!text.ToLower().StartsWith(CommandPrefix.ToLower()))
     {
         return(false);
     }
     return(true);
 }
 /// <summary>Full constructor, recommended.</summary>
 public CommandEntry(string _commandline, int bstart, int bend, AbstractCommand _command, Argument[] _arguments,
                     string _name, CommandPrefix _prefix, string _script, int _line, string fairtabs, Dictionary <string, Argument> nameds, ScriptEngine sys)
 {
     BlockStart     = bstart;
     BlockEnd       = bend;
     CommandLine    = _commandline;
     Command        = _command;
     Arguments      = _arguments;
     Name           = _name;
     Prefix         = _prefix;
     ScriptName     = _script;
     ScriptLine     = _line;
     FairTabulation = fairtabs;
     NamedArguments = nameds;
     System         = sys;
     if (Command == null)
     {
         throw new Exception("Invalid Command (null!)");
     }
 }
Example #4
0
        public static Dictionary <string, string> EmoDict = new Dictionary <string, string>(); // holds emoticon to emoji mappings

        /// <summary>
        /// Parses the terracord.xml configuration file
        /// </summary>
        public static void Parse()
        {
            // Set default locale if value cannot be read from terracord.xml
            LocaleString = "en-US";
            Locale       = new CultureInfo(LocaleString);
            // Set default timestamp format for Util.Log() called in exception in case terracord.xml cannot be parsed
            TimestampFormat = "MM/dd/yyyy HH:mm:ss zzz";
            // Do not terminate TShock by default if terracord.xml is unable to be parsed
            AbortOnError = false;

            try
            {
                // Create Terracord directory if it does not exist
                Directory.CreateDirectory(TerracordPath);
                // terracord.xml configuration file
                XDocument configFile = XDocument.Load($"{TerracordPath}terracord.xml");
                // terracord.xml root element
                XElement configOptions = configFile.Element("configuration");

                LocaleString = configOptions.Element("locale").Attribute("string").Value.ToString(Locale);
                ChangeLocale();
                BotToken      = configOptions.Element("bot").Attribute("token").Value.ToString(Locale);
                ChannelId     = ulong.Parse(configOptions.Element("channel").Attribute("id").Value.ToString(Locale), Locale);
                OwnerId       = ulong.Parse(configOptions.Element("owner").Attribute("id").Value.ToString(Locale), Locale);
                CommandPrefix = configOptions.Element("command").Attribute("prefix").Value.ToString(Locale);
                if (CommandPrefix.Length == 0 || CommandPrefix.Trim().Length == 0)
                {
                    throw new IOException("Command prefix is empty!");
                }
                RelayCommands   = bool.Parse(configOptions.Element("relay").Attribute("commands").Value.ToString(Locale));
                RemoteCommands  = bool.Parse(configOptions.Element("remote").Attribute("commands").Value.ToString(Locale));
                AuthorizedRoles = configOptions.Element("authorized").Attribute("roles").Value.ToString(Locale);
                BotGame         = configOptions.Element("game").Attribute("status").Value.ToString(Locale);
                TopicInterval   = uint.Parse(configOptions.Element("topic").Attribute("interval").Value.ToString(Locale), Locale);
                OfflineTopic    = configOptions.Element("topic").Attribute("offline").Value.ToString(Locale);
                OnlineTopic     = configOptions.Element("topic").Attribute("online").Value.ToString(Locale);

                // Populate broadcast RGB array values
                BroadcastColor = new byte[3]
                {
                    byte.Parse(configOptions.Element("color").Attribute("red").Value.ToString(Locale), Locale),
                    byte.Parse(configOptions.Element("color").Attribute("green").Value.ToString(Locale), Locale),
                    byte.Parse(configOptions.Element("color").Attribute("blue").Value.ToString(Locale), Locale)
                };

                SilenceBroadcasts = bool.Parse(configOptions.Element("silence").Attribute("broadcasts").Value.ToString(Locale));
                SilenceChat       = bool.Parse(configOptions.Element("silence").Attribute("chat").Value.ToString(Locale));
                SilenceSaves      = bool.Parse(configOptions.Element("silence").Attribute("saves").Value.ToString(Locale));
                AnnounceReconnect = bool.Parse(configOptions.Element("announce").Attribute("reconnect").Value.ToString(Locale));
                AvailableText     = configOptions.Element("available").Attribute("text").Value.ToString(Locale);
                UnavailableText   = configOptions.Element("unavailable").Attribute("text").Value.ToString(Locale);
                JoinText          = configOptions.Element("join").Attribute("text").Value.ToString(Locale);
                LeaveText         = configOptions.Element("leave").Attribute("text").Value.ToString(Locale);
                BroadcastText     = configOptions.Element("broadcast").Attribute("text").Value.ToString(Locale);
                PlayerText        = configOptions.Element("player").Attribute("text").Value.ToString(Locale);
                ChatText          = configOptions.Element("chat").Attribute("text").Value.ToString(Locale);
                IgnoreChat        = bool.Parse(configOptions.Element("ignore").Attribute("chat").Value.ToString(Locale));
                LogChat           = bool.Parse(configOptions.Element("log").Attribute("chat").Value.ToString(Locale));
                MessageLength     = int.Parse(configOptions.Element("message").Attribute("length").Value.ToString(Locale), Locale);
                DebugMode         = bool.Parse(configOptions.Element("debug").Attribute("mode").Value.ToString(Locale));
                TimestampFormat   = configOptions.Element("timestamp").Attribute("format").Value.ToString(Locale);
                AbortOnError      = bool.Parse(configOptions.Element("exception").Attribute("abort").Value.ToString(Locale));
                ConvertEmoticons  = bool.Parse(configOptions.Element("convert").Attribute("emoticons").Value.ToString(Locale));
                if (ConvertEmoticons)
                {
                    EmoDict = configFile.Descendants("map").ToDictionary(m => (string)m.Attribute("emoticon"), m => (string)m.Attribute("emoji"));
                }
            }
            catch (FileNotFoundException fnfe)
            {
                Util.Log($"Unable to parse terracord.xml: {fnfe.Message}", Util.Severity.Error);
                Generate();
            }
            // This will catch and log anything else such as SecurityException for a permission issue, FormatException during conversion, etc.
            catch (Exception e)
            {
                Util.Log($"Unable to parse terracord.xml: {e.Message}", Util.Severity.Error);
                throw;
            }
            Util.Log("terracord.xml parsed.", Util.Severity.Info);
            // Display configuration values
            if (Config.DebugMode)
            {
                Display();
            }
        }
Example #5
0
 /// <summary>Returns the character for the prefix.</summary>
 /// <param name="prefix">The prefix.</param>
 /// <returns>The character.</returns>
 public static char Character(this CommandPrefix prefix)
 {
     return(PREFIXES[(int)prefix - 1]);
 }
 /// <summary>Full constructor, recommended.</summary>
 public CommandEntry(string _commandline, int bstart, int bend, AbstractCommand _command, Argument[] _arguments,
                     string _name, CommandPrefix _prefix, string _script, int _line, string fairtabs, ScriptEngine sys)
     : this(_commandline, bstart, bend, _command, _arguments, _name, _prefix, _script, _line, fairtabs, new Dictionary <string, Argument>(), sys)
 {
 }
Example #7
0
        /// <summary>
        /// Handles a command issued via a Discord message. This does not test if it is a command. Please test with <see cref="IsCommand(string)"/> before running this.
        /// </summary>
        /// <param name="originalMessage">The Discord message sent by the command.</param>
        public static async Task HandleMessageCommand(DiscordMessage originalMessage)
        {
            DiscordUser author         = originalMessage.Author;
            BotContext  commandContext = BotContextRegistry.GetContext(originalMessage.Channel.Guild);

            XanBotLogger.WriteDebugLine("Executing command in bot context. Info:");
            XanBotLogger.WriteLine(commandContext.ToConsoleString(), isDebugModeOnly: true);

            XanBotMember member = XanBotMember.GetMemberFromUser(commandContext, author);
            string       text   = originalMessage.Content;

            if (text.ToLower().StartsWith(CommandPrefix.ToLower()))
            {
                text = text.Substring(CommandPrefix.Length);
            }
            while (AllowSpacesAfterPrefix && text.StartsWith(" "))
            {
                text = text.Substring(1);
            }
            string[] allArgs = ArgumentSplitter.SplitArgs(text);
            string   command = allArgs[0];

            string[] args = new string[0];
            if (allArgs.Length > 1)
            {
                args = allArgs.Skip(1).ToArray();
            }

            // Catch case: Prevent excessive command length.
            if (command.Length > 32)
            {
                await ResponseUtil.RespondToAsync(originalMessage, "The command you input is too long.");

                XanBotLogger.WriteLine(string.Format("§aUser \"§6{0}§a\" issued a command that was considered too long to parse.", member.FullName));
                return;
            }
            // Catch case: Strip color formatting
            command.Replace(XanBotLogger.COLOR_CODE_SYM.ToString(), "");

            XanBotLogger.WriteDebugLine("Searching for command...");
            Command execCommand = null;
            string  cmdLower    = command.ToLower();

            // Search the context FIRST. That ensures that context commands can override stock commands.
            foreach (Command cmd in commandContext.Commands)
            {
                if (cmd.Name.ToLower() == cmdLower)
                {
                    execCommand = cmd;
                    XanBotLogger.WriteDebugLine($"Found command [{cmd.Name}] in context.");
                    break;
                }
                else
                {
                    if (cmd.AlternateNames != null)
                    {
                        foreach (string altName in cmd.AlternateNames)
                        {
                            if (altName.ToLower() == cmdLower)
                            {
                                execCommand = cmd;
                                break;
                            }
                        }
                    }
                }
            }

            if (execCommand == null)
            {
                foreach (Command cmd in Commands)
                {
                    if (cmd.Name.ToLower() == command.ToLower())
                    {
                        execCommand = cmd;
                        XanBotLogger.WriteDebugLine($"Found command [{cmd.Name}] globally.");
                        break;
                    }
                }
            }


            if (execCommand != null)
            {
                UsagePermissionPacket usagePerms = execCommand.CanUseCommand(member);
                if (usagePerms.CanUse)
                {
                    if (execCommand.CanUseCommandInThisChannel(member, originalMessage.Channel, out DiscordChannel optimalTargetChannel))
                    {
                        try
                        {
                            string allArgsText = "";
                            if (args.Length > 0)
                            {
                                allArgsText = text.Substring(command.Length + 1);
                            }
                            originalMessage.Channel.TriggerTypingAsync().GetAwaiter().GetResult();
                            await execCommand.ExecuteCommandAsync(commandContext, member, originalMessage, args, allArgsText);

                            XanBotLogger.WriteLine(string.Format("§aUser \"§6{0}§a\" issued command \"§6{1}§a\" with args {2}", member.FullName, command, ArrayToText(args)));
                        }
                        catch (CommandException commandErr)
                        {
                            string message = string.Format("§cFailed to issue command `{0}`: §1{1}", commandErr.Command.Name, commandErr.Message);
                            await ResponseUtil.RespondToAsync(originalMessage, message);

                            XanBotLogger.WriteLine(string.Format("§aUser \"§6{0}§a\" attempted to issue command \"§6{1}§a\" but it failed. The command gave the reason: §2{2}", member.FullName, commandErr.Command.Name, commandErr.Message));
                        }
                        catch (ArchonCommandException commandErr)
                        {
                            string message = string.Format("§cFailed to issue Archon Command `{0}`: §1{1}", commandErr.Command.Name, commandErr.Message);
                            await ResponseUtil.RespondToAsync(originalMessage, message);

                            XanBotLogger.WriteLine(string.Format("§aUser \"§6{0}§a\" attempted to issue Archon Command \"§6{1}§a\" but it failed. The command gave the reason: §2{2}", member.FullName, commandErr.Command.Name, commandErr.Message));
                        }
                        catch (TaskCanceledException taskCancel)
                        {
                            XanBotLogger.WriteException(taskCancel);
                        }
                    }
                    else
                    {
                        string message = string.Format($"You can't use this command here. Go to <#{optimalTargetChannel.Id}> instead.");
                        await ResponseUtil.RespondToAsync(originalMessage, message);
                    }
                }
                else
                {
                    //string message = string.Format("You are not authorized to use `{0}`. It is only available to permission level `{1}` and above (You are at `{2}`)", execCommand.Name, execCommand.RequiredPermissionLevel, member.PermissionLevel);
                    await ResponseUtil.RespondToAsync(originalMessage, usagePerms.ErrorMessage);

                    XanBotLogger.WriteLine(string.Format("§aUser \"§6{0}§a\" attempted to issue command \"§6{1}§a\" but it failed because they don't have a high enough permission level or because the command's CanUseCommand method returned false.", member.FullName, execCommand.Name));
                }
            }
            else
            {
                await ResponseUtil.RespondToAsync(originalMessage, "The command `" + command + "` does not exist.");

                XanBotLogger.WriteLine(string.Format("§aUser \"§6{0}§a\" attempted to issue command \"§6{1}§a\" but it failed because it doesn't exist.", member.FullName, command));
            }
        }