How to Build a Telegram Bot with C#: A Step-by-Step Guide

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 within the .NET ecosystem. In this guide, I'll walk you through building a simple Telegram bot using C# and the official `Telegram.Bot` library.
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 are powered by code running on servers, allowing them to perform tasks without human intervention. Think of them as smart assistants living inside your Telegram chats.
Why Build a Telegram Bot with C#?
- Performance: C# and .NET are known for their performance, making them suitable for high-throughput bot applications.
- Type Safety: C# provides strong typing, which helps catch errors at compile-time rather than runtime, leading to more robust code.
- Ecosystem: Leverage the vast .NET ecosystem, including libraries, tools, and frameworks.
- Scalability: .NET applications are well-suited for building scalable solutions, important for bots that might grow in popularity.
- Familiarity: If you're already a C# developer, building bots in your preferred language can significantly speed up development.
Prerequisites
Before we start coding, make sure you have:
- .NET SDK: Installed on your machine (e.g., .NET 8.0+ recommended).
- An IDE: Visual Studio, Visual Studio Code with C# extension, or JetBrains Rider.
- A Telegram Account: To create and test your bot.
Step 1: Create Your Bot with BotFather
The first step is to register your bot with Telegram's official bot, BotFather. This is where you get your unique API token.
- Open Telegram: Search for `@BotFather` and start a chat with him. Make sure it's the official one with a blue checkmark.
- Start a New Bot: Send the command `/newbot`.
- Choose a Name: BotFather will ask for a display name for your bot (e.g., "My C# Helper").
- Choose a Username: Then, a unique username (e.g., `MyCSharpHelperBot`). It must end with "bot".
- Get Your Token: BotFather will give you an API token (a long string of characters).Keep this token secret! It's like your bot's password.
Step 2: Set Up Your C# Project
We'll create a new .NET Console Application and install the `Telegram.Bot` NuGet package.
- Create a Project Directory and Console App:
dotnet new console -n MyTelegramBotCSharp cd MyTelegramBotCSharp
- Install the `Telegram.Bot` NuGet Package:
dotnet add package Telegram.Bot
Step 3: Write Your First Bot Code
Open the `Program.cs` file in your project directory and add the following code:
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.GetMeAsync();
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.SendTextMessageAsync(
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;
}
}
Important: Replace `"YOUR_BOT_TOKEN_HERE"` with the actual token you got from BotFather.
Step 4: Run Your Bot
Save the `Program.cs` file and run it from your terminal:
dotnet run
Your bot is now running! Open Telegram, search for your bot's username (e.g., `@MyCSharpHelperBot`), and start a chat.
- Send any other text message, and your bot will echo it back!
Understanding the Code
- `botToken`: Your bot's unique identifier.
- `TelegramBotClient`: The main class from the `Telegram.Bot` library used to interact with the Telegram Bot API.
- `StartReceiving`: This method starts the bot's polling mechanism, continuously checking for new updates from Telegram. It takes two main delegates: `HandleUpdateAsync` for processing incoming updates and `HandleErrorAsync` for handling any errors during polling.
- `HandleUpdateAsync`: This asynchronous function is where your bot's logic resides. It receives an `Update` object, which contains information about the incoming event (e.g., a new message). We filter for text messages and then respond based on the message content (e.g., `/start`, `/help`, or echoing other text).
- `HandleErrorAsync`: This function is called if any error occurs during the polling process. It's good practice to log these errors for debugging.
- `CancellationTokenSource`: Used to manage the cancellation of asynchronous operations, allowing you to gracefully stop the bot.
Next Steps: Expanding Your Bot's Capabilities
This is just the beginning! You can make your bot much more powerful:
- Inline Keyboards: Add interactive buttons to your messages.
- Callback Queries: Handle button presses.
- Conversations: Build multi-step interactions (e.g., asking a series of questions).
- Integrating APIs: Fetch data from external services (weather, news, stock prices).
- Databases: Store user data or other information (e.g., with SQLite or PostgreSQL).
- Deployment: Deploy your bot to a cloud server (like Azure, AWS, or Vercel for certain scenarios) so it can run 24/7.
Conclusion
Building a Telegram bot with C# provides a robust and scalable solution for automating tasks and interacting with users. The `Telegram.Bot` library simplifies the process, allowing you to focus on your bot's unique functionality.
Start with simple ideas, experiment, and don't be afraid to explore the extensive documentation of the `Telegram.Bot` library. The possibilities are truly endless!

Kiryl Bahdanovich
CEO and Founder at IT Busina