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

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