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

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