public static async Task <string> Fetch(string url, BotLog log, string useragent = null, Action <HttpWebRequest> callback = null) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = 1000 * 60; request.Headers[HttpRequestHeader.UserAgent] = useragent ?? UserAgent; callback?.Invoke(request); using (WebResponse answer = await request.GetResponseAsync()) using (StreamReader reader = new StreamReader(answer.GetResponseStream(), Encoding.UTF8)) { string result = reader.ReadToEnd(); return(result); } } catch (WebException e) { if (e.Status == WebExceptionStatus.Timeout) { log.Nice("HTTP", ConsoleColor.Red, "Request timed out for [ " + url + " ]"); } else if (e.Status == WebExceptionStatus.ConnectFailure) { log.Nice("HTTP", ConsoleColor.Red, "(404) Couln't reach [ " + url + " ]"); } else { log.Nice("HTTP", ConsoleColor.Red, "Unknown error [ " + url + " ]\n" + e.ToString()); } return(""); } }
private async Task BlackWhite(CommandReplyEmbed embedrep, SocketMessage msg, List <string> args) { string url = string.IsNullOrWhiteSpace(args[0]) ? Handler.GetLastPictureURL((msg.Channel as SocketChannel)) : args[0]; string path = null; if (!string.IsNullOrWhiteSpace(url)) //if getlastpicture returns nothing { path = await ImageProcess.DownloadImage(url); } if (path != null) { try { ImageProcess.Resize(path); ImageProcess.MakeBlackWhite(path); await msg.Channel.SendFileAsync(path); ImageProcess.DeleteImage(path); }catch (Exception e) { BotLog.Debug(e.ToString()); } } if (path == null) { await embedrep.Danger(msg, "Ugh", "There's no valid url to use!"); } }
public static void Run() { BotLog.Write(1, "UpdateStatsCache", "Entering (obsoleted does nothing"); UpdateBallotDistroData(); BotLog.Write(1, "UpdateStatsCache", "Exiting"); }
private static void OnNoon() { BotLog.Write(0, "MainCycle", "Noon entry"); try { if (!testMode) { /*TestTrace("Running RosterHousekeeping.RemindAllExpiries()..."); * RosterHousekeeping.RemindAllExpiries(); * TestTrace(" done.\r\n");*/ } } catch (Exception e) { TraceAndReport(e); } try { if (!testMode) { /*TestTrace("Running SupportDatabase.NotifyBouncingEmails()..."); * SupportDatabase.NotifyBouncingEmails(); * TestTrace(" done.\r\n");*/ } } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportDatabase.CloseDelayWarnings()..."); * SupportDatabase.CloseDelayWarnings(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportMailReview.Run()..."); * SupportMailReview.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Noon exit"); }
private void Setup(CommandsHandler handler, BotLog log) { this._Utils.Setup(handler, log); this._Social.Setup(handler, log); this._NSFW.Setup(handler, log); this._Search.Setup(handler, log); this._Image.Setup(handler, log); this._Fun.Setup(handler, log); this._Warframe.Setup(handler, log); }
public void UnloadCommands(CommandsHandler handler, BotLog log) { this._Utils.Unload(); this._Social.Unload(); this._NSFW.Unload(); this._Search.Unload(); this._Image.Unload(); this._Fun.Unload(); this._Warframe.Unload(); }
public CommandSource(CommandsHandler handler, BotLog log) { this._Utils = new UtilsCommands(); this._Social = new SocialCommands(); this._NSFW = new NSFWCommands(); this._Search = new SearchCommands(); this._Image = new ImageCommands(); this._Fun = new FunCommands(); this._Warframe = new WarframeCommands(); Setup(handler, log); }
private static void OnEveryMinute() { try { BotLog.Write(0, "MainCycle", "One-minute process (empty)"); } catch (Exception e) { TraceAndReport(e); } // empty }
private static void OnEveryTenSeconds() { try { BotLog.Write(0, "MainCycle", "Ten-second entry"); SystemSettings.HeartbeatBackend = (ulong)DateTime.UtcNow.ToUnix(); CommsTransmitter.Run(); BroadcastTimestamp(); try { /*TestTrace("Running EventProcessor.Run()..."); * EventProcessor.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running MailResolver.Run()..."); * MailResolver.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running MailProcessor.Run()..."); * MailProcessor.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Ten-second exit"); } catch (Exception e) { ExceptionMail.Send(e, true); } }
public static T Deserialize <T>(string json, BotLog log) { try { T deserialized = JsonConvert.DeserializeObject <T>(json); return(deserialized); } catch { log.Nice("JSON", ConsoleColor.Red, "Couldn't deserialize a string!"); log.Danger(json); return(default(T)); } }
public static string Serialize(Object obj, BotLog log) { try { string json = JsonConvert.SerializeObject(obj); return(json); } catch { log.Nice("JSON", ConsoleColor.Red, "Couldn't serialize a string!"); log.Danger(obj.ToString()); return(""); } }
private static void OnEveryTenSeconds() { try { BotLog.Write(0, "MainCycle", "Ten-second entry"); CommsTransmitter.Run(); try { /*TestTrace("Running EventProcessor.Run()..."); * EventProcessor.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running MailResolver.Run()..."); * MailResolver.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running MailProcessor.Run()..."); * MailProcessor.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Ten-second exit"); } catch (Exception e) { ExceptionMail.Send(e, true); } }
public void loadAIMLFromDatabase(IEnumerable <AIMLViewModel> lstAIML) { if (lstAIML.Count() != 0) { foreach (var item in lstAIML) { try { XmlDocument doc = new XmlDocument(); doc.LoadXml(item.Content); _bot.loadAIMLFromXML(doc, item.Src); }catch (Exception ex) { string msg = item.Content + ex.Message; BotLog.Info(msg); } } } }
public static async Task <string> Ask(SocketChannel chan, string sentence, BotLog log) { if (!_Cookies.TryGetValue(chan, out CookieContainer cookie)) { cookie = new CookieContainer(); _Cookies.Add(chan, cookie); } NameValueCollection values = HttpUtility.ParseQueryString(string.Empty); values["name"] = "EBot"; values["question"] = sentence; string parameters = values.ToString(); string html = await HTTP.Fetch(_URL + parameters, log, null, request => { request.CookieContainer = cookie; }); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNode SELECT = doc.DocumentNode.Element("html").Element("body").Element("div").Element("select"); foreach (HtmlNode node in SELECT.ChildNodes) { string start = "answer = "; if (node.InnerText.StartsWith(start)) { string answer = node.InnerText.Remove(0, start.Length); Random rand = new Random(); if (rand.Next(0, 100) <= 25) // 1/4 { string end = " " + _SentencesEnd[rand.Next(0, _SentencesEnd.Length - 1)]; answer = answer.Substring(0, answer.Length - 3) + end; } return(answer); } } return(null); }
public EBotClient(string token, string prefix) { Console.Clear(); Console.Title = "EBot's Logs"; this._Token = token; this._Prefix = prefix; this._Log = new BotLog(); this._Event = new LogEvent(); this._Spy = new SpyLog(); this._Handler = new CommandsHandler(); this._Source = new CommandSource(this._Handler, this._Log); this._Discord = new DiscordSocketClient(); this._DiscordREST = new DiscordRestClient(); this._Log.Nice("Config", ConsoleColor.Yellow, "Token used => [ " + token + " ]"); this._Log.Notify("Initializing"); this._Handler.Client = this._Discord; this._Handler._RESTClient = this._DiscordREST; this._Handler.Log = this._Log; this._Handler.Prefix = this._Prefix; this._Handler.Source = this._Source; this._Handler.EmbedReply.Log = this._Log; this._Handler.Initialize(); this._Spy.Client = this._Discord; this._Spy.RESTClient = this._DiscordREST; this._Spy.Log = this._Log; this._Spy.WatchWords(new string[] { "yara", "earu" }); this._Event.Client = this._Discord; this._Event.RESTClient = this._DiscordREST; this._Event.Prefix = this._Prefix; this._Event.Log = this._Log; this._Event.InitEvents(); CLIENT = this; }
private static void OnMidnight() { try { BotLog.Write(0, "MainCycle", "Midnight entry"); try { if (!testMode) { /*TestTrace("Running RosterHousekeeping.ChurnExpiredMembers()..."); * RosterHousekeeping.ChurnExpiredMembers(); * TestTrace(" done.\r\n");*/ } ExchangeRateSnapshot.Create(); } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running InternalPollMaintenance.Run()..."); * InternalPollMaintenance.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SwedishForumMemberCheck.Run()..."); * SwedishForumMemberCheck.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SalaryProcessor.Run()..."); * SalaryProcessor.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running TurnaroundTracker.Housekeeping()..."); * TurnaroundTracker.Housekeeping(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running Mappery.CreateUngPiratUptakeMap()..."); * Mappery.CreateUngPiratUptakeMap(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running RosterHousekeeping.TimeoutVolunteers()..."); * RosterHousekeeping.TimeoutVolunteers(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Midnight exit"); } catch (Exception e) { ExceptionMail.Send(e, true); TestTrace(e.ToString()); } }
private static void OnEveryHour() { DateTime startTime = DateTime.Now; try { BotLog.Write(0, "MainCycle", "One-hour entry"); try { /*TestTrace("Running BlogWatcher.Run()..."); * BlogWatcher.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running MediaWatcher.Run()..."); * MediaWatcher.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running PaymentGroupMapper.Run()..."); * PaymentGroupMapper.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running BlogTop50Scraper.Run()..."); * BlogTop50Scraper.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running Mappery.CreatePiratpartietOrganizationStrengthCircuitMap()..."); * Mappery.CreatePiratpartietOrganizationStrengthCircuitMap(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running Mappery.CreatePiratpartietOrganizationStrengthCityMap()..."); * Mappery.CreatePiratpartietOrganizationStrengthCityMap(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "One-hour exit"); } catch (Exception e) { TraceAndReport(e); } }
private static void OnEveryFiveMinutes() { try { BotLog.Write(0, "MainCycle", "Five-minute entry"); try { /*BotLog.Write(1, "FiveMinute", "Starting press release checker"); * TestTrace("Running PressReleaseChecker.Run()..."); * PressReleaseChecker.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*BotLog.Write(1, "FiveMinute", "Starting newsletter checker"); * TestTrace("Running NewsletterChecker.Run()..."); * NewsletterChecker.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*BotLog.Write(1, "FiveMinute", "Starting turnaround tracker"); * TestTrace("Running TurnaroundTracker.Run()..."); * TurnaroundTracker.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { // TestTrace(" done.\r\nRunning UpdateStatsCache.Run()..."); // UpdateStatsCache.Run(); /*TestTrace(" done.\r\nRunning TranslateUrls()..."); * TranslateUrls();*/ // Added during election rush 2010: clean up support database every five minutes instead of once a day // SMS notifications for bounces are turned off, so people don't get SMS notifications in the middle of the night } catch (Exception e) { TraceAndReport(e); } try { /*BotLog.Write(1, "FiveMinute", "Closing delay warnings"); * TestTrace("Running SupportDatabase.CloseDelayWarnings()..."); * SupportDatabase.CloseDelayWarnings(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportDatabase.NotifyBouncingEmails()..."); * BotLog.Write(1, "FiveMinute", "Notifying bouncing emails"); * SupportDatabase.NotifyBouncingEmails(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportMailReview.Run()..."); * BotLog.Write(1, "FiveMinute", "Running support mail review"); * SupportMailReview.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Five-minute exit"); } catch (Exception e) { ExceptionMail.Send(e, true); TestTrace(e.ToString()); } }
public static bool Run(SocketMessage msg, string code, out List <Object> returns, out string error, BotLog log) { SocketChannel chan = msg.Channel as SocketChannel; if (!_States.ContainsKey(chan) || _States[chan] == null) { _States[chan] = CreateState(chan); } Save(chan, code); bool success = true; try { Lua state = _States[chan]; code = SafeCode(state, code); Object[] parts = state.DoString(code, "SANDBOX"); returns = new List <object>(parts); error = ""; } catch (LuaException e) { returns = new List <object>(); error = e.Message; success = false; } catch (Exception e) //no lua return basically { returns = new List <object>(); error = e.Message; success = true; } return(success); }
internal static void Run() { OutboundComms comms = OutboundComms.GetOpen(); foreach (OutboundComm comm in comms) { BotLog.Write(1, "CommsTx", "OutboundComm #" + comm.Identity.ToString("N0")); if (!comm.Resolved) { BotLog.Write(2, "CommsTx", "--resolving"); ICommsResolver resolver = FindResolver(comm); resolver.Resolve(comm); comm.Resolved = true; int recipientCount = comm.Recipients.Count; BotLog.Write(2, "CommsTx", "--resolved to " + recipientCount.ToString("N0") + " recipients"); if (recipientCount > 1 && comm.SenderPersonId != 0) { // "Your message has been queued for delivery and the recipients have been resolved. // Your mail will be sent to, or be attempted to sent to, [RecipientCount] people in [Geography] in [OrganizationName]." NotificationStrings notifyStrings = new NotificationStrings(); NotificationCustomStrings customStrings = new NotificationCustomStrings(); notifyStrings[NotificationString.OrganizationName] = Organization.FromIdentity(comm.OrganizationId).Name; customStrings["RecipientCount"] = comm.Recipients.Count.ToString("N0"); if (resolver is IHasGeography) { customStrings["GeographyName"] = ((IHasGeography)resolver).Geography.Localized; } OutboundComm.CreateNotification(Organization.FromIdentity(comm.OrganizationId), NotificationResource.OutboundComm_Resolved, notifyStrings, customStrings, People.FromSingle(Person.FromIdentity(comm.SenderPersonId))); } comm.StartTransmission(); continue; // continue is not strictly necessary; could continue processing the same OutboundComm after resolution } if (comm.TransmitterClass != "Swarmops.Utility.Communications.CommsTransmitterMail") { throw new NotImplementedException(); } ICommsTransmitter transmitter = new CommsTransmitterMail(); const int batchSize = 1000; OutboundCommRecipients recipients = comm.GetRecipientBatch(batchSize); PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); BotLog.Write(2, "CommsTx", "--transmitting to " + recipients.Count.ToString("N0") + " recipients"); foreach (OutboundCommRecipient recipient in recipients) { try { transmitter.Transmit(envelope, recipient.Person); recipient.CloseSuccess(); } catch (OutboundCommTransmitException e) { recipient.CloseFailed(e.Description); } } if (recipients.Count < batchSize) // Was this the last batch? { comm.Open = false; BotLog.Write(2, "CommsTx", "--closing"); OutboundComm reloadedComm = OutboundComm.FromIdentity(comm.Identity); // active object doesn't update as we get results, so need to load // from database to get final counts of successes and fails if (comm.RecipientCount > 1 && comm.SenderPersonId != 0) { BotLog.Write(2, "CommsTx", "--notifying"); ICommsResolver resolver = FindResolver(comm); // "Your message to [GeographyName] has been sent to all scheduled recipients. Of the [RecipientCount] planned recipients, // [RecipientsSuccess] succeeded from Swarmops' horizon. (These can fail later for a number of reasons, from broken // computers to hospitalized recipients.) Time spent transmitting: [TransmissionTime]." NotificationStrings notifyStrings = new NotificationStrings(); NotificationCustomStrings customStrings = new NotificationCustomStrings(); notifyStrings[NotificationString.OrganizationName] = Organization.FromIdentity(comm.OrganizationId).Name; customStrings["RecipientCount"] = reloadedComm.RecipientCount.ToString("N0"); customStrings["RecipientsSuccess"] = reloadedComm.RecipientsSuccess.ToString("N0"); TimeSpan resolveTime = comm.StartTransmitDateTime - comm.CreatedDateTime; TimeSpan transmitTime = comm.ClosedDateTime - comm.StartTransmitDateTime; TimeSpan totalTime = resolveTime + transmitTime; customStrings["TransmissionTime"] = FormatTimespan(transmitTime); customStrings["ResolvingTime"] = FormatTimespan(resolveTime); customStrings["TotalTime"] = FormatTimespan(totalTime); if (resolver is IHasGeography) { customStrings["GeographyName"] = ((IHasGeography)resolver).Geography.Localized; } OutboundComm.CreateNotification(Organization.FromIdentity(comm.OrganizationId), NotificationResource.OutboundComm_Sent, notifyStrings, customStrings, People.FromSingle(Person.FromIdentity(comm.SenderPersonId))); } } } }
private static void OnNoon() { BotLog.Write(0, "MainCycle", "Noon entry"); try { if (!PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) { // PPSE is still running PW4 code for this, so don't run for PPSE Payroll.ProcessMonthly(); // will only actually run on the 1st, but no harm in testing every noon } // Check all bitcoin accounts for previously-unseen transactions once a day Organizations allOrganizations = Organizations.GetAll(); foreach (Organization organization in allOrganizations) { // this actually checks hot storage too, but that's supposed // to be up to date since we're the ones handling it BitcoinUtility.CheckColdStorageForOrganization(organization); } if (!testMode) { /*TestTrace("Running RosterHousekeeping.RemindAllExpiries()..."); * RosterHousekeeping.RemindAllExpiries(); * TestTrace(" done.\r\n");*/ } } catch (Exception e) { TraceAndReport(e); } try { if (!testMode) { /*TestTrace("Running SupportDatabase.NotifyBouncingEmails()..."); * SupportDatabase.NotifyBouncingEmails(); * TestTrace(" done.\r\n");*/ } } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportDatabase.CloseDelayWarnings()..."); * SupportDatabase.CloseDelayWarnings(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportMailReview.Run()..."); * SupportMailReview.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Noon exit"); }
private static void OnEveryHour() { try { BotLog.Write(0, "MainCycle", "One-hour entry"); try { // This will upgrade the database schema if and only if we failed to do so on entry. if (SwarmDb.DbVersion < SwarmDb.DbVersionExpected) { BotLog.Write(1, "OneHour", "Entering DbUpgrade"); DatabaseMaintenance.UpgradeSchemata(); BotLog.Write(1, "OneHour", "Exited DbUpgrade"); } } catch (Exception e) { TraceAndReport(e); } try { BotLog.Write(1, "OneHour", "Entering Automatch"); Organizations organizations = Organizations.GetAll(); foreach (Organization organization in organizations) { if (organization.IsEconomyEnabled) { BotLog.Write(1, "OneHour", "Automatching org #" + organization.Identity.ToString(CultureInfo.InvariantCulture)); Payouts.AutomatchAgainstUnbalancedTransactions(organization); } } BotLog.Write(1, "OneHour", "Exited Automatch"); /*TestTrace("Running PaymentGroupMapper.Run()..."); * PaymentGroupMapper.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running BlogTop50Scraper.Run()..."); * BlogTop50Scraper.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running Mappery.CreatePiratpartietOrganizationStrengthCircuitMap()..."); * Mappery.CreatePiratpartietOrganizationStrengthCircuitMap(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running Mappery.CreatePiratpartietOrganizationStrengthCityMap()..."); * Mappery.CreatePiratpartietOrganizationStrengthCityMap(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "One-hour exit"); } catch (Exception e) { TraceAndReport(e); } }
private static Lua CreateState(SocketChannel chan) { try { Lua state = new Lua(); state.DoFile("External/Lua/Init.lua"); if (chan is IGuildChannel) { IGuildChannel c = chan as IGuildChannel; state.DoString(@" ENV.CHANNEL_ID = tonumber([[" + chan.Id.ToString() + @"]]) ENV.CHANNEL_NAME = [[" + c.Name + @"]] ENV.GUILD_ID = tonumber([[" + c.GuildId + @"]]) ENV.GUILD_NAME = [[" + c.Guild.Name + @"]] ", "Startup"); _Client.Discord.UserJoined += async user => { if (user.Guild == c.Guild) { state["USER"] = user as SocketUser; Object[] returns = state.DoString(@"return event.fire('OnMemberAdded',USER)"); state["USER"] = null; await _Client.Handler.EmbedReply.Send((chan as ISocketMessageChannel), "LuaEvent", returns[0].ToString()); } }; _Client.Discord.UserLeft += async user => { if (user.Guild == c.Guild) { state["USER"] = user as SocketUser; Object[] returns = state.DoString(@"return event.fire('OnMemberRemoved',USER)"); state["USER"] = null; await _Client.Handler.EmbedReply.Send((chan as ISocketMessageChannel), "LuaEvent", returns[0].ToString()); } }; } else { IDMChannel c = chan as IDMChannel; state.DoString(@" ENV.CHANNEL_ID = tonumber([[" + c.Id.ToString() + @"]]) ENV.CHANNEL_NAME = [[" + c.Name + @"]] ", "Startup"); } _Client.Discord.MessageReceived += async msg => { if ((msg.Channel as SocketChannel) == chan && msg.Author.Id != _App.Id) { state["USER"] = msg.Author; state["MESSAGE"] = msg; Object[] returns = state.DoString(@"return event.fire('OnMessageCreated',USER,MESSAGE)"); state["USER"] = null; state["MESSAGE"] = null; await _Client.Handler.EmbedReply.Send((chan as ISocketMessageChannel), "LuaEvent", returns[0].ToString()); } }; _Client.Discord.MessageDeleted += async(msg, c) => { IMessage mess = await msg.DownloadAsync(); if ((c as SocketChannel) == chan && mess.Author.Id != _App.Id) { state["MESSAGE"] = mess as SocketMessage; state["USER"] = mess.Author as SocketUser; Object[] returns = state.DoString(@"return event.fire('OnMessageDeleted',USER,MESSAGE)"); state["USER"] = null; state["MESSAGE"] = null; await _Client.Handler.EmbedReply.Send(c, "LuaEvent", returns[0].ToString()); } }; _Client.Discord.MessageUpdated += async(cache, msg, c) => { if ((c as SocketChannel) == chan && msg.Author.Id != _App.Id) { state["USER"] = msg.Author as SocketUser; state["MESSAGE"] = msg as SocketMessage; Object[] returns = state.DoString(@"return event.fire('OnMessageEdited',USER,MESSAGE)"); state["USER"] = null; state["MESSAGE"] = null; await _Client.Handler.EmbedReply.Send(c, "LuaEvent", returns[0].ToString()); } }; return(state); }catch (LuaException e) { BotLog.Debug(e.Message); } return(new Lua()); }
private static void Main(string[] args) { // Are we running yet? if (!SystemSettings.DatabaseInitialized) { // will restart the service every 15s until db initialized on OOBE // also, the read of DatabaseInitialized can and will fail if // we're not initalized enough to even have a database throw new InvalidOperationException(); } // Checking for schemata upgrade first of all, after seeing that db exists int startupDbVersion = Database.SwarmDb.DbVersion; DatabaseMaintenance.UpgradeSchemata(); testMode = false; SystemSettings.BackendHostname = Dns.GetHostName(); // Other one-time initializations FinancialTransactions.FixAllUnsequenced(); SupportFunctions.OperatingTopology = OperatingTopology.Backend; // Begin main loop UnixSignal[] killSignals = null; if (!Debugger.IsAttached) { killSignals = new UnixSignal[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }; } BotLog.Write(0, "MainCycle", string.Empty); BotLog.Write(0, "MainCycle", "-----------------------------------------------"); BotLog.Write(0, "MainCycle", string.Empty); if (args.Length > 0) { if (args[0].ToLower() == "test") { /* * BotLog.Write(0, "MainCycle", "Running self-tests"); * HeartBeater.Instance.Beat(heartbeatFile); // Otherwise Heartbeater.Beat() will fail in various places * * testMode = true; * Console.WriteLine("Testing All Maintenance Processes (except membership-changing ones)."); * PWLog.Write(PWLogItem.None, 0, PWLogAction.SystemTest, string.Empty, string.Empty); * * Console.WriteLine("\r\n10-second intervals:"); * OnEveryTenSeconds(); * Console.WriteLine("\r\nEvery minute:"); * OnEveryMinute(); * Console.WriteLine("\r\nEvery five minutes:"); * OnEveryFiveMinutes(); * Console.WriteLine("\r\nEvery hour:"); * OnEveryHour(); * Console.WriteLine("\r\nNoon:"); * OnNoon(); * Console.WriteLine("\r\nMidnight:"); * OnMidnight(); */ Console.WriteLine("Testing database access..."); Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).Name); Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).PasswordHash); Console.WriteLine("Creating OutboundComm..."); OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Backend); Console.WriteLine("Transmitting..."); OutboundComms comms = OutboundComms.GetOpen(); Console.WriteLine("{0} open items in outbound comms.", comms.Count); foreach (OutboundComm comm in comms) { if (comm.TransmitterClass != "Swarmops.Utility.Communications.CommsTransmitterMail") { throw new NotImplementedException(); } ICommsTransmitter transmitter = new CommsTransmitterMail(); OutboundCommRecipients recipients = comm.Recipients; PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); foreach (OutboundCommRecipient recipient in recipients) { transmitter.Transmit(envelope, recipient.Person); } } Console.Write("\r\nAll tests run. Waiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { Thread.Sleep(50); } Console.WriteLine("done."); BotLog.Write(0, "MainCycle", "Exiting self-tests"); return; } if (args[0].ToLower() == "console") { Console.WriteLine("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n"); // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ----------------------- INSERT ANY ONE-OFF ACTIONS HERE ------------------------- Console.Write("\r\nWaiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { Thread.Sleep(50); } Console.WriteLine("done."); return; } if (args[0].ToLowerInvariant() == "pdfregen") { if (args.Length > 1) { int docId = Int32.Parse(args[1]); PdfProcessor.Rerasterize(Document.FromIdentity(docId)); } else { Console.WriteLine("Regenerating all bitmaps from PDF uploads."); PdfProcessor.RerasterizeAll(); Console.WriteLine("Done."); } return; } if (args[0].ToLower() == "rsm") { Console.WriteLine("Testing character encoding: räksmörgås RÄKSMÖRGÅS"); return; } } /* * MailMessage message = new MailMessage(); * message.From = new MailAddress(Strings.MailSenderAddress, Strings.MailSenderName); * message.To.Add (new MailAddress ("*****@*****.**", "Rick Falkvinge (Piratpartiet)")); * message.Subject = "Räksmörgåsarnas ékÖNÖMÏåvdëlnïng"; * message.Body = "Hejsan hoppsan Räksmörgåsar."; * message.BodyEncoding = Encoding.Default; * message.SubjectEncoding = Encoding.Default; * * SmtpClient smtpClient = new SmtpClient ("localhost"); * smtpClient.Credentials = null; // mono bug * smtpClient.Send (message);*/ Console.WriteLine(" * Swarmops Backend starting"); BotLog.Write(0, "MainCycle", "Backend STARTING"); // Disable certificate checking due to Mono not installing with a certificate repository - this is UTTERLY broken SupportFunctions.DisableSslCertificateChecks(); // MONO BUG/MISFEATURE: Mono has no root certificates, so can't verify cert // Tell sysop we're starting OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Backend); // Check for existence of installation ID. If not, create one. Warning: has privacy implications when communicated. if (Persistence.Key["SwarmopsInstallationId"] == string.Empty) { Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString(); } // Check for existence of bitcoin hotwallet root BitcoinUtility.VerifyBitcoinHotWallet(); // Initialize backend socket server int backendSocketPort = SystemSettings.WebsocketPortBackend; _socketServer = new WebSocketServer(backendSocketPort); _socketServer.AddWebSocketService <BackendServices>("/Backend"); _socketServer.Start(); // Initialize socket client to Blockchain.Info (pending our own services) using ( _blockChainInfoSocket = new WebSocket("wss://ws.blockchain.info/inv?api_code=" + SystemSettings.BlockchainSwarmopsApiKey)) { // Begin maintenance loop DateTime cycleStartTime = DateTime.UtcNow; DateTime cycleEndTime; int lastSecond = cycleStartTime.Second; int lastMinute = cycleStartTime.Minute; int lastHour = cycleStartTime.Hour; bool exitFlag = false; _blockChainInfoSocket.OnOpen += new EventHandler(OnBlockchainOpen); _blockChainInfoSocket.OnError += new EventHandler <ErrorEventArgs>(OnBlockchainError); _blockChainInfoSocket.OnClose += new EventHandler <CloseEventArgs>(OnBlockchainClose); _blockChainInfoSocket.OnMessage += new EventHandler <MessageEventArgs>(OnBlockchainMessage); _blockChainInfoSocket.Connect(); while (!exitFlag) // exit is handled by signals handling at end of loop { BotLog.Write(0, "MainCycle", "Cycle Start"); cycleStartTime = DateTime.UtcNow; cycleEndTime = cycleStartTime.AddSeconds(10); try { OnEveryTenSeconds(); if (cycleStartTime.Second < lastSecond) { OnEveryMinute(); if (cycleStartTime.Minute % 5 == 0) { OnEveryFiveMinutes(); } } if (cycleStartTime.Minute < lastMinute) { OnEveryHour(); if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday) { OnTuesdayMorning(); } if (DateTime.Now.Hour == 7 && DateTime.Today.DayOfWeek == DayOfWeek.Monday) { OnMondayMorning(); } } if (cycleStartTime.Hour >= 12 && lastHour < 12) { OnNoon(); } if (cycleStartTime.Hour < lastHour) { OnMidnight(); } } catch (Exception e) { // Note each "OnEvery..." catches its own errors and sends Exception mails, // so that failure in one should not stop the others from running. This particular // code should never run. ExceptionMail.Send(new Exception("Failed in swarmops-backend main loop", e), true); } lastSecond = cycleStartTime.Second; lastMinute = cycleStartTime.Minute; lastHour = cycleStartTime.Hour; // Wait for a maximum of ten seconds (the difference between cycleStartTime and cycleEndTime) int iterationCount = 0; DateTime utcNow = DateTime.UtcNow; while (utcNow < cycleEndTime && !exitFlag) { int signalIndex = 250; // Handle important service orders (those that can't be lost in a random loss // of connection of a socket): BackendServiceOrders backendOrders = BackendServiceOrders.GetNextBatch(5); backendOrders.Execute(); // takes at most 250ms per BSO reqs // Block until a SIGINT or SIGTERM signal is generated, or 1/4 second has passed. // However, we can't do that in a development environment - it won't have the // Mono.Posix assembly, and won't understand UnixSignals. So people running this in // a dev environment will need to stop it manually. if (!Debugger.IsAttached) { signalIndex = UnixSignal.WaitAny(killSignals, 250); } else { TimeSpan timeLeft = (cycleEndTime - utcNow); BotLog.Write(0, "MainCycle Debug", string.Format(CultureInfo.InvariantCulture, "Waiting for {0:F2} more seconds for cycle end", timeLeft.TotalMilliseconds / 1000.0)); Thread.Sleep(250); } if (signalIndex < 250) { exitFlag = true; Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum + ", exiting"); BotLog.Write(0, "MainCycle", "EXIT SIGNAL (" + killSignals[signalIndex].Signum + "), terminating backend"); } utcNow = DateTime.UtcNow; // Every second, send an internal heartbeat if (iterationCount++ % 4 == 0) { InternalHeartbeat(); } } } } Console.WriteLine(" * Swarmops Backend stopping"); BotLog.Write(0, "MainCycle", "BACKEND EXITING, sending backend-termination notices"); /* * if (HeartBeater.Instance.WasKilled) * { * // removed unconditional delete, cron job that restarts bot uses it to know that it is intentionally down. * ExceptionMail.Send(new Exception("HeartBeater triggered restart of Swarmops Backend. Will commence after 800 seconds."), false); * }*/ BotLog.Write(0, "MainCycle", "...done"); /* * while (!MailTransmitter.CanExit) * { * System.Threading.Thread.Sleep(50); * }*/ _socketServer.Stop(); Thread.Sleep(2000); }
private static void OnNoon() { BotLog.Write(0, "MainCycle", "Noon entry"); try { if (!PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE)) { // PPSE is still running PW4 code for this, so don't run for PPSE Payroll.ProcessMonthly(); // will only actually run on the 1st, but no harm in testing every noon } if (!testMode) { /*TestTrace("Running RosterHousekeeping.RemindAllExpiries()..."); * RosterHousekeeping.RemindAllExpiries(); * TestTrace(" done.\r\n");*/ } } catch (Exception e) { TraceAndReport(e); } try { if (!testMode) { /*TestTrace("Running SupportDatabase.NotifyBouncingEmails()..."); * SupportDatabase.NotifyBouncingEmails(); * TestTrace(" done.\r\n");*/ } } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportDatabase.CloseDelayWarnings()..."); * SupportDatabase.CloseDelayWarnings(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } try { /*TestTrace("Running SupportMailReview.Run()..."); * SupportMailReview.Run(); * TestTrace(" done.\r\n");*/ } catch (Exception e) { TraceAndReport(e); } BotLog.Write(0, "MainCycle", "Noon exit"); }
public static void Run() { BotLog.Write(1, "SeForumCheck", "Entering"); Memberships memberships = Memberships.ForOrganization(Organization.PPSE); IForumDatabase forumDatabase = SwedishForumDatabase.GetDatabase(); int[] accountIds; try { accountIds = forumDatabase.GetAccountList(); } catch (Exception e) { ExceptionMail.Send(new Exception("Failed to connect to vBulletin", e), true); BotLog.Write(1, "SeForumCheck", "Failed to connect -- exiting"); return; } BotLog.Write(1, "SeForumCheck", "Primed db - entering promotion cycle"); Dictionary <int, bool> memberAccountLookup = new Dictionary <int, bool>(); // This is kind of suboptimal, but hey, it only runs once a night in the wolf hour. Person currentMember = null; foreach (Membership membership in memberships) { if (!membership.Active) { continue; } currentMember = membership.Person; try { if (currentMember.SwedishForumAccountId != 0) { if (!forumDatabase.IsPartyMember(currentMember.SwedishForumAccountId)) { // This guy is not listed as a party member, but should be. BotLog.Write(2, "SeForumCheck", "Promoting " + currentMember.Name); forumDatabase.SetPartyMember(currentMember.SwedishForumAccountId); } memberAccountLookup[currentMember.SwedishForumAccountId] = true; } } catch (Exception e) { // The forum account probably doesn't exist. Just remove it from the profile. BotLog.Write(2, "SeForumCheck", "Exception reading " + currentMember.Name + ": " + e.ToString()); try { currentMember.SwedishForumAccountId = 0; } catch (Exception e2) { string logMessage = "Exception removing " + currentMember.Name + "'s forum account: " + e2.ToString(); BotLog.Write(2, "SeForumCheck", logMessage); ExceptionMail.Send(new Exception(logMessage, e2)); } } } // Now that we have flagged all member accounts as member accounts, flag the rest as // non-party members. BotLog.Write(1, "SeForumCheck", "Promotion cycle done - entering demotion cycle"); foreach (int accountId in accountIds) { if (!memberAccountLookup.ContainsKey(accountId)) { if (forumDatabase.IsPartyMember(accountId)) { BotLog.Write(2, "SeForumCheck", "Demoting forum account " + forumDatabase.GetAccountName(accountId)); forumDatabase.SetPartyNonmember(accountId); } } } BotLog.Write(1, "SeForumCheck", "Demotion cycle complete -- exiting"); }
private static void Main(string[] args) { testMode = false; UnixSignal[] killSignals = { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }; BotLog.Write(0, "MainCycle", string.Empty); BotLog.Write(0, "MainCycle", "-----------------------------------------------"); BotLog.Write(0, "MainCycle", string.Empty); if (args.Length > 0) { if (args[0].ToLower() == "test") { /* * BotLog.Write(0, "MainCycle", "Running self-tests"); * HeartBeater.Instance.Beat(heartbeatFile); // Otherwise Heartbeater.Beat() will fail in various places * * testMode = true; * Console.WriteLine("Testing All Maintenance Processes (except membership-changing ones)."); * PWLog.Write(PWLogItem.None, 0, PWLogAction.SystemTest, string.Empty, string.Empty); * * Console.WriteLine("\r\n10-second intervals:"); * OnEveryTenSeconds(); * Console.WriteLine("\r\nEvery minute:"); * OnEveryMinute(); * Console.WriteLine("\r\nEvery five minutes:"); * OnEveryFiveMinutes(); * Console.WriteLine("\r\nEvery hour:"); * OnEveryHour(); * Console.WriteLine("\r\nNoon:"); * OnNoon(); * Console.WriteLine("\r\nMidnight:"); * OnMidnight(); */ Console.WriteLine("Testing database access..."); Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).Name); Console.WriteLine(SwarmDb.GetDatabaseForReading().GetPerson(1).PasswordHash); Console.WriteLine("Creating OutboundComm..."); OutboundComm.CreateNotification(null, NotificationResource.System_Startup); Console.WriteLine("Transmitting..."); OutboundComms comms = OutboundComms.GetOpen(); Console.WriteLine("{0} open items in outbound comms.", comms.Count); foreach (OutboundComm comm in comms) { if (comm.TransmitterClass != "Swarmops.Utility.Communications.CommsTransmitterMail") { throw new NotImplementedException(); } ICommsTransmitter transmitter = new CommsTransmitterMail(); OutboundCommRecipients recipients = comm.Recipients; PayloadEnvelope envelope = PayloadEnvelope.FromXml(comm.PayloadXml); foreach (OutboundCommRecipient recipient in recipients) { transmitter.Transmit(envelope, recipient.Person); } } Console.Write("\r\nAll tests run. Waiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { Thread.Sleep(50); } Console.WriteLine("done."); BotLog.Write(0, "MainCycle", "Exiting self-tests"); return; } if (args[0].ToLower() == "console") { Console.WriteLine("\r\nRunning Swarmops-Backend in CONSOLE mode.\r\n"); // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ----------------------- INSERT ANY ONE-OFF ACTIONS HERE ------------------------- Console.Write("\r\nWaiting for mail queue to flush... "); while (!MailTransmitter.CanExit) { Thread.Sleep(50); } Console.WriteLine("done."); return; } if (args[0].ToLower() == "rsm") { Console.WriteLine("Testing character encoding: räksmörgås RÄKSMÖRGÅS"); return; } } /* * MailMessage message = new MailMessage(); * message.From = new MailAddress(Strings.MailSenderAddress, Strings.MailSenderName); * message.To.Add (new MailAddress ("*****@*****.**", "Rick Falkvinge (Piratpartiet)")); * message.Subject = "Räksmörgåsarnas ékÖNÖMÏåvdëlnïng"; * message.Body = "Hejsan hoppsan Räksmörgåsar."; * message.BodyEncoding = Encoding.Default; * message.SubjectEncoding = Encoding.Default; * * SmtpClient smtpClient = new SmtpClient ("localhost"); * smtpClient.Credentials = null; // mono bug * smtpClient.Send (message);*/ Console.WriteLine(" * Swarmops Backend starting"); BotLog.Write(0, "MainCycle", "Backend STARTING"); OutboundComm.CreateNotification(null, NotificationResource.System_Startup); // Checking for schemata upgrade DatabaseMaintenance.UpgradeSchemata(); // Check for existence of installation ID. If not, create one. Warning: has privacy implications when communicated. if (Persistence.Key["SwarmopsInstallationId"] == string.Empty) { Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString(); } DateTime cycleStartTime = DateTime.Now; int lastSecond = cycleStartTime.Second; int lastMinute = cycleStartTime.Minute; int lastHour = cycleStartTime.Hour; bool exitFlag = false; while (!exitFlag) // exit is handled by signals handling at end of loop { BotLog.Write(0, "MainCycle", "Cycle Start"); cycleStartTime = DateTime.Now; try { OnEveryTenSeconds(); if (cycleStartTime.Second < lastSecond) { OnEveryMinute(); if (cycleStartTime.Minute % 5 == 0) { OnEveryFiveMinutes(); } } if (cycleStartTime.Minute < lastMinute) { OnEveryHour(); if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday) { OnTuesdayMorning(); } } if (cycleStartTime.Hour >= 12 && lastHour < 12) { OnNoon(); } if (cycleStartTime.Hour < lastHour) { OnMidnight(); } } catch (Exception e) { // Note each "OnEvery..." catches its own errors and sends Exception mails, // so that failure in one should not stop the others from running. This particular // code should never run. ExceptionMail.Send(new Exception("Failed in swarmops-backend main loop", e), true); } lastSecond = cycleStartTime.Second; lastMinute = cycleStartTime.Minute; lastHour = cycleStartTime.Hour; // Wait for a maximum of ten seconds while (DateTime.Now < cycleStartTime.AddSeconds(10) && !exitFlag) { // block until a SIGINT or SIGTERM signal is generated, or one second has passed. int signalIndex = UnixSignal.WaitAny(killSignals, 1000); if (signalIndex < 1000) { exitFlag = true; Console.WriteLine("Caught signal " + killSignals[signalIndex].Signum + ", exiting"); BotLog.Write(0, "MainCycle", "EXIT SIGNAL (" + killSignals[signalIndex].Signum + "), terminating backend"); } } } Console.WriteLine(" * Swarmops Backend stopping"); BotLog.Write(0, "MainCycle", "BACKEND EXITING, sending backend-termination notices"); /* * if (HeartBeater.Instance.WasKilled) * { * // removed unconditional delete, cron job that restarts bot uses it to know that it is intentionally down. * ExceptionMail.Send(new Exception("HeartBeater triggered restart of Swarmops Backend. Will commence after 800 seconds."), false); * }*/ BotLog.Write(0, "MainCycle", "...done"); /* * while (!MailTransmitter.CanExit) * { * System.Threading.Thread.Sleep(50); * }*/ Thread.Sleep(2000); }
public void Setup(CommandsHandler handler, BotLog log) { this.Handler = handler; this.Log = log; }
public UserEvents(DiscordClient dClient, BotContextFactory dbFactory, BotLog log, ActivityManager activityManager) { this.dClient = dClient; this.dbFactory = dbFactory; this.activityManager = activityManager; }