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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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.Exists(mode => mode == UserMode.r || mode == UserMode.o)) || 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.json");
  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.json");
  195. if (!File.Exists(path))
  196. {
  197. string defaultPath = Path.Combine(ConfigPath, "Module.Default.json");
  198. if (File.Exists(defaultPath))
  199. {
  200. File.Copy(defaultPath, path);
  201. }
  202. }
  203. if (File.Exists(path))
  204. {
  205. string configContents;
  206. using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
  207. {
  208. configContents = streamReader.ReadToEnd();
  209. }
  210. // Load the deserialized file into the config
  211. ConfigRWLock.EnterWriteLock();
  212. Module newModule = JsonConvert.DeserializeObject<Module>(configContents, JsonSettings);
  213. Copy(newModule);
  214. ConfigRWLock.ExitWriteLock();
  215. }
  216. ConfigFileRWLock.ExitReadLock();
  217. }
  218. public void AddServer()
  219. {
  220. string search = "SELECT * FROM `servers` WHERE " +
  221. "`name` = {0}";
  222. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name });
  223. if (!results.Any())
  224. {
  225. string query = "INSERT INTO `servers` SET " +
  226. "`name` = {0}";
  227. Bot.Database.Execute(query, new object[] { Bot.ServerConfig.Name });
  228. }
  229. }
  230. public void AddChannel(string channel)
  231. {
  232. string search = "SELECT * FROM `channels` WHERE " +
  233. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}) AND " +
  234. "`name` = {1}";
  235. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, channel });
  236. if (!results.Any())
  237. {
  238. string query = "INSERT INTO `channels` SET " +
  239. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  240. "`name` = {1}";
  241. Bot.Database.Execute(query, new object[] { Bot.ServerConfig.Name, channel });
  242. }
  243. }
  244. public void AddNick(Nick nick)
  245. {
  246. string search = "SELECT * FROM `nicks` WHERE " +
  247. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}) AND " +
  248. "`nickname` = {1}";
  249. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, nick.Nickname });
  250. if (!results.Any())
  251. {
  252. string insert = "INSERT INTO `nicks` SET " +
  253. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  254. "`nickname` = {1}";
  255. Bot.Database.Execute(insert, new object[] { Bot.ServerConfig.Name, nick.Nickname });
  256. }
  257. AddNickInfo(nick);
  258. }
  259. public void AddNickInfo(Nick nickInfo)
  260. {
  261. int argIndex = 2;
  262. string search = "SELECT * FROM `nickinfo` WHERE " +
  263. "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `nicks`.`server_id` = `servers`.`id` WHERE `nicks`.`nickname` = {0} AND `servers`.`name` = {1})";
  264. List<object> argList = new List<object>() { nickInfo.Nickname, Bot.ServerConfig.Name };
  265. if (!string.IsNullOrEmpty(nickInfo.Username))
  266. {
  267. search += " AND `username` = {" + argIndex + "}";
  268. argList.Add(nickInfo.Username);
  269. argIndex++;
  270. }
  271. if (!string.IsNullOrEmpty(nickInfo.Realname))
  272. {
  273. search += " AND `realname` = {" + argIndex + "}";
  274. argList.Add(nickInfo.Realname);
  275. argIndex++;
  276. }
  277. if (!string.IsNullOrEmpty(nickInfo.Host))
  278. {
  279. search += " AND `host` = {" + argIndex + "}";
  280. argList.Add(nickInfo.Host);
  281. }
  282. List<Dictionary<string, object>> results = Bot.Database.Query(search, argList.ToArray());
  283. if (!results.Any())
  284. {
  285. argIndex = 2;
  286. string insert = "INSERT INTO `nickinfo` SET " +
  287. "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `nicks`.`server_id` = `servers`.`id` WHERE `nicks`.`nickname` = {0} AND `servers`.`name` = {1})";
  288. argList = new List<object>() { nickInfo.Nickname, Bot.ServerConfig.Name };
  289. if (!string.IsNullOrEmpty(nickInfo.Username))
  290. {
  291. insert += ", `username` = {" + argIndex + "}";
  292. argList.Add(nickInfo.Username);
  293. argIndex++;
  294. }
  295. if (!string.IsNullOrEmpty(nickInfo.Realname))
  296. {
  297. insert += ", `realname` = {" + argIndex + "}";
  298. argList.Add(nickInfo.Realname);
  299. argIndex++;
  300. }
  301. if (!string.IsNullOrEmpty(nickInfo.Host))
  302. {
  303. insert += ", `host` = {" + argIndex + "}";
  304. argList.Add(nickInfo.Host);
  305. }
  306. Bot.Database.Execute(insert, argList.ToArray());
  307. }
  308. }
  309. public string GetNickname(int id)
  310. {
  311. string search = "SELECT `nickname` FROM `nicks` " +
  312. "WHERE `id` = {0}";
  313. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { id });
  314. string nickname = string.Empty;
  315. if (results.Any())
  316. {
  317. nickname = results.First()["nickname"].ToString();
  318. }
  319. return nickname;
  320. }
  321. public void SendResponse(MessageType messageType, string location, string nickname, string message, bool silent = false)
  322. {
  323. switch (messageType)
  324. {
  325. case MessageType.Channel:
  326. if (silent)
  327. {
  328. Bot.IRC.Command.SendNotice(nickname, message);
  329. }
  330. else
  331. {
  332. Bot.IRC.Command.SendPrivateMessage(location, message);
  333. }
  334. break;
  335. case MessageType.Query:
  336. Bot.IRC.Command.SendPrivateMessage(nickname, message);
  337. break;
  338. case MessageType.Notice:
  339. Bot.IRC.Command.SendNotice(nickname, message);
  340. break;
  341. }
  342. }
  343. }
  344. }