Created
August 14, 2024 19:49
-
-
Save alexandrebl/95f580808a6a17a9db97b421aafff8a9 to your computer and use it in GitHub Desktop.
Telegram Bot CSharp C# .Net
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Telegram.Bot; | |
| using Telegram.Bot.Exceptions; | |
| using Telegram.Bot.Polling; | |
| using Telegram.Bot.Types; | |
| using Telegram.Bot.Types.Enums; | |
| namespace ConsoleApp1; | |
| class Program | |
| { | |
| static TelegramBotClient Bot; | |
| static string BOT_TOKEN = ""; | |
| static async Task Main() { | |
| var cts = new CancellationTokenSource(); | |
| try { | |
| Bot = new TelegramBotClient(BOT_TOKEN); | |
| var me = await Bot.GetMeAsync(); | |
| Console.WriteLine($"Start listening for @{me.Username}"); | |
| await Bot.ReceiveAsync(new DefaultUpdateHandler(UpdateHandler, PollingErrorHandler), new ReceiverOptions(), cts.Token); | |
| async Task PollingErrorHandler(ITelegramBotClient telegramBotClient, Exception exception, CancellationToken cancellationToken) | |
| { | |
| var ErrorMessage = exception switch { | |
| ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", | |
| _ => exception.ToString() | |
| }; | |
| Console.WriteLine(ErrorMessage); | |
| } | |
| async Task UpdateHandler(ITelegramBotClient telegramBotClient, Update update, CancellationToken cancellationToken) | |
| { | |
| if (update.Type != UpdateType.Message) | |
| return; | |
| try { | |
| BotOnMessageReceived(update.Message); | |
| } catch (Exception exception) { | |
| await PollingErrorHandler(telegramBotClient, exception, cancellationToken); | |
| } | |
| } | |
| } catch (Exception ex) { | |
| Console.WriteLine(ex.Message); | |
| cts.Cancel(); | |
| } | |
| } | |
| static void BotOnMessageReceived(Message message) { | |
| Console.WriteLine($"Receive message type: {message.Type}, Chat Id: {message.Chat.Id}"); | |
| if (message.Type != MessageType.Text) | |
| return; | |
| Console.WriteLine( $"Received {message.Text}"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment