Skip to content

Commit 0f5be6d

Browse files
committed
Updated docs for v22.5
1 parent b5f1d39 commit 0f5be6d

File tree

17 files changed

+373
-434
lines changed

17 files changed

+373
-434
lines changed

Examples/Examples.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<TargetFramework>net8.0</TargetFramework>
@@ -11,7 +11,7 @@
1111
</ItemGroup>
1212

1313
<ItemGroup>
14-
<PackageReference Include="Telegram.Bot" Version="22.4.1" Condition="'$(Configuration)' == 'Release'" />
14+
<PackageReference Include="Telegram.Bot" Version="*-*" Condition="'$(Configuration)' == 'Release'" />
1515
<ProjectReference Include="..\..\Telegram.Bot\src\Telegram.Bot\Telegram.Bot.csproj" Condition="'$(Configuration)' == 'Debug'" />
1616
</ItemGroup>
1717

Examples/nuget.config

Lines changed: 0 additions & 7 deletions
This file was deleted.

src/2/reply-markup.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ You can have several rows and columns of inline buttons of mixed types.
8686

8787
### Callback buttons
8888

89-
When a user presses a [callback button], no messages are sent to the chat, and your bot simply receives an `update.CallbackQuery` instead.
89+
When a user presses a [callback button], no messages are sent to the chat, and your bot simply receives an `update.CallbackQuery` instead _(containing many information)_.
9090
Upon receiving this, your bot should answer to that query within 10 seconds, using `AnswerCallbackQuery` _(or else the button gets momentarily disabled)_
9191

9292
In this example, the arrays of `InlineKeyboardButton` are constructed from tuples `(title, callbackData)`:

src/3/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55
- [Webhooks](updates/webhook.md)
66
- [Download/Upload Files](files.md)
77
- [Inline Mode](inline.md)
8+
- [Library helpers](helpers.md)

