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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using Combot.IRCServices;
  8. using Combot.Configurations;
  9. using Combot.IRCServices.Messaging;
  10. namespace Combot
  11. {
  12. public class Bot
  13. {
  14. public event Action<BotError> ErrorEvent;
  15. public ServerConfig ServerConfig;
  16. public IRC IRC;
  17. public bool Connected = false;
  18. public Bot(ServerConfig serverConfig)
  19. {
  20. IRC = new IRC();
  21. ServerConfig = serverConfig;
  22. IRC.ConnectEvent += HandleConnectEvent;
  23. IRC.DisconnectEvent += HandleDisconnectEvent;
  24. IRC.Message.ServerReplyEvent += HandleReplyEvent;
  25. }
  26. /// <summary>
  27. /// Trys to connect to one of the IPs of the given hostname. If the connection was successful, it will login the nick.
  28. /// </summary>
  29. public void Connect()
  30. {
  31. bool serverConnected = false;
  32. int i = 0;
  33. do
  34. {
  35. if (ServerConfig.Hosts.Count > i)
  36. {
  37. IPAddress[] ipList = Dns.GetHostAddresses(ServerConfig.Hosts[i].Host);
  38. foreach (IPAddress ip in ipList)
  39. {
  40. serverConnected = IRC.Connect(ip, ServerConfig.Hosts[i].Port, 5000);
  41. if (serverConnected)
  42. {
  43. break;
  44. }
  45. }
  46. i++;
  47. }
  48. else
  49. {
  50. break;
  51. }
  52. }
  53. while (!serverConnected);
  54. if (serverConnected)
  55. {
  56. IRC.Login(ServerConfig.Name, new Nick() { Nickname = ServerConfig.Nickname, Host = Dns.GetHostName(), Realname = ServerConfig.Realname, Username = ServerConfig.Username });
  57. }
  58. }
  59. /// <summary>
  60. /// Disconnects from the current server.
  61. /// </summary>
  62. public void Disconnect()
  63. {
  64. IRC.Disconnect();
  65. Connected = false;
  66. }
  67. private void HandleConnectEvent()
  68. {
  69. Connected = true;
  70. }
  71. private void HandleDisconnectEvent()
  72. {
  73. Connected = false;
  74. }
  75. private void HandleReplyEvent(object sender, IReply e)
  76. {
  77. if (e.GetType() == typeof(ServerReplyMessage))
  78. {
  79. ServerReplyMessage reply = (ServerReplyMessage)e;
  80. // If the reply is Welcome, that means we are fully connected to the server and can now join the auto-join channels.
  81. if (reply.ReplyCode == IRCReplyCode.RPL_WELCOME && Connected)
  82. {
  83. foreach (ChannelConfig channel in ServerConfig.Channels)
  84. {
  85. IRC.IRCSendJoin(channel.Name, channel.Key);
  86. }
  87. }
  88. }
  89. }
  90. }
  91. }