Skip to content

Commit

Permalink
various updates
Browse files Browse the repository at this point in the history
  • Loading branch information
wiz0u committed Jun 29, 2024
1 parent 7716bc9 commit adc7ac2
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 61 deletions.
55 changes: 12 additions & 43 deletions Examples/1/ExampleBot.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// ANCHOR: usings
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
// ANCHOR_END: usings
Expand All @@ -13,53 +11,24 @@ internal class ExampleBot
private async Task BookExamples()
{
// ANCHOR: example-bot
using CancellationTokenSource cts = new();
using var cts = new CancellationTokenSource();
var bot = new TelegramBotClient("{YOUR_ACCESS_TOKEN_HERE}", cancellationToken: cts.Token);

// StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
var receiverOptions = new ReceiverOptions()
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates
};

bot.StartReceiving(HandleUpdateAsync, HandlePollingErrorAsync, receiverOptions);
bot.StartReceiving(HandleUpdate, async (bot, ex, ct) => Console.WriteLine(ex));

Check warning on line 16 in Examples/1/ExampleBot.cs

View workflow job for this annotation

GitHub Actions / Build and upload

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Check warning on line 16 in Examples/1/ExampleBot.cs

View workflow job for this annotation

GitHub Actions / Build and upload

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

var me = await bot.GetMeAsync();

Console.WriteLine($"Start listening for @{me.Username}");
Console.WriteLine($"@{me.Username} is running... Press Enter to terminate");
Console.ReadLine();
cts.Cancel(); // stop the bot

// Send cancellation request to stop bot
cts.Cancel();

async Task HandleUpdateAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken)
// method that handle updates coming for the bot:
async Task HandleUpdate(ITelegramBotClient bot, Update update, CancellationToken ct)
{
// Only process Message updates: https://core.telegram.org/bots/api#message
if (update.Message is not { } message)
return;
// Only process text messages
if (message.Text is not { } messageText)
return;

var chatId = message.Chat.Id;

Console.WriteLine($"Received a '{messageText}' message in chat {chatId}.");

// Echo received message text
Message sentMessage = await bot.SendTextMessageAsync(chatId, "You said:\n" + messageText);
}

Task HandlePollingErrorAsync(ITelegramBotClient bot, Exception exception, CancellationToken cancellationToken)
{
var ErrorMessage = exception switch
{
ApiRequestException apiRequestException
=> $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};

Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
if (update.Message is null) return; // we want only updates about new Message
if (update.Message.Text is null) return; // we want only updates about new Text Message
var msg = update.Message;
Console.WriteLine($"Received message '{msg.Text}' in {msg.Chat}");
// let's echo back received text in the chat
await bot.SendTextMessageAsync(msg.Chat, $"{msg.From} said: {msg.Text}");
}
// ANCHOR_END: example-bot
}
Expand Down
2 changes: 1 addition & 1 deletion src/3/inline.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Inline Mode

