Skip to content

Commit

Permalink
updating documentation for bot.OnUpdate
Browse files Browse the repository at this point in the history
  • Loading branch information
wiz0u committed Jul 18, 2024
1 parent 2c48dad commit 54315db
Show file tree
Hide file tree
Showing 17 changed files with 190 additions and 181 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ indent_size = 2
# Markdown Files
[*.md]
trim_trailing_whitespace = false
indent_size = 2
indent_size = 4
35 changes: 0 additions & 35 deletions Examples/1/ExampleBot.cs

This file was deleted.

18 changes: 0 additions & 18 deletions Examples/1/Quickstart.cs

This file was deleted.

75 changes: 27 additions & 48 deletions Examples/2/ReplyMarkup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,104 +10,83 @@ namespace BookExamples.Chapter2;

internal class ReplyMarkup
{
public readonly ITelegramBotClient bot = new TelegramBotClient("{YOUR_ACCESS_TOKEN_HERE}");
public readonly ITelegramBotClient bot = new TelegramBotClient("YOUR_BOT_TOKEN");
public readonly ChatId chatId = 12345;

private async Task SingleRowMarkup()
{
// ANCHOR: single-row
var buttons = new KeyboardButton[]
{
"Help me", "Call me ☎️",
};
var replyMarkup = new ReplyKeyboardMarkup(true)
.AddButtons("Help me", "Call me ☎️");

var sent = await bot.SendTextMessageAsync(chatId, "Choose a response",
replyMarkup: new ReplyKeyboardMarkup(buttons) { ResizeKeyboard = true });
var sent = await bot.SendTextMessageAsync(chatId, "Choose a response", replyMarkup: replyMarkup);
// ANCHOR_END: single-row
}

private async Task MultipleRowMarkup()
{
// ANCHOR: multiple-row
var buttons = new KeyboardButton[][]
{
new KeyboardButton[] { "Help me" },
new KeyboardButton[] { "Call me ☎️", "Write me ✉️" },
};
var replyMarkup = new ReplyKeyboardMarkup(true)
.AddButton("Help me")
.AddNewRow("Call me ☎️", "Write me ✉️");

var sent = await bot.SendTextMessageAsync(chatId, "Choose a response",
replyMarkup: new ReplyKeyboardMarkup(buttons) { ResizeKeyboard = true });
var sent = await bot.SendTextMessageAsync(chatId, "Choose a response", replyMarkup: replyMarkup);
// ANCHOR_END: multiple-row
}

private async Task RequestInfo()
{
// ANCHOR: request-info
var buttons = new[]
{
KeyboardButton.WithRequestLocation("Share Location"),
KeyboardButton.WithRequestContact("Share Contact"),
};
var replyMarkup = new ReplyKeyboardMarkup()
.AddButton(KeyboardButton.WithRequestLocation("Share Location"))
.AddButton(KeyboardButton.WithRequestContact("Share Contact"));

var sent = await bot.SendTextMessageAsync(chatId, "Who or Where are you?",
replyMarkup: new ReplyKeyboardMarkup(buttons));
var sent = await bot.SendTextMessageAsync(chatId, "Who or Where are you?", replyMarkup: replyMarkup);
// ANCHOR_END: request-info
}

private async Task RemoveKeyboard()
{
// ANCHOR: remove-keyboard
var sent = await bot.SendTextMessageAsync(chatId, "Removing keyboard",
replyMarkup: new ReplyKeyboardRemove());
await bot.SendTextMessageAsync(chatId, "Removing keyboard", replyMarkup: new ReplyKeyboardRemove());
// ANCHOR_END: remove-keyboard
}

private async Task CallbackButtons()
{
// ANCHOR: callback-buttons
var buttons = new InlineKeyboardButton[][]
{
new[] // first row
{
InlineKeyboardButton.WithCallbackData("1.1", "11"),
InlineKeyboardButton.WithCallbackData("1.2", "12"),
},
new[] // second row
{
InlineKeyboardButton.WithCallbackData("2.1", "21"),
InlineKeyboardButton.WithCallbackData("2.2", "22"),
},
};
var inlineMarkup = new InlineKeyboardMarkup()
.AddButton("1.1", "11") // first row, first button
.AddButton("1.2", "12") // first row, second button
.AddNewRow()
.AddButton("2.1", "21") // second row, first button
.AddButton("2.2", "22");// second row, second button

var sent = await bot.SendTextMessageAsync(chatId, "A message with an inline keyboard markup",
replyMarkup: new InlineKeyboardMarkup(buttons));
replyMarkup: inlineMarkup);
// ANCHOR_END: callback-buttons
}

