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 35KB

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