Only this pageAll pages
Powered by GitBook
1 of 10

Book

Loading...

Loading...

Loading...

Loading...

Loading...

Requests

Loading...

Loading...

Extras

Loading...

Polling

Ensure thatTelegram.Bots.Extensions.Pollingpackage is installed. See Installation.

Successful polling requires an implementation of IUpdateHandler so we will first address that with an example:

using System.Threading;
using System.Threading.Tasks;
using Telegram.Bots.Extensions.Polling;
using Telegram.Bots.Requests;
using Telegram.Bots.Types;

namespace Telegram.Bots.Example
{
  public class UpdateHandler : IUpdateHandler
  {
    public Task HandleAsync(IBotClient bot, Update update, CancellationToken token)
    {
      return update switch
      {
        MessageUpdate u when u.Data is TextMessage message => Echo(message),
        _ => Task.CompletedTask
      };

      Task Echo(TextMessage message) =>
        bot.HandleAsync(new SendText(message.Chat.Id, message.Text), token);
    }
  }
}

Now that an IUpdateHandler exists, we can create a .NET Core console application with the bot client and polling configured as such:

using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Telegram.Bots.Extensions.Polling;

namespace Telegram.Bots.Example
{
  public static class Program
  {
    public static Task Main() => new HostBuilder()
      .ConfigureServices((context, services) =>
      {
        services.AddBotClient("<bot-token>");
        services.AddPolling<UpdateHandler>();
      })
      .RunConsoleAsync();
  }
}

Run it and try sending a message to the bot.

Send Text

Send a simple text using chat id

Send a simple text using chat username

Send a website URL with its preview disabled

SendText request = new SendText(123456789, "Hello, World!");

Response<TextMessage> response = await bot.HandleAsync(request);
using Telegram.Bots.Requests.Usernames;

SendText request = new SendText("@yourgroup", "Hello, World!");

Response<TextMessage> response = await bot.HandleAsync(request);
SendText request = new SendText(123456789, "https://www.example.com")
{
  DisableWebPagePreview = true
};

Response<TextMessage> response = await bot.HandleAsync(request);
https://core.telegram.org/bots/api#sendMessage

Installation

The main library is available as Telegram.Bots. It provides all the Types and Requests along with the HTTP and JSON support.

https://www.nuget.org/packages/Telegram.Bots

To add long polling, Telegram.Bots.Extensions.Polling can be used.

https://www.nuget.org/packages/Telegram.Bots.Extensions.Polling

If you use the webhook approach and intend to respond to updates directly by returning the desired method data, you will need to integrate the serializer with your ASP.NET Core project and that can be done via Telegram.Bots.Extensions.AspNetCore.

https://www.nuget.org/packages/Telegram.Bots.Extensions.AspNetCore

Getting Updates

Telegram.Bots supports both Polling and Webhooks. This section describes how to integrate these mutually-exclusive approaches:

Polling
Webhook

Webhook

Describes the webhook approach to getting updates.

Get Me

https://core.telegram.org/bots/api#getMe

Get your bot's user information

Response<MyBot> response = await bot.HandleAsync(new GetMe());

if (response.Ok)
{
  MyBot myBot = response.Result;
  
  // ...
}
else
{
  Failure failure = response.Failure;
  
  // Basically you did not setup the bot token correctly
}

Introduction

Telegram.Bots is a .NET Standard wrapper for the Telegram Bot API.

Why was Telegram.Bots made?

I wanted to make a Telegram bot for my personal use and C# happened to be a reasonable language to write it in. I tried using the popular .NET Client for Telegram Bot API but found various issues with it during my use of it that I decided to make a wrapper for the Telegram Bot API from scratch, free from the implementation and interface issues I experienced in that library.

Why did you not simply fix those issues in that popular library?

Two words: breaking changes. My ideas for the Telegram Bot API wrapper were different enough to warrant breaking changes in that library. I did not want to break it and it would have been unreasonable to expect the caretakers of that library to accept my breaking changes, especially since the library does get its work done in most cases without really needing the changes I wanted in the library.

Can you give an example of a major difference between that popular library and Telegram.Bots?

Sure. I will give three but there are more:

  • That popular library throws exceptions when the Telegram servers return a failure response. That library also throws exceptions in cases where tasks are canceled or a timeout occurs. Telegram.Bots, on the other hand, returns the failure response during a failure. Even when a task is canceled or a timeout occurs, a failure response is returned with appropriate information. I found the exception-based approach to require me to learn the ways of the library in order to write resilient code. Telegram.Bots leaves the exceptions for exceptional cases.

  • That popular library maps each type made known by the Telegram Bot API documentation in pretty much the same manner as the documentation does. It does improve in some ways, particularly in places where types involve inline message targeting but it is still limited. Telegram.Bots, on the other hand, uses types in a manner which facilitates pattern matching on the types and allows only the data which is reasonable for any given type. For example, Telegram.Bots has a TextMessage type for text messages and StickerMessage for messages that are stickers, and so on. That popular library has a Message type to denote all kinds of messages and so there is a relative overhead with respect to object creation as well (since that class is bloated with unnecessary properties for any given type of message).

  • Telegram.Bots does not allow you to send useless information. Like, did you know that you can set up the title of an audio only when you are sending it as a file or as an inline audio result? If you send an audio as a URL or as a cached file, setting up the title in the request does not make any difference. Telegram.Bots takes care of all these cases.

For whom is Telegram.Bots written?

Telegram.Bots was primarily written to meet my particular aesthetic preferences and simplicity standards and I will be happy if you try it out and see the difference it makes in your journey to make interesting bots. That is why I made it available as a free and open source software and am writing all this documentation to make the process easier for those interested in trying Telegram.Bots out for themselves.

Telegram.Bots supports .NET Standard 2.1. Using Telegram.Bots will be a good idea for you if you are also interested in utilizing the new language and runtime features.

Alright, I am interested. Show me some code.

Telegram.Bots has some niceties which can be leveraged by utilizing the Microsoft.Extensions.DependencyInjection package. We will use that as it makes the code more manageable.

Here is one way you can get and then print the information about your bot:

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Telegram.Bots.Requests;
using Telegram.Bots.Types;

namespace Telegram.Bots.Example
{
  public static class Program
  {
    private static async Task Main()
    {
      var provider = new ServiceCollection()
        .AddBotClient("<bot-token>")
        .Services
        .BuildServiceProvider();

      var bot = provider.GetRequiredService<IBotClient>();

      Response<MyBot> response = await bot.HandleAsync(new GetMe());
      
      var serializer = provider.GetRequiredService<ISerializer>();

      Console.WriteLine(serializer.Serialize(response, Styling.Indented));
    }
  }
}

Of course, both Telegram and I expect you to not hard-code your bot token if you intend to make your program's source code free and open source (which is a great idea). But this one's an example. You can read the configuration from appsettings.json or read the bot token from the environment variable or load it up from some secret vault. Your choice.

Logo

Telegram.Bots