|
| 1 | +--- |
| 2 | +title: Formatting Text |
| 3 | +parent: /#walkthrough |
| 4 | +prev: /inline-queries |
| 5 | +--- |
| 6 | + |
| 7 | +Messages and media captions can contain formatting such as bold text, links, spoilers, and code. MTKruto can parse HTML or Markdown into Telegram message entities. |
| 8 | + |
| 9 | +## HTML |
| 10 | + |
| 11 | +Set `parseMode` to `"HTML"` for a message that contains supported HTML tags. |
| 12 | + |
| 13 | +```ts |
| 14 | +await client.sendMessage( |
| 15 | + chatId, |
| 16 | + 'Hello, <b>world</b>! Visit <a href="https://mtkru.to">MTKruto</a>.', |
| 17 | + { parseMode: "HTML" }, |
| 18 | +); |
| 19 | +``` |
| 20 | + |
| 21 | +Common supported tags include `<b>`, `<i>`, `<u>`, `<s>`, `<code>`, `<pre>`, `<blockquote>`, and `<a>`. |
| 22 | + |
| 23 | +## Markdown |
| 24 | + |
| 25 | +Set `parseMode` to `"Markdown"` to use Markdown formatting. |
| 26 | + |
| 27 | +```ts |
| 28 | +await ctx.reply( |
| 29 | + "Hello, *world*\\! Visit [MTKruto](https://mtkru.to)\\.", |
| 30 | + { parseMode: "Markdown" }, |
| 31 | +); |
| 32 | +``` |
| 33 | + |
| 34 | +Characters with special meaning must be escaped when they should appear literally. Be especially careful when inserting user-provided text into HTML or Markdown. |
| 35 | + |
| 36 | +## Default Parse Mode |
| 37 | + |
| 38 | +A default parse mode can be configured when constructing the client. It is then used whenever a method does not specify one. |
| 39 | + |
| 40 | +```ts |
| 41 | +const client = new Client({ |
| 42 | + parseMode: "HTML", |
| 43 | + /* ... */ |
| 44 | +}); |
| 45 | +``` |
| 46 | + |
| 47 | +Override the default for a single message by passing another parse mode, or pass `null` to disable parsing. |
| 48 | + |
| 49 | +```ts |
| 50 | +await client.sendMessage(chatId, "<b>This remains unchanged.</b>", { |
| 51 | + parseMode: null, |
| 52 | +}); |
| 53 | +``` |
| 54 | + |
| 55 | +## Explicit Entities |
| 56 | + |
| 57 | +You can provide {{ "MessageEntity" |> t }} objects instead of using markup. Entity offsets and lengths use UTF-16 code units, which is how JavaScript measures string length. |
| 58 | + |
| 59 | +```ts |
| 60 | +const text = "Important message"; |
| 61 | + |
| 62 | +await client.sendMessage(chatId, text, { |
| 63 | + parseMode: null, |
| 64 | + entities: [ |
| 65 | + { |
| 66 | + type: "bold", |
| 67 | + offset: 0, |
| 68 | + length: "Important".length, |
| 69 | + }, |
| 70 | + ], |
| 71 | +}); |
| 72 | +``` |
| 73 | + |
| 74 | +Explicit entities are useful when text is assembled dynamically because formatting does not depend on escaping markup characters. |
0 commit comments