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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. InitializeTable();
  42. SetDefaults();
  43. ConfigRWLock = new ReaderWriterLockSlim();
  44. ConfigFileRWLock = new ReaderWriterLockSlim();
  45. JsonSettings = new JsonSerializerSettings();
  46. JsonSettings.Converters.Add(new IPAddressConverter());
  47. JsonSettings.Converters.Add(new IPEndPointConverter());
  48. JsonSettings.Formatting = Formatting.Indented;
  49. }
  50. private void InitializeTable()
  51. {
  52. string sqlPath = Path.Combine(Directory.GetCurrentDirectory(), "CreateTable.sql");
  53. if (File.Exists(sqlPath))
  54. {
  55. string query = File.ReadAllText(sqlPath);
  56. Bot.Database.Execute(query);
  57. }
  58. }
  59. public void HandleCommandEvent(CommandMessage command)
  60. {
  61. // Check to make sure the command exists, the nick or channel isn't on a blacklist, and the module is loaded.
  62. if (Loaded
  63. && Enabled
  64. && !ChannelBlacklist.Contains(command.Location)
  65. && !NickBlacklist.Contains(command.Nick.Nickname)
  66. && Commands.Exists(c => c.Triggers.Contains(command.Command)
  67. && c.Enabled
  68. && !c.ChannelBlacklist.Contains(command.Location)
  69. && !c.NickBlacklist.Contains(command.Nick.Nickname)
  70. )
  71. )
  72. {
  73. // Figure out access of the nick
  74. Command cmd = Commands.Find(c => c.Triggers.Contains(command.Command));
  75. List<AccessType> nickAccessTypes = new List<AccessType>() { AccessType.User };
  76. foreach (PrivilegeMode privilege in command.Nick.Privileges)
  77. {
  78. nickAccessTypes.Add(Bot.PrivilegeModeMapping[privilege]);
  79. }
  80. 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)
  81. {
  82. nickAccessTypes.Add(AccessType.Owner);
  83. }
  84. command.Access.AddRange(nickAccessTypes);
  85. // If they have the correct access for the command, send it
  86. if (cmd.AllowedAccess.Exists(access => nickAccessTypes.Contains(access)))
  87. {
  88. // Make sure that the command isn't being spammed
  89. if (Bot.SpamCheck(Bot.IRC.Channels.Find(chan => chan.Name == command.Location), command.Nick, this, cmd))
  90. {
  91. ParseCommand(command);
  92. }
  93. }
  94. else
  95. {
  96. string noAccessMessage = string.Format("You do not have access to use \u0002{0}\u000F.", command.Command);
  97. SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noAccessMessage, true);
  98. }
  99. }
  100. }
  101. virtual public void Initialize() { }
  102. virtual public void ParseCommand(CommandMessage command) { }
  103. protected void OnError(string e)
  104. {
  105. string errorMsg = string.Format("[{0}] {1}", Name, e);
  106. EventHandler<string> handler = ModuleErrorEvent;
  107. if (handler != null)
  108. {
  109. handler(this, errorMsg);
  110. }
  111. }
  112. public void SetDefaults()
  113. {
  114. Name = string.Empty;
  115. ClassName = string.Empty;
  116. Enabled = false;
  117. ChannelBlacklist = new List<string>();
  118. NickBlacklist = new List<string>();
  119. ConfigPath = Directory.GetCurrentDirectory();
  120. Loaded = false;
  121. Commands = new List<Command>();
  122. Options = new List<Option>();
  123. }
  124. public void Copy(Module module)
  125. {
  126. Name = module.Name;
  127. ClassName = module.ClassName;
  128. Enabled = module.Enabled;
  129. ChannelBlacklist = new List<string>();
  130. foreach (string channel in module.ChannelBlacklist)
  131. {
  132. ChannelBlacklist.Add(channel);
  133. }
  134. NickBlacklist = new List<string>();
  135. foreach (string nick in module.NickBlacklist)
  136. {
  137. NickBlacklist.Add(nick);
  138. }
  139. Commands = new List<Command>();
  140. foreach (Command command in module.Commands)
  141. {
  142. Command newCommand = new Command();
  143. newCommand.Copy(command);
  144. Commands.Add(newCommand);
  145. }
  146. Options = new List<Option>();
  147. foreach (Option option in module.Options)
  148. {
  149. Option newOption = new Option();
  150. newOption.Copy(option);
  151. Options.Add(newOption);
  152. }
  153. }
  154. public Module CreateInstance(Bot bot)
  155. {
  156. Module newModule = new Module();
  157. if (!Loaded)
  158. {
  159. //create the class base on string
  160. //note : include the namespace and class name (namespace=Combot.Modules, class name=<class_name>)
  161. Assembly a = Assembly.LoadFrom(Path.Combine(ConfigPath, string.Format("{0}.dll", Name)));
  162. Type t = a.GetType("Combot.Modules.Plugins." + ClassName);
  163. //check to see if the class is instantiated or not
  164. if (t != null)
  165. {
  166. newModule = (Module)Activator.CreateInstance(t);
  167. newModule.Copy(this);
  168. newModule.Loaded = true;
  169. newModule.ConfigPath = ConfigPath;
  170. newModule.Bot = bot;
  171. newModule.Initialize();
  172. }
  173. }
  174. return newModule;
  175. }
  176. public object GetOptionValue(string name)
  177. {
  178. object foundValue = string.Empty;
  179. Option foundOption = Options.Find(opt => opt.Name == name);
  180. if (foundOption != null)
  181. {
  182. foundValue = foundOption.Value;
  183. if (foundValue == null)
  184. {
  185. foundValue = string.Empty;
  186. }
  187. }
  188. return foundValue;
  189. }
  190. public void SaveConfig()
  191. {
  192. ConfigFileRWLock.EnterWriteLock();
  193. // Serialize Config
  194. ConfigRWLock.EnterReadLock();
  195. string configContents = JsonConvert.SerializeObject(this, JsonSettings);
  196. ConfigRWLock.ExitReadLock();
  197. // Save config to file
  198. string path = Path.Combine(ConfigPath, "Module.json");
  199. using (StreamWriter streamWriter = new StreamWriter(path, false))
  200. {
  201. streamWriter.Write(configContents);
  202. }
  203. ConfigFileRWLock.ExitWriteLock();
  204. }
  205. public void LoadConfig()
  206. {
  207. ConfigFileRWLock.EnterReadLock();
  208. string path = Path.Combine(ConfigPath, "Module.json");
  209. if (!File.Exists(path))
  210. {
  211. string defaultPath = Path.Combine(ConfigPath, "Module.Default.json");
  212. if (File.Exists(defaultPath))
  213. {
  214. File.Copy(defaultPath, path);
  215. }
  216. }
  217. if (File.Exists(path))
  218. {
  219. string configContents;
  220. using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
  221. {
  222. configContents = streamReader.ReadToEnd();
  223. }
  224. // Load the deserialized file into the config
  225. ConfigRWLock.EnterWriteLock();
  226. Module newModule = JsonConvert.DeserializeObject<Module>(configContents, JsonSettings);
  227. Copy(newModule);
  228. ConfigRWLock.ExitWriteLock();
  229. }
  230. ConfigFileRWLock.ExitReadLock();
  231. }
  232. public void AddServer()
  233. {
  234. string search = "SELECT * FROM `servers` WHERE " +
  235. "`name` = {0}";
  236. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name });
  237. if (!results.Any())
  238. {
  239. string query = "INSERT INTO `servers` SET " +
  240. "`name` = {0}";
  241. Bot.Database.Execute(query, new object[] { Bot.ServerConfig.Name });
  242. }
  243. }
  244. public void AddChannel(string channel)
  245. {
  246. string search = "SELECT * FROM `channels` WHERE " +
  247. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}) AND " +
  248. "`name` = {1}";
  249. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, channel });
  250. if (!results.Any())
  251. {
  252. string query = "INSERT INTO `channels` SET " +
  253. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  254. "`name` = {1}";
  255. Bot.Database.Execute(query, new object[] { Bot.ServerConfig.Name, channel });
  256. }
  257. }
  258. public void AddNick(Nick nick)
  259. {
  260. string search = "SELECT * FROM `nicks` WHERE " +
  261. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}) AND " +
  262. "`nickname` = {1}";
  263. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, nick.Nickname });
  264. if (!results.Any())
  265. {
  266. string insert = "INSERT INTO `nicks` SET " +
  267. "`server_id` = (SELECT `id` FROM `servers` WHERE `name` = {0}), " +
  268. "`nickname` = {1}";
  269. Bot.Database.Execute(insert, new object[] { Bot.ServerConfig.Name, nick.Nickname });
  270. }
  271. AddNickInfo(nick);
  272. }
  273. public void AddNickInfo(Nick nickInfo)
  274. {
  275. int argIndex = 2;
  276. string search = "SELECT * FROM `nickinfo` WHERE " +
  277. "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `nicks`.`server_id` = `servers`.`id` WHERE `nicks`.`nickname` = {0} AND `servers`.`name` = {1})";
  278. List<object> argList = new List<object>() { nickInfo.Nickname, Bot.ServerConfig.Name };
  279. if (!string.IsNullOrEmpty(nickInfo.Username))
  280. {
  281. search += " AND `username` = {" + argIndex + "}";
  282. argList.Add(nickInfo.Username);
  283. argIndex++;
  284. }
  285. if (!string.IsNullOrEmpty(nickInfo.Realname))
  286. {
  287. search += " AND `realname` = {" + argIndex + "}";
  288. argList.Add(nickInfo.Realname);
  289. argIndex++;
  290. }
  291. if (!string.IsNullOrEmpty(nickInfo.Host))
  292. {
  293. search += " AND `host` = {" + argIndex + "}";
  294. argList.Add(nickInfo.Host);
  295. }
  296. List<Dictionary<string, object>> results = Bot.Database.Query(search, argList.ToArray());
  297. if (!results.Any())
  298. {
  299. argIndex = 2;
  300. string insert = "INSERT INTO `nickinfo` SET " +
  301. "`nick_id` = (SELECT `nicks`.`id` FROM `nicks` INNER JOIN `servers` ON `nicks`.`server_id` = `servers`.`id` WHERE `nicks`.`nickname` = {0} AND `servers`.`name` = {1})";
  302. argList = new List<object>() { nickInfo.Nickname, Bot.ServerConfig.Name };
  303. if (!string.IsNullOrEmpty(nickInfo.Username))
  304. {
  305. insert += ", `username` = {" + argIndex + "}";
  306. argList.Add(nickInfo.Username);
  307. argIndex++;
  308. }
  309. if (!string.IsNullOrEmpty(nickInfo.Realname))
  310. {
  311. insert += ", `realname` = {" + argIndex + "}";
  312. argList.Add(nickInfo.Realname);
  313. argIndex++;
  314. }
  315. if (!string.IsNullOrEmpty(nickInfo.Host))
  316. {
  317. insert += ", `host` = {" + argIndex + "}";
  318. argList.Add(nickInfo.Host);
  319. }
  320. Bot.Database.Execute(insert, argList.ToArray());
  321. }
  322. }
  323. public string GetNickname(int id)
  324. {
  325. string search = "SELECT `nickname` FROM `nicks` " +
  326. "WHERE `id` = {0}";
  327. List<Dictionary<string, object>> results = Bot.Database.Query(search, new object[] { id });
  328. string nickname = string.Empty;
  329. if (results.Any())
  330. {
  331. nickname = results.First()["nickname"].ToString();
  332. }
  333. return nickname;
  334. }
  335. public void SendResponse(MessageType messageType, string location, string nickname, string message, bool silent = false)
  336. {
  337. switch (messageType)
  338. {
  339. case MessageType.Channel:
  340. if (silent)
  341. {
  342. Bot.IRC.Command.SendNotice(nickname, message);
  343. }
  344. else
  345. {
  346. Bot.IRC.Command.SendPrivateMessage(location, message);
  347. }
  348. break;
  349. case MessageType.Query:
  350. Bot.IRC.Command.SendPrivateMessage(nickname, message);
  351. break;
  352. case MessageType.Notice:
  353. Bot.IRC.Command.SendNotice(nickname, message);
  354. break;
  355. }
  356. }
  357. }
  358. }