/// <summary> /// Abstract method for Help command. /// </summary> /// <param name="msg">Message containing command invocation.</param> /// <returns>Async Task performing Help function.</returns> protected virtual async Task HelpCommand(SocketMessage msg) { if (!(msg.Author is SocketGuildUser user)) { return; } await msg.DeleteAsyncSafe($"[{LogPref}][HELP]").ConfigureAwait(false); await msg.Channel.SendMessageAsync(String.Empty, false, BuildHelpEmbed(user)).ConfigureAwait(false); }
protected virtual async Task VerboseListCommand(SocketMessage msg) { string cmdPrefix = $"[{LogPref}][VLIST]"; await msg.DeleteAsyncSafe(cmdPrefix).ConfigureAwait(false); var regexMatch = Regex.Match(msg.Content, ListCommandRegex); if (!regexMatch.Success) { return; } var cmdKey = regexMatch.Groups["key"].Value; var itemsDict = new Dictionary <string, XElement>(); RPItemDictGenerator(GetRootByKey(cmdKey), String.IsNullOrWhiteSpace(cmdKey) ? String.Empty : $"{cmdKey}.", itemsDict); List <string> outputMsgs = new List <string>(); string output = String.Concat("**Розширений список цитат", String.IsNullOrWhiteSpace(cmdKey) ? String.Empty : @$ " за ключем `{cmdKey}`", $":**{Environment.NewLine}"); var dm = await msg.Author.GetOrCreateDMChannelAsync().ConfigureAwait(false); await dm.GenerateAndSendOutputMessages(output, itemsDict, getCitation, s => s, s => s).ConfigureAwait(false); await msg.Channel.SendMessageAsyncSafe($"{msg.Author.Mention} подивись в приватні повідомлення {EmojiCodes.Bumagi}").ConfigureAwait(false); async Task <string> getCitation(KeyValuePair <string, XElement> kvp) { try { string result = await File.ReadAllTextAsync(Path.Combine(_guildPath, ModuleFolder, kvp.Value.Value)).ConfigureAwait(false); if (result.Length > _msgLengthLimit) { return(String.Empty); } return($"`{kvp.Key}`{Environment.NewLine}{result}{Environment.NewLine}"); } catch (Exception ex) { ex.LogToConsole($"{cmdPrefix} Citation loading failed: {kvp.Value.Value}"); return(String.Empty); } } }
/// <summary> /// Abstract method for providing List of user uploaded content. /// </summary> /// <param name="msg">Message containing command invocation.</param> /// <returns>Async Task performing List function.</returns> protected virtual async Task ListCommand(SocketMessage msg) { var regexMatch = Regex.Match(msg.Content, ListCommandRegex); if (!regexMatch.Success) { return; } string cmdPrefix = $"[{LogPref}][LIST]"; await msg.DeleteAsyncSafe(cmdPrefix).ConfigureAwait(false); string keyStr = regexMatch.Groups["key"].Value; var list = RPKeyListGenerator(GetRootByKey(keyStr), String.IsNullOrWhiteSpace(keyStr) ? String.Empty : $"{keyStr}.", false); if (list.Count == 0) { return; } list.Add(keyStr); string output = String.Concat($"**Список доступних {ListItemString}", String.IsNullOrWhiteSpace(keyStr) ? String.Empty : $" за ключем `{keyStr}`", $":**{Environment.NewLine}```{Environment.NewLine}"); var dm = await msg.Author.GetOrCreateDMChannelAsync().ConfigureAwait(false); await dm.GenerateAndSendOutputMessages(output, list, s => $"{s}{Environment.NewLine}", s => $"```{Environment.NewLine}{s}", s => $"{s}```").ConfigureAwait(false); output = $"{msg.Author.Mention} подивись в приватні повідомлення {EmojiCodes.Bumagi}"; await msg.Channel.SendMessageAsyncSafe(output).ConfigureAwait(false); }
/// <summary> /// Command performing citation addition logic. /// </summary> /// <param name="msg">Message which invoked this command, containing citation to save.</param> /// <returns>Async Task performing citation addition logic.</returns> protected override async Task AddCommand(SocketMessage msg) { string logPrefix = $"[{LogPref}][ADD]"; await msg.DeleteAsyncSafe(logPrefix).ConfigureAwait(false); var regexMatch = Regex.Match(msg.Content, AddCommandRegex); if (!regexMatch.Success) { return; } string[] keys = regexMatch.Groups["key"].Value.Split('.'); if (_blacklistedKeys.Any(blKey => blKey.ExactAs(keys[0]))) { return; } Guid newItemGuid = Guid.NewGuid(); string newItemFileName = $"{newItemGuid}.dat"; try { await File.WriteAllTextAsync(Path.Combine(_guildPath, ModuleFolder, newItemFileName), regexMatch.Groups["content"].Value).ConfigureAwait(false); } catch (Exception ex) { ex.LogToConsole($"{logPrefix} Citation save failed: {msg.Content}"); throw; } XElement newItem = new XElement("item", new XAttribute("name", $"{newItemGuid}"), newItemFileName); XElement currentEl = _moduleConfig.Root; foreach (var key in keys) { XElement newEl = currentEl.Elements("key").FirstOrDefault( el => el.Attribute("name") != null && key.ExactAs(el.Attribute("name").Value)); if (newEl == null) { newEl = new XElement("key", new XAttribute("name", key)); currentEl.Add(newEl); } currentEl = newEl; } currentEl.Add(newItem); try { await ModuleConfigChanged().ConfigureAwait(false); } catch (Exception ex) { ex.LogToConsole($"{logPrefix} Config save failed."); throw; } Reconfigure(_configEl); await msg.Channel.SendMessageAsyncSafe($"Записав цитатку {EmojiCodes.DankPepe}").ConfigureAwait(false); }
protected virtual async Task ViewCommand(SocketMessage msg) { string cmdPrefix = $"[{LogPref}][VIEW]"; await msg.DeleteAsyncSafe(cmdPrefix).ConfigureAwait(false); if (!(msg.Author is SocketGuildUser user)) { return; } var regexMatch = Regex.Match(msg.Content, ListCommandRegex); if (!regexMatch.Success) { return; } var cmdKey = regexMatch.Groups["key"].Value; var itemsDict = new Dictionary <string, XElement>(); RPItemDictGenerator(GetRootByKey(cmdKey), String.IsNullOrWhiteSpace(cmdKey) ? String.Empty : $"{cmdKey}.", itemsDict); if (!itemsDict.Any()) { return; } var itemsList = itemsDict.ToList(); int index = 0; int oldIndex = -1; var embedMessage = await msg.Channel.SendMessageAsyncSafe("*Чекайте...*").ConfigureAwait(false); Emoji leftArrowEmoji = new Emoji("\u2b05\ufe0f"); Emoji rightArrowEmoji = new Emoji("\u27a1\ufe0f"); await embedMessage.AddReactionAsync(leftArrowEmoji).ConfigureAwait(false); await embedMessage.AddReactionAsync(rightArrowEmoji).ConfigureAwait(false); using ManualResetEventSlim mres = new ManualResetEventSlim(false); Task waiter = Task.Run(async() => { int timeoutTries = 12; while (timeoutTries-- > 0) { var reactLeftUsers = await embedMessage.GetReactionUsersAsync(leftArrowEmoji, 50).FlattenAsync().ConfigureAwait(false); var reactRightUsers = await embedMessage.GetReactionUsersAsync(rightArrowEmoji, 50).FlattenAsync().ConfigureAwait(false); bool isLeft = reactLeftUsers.Any(u => u.Id == msg.Author.Id); bool isRight = reactRightUsers.Any(u => u.Id == msg.Author.Id); if (isRight || isLeft) { timeoutTries = 12; } if (isRight ^ isLeft) { if (isLeft) { index = --index == -1 ? itemsList.Count - 1 : index; await embedMessage.RemoveReactionAsync(leftArrowEmoji, msg.Author).ConfigureAwait(false); } if (isRight) { index = ++index == itemsList.Count ? 0 : index; await embedMessage.RemoveReactionAsync(rightArrowEmoji, msg.Author).ConfigureAwait(false); } } await Task.Delay(5000).ConfigureAwait(false); } if (mres != null) { mres.Set(); } }); string headerStr = String.Empty; string descStr = String.Empty; string picUrl = String.Empty; while (mres != null && !mres.IsSet) { if (index != oldIndex) { oldIndex = index; var picKVP = itemsList[index]; picUrl = picKVP.Value.GetOrCreateDefaultAttributeValue("url", String.Empty); if (String.IsNullOrEmpty(picUrl)) { var fileMsg = await SendFileTask(_imgServiceChannel, Path.Combine(_guildPath, ModuleFolder, picKVP.Value.Value)).ConfigureAwait(false); picUrl = (fileMsg.Attachments.FirstOrDefault() ?? throw new ApplicationException("Failed to upload image.")).Url; picKVP.Value.Attribute("url").Value = picUrl; try { await ModuleConfigChanged().ConfigureAwait(false); } catch (Exception ex) { ex.LogToConsole($"{cmdPrefix} Config save failed."); } } headerStr = $"{(String.IsNullOrEmpty(cmdKey) ? String.Empty : $"за ключем `{cmdKey}` ")}({index + 1}/{itemsList.Count})";
protected override async Task AddCommand(SocketMessage msg) { string cmdPrefix = $"[{LogPref}][ADD]"; await msg.DeleteAsyncSafe(cmdPrefix).ConfigureAwait(false); if (!Regex.IsMatch(msg.Content, AddCommandRegex)) { return; } var regexMatch = Regex.Match(msg.Content, AddCommandRegex); string[] keys = regexMatch.Groups["key"].Value.Split('.'); if (_blacklistedKeys.Any(blKey => blKey.ExactAs(keys[0]))) { return; } XElement newItem; try { Attachment att = msg.Attachments.FirstOrDefault(att => RuleGenerator.IsImage(att)); if (att == null) { return; } string newItemGuidString = $"{Guid.NewGuid()}"; string newItemFileName = $"{newItemGuidString}{Path.GetExtension(att.Filename)}"; newItem = new XElement("item", new XAttribute("name", newItemGuidString), newItemFileName); string filepath = Path.Combine(_guildPath, ModuleFolder, newItemFileName); await DownloadFile(att, msg.Channel, filepath).ConfigureAwait(false); } catch (Exception ex) { ex.LogToConsole($"{cmdPrefix} File download failed: {regexMatch.Groups["key"].Value}"); throw; } XElement currentEl = _moduleConfig.Root; foreach (var key in keys) { XElement newEl = currentEl.Elements("key").FirstOrDefault( el => el.Attribute("name") != null && key.ExactAs(el.Attribute("name").Value)); if (newEl == null) { newEl = new XElement("key", new XAttribute("name", key)); currentEl.Add(newEl); } currentEl = newEl; } currentEl.Add(newItem); try { await ModuleConfigChanged().ConfigureAwait(false); } catch (Exception ex) { ex.LogToConsole($"{cmdPrefix} Config save failed."); throw; } Reconfigure(_configEl); await msg.Channel.SendMessageAsyncSafe("Зберіг пікчу " + EmojiCodes.DankPepe).ConfigureAwait(false); }