The easy to use and full featured Irc Bot everyone is talking about!
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Bot.cs 26KB

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