[![inline mode bot API](https://img.shields.io/badge/Bot_API_Doc-Inline%20Mode-blue.svg?style=flat-square)](https://core.telegram.org/bots/api#inline-mode)
[![inline queries example](https://img.shields.io/badge/Examples-Inline%20Queries-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/blob/master/Telegram.Bot.Examples.InlineQueries/Program.cs)
[![inline queries example](https://img.shields.io/badge/Examples-Inline%20Queries-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/blob/master/InlineQueries/Program.cs)

Telegram bots can be queried directly in the chat or via inline queries.

Expand Down
24 changes: 9 additions & 15 deletions src/3/updates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
There are two mutually exclusive ways of receiving updates for your bot — the long polling using [`getUpdates`] method on one hand and Webhooks on the other. Telegram is queueing updates until the bot receives them either way, but they will not be kept longer than 24 hours.

- With long polling, the client requests information from the server using [`getUpdates`] method, but with the expectation the server may not respond immediately. If the server has no new information for the client when the poll is received, instead of sending an empty response, the server holds the request open and waits for response information to become available. Once it does have new information, the server immediately sends a response to the client, completing the request. Upon receipt of the server response, the client often immediately issues another server request.
- [Setting a webhook] means you supplying Telegram with a location in the form of an URL, on which your bot listens for updates. Telegram need to be able to connect and post updates to that URL.
- [Setting a webhook](webhook.md) means you supplying Telegram with a location in the form of an URL, on which your bot listens for updates. Telegram need to be able to connect and post updates to that URL.
To be able to handle webhook updates you'll need a server that:
- Supports IPv4, IPv6 is currently not supported for webhooks.
- Accepts incoming POSTs from subnets 149.154.160.0/20 and 91.108.4.0/22 on port 443, 80, 88, or 8443.
Expand All @@ -12,29 +12,23 @@ To be able to handle webhook updates you'll need a server that:
- Uses a CN or SAN that matches the domain you’ve supplied on setup.
- Supplies all intermediate certificates to complete a verification chain.

You can find more useful information on setting webhook in [Marvin's Marvellous Guide to All Things Webhook]
You can find more useful information on setting webhook in [Marvin's Marvellous Guide to All Things Webhook](https://core.telegram.org/bots/webhooks)

Each user interaction with your bot results in new
[Update] object. Its fields will be set depending on update type.
[Update](https://github.com/TelegramBots/Telegram.Bot/blob/master/src/Telegram.Bot/Types/Update.cs) object. Its fields will be set depending on update type.

## Example projects

### Long polling

- [Simple console application]. Demonstrates the use of the [Telegram.Bot.Extensions.Polling] package.
- [Console application](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Console). Demonstrates a basic bot with some commands.
- [Advanced console application](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Console.Advanced). Demonstrates the use of many advanced programming features.

### Webhook

- [ASP.NET Core] application
- [Azure Functions]
- [AWS Lambda]
- [ASP.NET Core](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.MinimalAPIs) web application with Minimal APIs
- [ASP.NET Core](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.Controllers) web application with Controllers
- [Azure Functions](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Serverless/AzureFunctions.Webhook)
- [AWS Lambda](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Serverless/AwsLambda.Webhook)

[`getUpdates`]: https://core.telegram.org/bots/api#getupdates
[Setting a webhook]: https://core.telegram.org/bots/api#setwebhook
[Update]: https://github.com/Fedorus/Telegram.Bot/blob/master/src/Telegram.Bot/Types/Update.cs
[Marvin's Marvellous Guide to All Things Webhook]: https://core.telegram.org/bots/webhooks
[Simple console application]: https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Telegram.Bot.Examples.Polling
[Telegram.Bot.Extensions.Polling]:https://github.com/TelegramBots/Telegram.Bot.Extensions.Polling
[ASP.NET Core]: https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Telegram.Bot.Examples.WebHook
[Azure Functions]: https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Serverless/Telegram.Bot.Examples.AzureFunctions.WebHook
[AWS Lambda]: https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Serverless/Telegram.Bot.Examples.AwsLambda.WebHook
4 changes: 2 additions & 2 deletions src/3/updates/webhook.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Webhooks

[![Webhook guide](https://img.shields.io/badge/Bot_API-Webhook%20guide-blue.svg?style=flat-square)](https://core.telegram.org/bots/webhooks)
[![Webhook ASP.NET example](https://img.shields.io/badge/Examples-ASP.NET%20WebApp-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Telegram.Bot.Examples.WebHook)
[![Webhook ASP.NET example](https://img.shields.io/badge/Examples-ASP.NET%20WebApp-green?style=flat-square)](https://github.com/TelegramBots/Telegram.Bot.Examples/tree/master/Webhook.MinimalAPIs)

With Webhook, your application gets notified automatically by Telegram when new updates arrive for your bot.

Expand Down Expand Up @@ -57,7 +57,7 @@ async Task HandleUpdate(Update update)
Your update handler code is ready, now you need to instruct Telegram to send updates to your URL, by running:
```csharp
var bot = new TelegramBotClient("YOUR_BOT_TOKEN");
await bot.SetWebhookAsync("https://your.host:port/bot", allowedUpdates: []);
await bot.SetWebhookAsync("https://your.public.host:port/bot", allowedUpdates: []);
```

You can now deploy your app to your webapp host machine.
Expand Down

0 comments on commit adc7ac2

Please sign in to comment.