src/3/helpers.md

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# List of helpers in the library
2+
3+
Our library is mainly a bridge between your application and Telegram Bot API.
4+
However, to simplify your life, we also provide a set of additional helpers methods and services, listed below.
5+
6+
> For more advanced features, you can look at [high-level bot frameworks](https://github.com/TelegramBots/Telegram.Bot/wiki) constructed around our library
7+
8+
## Message and format helpers
9+
10+
- `message.MessageLink()`: Returns the <a href="t.me">t.me/...</a> link to this message, or `null` if the message was not in a Supergroup or Channel
11+
- `message.IsServiceMessage`: Detect service messages vs content messages
12+
- `message.ToMarkdown()` to convert the message to Markdown format
13+
- `message.ToHtml()` to convert the message to HTML format
14+
- `Markdown.Escape()` to escape reserved Markdown characters in a string
15+
- `HtmlText.Escape()` to escape reserved HTML characters in a string
16+
- `HtmlText.ToPlain()` to convert HTML string to plain text _(removing tags)_
17+
- `HtmlText.PlainText()` to get the number of characters of plain text from HTML
18+
- `HtmlText.Truncate()` to truncate HTML string to a number of plain-text characters _(while still preserving the formatting)_
19+
20+
## Easier information
21+
- `chat.ToString()` & `user.ToString()` to easily print/log information about the chat/user
22+
- `ChatMember` has properties `IsAdmin` and `IsInChat` to simplify testing if the user is an admin or currently inside the chat
23+
24+
## Updates
25+
- `bot.DropPendingUpdates()` to clear the pending updates queue
26+
- `Update.AllTypes` is a constant array containing all `UpdateType`s, usable with `GetUpdates`/`SetWebhook`
27+
- `bot.OnMessage` / `bot.OnUpdate` events to easily subscribe to messages or updates
28+
_(these automatically start a background task to poll for updates)_
29+
30+
## Telegram files
31+
- `bot.GetInfoAndDownloadFile` to get file information and download it in a single call
32+
- `TelegramBotClient.GetFileIdType(fileId)` to determine the type of object stored behind a FileId _(photo, video, etc)_
33+
34+
## Simplified constructors and implicit conversions
35+
We've added easier ways to construct various instances from other types, especially when passing arguments to methods:
36+
- `ChatPermissions(bool)` and `ChatAdministratorRights(bool)` constructors to set all Can* fields to the specified value
37+
- `ReactionType` from an emoji (string) or a customEmojiId (long)
38+
- `ReplyParameters` from a messageId (int), or a `Message` class, so you can pass these directly for the `replyParameters:` argument
39+
- `LinkPreviewOptions` from a `bool` where `true` means to disable the preview
40+
- `LabeledPrice` from tuple `(string label, long amount)`
41+
- `BotCommand` from tuple `(string command, string description)`
42+
- `BotCommandScope` has several static methods to construct scopes
43+
- `InputFile` from a fileId or URL (string) or a `Stream` or a received media file
44+
45+
Examples:
46+
```csharp
47+
await bot.RestrictChatMember(chatId, userId, new ChatPermissions(true)); // unmute
48+
await bot.SetMessageReaction(msg.Chat, msg.Id, ["👍"]);
49+
await bot.SendMessage(msg.Chat, "Visit t.me/tgbots_dotnet", replyParameters: msg, linkPreviewOptions: true);
50+
await bot.SendInvoice(chatId, "Product", "Description", "ProductID", "XTR", [("Price", 500)]);
51+
await Bot.SetMyCommands([("/start", "Start the bot"), ("/privacy", "Privacy policy")], BotCommandScope.AllPrivateChats());
52+
await bot.SendPhoto(msg.Chat, "https://picsum.photos/310/200.jpg");
53+
await bot.SendVideo(msg.Chat, msg.Video, "Sending your video back");
54+
```
55+
56+
## Reply Markup
57+
58+
Keyboards can be easily constructed by passing directly the following type of objects for the `replyMarkup:` parameter:
59+
60+
| Type | Meaning |
61+
|------|---------|
62+
| `string` | single keyboard text button |
63+
| `string[]` | keyboard text buttons on one row |
64+
| `string[][]` | multiple keyboard text buttons |
65+
| `KeyboardButton` | single keyboard button |
66+
| `KeyboardButton[]` | multiple keyboard buttons on one row |
67+
| `KeyboardButton[][]` or<br/>`IEnumerable<KeyboardButton>[]` | multiple keyboard buttons |
68+
| `InlineKeyboardButton` | single inline button |
69+
| `InlineKeyboardButton[]` | inline buttons on 1 row |
70+
| `InlineKeyboardButton[][]` or<br/> `IEnumerable<InlineKeyboardButton>[]` | multiple inline buttons |
71+
72+
Additionally, `InlineKeyboardButton` can be implicitly constructed from a tuple `(string text, string callbackOrUrl)` for Callback or Url buttons
73+
```csharp
74+
await bot.SendMessage(msg.Chat, "Visit our website", replyMarkup: InlineKeyboardButton.WithUrl("Click here", "https://telegrambots.github.io/book/"));
75+
await bot.SendMessage(botOwnerId, $"Annoying user: {msg.From}", replyMarkup: new InlineKeyboardButton[]
76+
{ ("Ban him", $"BAN {msg.From.Id}"), ("Mute him", $"MUTE {msg.From.Id}") });
77+
await bot.SendMessage(msg.Chat, "Keyboard buttons:", replyMarkup: new string[] { "MENU", "INFO", "LANGUAGE" });
78+
```
79+
### Constructing dynamically
80+
`ReplyKeyboardMarkup` & `InlineKeyboardMarkup` have methods to help you construct keyboards dynamically:
81+
```csharp
82+
var replyMarkup = new InlineKeyboardMarkup()
83+
.AddButton(InlineKeyboardButton.WithUrl("Link to Repository", "https://github.com/TelegramBots/Telegram.Bot"))
84+
.AddNewRow().AddButton("callback").AddButton("caption", "data")
85+
.AddNewRow("with", "three", "buttons")
86+
.AddNewRow().AddButtons("A", "B", InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch"));
87+
```
88+
89+
And you can use `new ReplyKeyboardMarkup(true)` to resize the reply keyboard.
90+
91+
## Mini-App and Login widget validation
92+
- `AuthHelpers.ParseValidateData` should be used to confirm the authenticity of data received along Telegram's Mini-Apps or the Login Widget javascript requests

src/3/updates/webhook.md

Lines changed: 58 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -4,85 +4,55 @@
44

55
With Webhook, your web application gets notified [sequentially](#updates-are-posted-sequentially-to-your-webapp), automatically by Telegram when new updates arrive for your bot.
66

7-
Your application will receive HTTP POST requests with an Update structure in the body, using specific JSON serialization settings `Telegram.Bot.JsonBotAPI.Options`.
7+
Your application will receive HTTP POST requests with an Update structure in the JSON body.
88

9-
Below, you will find how to configure an **ASP.NET Core Web API** project to make it work with Telegram.Bot, either with Controllers or Minimal APIs
9+
> Since version 22.5 of the library, you no longer need to configure the JSON serialization settings for your WebApp in most cases.
10+
> But if necessary, refer to section **[Configure JSON serialization settings](#configure-json-serialization-settings)** below.
1011
11-
⚠️ IMPORTANT: This guide describes configuration for versions 21.* and later of the library _(based on System.Text.Json rather than NewtonsoftJson)_. If you're using older versions, [you should upgrade first](../../migrate/Version-21.x.md)!
12+
Here are example codes for handling updates, depending on the types of ASP.NET projects:
1213

13-
## ASP.NET Core with Controllers (MVC)
14-
[![ASP.NET example with Controllers](https://img.shields.io/badge/Examples-Webhook.Controllers-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.Controllers)
15-
16-
First you need to configure your Web App startup code:
17-
- Locate the line `services.AddControllers();` _(in Program.cs or Startup.cs)_
18-
- If you're using .NET 6.0 or more recent, add the line:
14+
* **ASP.NET Core with Controllers (MVC)** [![ASP.NET example with Controllers](https://img.shields.io/badge/Examples-Webhook.Controllers-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.Controllers)
1915
```csharp
20-
services.ConfigureTelegramBotMvc();
16+
// Add this action in a controller class (like BotController.cs):
17+
[HttpPost]
18+
public async Task HandleUpdate([FromBody] Update update)
19+
{
20+
// put your code to handle one Update here.
21+
}
2122
```
22-
- For older .NET versions, add the line:
23+
* **ASP.NET Core with Minimal APIs** [![ASP.NET example with Minimal APIs](https://img.shields.io/badge/Examples-Webhook.MinimalAPIs-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.MinimalAPIs)
2324
```csharp
24-
services.ConfigureTelegramBot<Microsoft.AspNetCore.Mvc.JsonOptions>(opt => opt.JsonSerializerOptions);
25-
```
26-
27-
Next, in a controller class (like BotController.cs), you need to add an action for the updates. Typically:
28-
```csharp
29-
[HttpPost]
30-
public async Task HandleUpdate([FromBody] Update update)
31-
{
32-
// put your code to handle one Update here.
33-
}
34-
```
35-
36-
Good, now skip to [SetWebHook](#setwebhook) below
37-
38-
## ASP.NET Core with Minimal APIs
39-
[![ASP.NET example with Minimal APIs](https://img.shields.io/badge/Examples-Webhook.MinimalAPIs-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.MinimalAPIs)
25+
app.MapPost("/bot", (Update update) => HandleUpdate(update));
26+
...
4027

41-
First you need to configure your Web App startup code:
42-
- Locate the line `builder.Build();` _(in Program.cs)_
43-
- Above it, insert the line:
28+
async Task HandleUpdate(Update update)
29+
{
30+
// put your code to handle one Update here.
31+
}
32+
```
33+
* **Old ASP.NET 4.x support**
4434
```csharp
45-
builder.Services.ConfigureTelegramBot<Microsoft.AspNetCore.Http.Json.JsonOptions>(opt => opt.SerializerOptions);
35+
public async Task<IHttpActionResult> Post()
36+
{
37+
Update update;
38+
using (var body = await Request.Content.ReadAsStreamAsync())
39+
update = System.Text.Json.JsonSerializer.Deserialize<Update>(body, JsonBotAPI.Options);
40+
await HandleUpdate(update);
41+
return Ok();
42+
}
4643
```
4744

48-
Next, you need to map an action for the updates. Typically:
49-
```csharp
50-
app.MapPost("/bot", (Update update) => HandleUpdate(update));
51-
...
52-
53-
async Task HandleUpdate(Update update)
54-
{
55-
// put your code to handle one Update here.
56-
}
57-
```
58-
59-
Good, now skip to [SetWebHook](#setwebhook) below
60-
61-
## Old ASP.NET 4.x support
62-
63-
For older .NET Framework usage, you may use the following code:
64-
```csharp
65-
public async Task<IHttpActionResult> Post()
66-
{
67-
Update update;
68-
using (var body = await Request.Content.ReadAsStreamAsync())
69-
update = System.Text.Json.JsonSerializer.Deserialize<Update>(body, JsonBotAPI.Options);
70-
await HandleUpdate(update);
71-
return Ok();
72-
}
73-
```
74-
75-
## SetWebHook
76-
Your update handler code is ready, now you need to instruct Telegram to send updates to your URL, by running:
45+
Now that your update handler code is ready, you need to instruct Telegram to start sending updates to your URL, by running:
7746
```csharp
7847
var bot = new TelegramBotClient("YOUR_BOT_TOKEN");
7948
await bot.SetWebhook("https://your.public.host:port/bot", allowedUpdates: []);
8049
```
8150

82-
You can now deploy your app to your webapp host machine.
51+
Great! You can now deploy your app to your webapp host machine.
8352

8453
_Note: If you decide to switch back to [Long Polling](polling.md), remember to call `bot.DeleteWebhook()`_
8554

55+
8656
## Common issues
8757

8858
- You need a [supported certificate](https://core.telegram.org/bots/faq#i-39m-having-problems-with-webhooks)
@@ -118,3 +88,30 @@ Initially Telegram will resend the failed update quickly, then with increasing i
11888

11989
If you need to process the incoming updates faster, in parallel, you will want to delegate their handling separately and acknowledge the POST request by returning from the controller immediately.
12090
For more details, refer to [this section of our documentation](.#sequential-vs-parallel-updates).
91+
92+
93+
## Configure JSON serialization settings
94+
95+
Telegram updates & requests are sent using JSON payloads with `snake_case` property names.
96+
Such serialization is normally achieved thanks to `Telegram.Bot.JsonBotAPI.Options` serialization settings.
97+
98+
Since version 22.5, the library should already be compatible with Telegram Webhook without needing extra configuration for your WebApp.
99+
100+
In some rare cases _(like [Native AOT](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot) / [Blazor](https://learn.microsoft.com/en-us/aspnet/core/blazor/webassembly-build-tools-and-aot) / [Trimming](https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/trim-self-contained))_, this might still be necessary and here is how to configure your project:
101+
* **ASP.NET Core with Minimal APIs**
102+
Locate the line `builder.Build();` _(in Program.cs)_ and insert this line <u>above</u>:
103+
```csharp
104+
builder.Services.ConfigureTelegramBot<Microsoft.AspNetCore.Http.Json.JsonOptions>(opt => opt.SerializerOptions);
105+
```
106+
* **ASP.NET Core with Controllers** _(recommended method for .NET 6.0+)_
107+
Add the [nuget package](https://www.nuget.org/packages/Telegram.Bot.AspNetCore) `Telegram.Bot.AspNetCore` to your project.
108+
Locate the line `services.AddControllers();` _(in Program.cs or Startup.cs)_ and add this line below:
109+
```csharp
110+
services.ConfigureTelegramBotMvc();
111+
```
112+
* **ASP.NET Core with Controllers** _(any .NET version)_
113+
Locate the line `services.AddControllers();` _(in Program.cs or Startup.cs)_ and add this line below:
114+
```csharp
115+
services.ConfigureTelegramBot<Microsoft.AspNetCore.Mvc.JsonOptions>(opt => opt.JsonSerializerOptions);
116+
```
117+

0 commit comments

Comments
 (0)