public override async Task PerformAction(SocketReaction option) { switch (option.Emote.ToString()) { case ReactionHandler.CHECK_STR: Program.Settings.AdminUsers.Add(User.Id); Program.Settings.SaveJson(); await Context.Channel.SendMessageAsync(BotUtils.KamtroText($"Added user {BotUtils.GetFullUsername(User)} as an admin.")); KLog.Important($"User {BotUtils.GetFullUsername(User)} added as an admin"); EventQueueManager.RemoveEvent(this); await Message.DeleteAsync(); break; case ReactionHandler.DECLINE_STR: EventQueueManager.RemoveEvent(this); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Action Canceled.")); await Message.DeleteAsync(); break; } }
public override async Task PerformAction(SocketReaction option) { string number = option.Emote.ToString(); if (NUMBERS.Contains(number)) { int chosenIndex = Numbers.IndexOf(number); if (chosenIndex >= 0 && chosenIndex <= 10) { // if the index is valid SocketGuildUser su = UserOptions[chosenIndex]; if (hasContext) { // If this is the type of embed that needs context await selectedActionWithContext(su, Context); // Call the context method } else { await selectedAction(su); // Call the method passed in. } EventQueueManager.RemoveEvent(this); // Remove it from the queue if (Channel == null) { return; } await Channel.DeleteMessageAsync(Message); } } }
public override async Task ButtonAction(SocketReaction action) { switch (action.Emote.ToString()) { case ReactionHandler.DECLINE_STR: EventQueueManager.RemoveMessageEvent(Context.User.Id); await Context.Message.Channel.SendMessageAsync(BotUtils.KamtroText("Thank you for editing the log.")); await Message.DeleteAsync(); return; case ReactionHandler.CHECK_STR: HandleConfirm(); OpCursor = 0; // reset the cursor break; case BACK: if (!BackMap.ContainsKey(PageNum) || PageNum == 14) { PageNum = 1; break; } PageNum = BackMap[PageNum]; break; } await UpdateEmbed(); }
/// <param name="parentItemId">ID of the parent OneDrive item (folder/album/bundle).</param> public OneDriveProvider(string parentItemId) { this.parentItemId = parentItemId; if (EventQueueManager.Instance == null) { EventQueueManager.Init(); } }
public override void Init() { base.Init(); EventQueueManager.ResetInstance(); _eventProducer = new EventProducer(new AppConfigEventGeneratorsProvider().GetAll().ToArray()); _messageBuilderConsumer = new MessageBuilder(); }
public async override Task PerformAction(SocketReaction option) { if (option.Emote.ToString() == ReactionHandler.CHECK_STR) { await Hacked(); } EventQueueManager.RemoveEvent(this); }
public void ShouldUnregisterToEventEnqueuedEvent() { EventQueueManager.Instance.GetType(); // trigger lazy initialization EventQueueManager.OnEventEnqueued(EventPriority.High, 1); EventQueueManager.ResetInstance(); EventQueueManager.Instance.GetType(); // trigger lazy initialization EventQueueManager.OnEventEnqueued(EventPriority.High, 1); Assert.AreEqual(2, TelemetryCollector.GetDataAndReset()[CounterType.EnqueuedHighPriorityEvent]); }
public void PublishIncomingNotificationsViaWebSocket() { var cmdReq = new CommandRequest("cmd-req-name", "123123123"); var cmdRes = new CommandResponse(cmdReq); var @event = new IntegrationEvent <CommandResponse>(cmdRes, IntegrationEventAction.Created); EventQueueManager.Publish(@event); Thread.Sleep(250); Buffer.Any(x => x != 0).ShouldBeTrue(); }
/// <summary> /// Display the message, menu options and all /// </summary> /// <returns></returns> /// <param name="channel">The channel to display the message in. If left empty, it will be displayed in the channel the command was called in</param> public override async Task Display(IMessageChannel channel = null, string message = "") { if (channel == null) { channel = Context.Channel; } await base.Display(channel, message); await AddReactions(); // Add the reactions EventQueueManager.AddEvent(this); // Add the embed to the event queue with the correct ID }
public override async Task ButtonAction(SocketReaction action) { switch (action.Emote.ToString()) { case ReactionHandler.CHECK_STR: // On confirm if (!AllFieldsFilled()) { return; // Do nothing if the fields are not filled. } // otherwise, add the strike. StrikeDataNode str = new StrikeDataNode(Context.User, Reason); int strikes = AdminDataManager.AddStrike(Target, str); if (strikes >= 3) { await Context.Channel.SendMessageAsync(BotUtils.KamtroText($"{BotUtils.GetFullUsername(Target)} has 3 strikes")); break; } await Context.Channel.SendMessageAsync(BotUtils.KamtroText($"Added strike for {BotUtils.GetFullUsername(Target)}. They now have {strikes} strike{((strikes == 1) ? "":"s")}.")); if (notifyUser) { bool sent = await BotUtils.DMUserAsync(BotUtils.GetGUser(Target.Id), new StrikeNotifyEmbed(str.Reason, strikes).GetEmbed()); if (!sent) { await Context.Channel.SendMessageAsync(BotUtils.BadDMResponse); } } break; case diamond: // toggles the notification of the user notifyUser = !notifyUser; await UpdateEmbed(); return; } EventQueueManager.RemoveMessageEvent(this); // now remove the event }
public override async Task PerformAction(SocketReaction action) { switch (action.Emote.ToString()) { case ReactionHandler.DECLINE_STR: EventQueueManager.RemoveMessageEvent(this); await Message.DeleteAsync(); await Context.Channel.SendMessageAsync(BotUtils.KamtroText($"The ban on {BotUtils.GetFullUsername(Target)} has been cancelled.")); break; default: await ButtonAction(action); // if none of the predefined actions were used, it must be a custom action. break; } }
public async override Task PerformAction(SocketReaction option) { switch (option.Emote.ToString()) { case CHECK: await option.Channel.SendMessageAsync(BotUtils.KamtroText("You can now see the lewd owo")); EventQueueManager.RemoveEvent(this); await BotUtils.GetGUser(Context).AddRoleAsync(ServerData.NSFWRole); break; case DECLINE: await option.Channel.SendMessageAsync(BotUtils.KamtroText("Understood.")); EventQueueManager.RemoveEvent(this); break; } }
public override async Task PerformAction(SocketReaction option) { string number = option.Emote.ToString(); if (NUMBERS.Contains(number)) { int chosenIndex = Numbers.IndexOf(number); if (chosenIndex >= 0 && chosenIndex <= 10) { await SelectedAction(Options[chosenIndex]); // Call the method passed in. } EventQueueManager.RemoveEvent(this); // Remove it from the queue if (Context.Channel == null) { return; } await Context.Channel.DeleteMessageAsync(Message); } }
public override async Task PerformAction(SocketReaction option) { switch (option.Emote.ToString()) { case ReactionHandler.CHECK_STR: await Action(true); EventQueueManager.RemoveEvent(this); await Message.DeleteAsync(); break; case ReactionHandler.DECLINE_STR: await Action(false); EventQueueManager.RemoveEvent(this); await Message.DeleteAsync(); break; } }
protected IntegrationTestBase() { var path = PlatformServices.Default.Application.ApplicationBasePath; var serverDirectory = Path.GetFullPath(Path.Combine(path, @"../../../../../Application/Programmer.WebServer")); if (!Directory.Exists(serverDirectory)) { throw new DirectoryNotFoundException("Failed to find server root dir in path: " + serverDirectory); } var configurationRoot = new ConfigurationBuilder() .SetBasePath(serverDirectory) .AddJsonFile("appsettings.Test.json") .Build(); var builder = new WebHostBuilder() .UseContentRoot(serverDirectory) .UseStartup <Startup>() // .UseUrls(BaseUri.AbsoluteUri) .UseConfiguration(configurationRoot); Configuration = configurationRoot.Providers.FirstOrDefault(); var server = new TestServer(builder); HttpClient = server.CreateClient(); HttpClient.BaseAddress = server.BaseAddress;; var wsc = server.CreateWebSocketClient(); WebSocket = wsc.ConnectAsync(new Uri(server.BaseAddress, "ws"), CancellationToken.None).Result; _buffer = WebSocket.CreateClientBuffer(1024, 1024); Task.Run(() => WebSocket.ReceiveAsync(_buffer, CancellationToken.None)); EventQueueManager = new EventQueueManager(); EventQueueManager.Flush(); EventQueueManager.Setup(Configuration); }
public override async Task ButtonAction(SocketReaction action) { if (action.Emote.ToString() == ReactionHandler.CHECK_STR) { TimeZone.Replace(" ", ""); if (Regex.IsMatch(TimeZone, PATTERN)) { TimeZoneNode node = new TimeZoneNode(Regex.Match(TimeZone, PATTERN).Value); UserDataManager.GetUserData(BotUtils.GetGUser(Context)).TimeZone = node; UserDataManager.SaveUserData(); EventQueueManager.RemoveMessageEvent(this); await Message.DeleteAsync(); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Time zone set successfuly!")); } else { BadFormat = true; await UpdateEmbed(); } } }
public async override Task PerformAction(SocketReaction option) { switch (option.Emote.ToString()) { case MODIFY: kamtroText = !kamtroText; await Message.ModifyAsync(x => x.Embed = GetEmbed()); break; case END: if (targetChannel != null) { await option.Channel.SendMessageAsync(BotUtils.KamtroText($"You will no longer send messages to {targetChannel.Name}.")); } else if (targetUser != null) { await option.Channel.SendMessageAsync(BotUtils.KamtroText($"You will no longer send messages to {targetUser.Username}#{targetUser.Discriminator}.")); } EventQueueManager.RemoveEvent(this); break; } }
public override async Task ButtonAction(SocketReaction action) { switch (action.Emote.ToString()) { case ReactionHandler.CHECK_STR: if (Remove) { await RemRole(); } else { await AddRole(); } Program.ReloadConfig(); EventQueueManager.RemoveEvent(this); await Message.DeleteAsync(); break; case ReactionHandler.DECLINE_STR: if (Remove) { await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Role deletion has been cancelled.")); } else { await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Role addition has been cancelled.")); } EventQueueManager.RemoveMessageEvent(this); await Context.Channel.DeleteMessageAsync(Message); break; } }
/// <summary> /// Displays the embed. /// </summary> /// -C /// <param name="channel">The channel to display the embed in</param> /// <returns></returns> public override async Task Display(IMessageChannel channel = null, string message = "") { await base.Display(channel, message); EventQueueManager.AddMessageEvent(this); }
public override async Task PerformAction(SocketReaction option) { string opt = option.Emote.ToString(); switch (opt) { case ReactionHandler.CHECK_STR: if (Emote == BotUtils.ZeroSpace || Emote == EmptyOrInvalidEmote) { Emote = EmptyOrInvalidEmote; await UpdateEmbed(); return; } if (ReactionHandler.RoleMap.ContainsKey(Emote)) { if (ServerData.Server.GetRole(ReactionHandler.RoleMap[Emote]) == null) { ulong id = ReactionHandler.RoleMap[Emote]; ReactionHandler.RoleMap.Remove(Emote); ReactionHandler.SaveRoleMap(); EventQueueManager.RemoveEvent(this); await ReactionHandler.CloseActionEmbedAsync(this); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Something went wrong! Please use the command again!")); KLog.Info($"[REE] Role was null! ID: {id}"); return; } Emote = $"The role {ServerData.Server.GetRole(ReactionHandler.RoleMap[Emote]).Mention} already has that emote!"; await UpdateEmbed(); break; } if (ServerData.Server.GetRole(Role.Id) == null) { ulong id = ReactionHandler.RoleMap[Emote]; EventQueueManager.RemoveEvent(this); await ReactionHandler.CloseActionEmbedAsync(this); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Something went wrong! Please use the command again!")); KLog.Info($"[REE] Role was null! ID: {id}"); return; } ReactionHandler.RoleMap.Add(Emote, Role.Id); ReactionHandler.SaveRoleMap(); await GeneralHandler.UpdateRoleMessage(); EventQueueManager.RemoveEvent(this); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Emote Association Added.")); await Message.DeleteAsync(); break; case ReactionHandler.DECLINE_STR: EventQueueManager.RemoveEvent(this); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Action Canceled.")); await Message.DeleteAsync(); break; default: Emote = option.Emote.ToString(); await UpdateEmbed(); break; } }
public void TestInitialize() { EventQueueManager.ResetInstance(); _queueManager = EventQueueManager.Instance; }
protected override async Task Process() { var e = DeserializeTyped(); if (e is OrganizationEventBase organizationEvent) { Logger.LogInformation("Event {@eventGroup} {@eventName} {@organizationKey} {@initiatorOrganizationKey}/{@initiatorUserKey} {@initiatorUserAgent}", "Organization", organizationEvent.Name, organizationEvent.OrganizationIdentifier?.OrganizationKey, organizationEvent.UserIdentifier?.OrganizationKey, organizationEvent.UserIdentifier?.UserKey, organizationEvent.UserAgent ); } else if (e is UserEventBase userEvent) { Logger.LogInformation("Event {@eventGroup} {@eventName} {@organizationKey}/{@userKey} {@initiatorOrganizationKey}/{@initiatorUserKey} {@initiatorUserAgent}", "User", userEvent.Name, userEvent.UserIdentifierTopic?.OrganizationKey, userEvent.UserIdentifierTopic?.UserKey, userEvent.UserIdentifier?.OrganizationKey, userEvent.UserIdentifier?.UserKey, userEvent.UserAgent ); } else if (e is FolderEventBase folderEvent) { Logger.LogInformation("Event {@eventGroup} {@eventName} {@organizationKey}/{@folderKey} {@initiatorOrganizationKey}/{@initiatorUserKey} {@initiatorUserAgent}", "Folder", folderEvent.Name, folderEvent.FolderIdentifier?.OrganizationKey, folderEvent.FolderIdentifier?.FolderKey, folderEvent.UserIdentifier?.OrganizationKey, folderEvent.UserIdentifier?.UserKey, folderEvent.UserAgent ); if (e is FolderPutEvent || e is FolderPostEvent) { await EnqueueAsync("Index", new IndexMessage { Action = IndexMessage.IndexActions.IndexFolder, Identifier = new FileIdentifier(folderEvent.FolderIdentifier, null) }); } } else if (e is FileEventBase fileEvent) { Logger.LogInformation("Event {@eventGroup} {@eventName} {@organizationKey}/{@folderKey}/{@fileKey} {@initiatorOrganizationKey}/{@initiatorUserKey} {@initiatorUserAgent}", "File", fileEvent.Name, fileEvent.FileIdentifier?.OrganizationKey, fileEvent.FileIdentifier?.FolderKey, fileEvent.FileIdentifier?.FileKey, fileEvent.UserIdentifier?.OrganizationKey, fileEvent.UserIdentifier?.UserKey, fileEvent.UserAgent ); if ( e is FilePostEvent || e is FilePostEvent || e is FilePutEvent || e is FileContentsUploadCompleteEvent || e is FileTextContentChangeEvent) { await EnqueueAsync("Index", new IndexMessage { Action = IndexMessage.IndexActions.IndexFile, Identifier = fileEvent.FileIdentifier }); } else if (e is FileDeleteEvent) { await EnqueueAsync("Index", new IndexMessage { Action = IndexMessage.IndexActions.DeleteFile, Identifier = fileEvent.FileIdentifier }); } var eventHandler = new EventQueueManager() as EventQueueMapBase; await eventHandler.HandleEventAsync(e, async (queue, message) => { Logger.LogDebug($" -> Queueing {queue} {message}"); await API.Queue.EnqueueAsync(queue, message); }, API); } else { Logger.LogInformation("Event {@eventGroup} {@eventName} {@initiatorOrganizationKey}/{@initiatorUserKey} {@initiatorUserAgent}", null, e.Name, e.UserIdentifier?.OrganizationKey, e.UserIdentifier?.UserKey, e.UserAgent ); } }
/// <summary> /// Garbage collection thread method. /// This stops kamtro from waiting for interfaces that are going to be unused. /// </summary> /// <remarks> /// VERY IMPORTANT: This method has the potential to cause a race condition with the autosave thread. This is why the two should NEVER /// access the same variables. /// /// -C /// </remarks> public static void GarbageCollection() { DateTime now; TimeSpan span; while (GCReady && GCLoop) { if (PauseGC) { Thread.Sleep(new TimeSpan(0, 1, 0)); continue; } GCInProgress = true; List <EventQueueNode> toRemove = new List <EventQueueNode>(); List <ulong> toRemoveMsg = new List <ulong>(); now = DateTime.Now; foreach (KeyValuePair <ulong, MessageEventNode> action in EventQueueManager.MessageEventQueue.AsEnumerable()) { span = now - action.Value.TimeCreated; if (span > action.Value.Interface.Timeout) { toRemoveMsg.Add(action.Key); // Let user know embed is disabled action.Value.Interface.Message.ModifyAsync(x => x.Content = KamtroText("This embed is no longer in use.")); action.Value.Interface.Message.ModifyAsync(x => x.Embed = null); } } foreach (ulong node in toRemoveMsg) { EventQueueManager.RemoveMessageEvent(node); Console.WriteLine($"[GC] Message Event from user {node} removed."); } foreach (KeyValuePair <ulong, List <EventQueueNode> > action in EventQueueManager.EventQueue.AsEnumerable()) { foreach (EventQueueNode node in action.Value) { span = now - node.TimeCreated; if (span > node.EventAction.Timeout || node.IsAlone && span > node.EventAction.Timeout) { toRemove.Add(node); // Let user know embed is disabled node.EventAction.Message.ModifyAsync(x => x.Content = KamtroText("This embed is no longer in use.")); node.EventAction.Message.ModifyAsync(x => x.Embed = null); } } foreach (EventQueueNode node in toRemove) { action.Value.Remove(node); Console.WriteLine($"[GC] Event from user {action.Key} removed. {((node.IsAlone) ? "Event was paired with message event from same user." : "")}"); } } GCInProgress = false; Thread.Sleep(new TimeSpan(0, 1, 0)); } }
public override async Task ButtonAction(SocketReaction action) { switch (action.Emote.ToString()) { case ReactionHandler.CHECK_STR: // verify inputs int k, t, p; // kamtrokens, temp rep, and perm rep respectively if (!(int.TryParse(KamtrokenReward, out k) && int.TryParse(TempRepReward, out t) && int.TryParse(PermRepReward, out p))) { InvalidNumberWarning = true; await UpdateEmbed(); return; } // Color string c = EmbedColor.Replace("#", "").Replace("0x", "").Replace("x", ""); uint cc; if (!uint.TryParse(c, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out cc)) { InvalidNumberWarning = true; await UpdateEmbed(); return; } Color ec = new Color(cc); // Add the stats UserDataNode data = UserDataManager.GetUserData(Winner); data.Kamtrokens += k; data.ReputationToGive += t; data.MaxReputation += p; UserDataManager.SaveUserData(); // Send the gift string wins = ""; if (k > 0) { wins += $"{k} Kamtroken{(k == 1 ? "":"s")}"; } if (t > 0) { if (wins.Length != 0) { wins += ", "; } wins += $"{t} Temporary Reputation Point{(t == 1 ? "" : "s")}"; } wins.TrimEnd(',', ' '); if (k == 0 && t == 0) { wins = ""; } if (p > 0) { wins += $"\n\nIn addition, the amount of repuation you get per week has been increaced by {p}"; } await BotUtils.DMUserAsync(Winner, new BasicEmbed("Congradulations!", $"You have won {(string.IsNullOrWhiteSpace(wins) ? "my appreciation!":wins)}", "Winnings", ec, "", MessageText).GetEmbed()); // Update the embed GiftSent = true; await UpdateEmbed(); EventQueueManager.RemoveMessageEvent(this); break; case ReactionHandler.DECLINE_STR: EventQueueManager.RemoveMessageEvent(this); await Message.DeleteAsync(); await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Reward Sending Canceled.")); break; } }