Book
  • Introduction
  • Installation
  • Getting Updates
    • Polling
    • Webhook
  • Requests
    • Get Me
    • Send Text
  • Extras
    • Logo
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Getting Updates

Polling

PreviousGetting UpdatesNextWebhook

Last updated 4 years ago

Was this helpful?

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

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.

Installation