private async Task UrlButtons()
{
// ANCHOR: url-buttons
var buttons = new[]
{
InlineKeyboardButton.WithUrl("Repository Link", "https://github.com/TelegramBots/Telegram.Bot")
};
var inlineMarkup = new InlineKeyboardMarkup()
.AddButton(InlineKeyboardButton.WithUrl("Repository Link", "https://github.com/TelegramBots/Telegram.Bot"));

var sent = await bot.SendTextMessageAsync(chatId, "A message with an inline keyboard markup",
replyMarkup: new InlineKeyboardMarkup(buttons));
replyMarkup: inlineMarkup);
// ANCHOR_END: url-buttons
}

private async Task SwitchToInline()
{
// ANCHOR: switch-to-inline
var buttons = new[]
{
InlineKeyboardButton.WithSwitchInlineQuery("switch_inline_query"),
InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch_inline_query_current_chat"),
};
var inlineMarkup = new InlineKeyboardMarkup()
.AddButton(InlineKeyboardButton.WithSwitchInlineQuery("switch_inline_query"))
.AddButton(InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch_inline_query_current_chat"));

var sent = await bot.SendTextMessageAsync(chatId, "A message with an inline keyboard markup",
replyMarkup: new InlineKeyboardMarkup(buttons));
replyMarkup: inlineMarkup);
// ANCHOR_END: switch-to-inline
}
}
4 changes: 2 additions & 2 deletions Examples/2/SendMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Examples.Chapter2;

internal class SendMessage
{
public readonly ITelegramBotClient bot = new TelegramBotClient("{YOUR_ACCESS_TOKEN_HERE}");
public readonly ITelegramBotClient bot = new TelegramBotClient("YOUR_BOT_TOKEN");
public readonly ChatId chatId = 12345;
public readonly Update update = new ();

Expand Down Expand Up @@ -90,7 +90,7 @@ private async Task SendPoll()
// ANCHOR_END: send-poll

// ANCHOR: stop-poll
Poll poll = await bot.StopPollAsync(pollMessage.Chat.Id, pollMessage.MessageId);
Poll poll = await bot.StopPollAsync(pollMessage.Chat, pollMessage.MessageId);
// ANCHOR_END: stop-poll
}

Expand Down
2 changes: 1 addition & 1 deletion Examples/3/Files.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Examples.Chapter3;

