using System.Linq; using Telegram.Bot.Types.Enums; namespace TelegramBotBase.Markdown; /// /// https://core.telegram.org/bots/api#markdownv2-style /// public static class Generator { public static ParseMode OutputMode { get; set; } = ParseMode.Markdown; /// /// Generates a link with title in Markdown or HTML /// /// /// /// /// public static string Link(this string url, string title = null, string tooltip = null) { return OutputMode switch { ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")", ParseMode.Html => $"{title ?? ""}", _ => url }; } /// /// Returns a Link to the User, title is optional. /// /// /// /// public static string MentionUser(this int userId, string title = null) { return Link("tg://user?id=" + userId, title); } /// /// Returns a Link to the User, title is optional. /// /// /// /// public static string MentionUser(this string username, string title = null) { return Link("tg://user?id=" + username, title); } /// /// Returns a bold text in Markdown or HTML /// /// /// public static string Bold(this string text) { return OutputMode switch { ParseMode.Markdown => "*" + text + "*", ParseMode.Html => "" + text + "", _ => text }; } /// /// Returns a strike through in Markdown or HTML /// /// /// public static string Strikesthrough(this string text) { return OutputMode switch { ParseMode.Markdown => "~" + text + "~", ParseMode.Html => "" + text + "", _ => text }; } /// /// Returns a italic text in Markdown or HTML /// /// /// public static string Italic(this string text) { return OutputMode switch { ParseMode.Markdown => "_" + text + "_", ParseMode.Html => "" + text + "", _ => text }; } /// /// Returns a underline text in Markdown or HTML /// /// /// public static string Underline(this string text) { return OutputMode switch { ParseMode.Markdown => "__" + text + "__", ParseMode.Html => "" + text + "", _ => text }; } /// /// Returns a monospace text in Markdown or HTML /// /// /// public static string Monospace(this string text) { return OutputMode switch { ParseMode.Markdown => "`" + text + "`", ParseMode.Html => "" + text + "", _ => text }; } /// /// Returns a multi monospace text in Markdown or HTML /// /// /// public static string MultiMonospace(this string text) { return OutputMode switch { ParseMode.Markdown => "```" + text + "```", ParseMode.Html => "
" + text + "
", _ => text }; } /// /// Escapes all characters as stated in the documentation: https://core.telegram.org/bots/api#markdownv2-style /// /// /// public static string MarkdownV2Escape(this string text, params char[] toKeep) { var toEscape = new[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray()); } public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\') { return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem)); } }