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.

Bot.cs 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Combot.IRCServices;
  11. using Combot.Configurations;
  12. using Combot.Databases;
  13. using Combot.IRCServices.Messaging;
  14. using Combot.Modules;
  15. namespace Combot
  16. {
  17. public class Bot
  18. {
  19. public event Action<CommandMessage> CommandReceivedEvent;
  20. public event Action<BotError> ErrorEvent;
  21. public ServerConfig ServerConfig;
  22. public IRC IRC;
  23. public Database Database;
  24. public List<Module> Modules;
  25. public bool Connected = false;
  26. public bool LoggedIn = false;
  27. public DateTime ConnectionTime;
  28. public DateTime LoadTime;
  29. public Dictionary<PrivilegeMode, AccessType> PrivilegeModeMapping = new Dictionary<PrivilegeMode, AccessType>() { { PrivilegeMode.v, AccessType.Voice }, { PrivilegeMode.h, AccessType.HalfOperator }, { PrivilegeMode.o, AccessType.Operator }, { PrivilegeMode.a, AccessType.SuperOperator }, { PrivilegeMode.q, AccessType.Founder } };
  30. public Dictionary<ChannelMode, AccessType> ChannelModeMapping = new Dictionary<ChannelMode, AccessType>() { { ChannelMode.v, AccessType.Voice }, { ChannelMode.h, AccessType.HalfOperator }, { ChannelMode.o, AccessType.Operator }, { ChannelMode.a, AccessType.SuperOperator }, { ChannelMode.q, AccessType.Founder } };
  31. private bool GhostSent;
  32. private int CurNickChoice;
  33. private int RetryCount;
  34. private bool RetryAllowed;
  35. public Bot(ServerConfig serverConfig)
  36. {
  37. Modules = new List<Module>();
  38. GhostSent = false;
  39. CurNickChoice = 0;
  40. RetryCount = 0;
  41. ServerConfig = serverConfig;
  42. LoadTime = DateTime.Now;
  43. ConnectionTime = DateTime.Now;
  44. IRC = new IRC(serverConfig.MaxMessageLength, serverConfig.MessageSendDelay);
  45. IRC.ConnectEvent += HandleConnectEvent;
  46. IRC.DisconnectEvent += HandleDisconnectEvent;
  47. IRC.Message.ServerReplyEvent += HandleReplyEvent;
  48. IRC.Message.ChannelMessageReceivedEvent += HandleChannelMessageReceivedEvent;
  49. IRC.Message.PrivateMessageReceivedEvent += HandlePrivateMessageReceivedEvent;
  50. IRC.Message.PrivateNoticeReceivedEvent += HandlePrivateNoticeReceivedEvent;
  51. IRC.Message.JoinChannelEvent += HandleJoinEvent;
  52. IRC.Message.KickEvent += HandleKickEvent;
  53. IRC.Message.ChannelModeChangeEvent += HandleChannelModeChangeEvent;
  54. Database = new Database(serverConfig.Database);
  55. Database.MysqlErrorEvent += HandleMysqlErrorEvent;
  56. LoadModules();
  57. }
  58. /// <summary>
  59. /// Trys to connect to one of the IPs of the given hostname. If the connection was successful, it will login the nick.
  60. /// </summary>
  61. public void Connect()
  62. {
  63. ConnectionTime = DateTime.Now;
  64. GhostSent = false;
  65. CurNickChoice = 0;
  66. RetryAllowed = ServerConfig.Reconnect;
  67. bool serverConnected = false;
  68. int i = 0;
  69. do
  70. {
  71. if (ServerConfig.Hosts.Count > i)
  72. {
  73. try
  74. {
  75. IPAddress[] ipList = Dns.GetHostAddresses(ServerConfig.Hosts[i].Host);
  76. foreach (IPAddress ip in ipList)
  77. {
  78. serverConnected = IRC.Connect(ip, ServerConfig.Hosts[i].Port);
  79. if (serverConnected)
  80. {
  81. break;
  82. }
  83. }
  84. i++;
  85. }
  86. catch (SocketException ex)
  87. {
  88. break;
  89. }
  90. }
  91. else
  92. {
  93. break;
  94. }
  95. }
  96. while (!serverConnected);
  97. if (serverConnected)
  98. {
  99. if (CurNickChoice < ServerConfig.Nicknames.Count)
  100. {
  101. IRC.Login(ServerConfig.Name, new Nick()
  102. {
  103. Nickname = ServerConfig.Nicknames[CurNickChoice],
  104. Host = Dns.GetHostName(),
  105. Realname = ServerConfig.Realname,
  106. Username = ServerConfig.Username
  107. });
  108. }
  109. else
  110. {
  111. Disconnect();
  112. }
  113. }
  114. else
  115. {
  116. Reconnect();
  117. }
  118. }
  119. /// <summary>
  120. /// Disconnects from the current server.
  121. /// </summary>
  122. public void Disconnect()
  123. {
  124. RetryAllowed = false;
  125. RetryCount = 0;
  126. IRC.Disconnect();
  127. Connected = false;
  128. LoggedIn = false;
  129. }
  130. private void Reconnect()
  131. {
  132. if (RetryAllowed)
  133. {
  134. if (ErrorEvent != null)
  135. {
  136. ErrorEvent(new BotError() { Message = string.Format("Retrying connection in {0} seconds.", (int)Math.Pow(2, RetryCount)), Type = ErrorType.IRC });
  137. }
  138. Task.Run(() =>
  139. {
  140. Thread.Sleep(1000 * (int)Math.Pow(2, RetryCount));
  141. RetryCount++;
  142. Connect();
  143. });
  144. }
  145. }
  146. private void HandleConnectEvent()
  147. {
  148. Connected = true;
  149. RetryCount = 0;
  150. }
  151. private void HandleDisconnectEvent()
  152. {
  153. Connected = false;
  154. Reconnect();
  155. }
  156. public void LoadModules()
  157. {
  158. // Get all config files from Module directory
  159. string[] moduleLocations = Directory.GetDirectories(ServerConfig.ModuleLocation);
  160. foreach (string location in moduleLocations)
  161. {
  162. LoadModule(location);
  163. }
  164. }
  165. public bool LoadModule(string module)
  166. {
  167. Module newModule = new Module();
  168. newModule.ConfigPath = module;
  169. newModule.LoadConfig();
  170. if (newModule.Enabled && !Modules.Exists(mod => mod.ClassName == newModule.ClassName))
  171. {
  172. if (File.Exists(string.Format(@"{0}\{1}.dll", module, newModule.Name)))
  173. {
  174. Module loadedModule = newModule.CreateInstance(this);
  175. if (loadedModule.Loaded)
  176. {
  177. loadedModule.ModuleErrorEvent += HandleModuleErrorEvent;
  178. Modules.Add(loadedModule);
  179. return true;
  180. }
  181. }
  182. }
  183. return false;
  184. }
  185. public void UnloadModules()
  186. {
  187. List<Module> moduleList = Modules;
  188. for (int i = 0; i < moduleList.Count; i++)
  189. {
  190. UnloadModule(moduleList[i].Name);
  191. }
  192. }
  193. public bool UnloadModule(string moduleName)
  194. {
  195. Module module = Modules.Find(mod => mod.Name.ToLower() == moduleName.ToLower());
  196. if (module != null)
  197. {
  198. module.Loaded = false;
  199. Modules.Remove(module);
  200. return true;
  201. }
  202. return false;
  203. }
  204. public bool CheckChannelAccess(string channel, string nickname, AccessType access)
  205. {
  206. if (nickname == IRC.Nickname)
  207. {
  208. return true;
  209. }
  210. Channel foundChannel = IRC.Channels.Find(chan => chan.Name == channel);
  211. if (foundChannel != null)
  212. {
  213. Nick foundNick = foundChannel.Nicks.Find(nick => nick.Nickname == nickname);
  214. if (foundNick != null && ServerConfig.Owners.Contains(nickname) && foundNick.Modes.Contains(UserMode.r))
  215. {
  216. return true;
  217. }
  218. if (foundNick != null)
  219. {
  220. for (int i = 0; i < foundNick.Privileges.Count; i++)
  221. {
  222. switch (PrivilegeModeMapping[foundNick.Privileges[i]])
  223. {
  224. case AccessType.User:
  225. if (access == AccessType.User)
  226. {
  227. return true;
  228. }
  229. break;
  230. case AccessType.Voice:
  231. if (access == AccessType.User || access == AccessType.Voice)
  232. {
  233. return true;
  234. }
  235. break;
  236. case AccessType.HalfOperator:
  237. if (access == AccessType.User || access == AccessType.Voice || access == AccessType.HalfOperator)
  238. {
  239. return true;
  240. }
  241. break;
  242. case AccessType.Operator:
  243. if (access == AccessType.User || access == AccessType.Voice || access == AccessType.HalfOperator || access == AccessType.Operator)
  244. {
  245. return true;
  246. }
  247. break;
  248. case AccessType.SuperOperator:
  249. if (access == AccessType.User || access == AccessType.Voice || access == AccessType.HalfOperator || access == AccessType.Operator || access == AccessType.SuperOperator)
  250. {
  251. return true;
  252. }
  253. break;
  254. case AccessType.Founder:
  255. if (access == AccessType.User || access == AccessType.Voice || access == AccessType.HalfOperator || access == AccessType.Operator || access == AccessType.SuperOperator || access == AccessType.Founder)
  256. {
  257. return true;
  258. }
  259. break;
  260. case AccessType.Owner:
  261. return true;
  262. break;
  263. }
  264. }
  265. }
  266. }
  267. return false;
  268. }
  269. public bool CheckChannelAccess(string channel, string nickname, List<AccessType> access)
  270. {
  271. bool hasAccess = false;
  272. for (int i = 0; i < access.Count; i++)
  273. {
  274. hasAccess = CheckChannelAccess(channel, nickname, access[i]);
  275. if (hasAccess)
  276. {
  277. break;
  278. }
  279. }
  280. return hasAccess;
  281. }
  282. /// <summary>
  283. /// Checks to see if the first nick has access to perform a command on the second nick
  284. /// </summary>
  285. /// <param name="channel">Channel the command is being applied on</param>
  286. /// <param name="firstNick">The nick applying the command</param>
  287. /// <param name="secondNick">The nick the command is being performed on</param>
  288. /// <returns></returns>
  289. public bool CheckNickAccess(string channel, string firstNick, string secondNick)
  290. {
  291. if (firstNick == IRC.Nickname)
  292. {
  293. return true;
  294. }
  295. Channel foundChannel = IRC.Channels.Find(chan => chan.Name == channel);
  296. if (foundChannel != null)
  297. {
  298. Nick foundFirstNick = foundChannel.Nicks.Find(nick => nick.Nickname == firstNick);
  299. Nick foundSecondNick = foundChannel.Nicks.Find(nick => nick.Nickname == secondNick);
  300. if (foundFirstNick != null && ServerConfig.Owners.Contains(firstNick) && foundFirstNick.Modes.Contains(UserMode.r))
  301. {
  302. return true;
  303. }
  304. if (foundFirstNick != null && foundSecondNick != null)
  305. {
  306. for (int i = 0; i < foundSecondNick.Privileges.Count; i++)
  307. {
  308. switch (foundSecondNick.Privileges[i])
  309. {
  310. case PrivilegeMode.v:
  311. if (!foundFirstNick.Privileges.Contains(PrivilegeMode.v) && !foundFirstNick.Privileges.Contains(PrivilegeMode.h) && !foundFirstNick.Privileges.Contains(PrivilegeMode.o) && !foundFirstNick.Privileges.Contains(PrivilegeMode.a) && !foundFirstNick.Privileges.Contains(PrivilegeMode.q))
  312. {
  313. return false;
  314. }
  315. break;
  316. case PrivilegeMode.h:
  317. if (!foundFirstNick.Privileges.Contains(PrivilegeMode.h) && !foundFirstNick.Privileges.Contains(PrivilegeMode.o) && !foundFirstNick.Privileges.Contains(PrivilegeMode.a) && !foundFirstNick.Privileges.Contains(PrivilegeMode.q))
  318. {
  319. return false;
  320. }
  321. break;
  322. case PrivilegeMode.o:
  323. if (!foundFirstNick.Privileges.Contains(PrivilegeMode.o) && !foundFirstNick.Privileges.Contains(PrivilegeMode.a) && !foundFirstNick.Privileges.Contains(PrivilegeMode.q))
  324. {
  325. return false;
  326. }
  327. break;
  328. case PrivilegeMode.a:
  329. if (!foundFirstNick.Privileges.Contains(PrivilegeMode.a) && !foundFirstNick.Privileges.Contains(PrivilegeMode.q))
  330. {
  331. return false;
  332. }
  333. break;
  334. case PrivilegeMode.q:
  335. if (!foundFirstNick.Privileges.Contains(PrivilegeMode.q))
  336. {
  337. return false;
  338. }
  339. break;
  340. }
  341. }
  342. }
  343. else
  344. {
  345. return false;
  346. }
  347. }
  348. else
  349. {
  350. return false;
  351. }
  352. return true;
  353. }
  354. public void ExecuteCommand(string message, string location, MessageType type)
  355. {
  356. ParseCommandMessage(DateTime.Now, message, new Nick { Nickname = IRC.Nickname }, location, type);
  357. }
  358. public bool IsCommand(string message)
  359. {
  360. bool isCommand = false;
  361. string[] msgArgs = message.Split(new[] {' '}, 2, StringSplitOptions.RemoveEmptyEntries);
  362. if (msgArgs.Any())
  363. {
  364. string command = msgArgs[0].Remove(0, ServerConfig.CommandPrefix.Length);
  365. // Find the module that contains the command
  366. Module module = Modules.Find(mod => mod.Commands.Exists(c => c.Triggers.Contains(command)) && mod.Loaded && mod.Enabled);
  367. if (module != null)
  368. {
  369. // Find the command
  370. Command cmd = module.Commands.Find(c => c.Triggers.Contains(command));
  371. if (cmd != null)
  372. {
  373. isCommand = true;
  374. }
  375. }
  376. }
  377. return isCommand;
  378. }
  379. private void HandleJoinEvent(object sender, JoinChannelInfo info)
  380. {
  381. if (info.Nick.Nickname == IRC.Nickname)
  382. {
  383. if (!ServerConfig.Channels.Exists(chan => chan.Name == info.Channel))
  384. {
  385. ChannelConfig chanConfig = new ChannelConfig();
  386. chanConfig.Name = info.Channel;
  387. ServerConfig.Channels.Add(chanConfig);
  388. ServerConfig.Save();
  389. }
  390. }
  391. }
  392. private void HandleKickEvent(object sender, KickInfo info)
  393. {
  394. if (info.KickedNick.Nickname == IRC.Nickname)
  395. {
  396. ServerConfig.Channels.RemoveAll(chan => chan.Name == info.Channel);
  397. ServerConfig.Save();
  398. }
  399. }
  400. private void HandleChannelModeChangeEvent(object sender, ChannelModeChangeInfo e)
  401. {
  402. ChannelConfig channel = ServerConfig.Channels.Find(chan => chan.Name == e.Channel);
  403. if (channel != null)
  404. {
  405. foreach (ChannelModeInfo mode in e.Modes)
  406. {
  407. switch (mode.Mode)
  408. {
  409. case ChannelMode.k:
  410. if (mode.Set)
  411. {
  412. channel.Key = mode.Parameter;
  413. }
  414. else
  415. {
  416. channel.Key = string.Empty;
  417. }
  418. ServerConfig.Save();
  419. break;
  420. }
  421. }
  422. }
  423. }
  424. private void HandleReplyEvent(object sender, IReply e)
  425. {
  426. if (e.GetType() == typeof(ServerReplyMessage))
  427. {
  428. ServerReplyMessage reply = (ServerReplyMessage)e;
  429. switch (reply.ReplyCode)
  430. {
  431. case IRCReplyCode.RPL_WELCOME:
  432. // If the reply is Welcome, that means we are fully connected to the server.
  433. LoggedIn = true;
  434. if (!GhostSent && IRC.Nickname != ServerConfig.Nicknames[CurNickChoice])
  435. {
  436. IRC.Command.SendPrivateMessage("NickServ", string.Format("GHOST {0} {1}", ServerConfig.Nicknames[CurNickChoice], ServerConfig.Password));
  437. Thread.Sleep(1000);
  438. IRC.Command.SendNick(ServerConfig.Nicknames[CurNickChoice]);
  439. GhostSent = true;
  440. }
  441. // Identify to NickServ if need be
  442. IRC.Command.SendPrivateMessage("NickServ", string.Format("IDENTIFY {0}", ServerConfig.Password));
  443. // Join all required channels
  444. // Delay joining channels for configured time
  445. Thread.Sleep(ServerConfig.JoinDelay);
  446. foreach (ChannelConfig channel in ServerConfig.Channels)
  447. {
  448. IRC.Command.SendJoin(channel.Name, channel.Key);
  449. }
  450. break;
  451. }
  452. }
  453. else if (e.GetType() == typeof(ServerErrorMessage))
  454. {
  455. ServerErrorMessage error = (ServerErrorMessage) e;
  456. switch (error.ErrorCode)
  457. {
  458. case IRCErrorCode.ERR_NOTREGISTERED:
  459. if (ServerConfig.AutoRegister && ServerConfig.Password != string.Empty && ServerConfig.Email != string.Empty)
  460. {
  461. IRC.Command.SendPrivateMessage("NickServ", string.Format("REGISTER {0} {1}", ServerConfig.Password, ServerConfig.Email));
  462. }
  463. break;
  464. case IRCErrorCode.ERR_NICKNAMEINUSE:
  465. if (LoggedIn == false)
  466. {
  467. string nick = string.Empty;
  468. if (IRC.Nickname == ServerConfig.Nicknames[CurNickChoice] && ServerConfig.Nicknames.Count > CurNickChoice + 1)
  469. {
  470. CurNickChoice++;
  471. nick = ServerConfig.Nicknames[CurNickChoice];
  472. }
  473. else
  474. {
  475. Random rand = new Random();
  476. nick = string.Format("{0}_{1}", ServerConfig.Nicknames.First(), rand.Next(100000).ToString());
  477. }
  478. IRC.Login(ServerConfig.Name, new Nick()
  479. {
  480. Nickname = nick,
  481. Host = Dns.GetHostName(),
  482. Realname = ServerConfig.Realname,
  483. Username = ServerConfig.Username
  484. });
  485. }
  486. break;
  487. }
  488. }
  489. }
  490. private void HandleChannelMessageReceivedEvent(object sender, ChannelMessage e)
  491. {
  492. // The message was a command
  493. if (e.Message.StartsWith(ServerConfig.CommandPrefix))
  494. {
  495. if (!ServerConfig.ChannelBlacklist.Contains(e.Channel)
  496. && !ServerConfig.NickBlacklist.Contains(e.Sender.Nickname)
  497. )
  498. {
  499. ParseCommandMessage(e.TimeStamp, e.Message, e.Sender, e.Channel, MessageType.Channel);
  500. }
  501. }
  502. }
  503. private void HandlePrivateMessageReceivedEvent(object sender, PrivateMessage e)
  504. {
  505. // The message was a command
  506. if (e.Message.StartsWith(ServerConfig.CommandPrefix))
  507. {
  508. if (!ServerConfig.NickBlacklist.Contains(e.Sender.Nickname))
  509. {
  510. ParseCommandMessage(e.TimeStamp, e.Message, e.Sender, e.Sender.Nickname, MessageType.Query);
  511. }
  512. }
  513. }
  514. private void HandlePrivateNoticeReceivedEvent(object sender, PrivateNotice e)
  515. {
  516. // The notice was a command
  517. if (e.Message.StartsWith(ServerConfig.CommandPrefix))
  518. {
  519. if (!ServerConfig.NickBlacklist.Contains(e.Sender.Nickname))
  520. {
  521. ParseCommandMessage(e.TimeStamp, e.Message, e.Sender, e.Sender.Nickname, MessageType.Notice);
  522. }
  523. }
  524. }
  525. private void ParseCommandMessage(DateTime timestamp, string message, Nick sender, string location, MessageType messageType)
  526. {
  527. // Extract command and arguments
  528. string[] msgArgs = message.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
  529. string command = msgArgs[0].Remove(0, ServerConfig.CommandPrefix.Length);
  530. List<string> argsOnly = msgArgs.ToList();
  531. argsOnly.RemoveAt(0);
  532. // Find the module that contains the command
  533. Module module = Modules.Find(mod => mod.Commands.Exists(c => c.Triggers.Contains(command)) && mod.Loaded && mod.Enabled);
  534. if (module != null)
  535. {
  536. // Find the command
  537. Command cmd = module.Commands.Find(c => c.Triggers.Contains(command));
  538. if (cmd != null)
  539. {
  540. CommandMessage newCommand = new CommandMessage();
  541. newCommand.Nick.Copy(sender);
  542. bool nickFound = false;
  543. IRC.Channels.ForEach(channel => channel.Nicks.ForEach(nick =>
  544. {
  545. if (nick.Nickname == newCommand.Nick.Nickname)
  546. {
  547. nickFound = true;
  548. newCommand.Nick.AddModes(nick.Modes);
  549. newCommand.Nick.AddPrivileges(nick.Privileges);
  550. }
  551. }));
  552. // Nickname has not been found, so need to run a query for nick's modes
  553. if (!nickFound)
  554. {
  555. string whoStyle = string.Format(@"[^\s]+\s[^\s]+\s[^\s]+\s[^\s]+\s({0})\s(?<Modes>[^\s]+)\s:[\d]\s(.+)", newCommand.Nick.Nickname);
  556. Regex whoRegex = new Regex(whoStyle);
  557. IRC.Command.SendWho(newCommand.Nick.Nickname);
  558. ServerReplyMessage whoReply = IRC.Message.GetServerReply(IRCReplyCode.RPL_WHOREPLY, whoStyle);
  559. if (whoReply != null && whoReply.ReplyCode != 0)
  560. {
  561. Match whoMatch = whoRegex.Match(whoReply.Message);
  562. List<UserModeInfo> modeInfoList = IRC.ParseUserModeString(whoMatch.Groups["Modes"].ToString());
  563. modeInfoList.ForEach(info =>
  564. {
  565. if (info.Set)
  566. {
  567. newCommand.Nick.AddMode(info.Mode);
  568. }
  569. });
  570. }
  571. }
  572. newCommand.TimeStamp = timestamp;
  573. newCommand.Location = location;
  574. newCommand.MessageType = messageType;
  575. newCommand.Command = command;
  576. // Check arguments against required arguments
  577. List<string> usedArgs = new List<string>();
  578. if (argsOnly.Any())
  579. {
  580. usedArgs.AddRange(argsOnly.First().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList());
  581. }
  582. List<CommandArgument> validArguments = cmd.GetValidArguments(usedArgs, messageType);
  583. if (argsOnly.Count > 0)
  584. {
  585. string[] argSplit = argsOnly.First().Split(new[] { ' ' }, validArguments.Count, StringSplitOptions.RemoveEmptyEntries);
  586. for (int i = 0; i < validArguments.Count && i <= argSplit.GetUpperBound(0); i++)
  587. {
  588. newCommand.Arguments.Add(validArguments[i].Name, argSplit[i]);
  589. }
  590. }
  591. bool invalidArgs = false;
  592. for (int i = 0; i < newCommand.Arguments.Count; i++)
  593. {
  594. if (validArguments[i].AllowedValues.Count > 0)
  595. {
  596. // Check to see if any of the arguments are invalid
  597. string argVal = newCommand.Arguments[validArguments[i].Name];
  598. if (!validArguments[i].AllowedValues.Exists(val => val.ToLower() == argVal.ToLower()))
  599. {
  600. invalidArgs = true;
  601. string argHelp = string.Format(" \u0002{0}\u0002", string.Join(" ", validArguments.Select(arg =>
  602. {
  603. string argString = string.Empty;
  604. if (arg.DependentArguments.Count > 0)
  605. {
  606. argString = "(";
  607. }
  608. if (arg.Required)
  609. {
  610. argString += "\u001F" + arg.Name + "\u001F";
  611. }
  612. else
  613. {
  614. argString += "[\u001F" + arg.Name + "\u001F]";
  615. }
  616. if (arg.DependentArguments.Count > 0)
  617. {
  618. argString += string.Format("\u0002:When {0}\u0002)", string.Join(" or ", arg.DependentArguments.Select(dep => { return string.Format("\u0002\u001F{0}\u001F\u0002=\u0002{1}\u0002", dep.Name, string.Join(",", dep.Values)); })));
  619. }
  620. return argString;
  621. })));
  622. string invalidMessage = string.Format("Invalid value for \u0002{0}\u0002 in \u0002{1}{2}\u0002{3}. Valid options are \u0002{4}\u0002.", validArguments[i].Name, ServerConfig.CommandPrefix, command, argHelp, string.Join(", ", validArguments[i].AllowedValues));
  623. module.SendResponse(messageType, location, sender.Nickname, invalidMessage);
  624. break;
  625. }
  626. }
  627. }
  628. if (validArguments.FindAll(arg => arg.Required).Count <= newCommand.Arguments.Count)
  629. {
  630. if (!invalidArgs)
  631. {
  632. if (CommandReceivedEvent != null)
  633. {
  634. CommandReceivedEvent(newCommand);
  635. }
  636. }
  637. }
  638. else
  639. {
  640. string argHelp = string.Format(" \u0002{0}\u0002", string.Join(" ", validArguments.Select(arg =>
  641. {
  642. string argString = string.Empty;
  643. if (arg.DependentArguments.Count > 0)
  644. {
  645. argString = "(";
  646. }
  647. if (arg.Required)
  648. {
  649. argString += "\u001F" + arg.Name + "\u001F";
  650. }
  651. else
  652. {
  653. argString += "[\u001F" + arg.Name + "\u001F]";
  654. }
  655. if (arg.DependentArguments.Count > 0)
  656. {
  657. argString += string.Format("\u0002:When {0}\u0002)", string.Join(" or ", arg.DependentArguments.Select(dep => { return string.Format("\u0002\u001F{0}\u001F\u0002=\u0002{1}\u0002", dep.Name, string.Join(",", dep.Values)); })));
  658. }
  659. return argString;
  660. })));
  661. string missingArgument = string.Format("Missing a required argument for \u0002{0}{1}\u0002{2}. The required arguments are \u0002{3}\u0002.", ServerConfig.CommandPrefix, command, argHelp, string.Join(", ", validArguments.Where(arg => arg.Required).Select(arg => arg.Name)));
  662. module.SendResponse(messageType, location, sender.Nickname, missingArgument);
  663. }
  664. }
  665. }
  666. }
  667. private void HandleMysqlErrorEvent(object sender, string message)
  668. {
  669. BotError error = new BotError();
  670. error.Message = message;
  671. error.Type = ErrorType.MySQL;
  672. if (ErrorEvent != null)
  673. {
  674. ErrorEvent(error);
  675. }
  676. }
  677. private void HandleModuleErrorEvent(object sender, string message)
  678. {
  679. BotError error = new BotError();
  680. error.Message = message;
  681. error.Type = ErrorType.Module;
  682. if (ErrorEvent != null)
  683. {
  684. ErrorEvent(error);
  685. }
  686. }
  687. }
  688. }