Advertisement
rmsoft1

CustomCommandProcessor.cs

Apr 29th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.46 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using RMSoftware.IO;
  7. using Discord.WebSocket;
  8. using Discord;
  9. using System.Runtime.InteropServices;
  10. using System.Reflection;
  11. using Discord.Commands;
  12.  
  13. namespace RMSoftware.ModularBot
  14. {
  15.     /// <summary>
  16.     /// This is a twitch style command manager
  17.     /// </summary>
  18.     public class CustomCommandManager
  19.     {
  20.  
  21.         INIFile CmdDB = new INIFile("commands.ini");
  22.         /// <summary>
  23.         /// Adds a command to the bot.
  24.         /// </summary>
  25.         /// <param name="Command">command tag (without !)</param>
  26.         /// <param name="Action">The command response/action</param>
  27.         /// <param name="Restricted">If restricted, only people with roles that are whitelisted in the rolemgmt's database can use the command.</param>
  28.         public string AddCommand(string Command, string Action, bool Restricted)
  29.         {
  30.             if (CmdDB.CheckForCategory(Command.Replace(Program.CommandPrefix.ToString(), "")))
  31.             {
  32.                 return "That command already exists!";
  33.             }
  34.             CmdDB.CreateCategory(Command.Replace(Program.CommandPrefix.ToString(), ""));
  35.             CmdDB.CreateEntry(Command.Replace(Program.CommandPrefix.ToString(), ""), "action", Action);
  36.             CmdDB.CreateEntry(Command.Replace(Program.CommandPrefix.ToString(), ""), "restricted", Restricted);
  37.             return "Command added to the DB. Please remember to save.";
  38.         }
  39.         public string EditCommand(string Command, string newAction, bool Restricted)
  40.         {
  41.             if (!CmdDB.CheckForCategory(Command.Replace(Program.CommandPrefix.ToString(), "")))
  42.             {
  43.                 return "That command does not exists!";
  44.             }
  45.             CmdDB.GetCategoryByName(Command.Replace(Program.CommandPrefix.ToString(), "")).GetEntryByName("action").SetValue(newAction);
  46.             CmdDB.GetCategoryByName(Command.Replace(Program.CommandPrefix.ToString(), "")).GetEntryByName("restricted").SetValue(Restricted);
  47.             return "Command edited. Please remember to save.";
  48.         }
  49.  
  50.         public string AddCommand(string Command, string Action, bool Restricted, ulong guildID)
  51.         {
  52.             if (CmdDB.CheckForCategory(Command.Replace(Program.CommandPrefix.ToString(), "")))
  53.             {
  54.                 return "That command already exists!";
  55.             }
  56.             CmdDB.CreateCategory(Command.Replace(Program.CommandPrefix.ToString(), ""));
  57.             CmdDB.CreateEntry(Command.Replace(Program.CommandPrefix.ToString(), ""), "action", Action);
  58.             CmdDB.CreateEntry(Command.Replace(Program.CommandPrefix.ToString(), ""), "restricted", Restricted);
  59.             CmdDB.CreateEntry(Command.Replace(Program.CommandPrefix.ToString(), ""), "guildID", guildID);
  60.             return "Command added to the DB. Please remember to save.";
  61.         }
  62.  
  63.         public void Save()
  64.         {
  65.             CmdDB.SaveConfiguration();
  66.         }
  67.         public void DeleteCommand(string Command)
  68.         {
  69.             CmdDB.DeleteCategory(Command.Replace(Program.CommandPrefix.ToString(), ""));
  70.         }
  71.         public bool successful = false;
  72.         /// <summary>
  73.         /// Process user input for custom command module
  74.         /// </summary>
  75.         /// <param name="arg"></param>
  76.         public async Task<bool> Process(IMessage arg)//Arg Change
  77.         {
  78.  
  79.             string content = arg.Content;
  80.             bool hasrole = false;
  81.             bool IsTTS = false;
  82.             int argPos = 1;
  83.             if (!arg.Content.StartsWith(Program.CommandPrefix.ToString())) return false;
  84.             //substring the text into two parts.
  85.             try
  86.             {
  87.                
  88.                 string cmd = content.Substring(argPos).Split(' ')[0];//get the command bit.
  89.                 if(cmd.EndsWith("TTS"))
  90.                 {
  91.                     SocketGuildUser a = arg.Author as SocketGuildUser;
  92.                     if(a == null)
  93.                     {
  94.                         return false;
  95.                     }
  96.                     if(Program.rolemgt.CheckUserRole(a))
  97.                     {
  98.                         IsTTS = true;
  99.                         cmd = cmd.Remove(cmd.Length - 3);
  100.                     }
  101.                     else
  102.                     {
  103.                         await arg.Channel.SendMessageAsync("Hey " + arg.Author.Mention + ", You don't have permission to TTS this command.");
  104.                     }
  105.                 }
  106.                 string parameters = content.Replace(Program.CommandPrefix.ToString()+""+cmd, "").Trim();
  107.  
  108.                 //find the command in the file.
  109.  
  110.                 if (CmdDB.CheckForCategory(cmd))
  111.                 {
  112.                     if (CmdDB.GetCategoryByName(cmd).CheckForEntry("guildID"))//NEW: Check for guild id. If this entry exists, continune.
  113.                     {
  114.                         ulong id = CmdDB.GetCategoryByName(cmd).GetEntryByName("guildID").GetAsUlong();
  115.                         if ((arg.Author as IGuildUser) == null)
  116.                         {
  117.                             await Retry.Do(async () => await arg.Channel.SendMessageAsync("Hey, I know you really want to see that work, but this is my dm..." +
  118.                                 " This command will only work on a specific guild. "), TimeSpan.FromMilliseconds(140));
  119.  
  120.                             return true;
  121.                         }
  122.                         if ((arg.Author as IGuildUser)?.Guild == null)
  123.                         {
  124.                             await Retry.Do(async () => await arg.Channel.SendMessageAsync("Hey, I know you really want to see that work, but this is my dm..." +
  125.                                 " This command will only work on a specific guild. "), TimeSpan.FromMilliseconds(140));
  126.  
  127.                             return true;
  128.                         }
  129.  
  130.                         if (id != (arg.Author as IGuildUser).Guild?.Id)
  131.                         {
  132.                             await Retry.Do(async () => await arg.Channel.SendMessageAsync("Hey " + arg.Author.Mention + ", Wrong guild."), TimeSpan.FromMilliseconds(140));
  133.  
  134.                             return true;
  135.                         }
  136.                     }
  137.                     if (CmdDB.GetCategoryByName(cmd).GetEntryByName("restricted").GetAsBool())
  138.                     {
  139.  
  140.  
  141.                         SocketGuildUser user = ((SocketGuildUser)arg.Author);
  142.  
  143.                         if (Program.rolemgt.CheckUserRole(user))
  144.                         {
  145.                             hasrole = true;
  146.                         }
  147.                         if (!hasrole)
  148.                         {
  149.                             await Retry.Do(async () => await arg.Channel.SendMessageAsync("Hey " + arg.Author.Mention + ", You don't have permission to use this command!"), TimeSpan.FromMilliseconds(140));
  150.  
  151.                             successful = false;
  152.                             return true;
  153.                         }
  154.                     }
  155.  
  156.                    
  157.                     string response = CmdDB.GetCategoryByName(cmd).GetEntryByName("action").GetAsString();
  158.  
  159.                     if (response.StartsWith("splitparam"))
  160.                     {
  161.                         string[] responsearray = CmdDB.GetCategoryByName(cmd).GetEntryByName("action").GetAsString().Split('|');
  162.                         int paramcount = int.Parse(responsearray[0].Trim().Split(' ')[1]);
  163.                         string[] paramarray = parameters.Split(' ');
  164.                         response = responsearray[1].Trim();
  165.                         for (int i = 0; i < paramcount; i++)
  166.                         {
  167.                             response = response.Replace("{" + i + "}", paramarray[i]);
  168.                         }
  169.                     }
  170.                     else
  171.                     {
  172.                         response = response.Replace("{params}", parameters);
  173.                     }
  174.                     if (response.StartsWith("EXEC"))
  175.                     {
  176.                         string[] resplit = response.Replace("EXEC ", "").Split(' ');
  177.                         if (resplit.Length < 3)
  178.                         {
  179.                             await Retry.Do(async () => await arg.Channel.SendMessageAsync("The command failed to execute... EXEC method malformed"), TimeSpan.FromMilliseconds(140));
  180.  
  181.                             successful = true;
  182.                             return true;
  183.                         }
  184.                         string modpath = System.IO.Path.GetFullPath("ext/" + resplit[0]);
  185.                         string nsdotclass = resplit[1];
  186.                         string mthd = resplit[2];
  187.                         string strargs = "";
  188.                         for (int i = 3; i < resplit.Length; i++)
  189.                         {
  190.                             strargs += resplit[i] + " ";
  191.                         }
  192.                         object[] parameter = { arg, strargs.Replace("{params}", parameters).Trim() };
  193.                         Assembly asm = Assembly.LoadFile(modpath);
  194.                         Type t = asm.GetType(nsdotclass, true);
  195.                         MethodInfo info = t.GetMethod(mthd, BindingFlags.Public | BindingFlags.Static);
  196.                         info.Invoke(null, parameter);
  197.                         successful = true;
  198.                         return true;
  199.                     }
  200.                     if (response.StartsWith("CLI_EXEC"))//EXEC with client instead of context
  201.                     {
  202.                         string[] resplit = response.Replace("CLI_EXEC ", "").Split(' ');
  203.                         if (resplit.Length < 3)
  204.                         {
  205.                             await Retry.Do(async () => await arg.Channel.SendMessageAsync("The command failed to execute... CLI_EXEC method malformed"), TimeSpan.FromMilliseconds(140));
  206.  
  207.                             successful = true;
  208.                             return true;
  209.                         }
  210.                         string modpath = System.IO.Path.GetFullPath("ext/" + resplit[0]);
  211.                         string nsdotclass = resplit[1];
  212.                         string mthd = resplit[2];
  213.                         string strargs = "";
  214.                         for (int i = 3; i < resplit.Length; i++)
  215.                         {
  216.                             strargs += resplit[i] + " ";
  217.                         }
  218.                         object[] parameter = { Program._client, arg, strargs.Replace("{params}", parameters).Trim() };
  219.                         Assembly asm = Assembly.LoadFile(modpath);
  220.                         Type t = asm.GetType(nsdotclass, true);
  221.                         MethodInfo info = t.GetMethod(mthd, BindingFlags.Public | BindingFlags.Static);
  222.                         info.Invoke(null, parameter);
  223.                         successful = true;
  224.                         return true;
  225.                     }
  226.                     string version = String.Format("{0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
  227.  
  228.                     RequestOptions op = new RequestOptions();
  229.                     op.RetryMode = RetryMode.AlwaysRetry;
  230.                     op.Timeout = 256;
  231.                     await Retry.Do(async () => await arg.Channel.SendMessageAsync(response.Replace("%appv%", "v" + version).Trim(),IsTTS), TimeSpan.FromMilliseconds(140));
  232.  
  233.                    
  234.                     successful = true;
  235.                     return true;
  236.  
  237.                 }
  238.                 else
  239.                 {
  240.                     return false;
  241.                 }
  242.  
  243.             }
  244.             catch (AggregateException ex)
  245.             {
  246.  
  247.                 await arg.Channel.SendMessageAsync("The request failed (MANY TIMES) due to some API related thing I can't sort out right now... please forgive me... (You can try that again if you want...)");
  248.                 successful = false;
  249.                 Program.LogToConsole(new LogMessage(LogSeverity.Error, "CritERR", ex.Message, ex));
  250.                 return false;
  251.             }
  252.             catch (Exception ex)
  253.             {
  254.  
  255.                 await arg.Channel.SendMessageAsync("There was a problem performing this command. See bot console for info");
  256.                 successful = false;
  257.                 Program.LogToConsole(new LogMessage(LogSeverity.Error, "CritERR", ex.Message, ex));
  258.                 return false;
  259.             }
  260.         }
  261.  
  262.         public INICategory[] GetAllCommand()
  263.         {
  264.             return CmdDB.Categories.ToArray();
  265.         }
  266.     }
  267. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement