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.

Last updated