Skip to content
Nill edited this page Sep 8, 2021 · 9 revisions

Telegram internally stores message formatting 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.

Because of this Telefrag offers a strongly-typed mechanism to address text. 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 "This will be <b>bold</b> and <i>italic</i>" as HTML
Markdown Telefrag.Markdown "**hi**" as Markdown
MarkdownV2 Telefrag.MarkdownV2 "*hello*" as MarkdownV2

Here is an example:

public async Task UpdateReceived(Context c, Update u) 
{
     u.Message.Reply("<b>Access denied</b>" as HTML);
     // 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.

Clone this wiki locally