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.

Module.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Reflection;
  8. using System.Threading;
  9. using Combot.Configurations;
  10. using Combot.Databases;
  11. using Combot.IRCServices;
  12. using Newtonsoft.Json;
  13. namespace Combot.Modules
  14. {
  15. public class Module
  16. {
  17. public string Name { get; set; }
  18. public string ClassName { get; set; }
  19. public bool Enabled { get; set; }
  20. public List<string> ChannelBlacklist { get; set; }
  21. public List<string> NickBlacklist { get; set; }
  22. public List<Command> Commands { get; set; }
  23. public List<Option> Options { get; set; }
  24. public event EventHandler<string> ModuleErrorEvent;
  25. public bool Loaded { get; set; }
  26. public bool ShouldSerializeLoaded()
  27. {
  28. return false;
  29. }
  30. public string ConfigPath { get; set; }
  31. public bool ShouldSerializeConfigPath()
  32. {
  33. return false;
  34. }
  35. protected Bot Bot;
  36. private ReaderWriterLockSlim ConfigRWLock;
  37. private ReaderWriterLockSlim ConfigFileRWLock;
  38. private JsonSerializerSettings JsonSettings;
  39. public Module()
  40. {
  41. SetDefaults();
  42. ConfigRWLock = new ReaderWriterLockSlim();
  43. ConfigFileRWLock = new ReaderWriterLockSlim();
  44. JsonSettings = new JsonSerializerSettings();
  45. JsonSettings.Converters.Add(new IPAddressConverter());
  46. JsonSettings.Converters.Add(new IPEndPointConverter());
  47. JsonSettings.Formatting = Formatting.Indented;
  48. }
  49. public void HandleCommandEvent(CommandMessage command)
  50. {
  51. // Check to make sure the command exists, the nick or channel isn't on a blacklist, and the module is loaded.
  52. if (Loaded
  53. && Enabled
  54. && !ChannelBlacklist.Contains(command.Location)
  55. && !NickBlacklist.Contains(command.Nick.Nickname)
  56. && Commands.Exists(c => c.Triggers.Contains(command.Command)
  57. && c.Enabled
  58. && !c.ChannelBlacklist.Contains(command.Location)
  59. && !c.NickBlacklist.Contains(command.Nick.Nickname)
  60. )
  61. )
  62. {
  63. // Figure out access of the nick
  64. Command cmd = Commands.Find(c => c.Triggers.Contains(command.Command));
  65. List<AccessType> nickAccessTypes = new List<AccessType>() { AccessType.User };
  66. foreach (PrivilegeMode privilege in command.Nick.Privileges)
  67. {
  68. nickAccessTypes.Add(Bot.PrivilegeModeMapping[privilege]);
  69. }
  70. if ((Bot.ServerConfig.Owners.Contains(command.Nick.Nickname) && command.Nick.Modes.Contains(UserMode.r)) || command.Nick.Nickname == Bot.IRC.Nickname)
  71. {
  72. nickAccessTypes.Add(AccessType.Owner);
  73. }
  74. command.Access.AddRange(nickAccessTypes);
  75. // If they have the correct access for the command, send it
  76. if (cmd.AllowedAccess.Exists(access => nickAccessTypes.Contains(access)))
  77. {
  78. ParseCommand(command);
  79. }
  80. else
  81. {
  82. string noAccessMessage = string.Format("You do not have access to use \u0002{0}\u000F.", command.Command);
  83. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noAccessMessage);
  84. }
  85. }
  86. }
  87. virtual public void Initialize() { }
  88. virtual public void ParseCommand(CommandMessage command) { }
  89. protected void OnError(string e)
  90. {
  91. string errorMsg = string.Format("[{0}] {1}", Name, e);
  92. EventHandler<string> handler = ModuleErrorEvent;
  93. if (handler != null)
  94. {
  95. handler(this, errorMsg);
  96. }
  97. }
  98. public void SetDefaults()
  99. {
  100. Name = string.Empty;
  101. ClassName = string.Empty;
  102. Enabled = false;
  103. ChannelBlacklist = new List<string>();
  104. NickBlacklist = new List<string>();
  105. ConfigPath = Directory.GetCurrentDirectory();
  106. Loaded = false;
  107. Commands = new List<Command>();
  108. Options = new List<Option>();
  109. }
  110. public void Copy(Module module)
  111. {
  112. Name = module.Name;
  113. ClassName = module.ClassName;
  114. Enabled = module.Enabled;
  115. ChannelBlacklist = new List<string>();
  116. foreach (string channel in module.ChannelBlacklist)
  117. {
  118. ChannelBlacklist.Add(channel);
  119. }
  120. NickBlacklist = new List<string>();
  121. foreach (string nick in module.NickBlacklist)
  122. {
  123. NickBlacklist.Add(nick);
  124. }
  125. Commands = new List<Command>();
  126. foreach (Command command in module.Commands)
  127. {
  128. Command newCommand = new Command();
  129. newCommand.Copy(command);
  130. Commands.Add(newCommand);
  131. }
  132. Options = new List<Option>();
  133. foreach (Option option in module.Options)
  134. {
  135. Option newOption = new Option();
  136. newOption.Copy(option);
  137. Options.Add(newOption);
  138. }
  139. }
  140. public Module CreateInstance(Bot bot)
  141. {
  142. Module newModule = new Module();
  143. if (!Loaded)
  144. {
  145. //create the class base on string
  146. //note : include the namespace and class name (namespace=Combot.Modules, class name=<class_name>)
  147. Assembly a = Assembly.LoadFrom(Path.Combine(ConfigPath, string.Format("{0}.dll", Name)));
  148. Type t = a.GetType("Combot.Modules.Plugins." + ClassName);
  149. //check to see if the class is instantiated or not
  150. if (t != null)
  151. {
  152. newModule = (Module)Activator.CreateInstance(t);
  153. newModule.Copy(this);
  154. newModule.Loaded = true;
  155. newModule.ConfigPath = ConfigPath;
  156. newModule.Bot = bot;
  157. newModule.Initialize();
  158. }
  159. }
  160. return newModule;
  161. }
  162. public object GetOptionValue(string name)
  163. {
  164. object foundValue = null;
  165. Option foundOption = Options.Find(opt => opt.Name == name);
  166. if (foundOption != null)
  167. {
  168. foundValue = foundOption.Value;
  169. if (foundValue == null)
  170. {
  171. foundValue = string.Empty;
  172. }
  173. }
  174. return foundValue;
  175. }
  176. public void SaveConfig()
  177. {
  178. ConfigFileRWLock.EnterWriteLock();
  179. // Serialize Config
  180. ConfigRWLock.EnterReadLock();
  181. string configContents = JsonConvert.SerializeObject(this, JsonSettings);
  182. ConfigRWLock.ExitReadLock();
  183. // Save config to file
  184. string path = Path.Combine(ConfigPath, "Module.config");
  185. using (StreamWriter streamWriter = new StreamWriter(path, false))
  186. {
  187. streamWriter.Write(configContents);
  188. }
  189. ConfigFileRWLock.ExitWriteLock();
  190. }
  191. public void LoadConfig()
  192. {
  193. ConfigFileRWLock.EnterReadLock();
  194. string path = Path.Combine(ConfigPath, "Module.config");
  195. if (File.Exists(path))
  196. {
  197. string configContents;
  198. using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
  199. {
  200. configContents = streamReader.ReadToEnd();
  201. }
  202. // Load the deserialized file into the config
  203. ConfigRWLock.EnterWriteLock();
  204. Module newModule = JsonConvert.DeserializeObject<Module>(configContents, JsonSettings);
  205. Copy(newModule);
  206. ConfigRWLock.ExitWriteLock();
  207. }
  208. ConfigFileRWLock.ExitReadLock();
  209. }
  210. public void AddServer()
  211. {
  212. string search = "SELECT * FROM `servers` WHERE " +
  213. "`name` = {0}";
  214. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name });
  215. if (!results.Any())
  216. {
  217. string query = "INSERT INTO `servers` SET " +
  218. "`name` = {0}";
  219. Bot.Database.Execute(query, new object[] { Bot.ServerConfig.Name });
  220. }
  221. }
  222. public void AddChannel(string channel)
  223. {
  224. string search = "SELECT * FROM `channels` WHERE " +
  225. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}) AND " +
  226. "`name` = {1}";
  227. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, channel });
  228. if (!results.Any())
  229. {
  230. string query = "INSERT INTO `channels` SET " +
  231. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  232. "`name` = {1}";
  233. Bot.Database.Execute(query, new object[] { Bot.ServerConfig.Name, channel });
  234. }
  235. }
  236. public void AddNick(string nickname)
  237. {
  238. string search = "SELECT * FROM `nicks` WHERE " +
  239. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}) AND " +
  240. "`nickname` = {1}";
  241. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, nickname });
  242. if (!results.Any())
  243. {
  244. string insert = "INSERT INTO `nicks` SET " +
  245. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  246. "`nickname` = {1}";
  247. Bot.Database.Execute(insert, new object[] { Bot.ServerConfig.Name, nickname });
  248. }
  249. }
  250. public string GetNickname(int id)
  251. {
  252. string search = "SELECT `nickname` FROM `nicks` " +
  253. "WHERE `id` = {0}";
  254. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { id });
  255. string nickname = string.Empty;
  256. if (results.Any())
  257. {
  258. nickname = results.First()["nickname"].ToString();
  259. }
  260. return nickname;
  261. }
  262. public void SendResponse(MessageType messageType, string location, string nickname, string message)
  263. {
  264. switch (messageType)
  265. {
  266. case MessageType.Channel:
  267. Bot.IRC.Command.SendPrivateMessage(location, message);
  268. break;
  269. case MessageType.Query:
  270. Bot.IRC.Command.SendPrivateMessage(nickname, message);
  271. break;
  272. case MessageType.Notice:
  273. Bot.IRC.Command.SendNotice(nickname, message);
  274. break;
  275. }
  276. }
  277. }
  278. }