internal class Files
{
public readonly ITelegramBotClient bot = new TelegramBotClient("{YOUR_ACCESS_TOKEN_HERE}");
public readonly ITelegramBotClient bot = new TelegramBotClient("YOUR_BOT_TOKEN");
public readonly ChatId chatId = 12345;
public readonly Update update = new();

Expand Down
2 changes: 1 addition & 1 deletion Examples/3/Inline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace BookExamples.Chapter3;

internal class Inline
{
public readonly ITelegramBotClient bot = new TelegramBotClient("{YOUR_ACCESS_TOKEN_HERE}");
public readonly ITelegramBotClient bot = new TelegramBotClient("YOUR_BOT_TOKEN");
// ANCHOR: arrays
private readonly string[] sites = { "Google", "Github", "Telegram", "Wikipedia" };
private readonly string[] siteDescriptions =
Expand Down
35 changes: 0 additions & 35 deletions Examples/3/LongPolling.cs

This file was deleted.

2 changes: 1 addition & 1 deletion Examples/Examples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Telegram.Bot" Version="21.4.1" />
<PackageReference Include="Telegram.Bot" Version="21.7.0" />
</ItemGroup>

<PropertyGroup>
Expand Down
52 changes: 32 additions & 20 deletions src/1/example-bot.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
# Full Example - Your first bot
# Your First Chat Bot

On the [previous page] we got an access token and used the [`getMe`] method to check our setup.
On the [previous page](quickstart.md) we got a bot token and used the [`getMe`](https://core.telegram.org/bots/api#getme) method to check our setup.
Now, it is time to make an _interactive_ bot that gets users' messages and replies to them like in this screenshot:

![Example Image](docs/shot-example_bot.jpg)

Copy the following code to `Program.cs`.

> ⚠️ Replace `{YOUR_ACCESS_TOKEN_HERE}` with the access token from the [`@BotFather`].
> ⚠️ Replace `YOUR_BOT_TOKEN` with the bot token obtained from [`@BotFather`].
```c#
{{#include ../../Examples/1/ExampleBot.cs:usings}}

{{#include ../../Examples/1/ExampleBot.cs:example-bot}}
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

using var cts = new CancellationTokenSource();
var bot = new TelegramBotClient("YOUR_BOT_TOKEN", cancellationToken: cts.Token);
var me = await bot.GetMeAsync();
bot.OnMessage += OnMessage;

Console.WriteLine($"@{me.Username} is running... Press Enter to terminate");
Console.ReadLine();
cts.Cancel(); // stop the bot
// method that handle messages received by the bot:
async Task OnMessage(Message msg, UpdateType type)
{
if (msg.Text is null) return; // we only handle Text messages here
Console.WriteLine($"Received {type} '{msg.Text}' in {msg.Chat}");
// let's echo back received text in the chat
await bot.SendTextMessageAsync(msg.Chat, $"{msg.From} said: {msg.Text}");
}
```

Run the program:
Expand All @@ -22,27 +40,21 @@ dotnet run
```

It runs waiting for text messages unless forcefully stopped by pressing Enter. Open a private chat with your bot in
Telegram and send a text message to it. Bot should reply in no time.
Telegram and send a text message to it. Bot should reply immediately.

By setting `bot.OnMessage`, the bot client starts polling Telegram servers for messages received by the bot.
This is done automatically in the background, so your program continue to execute and we use `Console.ReadLine()` to keep it running until you press Enter.

By invoking [`StartReceiving(...)`] bot client starts fetching updates using [`getUpdates`] method for the bot
from Telegram servers. This operation does not block the caller thread, because it is done on the ThreadPool. We use `Console.ReadLine()` to keep the app running.
When user sends a message, the `OnMessage(...)` method gets invoked with the `Message` object passed as an argument (and the type of update).

When user sends a message, the `OnUpdate(...)` method gets invoked with the `Update` object passed as an argument.
We check `Message.Type` and skip the rest if it is not a text message.
Finally, we send a text message back to the same chat we got the message from.

The second argument to `StartReceiving` is a lambda method invoked in case of an error that occurred while fetching updates.

If you take a look at the console, the program outputs the `chatId` value. **Copy the chat id number** to make testing easier
for yourself on the next pages.
If you take a look at the console, the program outputs the `chatId` numeric value.
In a private chat with you, it would be your `userId`, so remember it as it's useful to send yourself messages.

```text
Received a 'text' message in chat 123456789.
Received Message 'test' in Private chat with @You (123456789).
```

<!-- -->

[previous page]: quickstart.md
[`getMe`]: https://core.telegram.org/bots/api#getme
[`getUpdates`]: https://core.telegram.org/bots/api#getupdates
[`StartReceiving(...)`]: https://github.com/TelegramBots/Telegram.Bot.Extensions.Polling/blob/master/src/Telegram.Bot.Extensions.Polling/Extensions/TelegramBotClientPollingExtensions.cs
Loading

0 comments on commit 54315db

Please sign in to comment.