The easy to use and full featured Irc Bot everyone is talking about!
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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