public async Task DelwarnCmd( CommandContext ctx, [Description("The user you're removing a warn from. Accepts many formats.")] DiscordUser targetUser, [Description("The ID for the warning you want to delete.")] ulong warnId ) { UserWarning warning = GetWarning(targetUser.Id, warnId); if (warning == null) { await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I couldn't find a warning for that user with that ID! Please check again."); } else if (GetPermLevel(ctx.Member) == ServerPermLevel.CommunityManager && warning.ModUserId != ctx.User.Id) { await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} {ctx.User.Mention}, as a Trial Moderator you cannot edit or delete warnings that aren't issued by you!"); } else { DelWarning(warning); await ctx.RespondAsync($"{Program.cfgjson.Emoji.Deleted} Successfully deleted warning `{Pad(warnId)}` (belonging to {targetUser.Mention})"); await Program.logChannel.SendMessageAsync($"{Program.cfgjson.Emoji.Deleted} Warning deleted:" + $"`{Pad(warnId)}` (belonging to {targetUser.Mention}, deleted by {ctx.Member.Username}#{ctx.Member.Discriminator})", await FancyWarnEmbedAsync(warning, true, 0xf03916)); } }
public static async Task <DiscordEmbed> FancyWarnEmbedAsync(UserWarning warning, bool detailed = false, int colour = 0xFEC13D, bool showTime = true) { DiscordUser targetUser = await Program.discord.GetUserAsync(warning.TargetUserId); DiscordEmbedBuilder embed = new DiscordEmbedBuilder() .WithDescription($"**Reason**\n{warning.WarnReason}") .WithColor(new DiscordColor(colour)) .WithTimestamp(DateTime.Now) .WithFooter( $"User ID: {warning.TargetUserId}", null ) .WithAuthor( $"Warning for {targetUser.Username}#{targetUser.Discriminator}", null, targetUser.AvatarUrl ) .AddField("Warning ID", Pad(warning.WarningId), true); if (detailed) { embed.AddField("Responsible moderator", $"<@{warning.ModUserId}>") .AddField("Message link", warning.ContextLink == null ? "N/A" : $"[`Jump to warning`]({warning.ContextLink})"); } if (showTime) { embed.AddField("Time", detailed ? $"{warning.WarnTimestamp.ToUniversalTime()} UTC" : $"{TimeToPrettyFormat((DateTime.Now - warning.WarnTimestamp))}", true); } return(embed); }
public bool TryEditDeliveryType(string id, uint orderNumber, DeliveryType newType) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state != OrderState.Formation) { UserWarning?.Invoke("Тип доставки можно менять только во время формирования заказа"); return(false); } order.DeliveryType = newType; CheckCustomerDiscounts(id); StateChanged?.Invoke(); return(true); }
/// <summary> /// Posts a notification that a user was warned. /// </summary> /// <param name="warning">The warning.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <Result> NotifyUserWarningAddedAsync(UserWarning warning) { var getChannel = await GetModerationLogChannelAsync(warning.Server.DiscordID); if (!getChannel.IsSuccess) { return(Result.FromError(getChannel)); } var channel = getChannel.Entity; var eb = new Embed { Colour = _feedback.Theme.Warning, Title = $"User Warned (#{warning.ID})", Description = $"<@{warning.User.DiscordID}> (ID {warning.User.DiscordID}) was warned by " + $"<@{warning.Author.DiscordID}>.\n" + $"Reason: {warning.Reason}" }; var sendResult = await _feedback.SendEmbedAsync(channel, eb); return(sendResult.IsSuccess ? Result.FromSuccess() : Result.FromError(sendResult)); }
/// <summary> /// Sets the reasons of the given warning. /// </summary> /// <param name="warning">The warning.</param> /// <param name="reason">The reason.</param> /// <param name="ct">The cancellation token in use.</param> /// <returns>A modification result which may or may not have succeeded.</returns> public async Task <ModifyEntityResult> SetWarningReasonAsync ( UserWarning warning, string reason, CancellationToken ct = default ) { if (reason.IsNullOrWhitespace()) { return(ModifyEntityResult.FromError("You must provide some reason for the warning.")); } if (reason.Length > 1024) { return(ModifyEntityResult.FromError ( "The warning is too long. It can be at most 1024 characters." )); } if (warning.Reason == reason) { return(ModifyEntityResult.FromError("That's already the warning's reason.")); } warning.Reason = reason; warning.NotifyUpdate(); await _database.SaveChangesAsync(ct); return(ModifyEntityResult.FromSuccess()); }
public bool TryPushNextState(string id, uint orderNumber) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state >= OrderState.Completed) { UserWarning?.Invoke("Заказ уже находится в завершенном состоянии"); return(false); } if (order.OrderLinesAmount == 0) { UserWarning?.Invoke("Заказ не должен быть пустым"); return(false); } order.NextOrderState(); StateChanged?.Invoke(); return(true); }
public bool TryEditCreationDate(string id, uint orderNumber, DateTimeOffset newDate) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state != OrderState.Formation) { UserWarning?.Invoke("Дату создания заказа можно менять только на этапе формирования"); return(false); } order.CreationDate = newDate; CheckCustomerDiscounts(id); StateChanged?.Invoke(); return(true); }
public static void ReloadItemfilter() { // store current clipboard string oldClipboard = Clipboard.GetText(); string chatCommand = BuildChatCommand(); if (chatCommand is null) { return; } Clipboard.SetText(BuildChatCommand()); var poeWindow = FindWindow(null, "Path of Exile"); if (poeWindow == IntPtr.Zero) { UserWarning.WarnUser("Could not find Window! Please make sure Path of Exile is running.", "Window not found"); return; } // get Path of Exile in the foreground to actually sendKeys to it SetForegroundWindow(poeWindow); // send the chat commands System.Windows.Forms.SendKeys.SendWait("{ENTER}"); System.Windows.Forms.SendKeys.SendWait("^(v)"); System.Windows.Forms.SendKeys.SendWait("{ENTER}"); // restore clipboard Clipboard.SetText(oldClipboard); }
public bool TryCancelOrder(string id, uint orderNumber) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state == OrderState.Formation) { UserWarning?.Invoke("Нельзя отменить неподтвержденный заказ"); return(false); } if (order.state >= OrderState.Completed) { UserWarning?.Invoke("Заказ уже завершен"); return(false); } order.CancelOrder(); StateChanged?.Invoke(); return(true); }
public bool TryRemoveDiscount(string id, uint orderNumber, string discountName) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state != OrderState.Formation) { UserWarning?.Invoke("Скидки должны быть применены на стадии формирования заказа"); return(false); } if (!discounts.TryGetValue(discountName, out Discount discount)) { UserWarning?.Invoke("В базе не найдено скидки с подобным именем"); return(false); } if (!order.discounts.Remove(discount.Family)) { UserWarning?.Invoke("В заказе не найдено скидки с подобным именем"); return(false); } StateChanged?.Invoke(); return(true); }
/// <summary> /// Posts a notification that a warning was rescinded. /// </summary> /// <param name="warning">The warning.</param> /// <param name="rescinder">The person who rescinded the warning.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task NotifyUserWarningRemoved(UserWarning warning, IGuildUser rescinder) { var guild = _client.GetGuild((ulong)warning.Server.DiscordID); var getChannel = await GetModerationLogChannelAsync(guild); if (!getChannel.IsSuccess) { return; } var channel = getChannel.Entity; var eb = _feedback.CreateEmbedBase(); eb.WithTitle($"Warning Removed (#{warning.ID})"); eb.WithColor(Color.Green); var whoDidIt = rescinder.IsMe(_client) ? "(expired)" : $"by {rescinder.Mention}"; eb.WithDescription ( $"A warning was removed from {MentionUtils.MentionUser((ulong)warning.User.DiscordID)} " + $"(ID {warning.User.DiscordID}) {whoDidIt}." ); await _feedback.SendEmbedAsync(channel, eb.Build()); }
/// <summary> /// Posts a notification that a user was warned. /// </summary> /// <param name="warning">The warning.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task NotifyUserWarningAdded(UserWarning warning) { var guild = _client.GetGuild((ulong)warning.Server.DiscordID); var getChannel = await GetModerationLogChannelAsync(guild); if (!getChannel.IsSuccess) { return; } var channel = getChannel.Entity; var author = guild.GetUser((ulong)warning.Author.DiscordID); var eb = _feedback.CreateEmbedBase(); eb.WithTitle($"User Warned (#{warning.ID})"); eb.WithColor(Color.Orange); var warnedUser = guild.GetUser((ulong)warning.User.DiscordID); eb.WithDescription ( $"{warnedUser.Mention} (ID {warnedUser.Id}) was warned by {author.Mention}.\n" + $"Reason: {warning.Reason}" ); await _feedback.SendEmbedAsync(channel, eb.Build()); }
public bool TryEditItemQuantity(string id, uint orderNumber, string itemArticle, uint newQuantity) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state != OrderState.Formation) { UserWarning?.Invoke("Состав заказа можно менять только во время формирования заказа"); return(false); } if (!items.TryGetValue(itemArticle, out Item item)) { UserWarning?.Invoke("В базе нет товара с данным артикулом"); return(false); } order.SetItemQuantity(item, newQuantity); CheckCustomerDiscounts(id); StateChanged?.Invoke(); return(true); }
public async Task WarnAsync( IDiscordGuild guild, MessageContext context, IDiscordGuildUser user, [Optional, Remaining] string reason) { var @event = await _eventManager.CallAsync(new UserWarnEvent(user, context.User, reason)); if (@event.IsCancelled) { return; } var warning = new UserWarning { GuildId = guild.Id, UserId = user.Id, ModeratorId = context.User.Id, Reason = reason, Created = DateTime.UtcNow }; await _warningRepository.AddAsync(warning); await _consoleService.UpdateWarningMessageAsync(context, warning, user, context.User); }
private async Task ReturnsUnsuccessfulIfWarningDoesNotExist() { var warning = new UserWarning(new Server(0), new User(0), new User(1), "Dummy thicc"); var result = await this.Warnings.DeleteWarningAsync(warning); Assert.False(result.IsSuccess); }
public bool DeleteItem(string itemArticle) { if (!items.ContainsKey(itemArticle)) { UserWarning?.Invoke("В базе нет товара с данным артикулом"); return(false); } items.Remove(itemArticle); StateChanged?.Invoke(); return(true); }
public bool TryAddOrder(string id, Order order) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } customer.OrderManager.AddOrder(order); StateChanged?.Invoke(); return(true); }
private static string BuildFilterReloadCommand() { var filterName = GetFilterName(); if (!string.IsNullOrEmpty(filterName)) { return("/itemfilter " + filterName); } UserWarning.WarnUser("No filter found. Please set your filter in settings", "No filter found"); return(null); }
public bool TryEditName(string id, FullName name) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } customer.Name = name; StateChanged?.Invoke(); return(true); }
private static string BuildChatCommand() { string filterName = GetFilterName().Trim(); Trace.WriteLine("filtername", filterName); if (String.IsNullOrEmpty(filterName)) { UserWarning.WarnUser("No filter found. Please set your filter in settings", "No filter found"); return(null); } return("/itemfilter " + filterName); }
public static bool DelWarning(UserWarning warning) { if (Program.db.HashExists(warning.TargetUserId.ToString(), warning.WarningId)) { Program.db.HashDelete(warning.TargetUserId.ToString(), warning.WarningId); return(true); } else { return(false); } }
public bool TryEditPhoneNumber(string id, string newNumber) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } customer.ContactPhone = newNumber; StateChanged?.Invoke(); return(true); }
// Customer public bool TryEditPrivilege(string id, Privilege newPrivilege) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } customer.Privilege = newPrivilege; CheckCustomerDiscounts(id); StateChanged?.Invoke(); return(true); }
/// <summary> /// Deletes the given warning. /// </summary> /// <param name="warning">The warning to delete.</param> /// <returns>A deletion result which may or may warning have succeeded.</returns> public async Task <DeleteEntityResult> DeleteWarningAsync(UserWarning warning) { if (!_database.UserWarnings.Any(n => n.ID == warning.ID)) { return(DeleteEntityResult.FromError ( "That warning isn't in the database. This is probably an error in the bot." )); } _database.UserWarnings.Remove(warning); await _database.SaveChangesAsync(); return(DeleteEntityResult.FromSuccess()); }
public bool TryDeleteOrder(string id, uint orderNumber) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.ContainsOrder(orderNumber)) { UserWarning?.Invoke("У клиента нет заказа с указанным номером"); return(false); } customer.OrderManager.RemoveOrder(orderNumber); StateChanged?.Invoke(); return(true); }
public int getUserWarning(string theUserName, int?theWarningId) { User u = lsUsers.getUser(theUserName); if (u == null) { u = addNewUser(theUserName); } UserWarning uw = u.user_warnings.getUserWarning(theWarningId); if (uw == null) { u.user_warnings.addWarning(theWarningId, dbUserCommunication, u); return(0); } return(uw.number); }
public async Task WarnDetailsCmd( CommandContext ctx, [Description("The user you're looking up detailed warn information for. Accepts many formats.")] DiscordUser targetUser, [Description("The ID of the warning you're looking at in detail.")] ulong warnId ) { UserWarning warning = GetWarning(targetUser.Id, warnId); if (warning == null) { await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I couldn't find a warning for that user with that ID! Please check again."); } else { await ctx.RespondAsync(null, await FancyWarnEmbedAsync(warning, true)); } }
public static void ReloadFilter() { // Saving state of current clipboard // TODO How does this work if you have non-text on your clipboard? var oldClipboard = Clipboard.GetText(); var chatCommand = BuildFilterReloadCommand(); if (chatCommand is null) { return; } Clipboard.SetDataObject(chatCommand); // Map all current window names to their associated "handle to a window" pointers (HWND) var openWindows = GetOpenWindows(); foreach (var window in openWindows) { var handle = window.Key; var title = window.Value; Console.WriteLine("{0}: {1}", handle, title); } // Find the Process ID associated with the 'Path of Exile' game window var poeWindow = openWindows.FirstOrDefault(x => x.Value == "Path of Exile").Key; if (poeWindow == HWND.Zero) { UserWarning.WarnUser("Could not find Window! Please make sure Path of Exile is running.", "Window not found"); return; } // Get 'Path of Exile' window in the foreground to actually send input to said window SetForegroundWindow(poeWindow); // Compose a series of commands we send to the game window (the in-game chat box, specifically) SendKeys.SendWait("{ENTER}"); SendKeys.SendWait("^(v)"); SendKeys.SendWait("{ENTER}"); // restore clipboard Clipboard.SetDataObject(oldClipboard); }
/// <summary> /// Sets the contextually relevant message for the warning. /// </summary> /// <param name="warning">The warning.</param> /// <param name="messageID">The message.</param> /// <returns>A modification result which may or may not have succeeded.</returns> public async Task <ModifyEntityResult> SetWarningContextMessageAsync ( UserWarning warning, long messageID ) { if (warning.MessageID == messageID) { return(ModifyEntityResult.FromError("That's already the warning's context message.")); } warning.MessageID = messageID; warning.NotifyUpdate(); await _database.SaveChangesAsync(); return(ModifyEntityResult.FromSuccess()); }
public bool TryAddDiscount(string id, uint orderNumber, string discountName) { if (!customers.TryGetValue(id, out Customer customer)) { UserWarning?.Invoke("Клиент с указанным id не найден в базе"); return(false); } if (!customer.OrderManager.TryGetOrder(orderNumber, out Order order)) { UserWarning?.Invoke("Заказ с указанным номером не найден в базе"); return(false); } if (order.state != OrderState.Formation) { UserWarning?.Invoke("Скидки должны быть применены на стадии формирования заказа"); return(false); } if (!discounts.TryGetValue(discountName, out Discount discount)) { UserWarning?.Invoke("В базе не найдено скидки с подобным именем"); return(false); } var check = discount.Check(customer, order); if (!check.Item1) { UserWarning?.Invoke(check.Item2); return(false); } if (order.discounts.TryGetValue(discount.Family, out Discount discountToRemove)) { DiscountDenied(orderNumber, discountToRemove.Name, string.Format("Скидка замещена другой скидкой ({0})", discount.Name)); order.discounts.Remove(discount.Family); } order.discounts.Add(discount.Family, discount); StateChanged?.Invoke(); return(true); }