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

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