-
Notifications
You must be signed in to change notification settings - Fork 1
Text
Telegram internally stores message formatted as plain text plus several entities that describe bold, underline, hyperlinks, etc., but the various Telegram APIs accept text in several forms.
Often times bugs occur when strings are not properly escaped and are parsed by Telegram as Markdown or HTML when they are in fact plan text; Telegram will refuse messages with invalid markup, such as an unescaped '<' or '&' character and everything may be working fine in your own testing until some random person in some random chat manages to say something that provokes the bug.
Because of this, Telefrag offers a strongly-typed mechanism to address text formatting metadata. The following options can be used anyplace a method or property accepts the TelegramText type.
| Parse Mode | Type | C# Usage |
|---|---|---|
| Plain text | System.String | "this text will be treated as plain and thus can safely contain unescaped <.< & other weirdness" |
| HTML | Telefrag.HTML | (HTML)"This will be <b>bold</b> and <i>italic</i>" |
| Markdown | Telefrag.Markdown | (Markdown)"**hi**" |
| MarkdownV2 | Telefrag.MarkdownV2 | (MarkdownV2)"*hello*" |
Here is an example:
public async Task UpdateReceived(Context c, Update u)
{
u.Message.Reply("(HTML)<b>Access denied</b>");
// or
u.Message.SendMessage((Markdown)"Let's get **freaky**");
}This works because you can implicitly cast a string to any of these formatting types. You can also explicitly instantiate one if you wanted:
var html = new HTML("<b>Access Denied</b>");
u.Message.SendMessage(html);Each of these formatters inherits from TelegramText which exposes the raw components as ParseMode and MarkupString. You can also create a TelegramText from its parse_mode and text components by using the factory method TelegramText.Create()
TelegramText also supports conversion from FormattableString, for example:
HTML error = "<b>Access denied</b>";
u.Message.SendMessage(text: $"Error: {error}");The value passed into the 'text' parameter will be an HTML object representing the value 'Error: <b>Access Denied</b>' because the interpolated string was populated by an HTML object. The Type passed into text would be PlainText had only strings been inserted.