The easy to use and full featured Irc Bot everyone is talking about!
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. public void ExecuteCommand(string message, string location, MessageType type)
  199. {
  200. ParseCommandMessage(DateTime.Now, message, new Nick { Nickname = IRC.Nickname }, location, type);
  201. }
  202. private void HandleConnectEvent()
  203. {
  204. Connected = true;
  205. }
  206. private void HandleDisconnectEvent()
  207. {
  208. Connected = false;
  209. }
  210. private void HandleJoinEvent(object sender, JoinChannelInfo info)
  211. {
  212. if (info.Nick.Nickname == IRC.Nickname)
  213. {
  214. if (!ServerConfig.Channels.Exists(chan => chan.Name == info.Channel))
  215. {
  216. ChannelConfig chanConfig = new ChannelConfig();
  217. chanConfig.Name = info.Channel;
  218. ServerConfig.Channels.Add(chanConfig);
  219. ServerConfig.Save();
  220. }
  221. }
  222. }
  223. private void HandleKickEvent(object sender, KickInfo info)
  224. {
  225. if (info.KickedNick.Nickname == IRC.Nickname)
  226. {
  227. ServerConfig.Channels.RemoveAll(chan => chan.Name == info.Channel);
  228. ServerConfig.Save();
  229. }
  230. }
  231. private void HandleChannelModeChangeEvent(object sender, ChannelModeChangeInfo e)
  232. {
  233. ChannelConfig channel = ServerConfig.Channels.Find(chan => chan.Name == e.Channel);
  234. if (channel != null)
  235. {
  236. foreach (ChannelModeInfo mode in e.Modes)
  237. {
  238. switch (mode.Mode)
  239. {
  240. case ChannelMode.k:
  241. if (mode.Set)
  242. {
  243. channel.Key = mode.Parameter;
  244. }
  245. else
  246. {
  247. channel.Key = string.Empty;
  248. }
  249. ServerConfig.Save();
  250. break;
  251. }
  252. }
  253. }
  254. }
  255. private void HandleReplyEvent(object sender, IReply e)
  256. {
  257. if (e.GetType() == typeof(ServerReplyMessage))
  258. {
  259. ServerReplyMessage reply = (ServerReplyMessage)e;
  260. switch (reply.ReplyCode)
  261. {
  262. case IRCReplyCode.RPL_WELCOME:
  263. // If the reply is Welcome, that means we are fully connected to the server.
  264. LoggedIn = true;
  265. if (!GhostSent && IRC.Nickname != ServerConfig.Nicknames[CurNickChoice])
  266. {
  267. IRC.SendPrivateMessage("NickServ", string.Format("GHOST {0} {1}", ServerConfig.Nicknames[CurNickChoice], ServerConfig.Password));
  268. Thread.Sleep(1000);
  269. IRC.SendNick(ServerConfig.Nicknames[CurNickChoice]);
  270. GhostSent = true;
  271. }
  272. // Identify to NickServ if need be
  273. IRC.SendPrivateMessage("NickServ", string.Format("IDENTIFY {0}", ServerConfig.Password));
  274. // Join all required channels
  275. // Delay joining channels for configured time
  276. Thread.Sleep(ServerConfig.JoinDelay);
  277. foreach (ChannelConfig channel in ServerConfig.Channels)
  278. {
  279. IRC.SendJoin(channel.Name, channel.Key);
  280. }
  281. break;
  282. }
  283. }
  284. else if (e.GetType() == typeof(ServerErrorMessage))
  285. {
  286. ServerErrorMessage error = (ServerErrorMessage) e;
  287. switch (error.ErrorCode)
  288. {
  289. case IRCErrorCode.ERR_NOTREGISTERED:
  290. if (ServerConfig.AutoRegister && ServerConfig.Password != string.Empty && ServerConfig.Email != string.Empty)
  291. {
  292. IRC.SendPrivateMessage("NickServ", string.Format("REGISTER {0} {1}", ServerConfig.Password, ServerConfig.Email));
  293. }
  294. break;
  295. case IRCErrorCode.ERR_NICKNAMEINUSE:
  296. if (LoggedIn == false)
  297. {
  298. string nick = string.Empty;
  299. if (IRC.Nickname == ServerConfig.Nicknames[CurNickChoice] && ServerConfig.Nicknames.Count > CurNickChoice + 1)
  300. {
  301. CurNickChoice++;
  302. nick = ServerConfig.Nicknames[CurNickChoice];
  303. }
  304. else
  305. {
  306. Random rand = new Random();
  307. nick = string.Format("{0}_{1}", ServerConfig.Nicknames.First(), rand.Next(100000).ToString());
  308. }
  309. IRC.Login(ServerConfig.Name, new Nick()
  310. {
  311. Nickname = nick,
  312. Host = Dns.GetHostName(),
  313. Realname = ServerConfig.Realname,
  314. Username = ServerConfig.Username
  315. });
  316. }
  317. break;
  318. }
  319. }
  320. }
  321. private void HandleChannelMessageReceivedEvent(object sender, ChannelMessage e)
  322. {
  323. // The message was a command
  324. if (e.Message.StartsWith(ServerConfig.CommandPrefix))
  325. {
  326. if (!ServerConfig.ChannelBlacklist.Contains(e.Channel)
  327. && !ServerConfig.NickBlacklist.Contains(e.Sender.Nickname)
  328. )
  329. {
  330. ParseCommandMessage(e.TimeStamp, e.Message, e.Sender, e.Channel, MessageType.Channel);
  331. }
  332. }
  333. }
  334. private void HandlePrivateMessageReceivedEvent(object sender, PrivateMessage e)
  335. {
  336. // The message was a command
  337. if (e.Message.StartsWith(ServerConfig.CommandPrefix))
  338. {
  339. if (!ServerConfig.NickBlacklist.Contains(e.Sender.Nickname))
  340. {
  341. ParseCommandMessage(e.TimeStamp, e.Message, e.Sender, e.Sender.Nickname, MessageType.Query);
  342. }
  343. }
  344. }
  345. private void HandlePrivateNoticeReceivedEvent(object sender, PrivateNotice e)
  346. {
  347. // The notice was a command
  348. if (e.Message.StartsWith(ServerConfig.CommandPrefix))
  349. {
  350. if (!ServerConfig.NickBlacklist.Contains(e.Sender.Nickname))
  351. {
  352. ParseCommandMessage(e.TimeStamp, e.Message, e.Sender, e.Sender.Nickname, MessageType.Notice);
  353. }
  354. }
  355. }
  356. private void ParseCommandMessage(DateTime timestamp, string message, Nick sender, string location, MessageType messageType)
  357. {
  358. // Extract command and arguments
  359. string[] msgArgs = message.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
  360. string command = msgArgs[0].Remove(0, ServerConfig.CommandPrefix.Length);
  361. List<string> argsOnly = msgArgs.ToList();
  362. argsOnly.RemoveAt(0);
  363. // Find the module that contains the command
  364. Module module = Modules.Find(mod => mod.Commands.Exists(c => c.Triggers.Contains(command)) && mod.Loaded);
  365. if (module != null)
  366. {
  367. // Find the command
  368. Command cmd = module.Commands.Find(c => c.Triggers.Contains(command));
  369. if (cmd != null)
  370. {
  371. CommandMessage newCommand = new CommandMessage();
  372. newCommand.Nick.Copy(sender);
  373. bool nickFound = false;
  374. IRC.Channels.ForEach(channel => channel.Nicks.ForEach(nick =>
  375. {
  376. if (nick.Nickname == newCommand.Nick.Nickname)
  377. {
  378. nickFound = true;
  379. newCommand.Nick.AddModes(nick.Modes);
  380. newCommand.Nick.AddPrivileges(nick.Privileges);
  381. }
  382. }));
  383. // Nickname has not been found, so need to run a query for nick's modes
  384. if (!nickFound)
  385. {
  386. string whoStyle = string.Format(@"[^\s]+\s[^\s]+\s[^\s]+\s[^\s]+\s({0})\s(?<Modes>[^\s]+)\s:[\d]\s(.+)", newCommand.Nick.Nickname);
  387. Regex whoRegex = new Regex(whoStyle);
  388. IRC.SendWho(newCommand.Nick.Nickname);
  389. ServerReplyMessage whoReply = IRC.Message.GetServerReply(IRCReplyCode.RPL_WHOREPLY, whoStyle);
  390. if (whoReply.ReplyCode != 0)
  391. {
  392. Match whoMatch = whoRegex.Match(whoReply.Message);
  393. List<UserModeInfo> modeInfoList = IRC.ParseUserModeString(whoMatch.Groups["Modes"].ToString());
  394. modeInfoList.ForEach(info =>
  395. {
  396. if (info.Set)
  397. {
  398. newCommand.Nick.AddMode(info.Mode);
  399. }
  400. });
  401. }
  402. }
  403. newCommand.TimeStamp = timestamp;
  404. newCommand.Location = location;
  405. newCommand.MessageType = messageType;
  406. newCommand.Command = command;
  407. // Check arguments against required arguments
  408. List<string> usedArgs = new List<string>();
  409. if (argsOnly.Any())
  410. {
  411. usedArgs.AddRange(argsOnly.First().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList());
  412. }
  413. List<CommandArgument> validArguments = cmd.GetValidArguments(usedArgs, messageType);
  414. if (argsOnly.Count > 0)
  415. {
  416. string[] argSplit = argsOnly.First().Split(new[] { ' ' }, validArguments.Count, StringSplitOptions.RemoveEmptyEntries);
  417. for (int i = 0; i < validArguments.Count && i <= argSplit.GetUpperBound(0); i++)
  418. {
  419. newCommand.Arguments.Add(validArguments[i].Name, argSplit[i]);
  420. }
  421. }
  422. bool invalidArgs = false;
  423. for (int i = 0; i < newCommand.Arguments.Count; i++)
  424. {
  425. if (validArguments[i].AllowedValues.Count > 0)
  426. {
  427. // Check to see if any of the arguments are invalid
  428. string argVal = newCommand.Arguments[validArguments[i].Name];
  429. if (!validArguments[i].AllowedValues.Exists(val => val.ToLower() == argVal.ToLower()))
  430. {
  431. invalidArgs = true;
  432. 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));
  433. switch (messageType)
  434. {
  435. case MessageType.Channel:
  436. case MessageType.Query:
  437. IRC.SendPrivateMessage(location, invalidMessage);
  438. break;
  439. case MessageType.Notice:
  440. IRC.SendNotice(location, invalidMessage);
  441. break;
  442. }
  443. break;
  444. }
  445. }
  446. }
  447. if (validArguments.FindAll(arg => arg.Required).Count <= newCommand.Arguments.Count)
  448. {
  449. if (!invalidArgs)
  450. {
  451. if (CommandReceivedEvent != null)
  452. {
  453. CommandReceivedEvent(newCommand);
  454. }
  455. }
  456. }
  457. else
  458. {
  459. 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)));
  460. if (messageType == MessageType.Channel || messageType == MessageType.Query)
  461. {
  462. IRC.SendPrivateMessage(location, missingArgument);
  463. }
  464. else if (messageType == MessageType.Notice)
  465. {
  466. IRC.SendNotice(location, missingArgument);
  467. }
  468. }
  469. }
  470. }
  471. }
  472. }
  473. }