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

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