telegram-bot-csharp

How to Create a Telegram Bot in C#

  • 4 min

Telegram.Bot is an open-source library designed to simplify the development of Telegram bots in .NET applications.

Telegram is one of the most popular messaging platforms. One of its advantages is a robust yet very simple API for creating bots that can interact with users, and even with other bots.

Telegram.Bot is a C# library that facilitates integration with the Telegram API to create and manage bots. It allows the implementation of features such as sending and receiving messages, command handling, among other functions.

Main features,

  • Easy integration with the Telegram API: Simplifies the use of Telegram API methods.
  • Support for commands and messages: Allows handling various types of user interactions.
  • Webhooks and Polling: Supports both methods for receiving bot updates.
  • Documentation and examples: Includes comprehensive documentation and examples to facilitate development.

For more information and to access the complete documentation, visit the Telegram.Bot repository on GitHub.

How to Set Up a Telegram Bot

The first thing we need to do is create the Bot on Telegram. For this

  1. Open the Telegram app and search for the @BotFather bot.
  2. Start a conversation with @BotFather and use the /newbot command to create a new bot.
  3. Follow the instructions to assign a name and a username to your bot.
  4. Once created, @BotFather will provide you with an API token. Save this token, as we will need it later.

Creating the Bot in C#

To start using Telegram.Bot, you first need to add the library to your C# project. This can be easily done via NuGet, the .NET package manager.

First, we open Visual Studio and create a new Console project. Now we install the Telegram.Bot library via NuGet.

You can do this using the following command in the Package Manager Console:

Install-Package Telegram.Bot

How to Use Telegram.Bot

Configure Your Bot

In your C# project, create a new Program class and configure the bot using the token provided by @BotFather.

using System;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Args;

class Program
{
    private static readonly string Token = "YOUR_TELEGRAM_BOT_TOKEN_HERE";
    private static TelegramBotClient botClient;
    
    static void Main(string[] args)
    {
        botClient = new TelegramBotClient(Token);
    
        var me = botClient.GetMeAsync().Result;
        Console.WriteLine($"Bot id: {me.Id}, Bot Name: {me.FirstName}");
    
        botClient.OnMessage += Bot_OnMessage;
        botClient.StartReceiving();
    
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        botClient.StopReceiving();
    }
    
    private static void Bot_OnMessage(object sender, MessageEventArgs e)
    {
        if (e.Message.Text != null)
        {
            Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id}.");
    
            botClient.SendTextMessageAsync(
                chatId: e.Message.Chat,
                text: "You said:\n" + e.Message.Text
            );
        }
    }
}
Copied!

In this example:

  • A TelegramBotClient is configured with the bot token.
  • It subscribes to the OnMessage event to handle incoming messages.
  • In the Bot_OnMessage method, it responds to text messages by sending a reply to the chat.

Handle Messages and Commands

Let’s improve the bot to handle basic commands like /start and /help.

private static void Bot_OnMessage(object sender, MessageEventArgs e)
{
    if (e.Message.Text != null)
    {
        Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id}.");

        switch (e.Message.Text.ToLower())
        {
            case "/start":
                botClient.SendTextMessageAsync(
                    chatId: e.Message.Chat,
                    text: "Welcome to the bot! Type /help to see available commands."
                );
                break;

            case "/help":
                botClient.SendTextMessageAsync(
                    chatId: e.Message.Chat,
                    text: "/start - Start the bot\n/help - Get help"
                );
                break;

            default:
                botClient.SendTextMessageAsync(
                    chatId: e.Message.Chat,
                    text: "You said:\n" + e.Message.Text
                );
                break;
        }
    }
}
Copied!

Send Images and Files

In addition to text, the bot can also send images and files. Let’s add a command to send an image.

private static void Bot_OnMessage(object sender, MessageEventArgs e)
{
    if (e.Message.Text != null)
    {
        Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id}.");

        switch (e.Message.Text.ToLower())
        {
            case "/start":
                botClient.SendTextMessageAsync(
                    chatId: e.Message.Chat,
                    text: "Welcome to the bot! Type /help to see available commands."
                );
                break;

            case "/help":
                botClient.SendTextMessageAsync(
                    chatId: e.Message.Chat,
                    text: "/start - Start the bot\n/help - Get help\n/photo - Get a photo"
                );
                break;

            case "/photo":
                botClient.SendPhotoAsync(
                    chatId: e.Message.Chat,
                    photo: "https://example.com/photo.jpg",
                    caption: "Here is your photo!"
                );
                break;

            default:
                botClient.SendTextMessageAsync(
                    chatId: e.Message.Chat,
                    text: "You said:\n" + e.Message.Text
                );
                break;
        }
    }
}
Copied!

Using Webhooks

If you prefer to use webhooks instead of polling, you can configure the webhook as follows:

var webhookUrl = "https://yourdomain.com/api/update";
await Bot.SetWebhookAsync(webhookUrl);
Copied!

Make sure your server can handle HTTPS requests and is correctly configured to receive updates.