Skip to main content

Engineering

How to Build a Telegram Bot with C#

July 21, 2025 · 10 min read

Hero image for How to Build a Telegram Bot with C#

Telegram bots are powerful tools for automation, interaction, and integration. While Python is a popular choice for bot development, C# offers a robust, type-safe, and performant alternative—especially for developers already working in the .NET ecosystem. This guide walks through building a simple Telegram bot using C# and the official Telegram.Bot library.

Key Takeaways

  • Register with BotFather, use Telegram.Bot in .NET, and keep handlers thin.
  • Long polling fits local dev; webhooks fit production behind HTTPS.
  • Structure commands and conversation state so business logic is unit-testable.
  • Never commit bot tokens—use environment variables or a secret store.
  • Validate webhook secret tokens and rate-limit user-facing actions.

What is a Telegram Bot?

A Telegram bot is an automated account that can interact with users, send messages, receive commands, and integrate with various services. They run on servers and perform tasks without human intervention—smart assistants inside your Telegram chats.

Why build with C#?

  • Performance: C# and .NET are well suited for high-throughput bot applications.
  • Type safety: Strong typing catches many errors at compile time rather than runtime.
  • Ecosystem: Use the full .NET library and tooling stack.
  • Scalability: .NET applications scale cleanly as your bot grows in usage.
  • Familiarity: If you already write C#, you can ship faster in your preferred language.

Prerequisites

Before you start, make sure you have:

  • .NET SDK — .NET 8.0 or later recommended
  • An IDE — Visual Studio, VS Code with the C# extension, or JetBrains Rider
  • A Telegram account — to create and test your bot

Step 1: Create your bot with BotFather

Register your bot with Telegram's official @BotFather bot to get a unique API token.

  1. Open Telegram — search for @BotFather and start a chat. Use the official account with the blue checkmark.
  2. Start a new bot — send /newbot.
  3. Choose a display name — e.g. "My C# Helper".
  4. Choose a username — must be unique and end with bot, e.g. MyCSharpHelperBot.
  5. Save your token — BotFather returns a long API token string. Keep it secret and never commit it to source control. In real projects, load it from environment variables or .NET user secrets.

Step 2: Set up the C# project

Create a console application and install Telegram.Bot:

dotnet new console -n MyTelegramBotCSharp
cd MyTelegramBotCSharp
dotnet add package Telegram.Bot

Step 3: Write your first bot code

Open Program.cs and replace its contents with:

using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

class Program
{
    private static string BotToken = "YOUR_BOT_TOKEN_HERE";

    static async Task Main()
    {
        var botClient = new TelegramBotClient(BotToken);
        using var cts = new CancellationTokenSource();

        var receiverOptions = new ReceiverOptions
        {
            AllowedUpdates = Array.Empty<UpdateType>() // receive all update types
        };

        botClient.StartReceiving(
            HandleUpdateAsync,
            HandleErrorAsync,
            receiverOptions,
            cancellationToken: cts.Token);

        var me = await botClient.GetMe();
        Console.WriteLine($"Bot started: @{me.Username}");

        Console.ReadLine(); // Keep app running
        cts.Cancel();       // Gracefully stop
    }

    static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken ct)
    {
        if (update.Message is not { } message) return;
        if (message.Text is not { } messageText) return;

        Console.WriteLine($"Received message from {message.Chat.Id}: {messageText}");

        await botClient.SendMessage(
            chatId: message.Chat.Id,
            text: $"You said: {messageText}",
            cancellationToken: ct);
    }

    static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken ct)
    {
        Console.WriteLine($"Bot error: {exception.Message}");
        return Task.CompletedTask;
    }
}

Replace YOUR_BOT_TOKEN_HERE with the token from BotFather, or read it from an environment variable before creating TelegramBotClient.

Step 4: Run your bot

From the project directory:

dotnet run

When the console shows your bot username, open Telegram, search for your bot (e.g. @MyCSharpHelperBot), and start a chat. Send any text message—the bot echoes it back.

Understanding the code

  • BotToken — your bot's unique credential for the Telegram Bot API.
  • TelegramBotClient — main client from Telegram.Bot for API calls.
  • StartReceiving — starts long polling: continuously fetches updates and dispatches them to HandleUpdateAsync and errors to HandleErrorAsync.
  • HandleUpdateAsync — your bot logic. Filters for text messages and replies (you can branch on /start, /help, etc.).
  • HandleErrorAsync — logs polling errors; extend with structured logging in production.
  • CancellationTokenSource — lets you stop receiving gracefully when the process shuts down.

For development, polling is the simplest path. In production, many teams switch to HTTPS webhooks—see Telegram Webhook Integration in .NET for ASP.NET Core setup, secret token validation, and deployment.

FAQ

How do I build a Telegram bot in C#?

Register a bot with BotFather to obtain a token, create a .NET console or ASP.NET Core project, and use the Telegram.Bot library to handle updates and send messages. Start with long polling for local development—it needs no public URL. Move to webhooks when you deploy behind HTTPS for lower latency and better scale.

Should I use long polling or webhooks for my Telegram bot?

Long polling is simpler for development: your process asks Telegram for pending updates on a loop. Webhooks push updates to your HTTPS endpoint and suit production behind a stable domain and certificate. Telegram requires a valid TLS certificate for webhooks; polling works anywhere you have outbound internet.

How do I structure bot commands and conversation flow?

Register commands with BotFather so they appear in the client menu. Handle /start and help text explicitly; route other messages through a small state machine or command router so logic stays testable. Keep handlers thin and push business rules into services you can unit test without the Telegram API.

What security practices matter for Telegram bots?

Store the bot token in environment variables or a secret manager—never commit it. Validate webhook requests using the secret token header when on webhooks. Rate-limit user actions and sanitize any content you echo back to prevent abuse. Treat bot tokens like passwords; rotate them if leaked.

From AI licenses to measurable impact

Licenses are table stakes. Tell me where adoption stalls - we turn fragmented AI usage into measured gains and an operating model that scales.

Get Your AI Adoption Score

3 minutes · Instant result · No sales call required