The easy to use and full featured Irc Bot everyone is talking about!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Custom_Commands.cs 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.Eventing.Reader;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using Combot.IRCServices;
  7. using Combot.IRCServices.Messaging;
  8. using System.IO;
  9. namespace Combot.Modules.Plugins
  10. {
  11. public class Custom_Commands : Module
  12. {
  13. public override void Initialize()
  14. {
  15. InitializeTable();
  16. Bot.CommandReceivedEvent += HandleCommandEvent;
  17. Bot.IRC.Message.ChannelMessageReceivedEvent += HandleChannelMessage;
  18. Bot.IRC.Message.PrivateMessageReceivedEvent += HandlePrivateMessage;
  19. Bot.IRC.Message.ChannelNoticeReceivedEvent += HandleChannelNotice;
  20. Bot.IRC.Message.PrivateNoticeReceivedEvent += HandlePrivateNotice;
  21. }
  22. private void InitializeTable()
  23. {
  24. string sqlPath = Path.Combine(Directory.GetCurrentDirectory(), ConfigPath, "CreateTable.sql");
  25. if (File.Exists(sqlPath))
  26. {
  27. string query = File.ReadAllText(sqlPath);
  28. Bot.Database.Execute(query);
  29. }
  30. }
  31. public override void ParseCommand(CommandMessage command)
  32. {
  33. Command foundCommand = Commands.Find(c => c.Triggers.Contains(command.Command));
  34. switch (foundCommand.Name)
  35. {
  36. case "Custom Command":
  37. string action = command.Arguments["Action"];
  38. switch (action.ToLower())
  39. {
  40. case "add":
  41. string addType = command.Arguments["Type"];
  42. string addPermission = command.Arguments["Permission"];
  43. string addChannels = (command.Arguments.ContainsKey("Channels")) ? command.Arguments["Channels"] : string.Empty;
  44. string addNicknames = (command.Arguments.ContainsKey("Nicknames")) ? command.Arguments["Nicknames"] : string.Empty;
  45. string addTrigger = command.Arguments["Trigger"];
  46. string addResponse = command.Arguments["Response"];
  47. AddCommand(command, addType, addPermission, addChannels, addNicknames, addTrigger, addResponse);
  48. break;
  49. case "del":
  50. DeleteCommand(command);
  51. break;
  52. case "edit":
  53. string editType = command.Arguments["Type"];
  54. string editPermission = command.Arguments["Permission"];
  55. string editChannels = (command.Arguments.ContainsKey("Channels")) ? command.Arguments["Channels"] : string.Empty;
  56. string editNicknames = (command.Arguments.ContainsKey("Nicknames")) ? command.Arguments["Nicknames"] : string.Empty;
  57. string editTrigger = command.Arguments["Trigger"];
  58. string editResponse = command.Arguments["Response"];
  59. EditCommand(command, editType, editPermission, editChannels, editNicknames, editTrigger, editResponse);
  60. break;
  61. case "view":
  62. if (command.Arguments.ContainsKey("Trigger"))
  63. {
  64. ViewTrigger(command, command.Arguments["Trigger"]);
  65. }
  66. else
  67. {
  68. ViewTriggers(command);
  69. }
  70. break;
  71. }
  72. break;
  73. }
  74. }
  75. private void HandleChannelMessage(object sender, ChannelMessage message)
  76. {
  77. if (Enabled && !Bot.IsCommand(message.Message))
  78. {
  79. string command = Bot.GetCommand(message.Message);
  80. if (!string.IsNullOrEmpty(command))
  81. {
  82. List<Dictionary<string, object>> foundTriggers = GetTrigger(message.Sender, null, message.Channel, message.Sender.Nickname, command);
  83. if (foundTriggers.Any())
  84. {
  85. foreach (Dictionary<string, object> foundTrigger in foundTriggers)
  86. {
  87. ExecuteCommand(MessageType.Channel, message.Channel, message.Sender, foundTrigger);
  88. }
  89. }
  90. }
  91. }
  92. }
  93. private void HandlePrivateMessage(object sender, PrivateMessage message)
  94. {
  95. if (Enabled && !Bot.IsCommand(message.Message))
  96. {
  97. string command = Bot.GetCommand(message.Message);
  98. if (!string.IsNullOrEmpty(command))
  99. {
  100. List<Dictionary<string, object>> foundTriggers = GetTrigger(message.Sender, null, null, message.Sender.Nickname, command);
  101. if (foundTriggers.Any())
  102. {
  103. foreach (Dictionary<string, object> foundTrigger in foundTriggers)
  104. {
  105. ExecuteCommand(MessageType.Query, message.Sender.Nickname, message.Sender, foundTrigger);
  106. }
  107. }
  108. }
  109. }
  110. }
  111. private void HandleChannelNotice(object sender, ChannelNotice message)
  112. {
  113. if (Enabled && !Bot.IsCommand(message.Message))
  114. {
  115. string command = Bot.GetCommand(message.Message);
  116. if (!string.IsNullOrEmpty(command))
  117. {
  118. List<Dictionary<string, object>> foundTriggers = GetTrigger(message.Sender, null, message.Channel, null, command);
  119. if (foundTriggers.Any())
  120. {
  121. foreach (Dictionary<string, object> foundTrigger in foundTriggers)
  122. {
  123. ExecuteCommand(MessageType.Notice, message.Channel, message.Sender, foundTrigger);
  124. }
  125. }
  126. }
  127. }
  128. }
  129. private void HandlePrivateNotice(object sender, PrivateNotice message)
  130. {
  131. if (Enabled && !Bot.IsCommand(message.Message))
  132. {
  133. string command = Bot.GetCommand(message.Message);
  134. if (!string.IsNullOrEmpty(command))
  135. {
  136. List<Dictionary<string, object>> foundTriggers = GetTrigger(message.Sender, null, null, message.Sender.Nickname, command);
  137. if (foundTriggers.Any())
  138. {
  139. foreach (Dictionary<string, object> foundTrigger in foundTriggers)
  140. {
  141. ExecuteCommand(MessageType.Notice, message.Sender.Nickname, message.Sender, foundTrigger);
  142. }
  143. }
  144. }
  145. }
  146. }
  147. /* Returns the parsed ID field if valid, otherwise returns 0 */
  148. private int HasValidCommandID(CommandMessage command)
  149. {
  150. int num = 0;
  151. int ret = 0;
  152. List<Dictionary<string, object>> foundTriggers = GetTrigger(command.Nick, "Self", string.Empty, string.Empty, null, true);
  153. if (int.TryParse(command.Arguments["ID"], out num))
  154. {
  155. if (foundTriggers.Count >= num && num > 0)
  156. {
  157. ret = num;
  158. }
  159. }
  160. return ret;
  161. }
  162. private void AddCommand(CommandMessage command, string type, string permission, string channels, string nicknames, string trigger, string response)
  163. {
  164. if (!Bot.IsCommand(trigger))
  165. {
  166. int maxTriggers = Convert.ToInt32(GetOptionValue("Max Commands"));
  167. List<Dictionary<string, object>> currentCommands = GetTrigger(command.Nick, "Self", string.Empty, string.Empty, null, true);
  168. if (currentCommands.Count < maxTriggers)
  169. {
  170. List<Dictionary<string, object>> foundTriggers = GetTrigger(command.Nick, null, channels, nicknames, trigger, false);
  171. if (!foundTriggers.Any())
  172. {
  173. AddNick(command.Nick);
  174. string query = "INSERT INTO `customcommands` SET " +
  175. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  176. "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `servers`.`id` = `nicks`.`server_id` WHERE `servers`.`name` = {1} && `nicks`.`nickname` = {2}), " +
  177. "`type` = {3}, " +
  178. "`permission` = {4}, " +
  179. "`channels` = {5}, " +
  180. "`nicknames` = {6}, " +
  181. "`trigger` = {7}, " +
  182. "`response` = {8}, " +
  183. "`date_added` = {9}";
  184. Bot.Database.Execute(query, new object[] {Bot.ServerConfig.Name, Bot.ServerConfig.Name, command.Nick.Nickname, type, permission, channels, nicknames, trigger, response, command.TimeStamp});
  185. string message = string.Format("You now have \u0002{0}\u0002 custom commands set.", currentCommands.Count + 1);
  186. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, message);
  187. }
  188. else
  189. {
  190. string errorMessage = string.Format("\u0002{0}\u0002 is already set as a command you can access.", trigger);
  191. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  192. }
  193. }
  194. else
  195. {
  196. string errorMessage = string.Format("You can not have more than \u0002{0}\u0002 custom commands set. Please delete one before adding another.", maxTriggers);
  197. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  198. }
  199. }
  200. else
  201. {
  202. string errorMessage = string.Format("There is already a command for \u0002{0}\u0002.", trigger);
  203. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  204. }
  205. }
  206. private void DeleteCommand(CommandMessage command)
  207. {
  208. List<Dictionary<string, object>> foundTriggers = GetTrigger(command.Nick, "Self", string.Empty, string.Empty, null, true);
  209. int triggerIndex = HasValidCommandID(command);
  210. if (triggerIndex > 0)
  211. {
  212. string query = "DELETE FROM `customcommands` " +
  213. "WHERE `id` = {0}";
  214. Bot.Database.Execute(query, new object[] { foundTriggers[triggerIndex - 1]["id"] });
  215. string message = string.Format("Command \u0002{0}\u0002 has been deleted.", triggerIndex);
  216. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, message);
  217. }
  218. else
  219. {
  220. string errorMessage = string.Format("\u0002{0}\u0002 is not a valid command number.", command.Arguments["ID"]);
  221. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  222. }
  223. }
  224. private void EditCommand(CommandMessage command, string type, string permission, string channels, string nicknames, string trigger, string response)
  225. {
  226. List<Dictionary<string, object>> foundTriggers = GetTrigger(command.Nick, "Self", string.Empty, string.Empty, null, true);
  227. int triggerIndex = HasValidCommandID(command);
  228. if (triggerIndex > 0)
  229. {
  230. string query = "UPDATE `customcommands` SET " +
  231. "`type` = {0}, " +
  232. "`permission` = {1}, " +
  233. "`channels` = {2}, " +
  234. "`nicknames` = {3}, " +
  235. "`trigger` = {4}, " +
  236. "`response` = {5} " +
  237. "WHERE `id` = {6}";
  238. Bot.Database.Execute(query, new object[] { type, permission, channels, nicknames, trigger, response, foundTriggers[triggerIndex - 1]["id"] });
  239. string message = string.Format("\u0002{0}\u0002 now has the response: {1}", trigger, response);
  240. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, message);
  241. }
  242. else
  243. {
  244. string errorMessage = string.Format("\u0002{0}\u0002 is not a valid command number.", command.Arguments["ID"]);
  245. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  246. }
  247. }
  248. private void ViewTriggers(CommandMessage command)
  249. {
  250. List<Dictionary<string, object>> foundTriggers = GetTrigger(command.Nick, "Self", string.Empty, string.Empty, null, true);
  251. if (foundTriggers.Any())
  252. {
  253. int index = 1;
  254. foreach (Dictionary<string, object> foundTrigger in foundTriggers)
  255. {
  256. string allowed = string.Empty;
  257. switch (foundTrigger["permission"].ToString().ToLower())
  258. {
  259. case "channels":
  260. allowed = " " + foundTrigger["channels"];
  261. break;
  262. case "nicks":
  263. allowed = " " + foundTrigger["nicknames"];
  264. break;
  265. }
  266. string response = string.Format("Command #{0} [{1}{2}] \u0002{3}{4}\u0002: {5}", index, foundTrigger["permission"], allowed, Bot.ServerConfig.CommandPrefix, foundTrigger["trigger"], foundTrigger["response"]);
  267. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, response, true);
  268. index++;
  269. }
  270. }
  271. else
  272. {
  273. string errorMessage = "There are no custom commands for you.";
  274. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  275. }
  276. }
  277. private void ViewTrigger(CommandMessage command, string trigger)
  278. {
  279. List<Dictionary<string, object>> foundTriggers = GetTrigger(command.Nick, null, command.Location, command.Nick.Nickname, trigger);
  280. if (foundTriggers.Any())
  281. {
  282. foreach (Dictionary<string, object> foundTrigger in foundTriggers)
  283. {
  284. string allowed = string.Empty;
  285. switch (foundTrigger["permission"].ToString().ToLower())
  286. {
  287. case "channels":
  288. allowed = " " + foundTrigger["channels"];
  289. break;
  290. case "nicks":
  291. allowed = " " + foundTrigger["nicknames"];
  292. break;
  293. }
  294. string response = string.Format("[{0}{1}] \u0002{2}{3}\u0002: {4}", foundTrigger["permission"], allowed, Bot.ServerConfig.CommandPrefix, foundTrigger["trigger"], foundTrigger["response"]);
  295. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, response, true);
  296. }
  297. }
  298. else
  299. {
  300. string errorMessage = string.Format("\u0002{0}\u0002 is not set as a custom command for that search.", trigger);
  301. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, errorMessage, true);
  302. }
  303. }
  304. private List<Dictionary<string, object>> GetTrigger(Nick caller, string permission, string channels, string nicknames, string trigger = null, bool edit = false)
  305. {
  306. string search = "SELECT * FROM `customcommands`" +
  307. " WHERE" +
  308. " `server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0})";
  309. int argCount = 1;
  310. List<object> arguments = new List<object>();
  311. arguments.Add(Bot.ServerConfig.Name);
  312. if (!string.IsNullOrEmpty(trigger))
  313. {
  314. search += " AND `trigger` = {" + argCount++ + "}";
  315. arguments.Add(trigger);
  316. }
  317. search += " AND ";
  318. string combine = "AND";
  319. if (string.IsNullOrEmpty(permission))
  320. {
  321. search += "(";
  322. combine = "OR";
  323. }
  324. if (!string.IsNullOrEmpty(channels) && (string.IsNullOrEmpty(permission) || permission.ToLower() == "channels"))
  325. {
  326. Regex channelRegex = new Regex(@"(?<Prefix>[\#]+)?(?<Prefix>[\&]+)?(?<Channel>[^\#|^\&|^,]+)");
  327. MatchCollection matches = channelRegex.Matches(channels);
  328. if (matches.Count > 0)
  329. {
  330. search += "(";
  331. foreach (Match match in matches)
  332. {
  333. if (match.Success)
  334. {
  335. search += "`channels` REGEXP {" + argCount++ + "} OR ";
  336. arguments.Add(string.Format(@"{0}[[:<:]]{1}[[:>:]]", string.Join(@"\\", match.Groups["Prefix"].ToString().ToCharArray()), match.Groups["Channel"]));
  337. }
  338. }
  339. search += "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `servers`.`id` = `nicks`.`server_id` WHERE `servers`.`name` = {" + argCount++ + "} && `nickname` = {" + argCount++ + "})";
  340. search += (edit) ? ")" : " OR `permission` = 'all')";
  341. arguments.Add(Bot.ServerConfig.Name);
  342. arguments.Add(caller.Nickname);
  343. }
  344. }
  345. if (!string.IsNullOrEmpty(nicknames) && (string.IsNullOrEmpty(permission) || permission.ToLower() == "nicks"))
  346. {
  347. if (!string.IsNullOrEmpty(channels) && string.IsNullOrEmpty(permission))
  348. search += " " + combine + " ";
  349. Regex nickRegex = new Regex(@"(?<Nickname>[^,]+)");
  350. MatchCollection matches = nickRegex.Matches(nicknames);
  351. if (matches.Count > 0)
  352. {
  353. search += "(";
  354. foreach (Match match in matches)
  355. {
  356. if (match.Success)
  357. {
  358. search += "`nicknames` REGEXP {" + argCount++ + "} OR ";
  359. arguments.Add(string.Format(@"[[:<:]]{0}[[:>:]]", match.Groups["Nickname"]));
  360. }
  361. }
  362. search += "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `servers`.`id` = `nicks`.`server_id` WHERE `servers`.`name` = {" + argCount++ + "} && `nickname` = {" + argCount++ + "})";
  363. search += (edit) ? ")" : " OR `permission` = 'all')";
  364. arguments.Add(Bot.ServerConfig.Name);
  365. arguments.Add(caller.Nickname);
  366. }
  367. }
  368. if (string.IsNullOrEmpty(permission) || permission.ToLower() == "self")
  369. {
  370. if (!string.IsNullOrEmpty(channels) || !string.IsNullOrEmpty(nicknames))
  371. search += " " + combine + " ";
  372. search += "(`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `servers`.`id` = `nicks`.`server_id` WHERE `servers`.`name` = {" + argCount++ + "} && `nickname` = {" + argCount++ + "})";
  373. search += (edit) ? ")" : " OR `permission` = 'all')";
  374. arguments.Add(Bot.ServerConfig.Name);
  375. arguments.Add(caller.Nickname);
  376. }
  377. if (string.IsNullOrEmpty(permission))
  378. {
  379. search += ")";
  380. }
  381. return Bot.Database.Query(search, arguments.ToArray());
  382. }
  383. private void ExecuteCommand(MessageType messageType, string location, Nick nick, Dictionary<string, object> trigger)
  384. {
  385. string type = trigger["type"].ToString();
  386. string message = trigger["response"].ToString();
  387. switch (type.ToLower())
  388. {
  389. case "response":
  390. message = "\u200B" + message;
  391. SendResponse(messageType, location, nick.Nickname, message);
  392. break;
  393. case "command":
  394. Bot.ExecuteCommand(Bot.ServerConfig.CommandPrefix + message, location, messageType, nick);
  395. break;
  396. case "list":
  397. // todo handle list commands
  398. break;
  399. }
  400. }
  401. }
  402. }