Language: EN

telegram-bot-csharp

How to Create a Telegram Bot in C#

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 that it has 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 functionalities such as sending and receiving messages, handling commands, among other features.

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 interactions with users.
  • Webhooks and Polling: Supports both methods to receive bot updates.
  • Documentation and examples: Includes comprehensive documentation and examples to facilitate development.

For more information and to access the full 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. To do this

  1. Open the Telegram app and search for the bot @BotFather.
  2. Start a conversation with @BotFather and use the command /newbot 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, open Visual Studio and create a new Console project. Now 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

Set Up Your Bot

In your C# project, create a new class Program 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
 			);
 		}
 	}
}

In this example:

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

Handle Messages and Commands

Let’s enhance 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;
        }
    }
}

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;
        }
    }
}

Using Webhooks

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

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

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