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

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