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

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