Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / AWS

How to Easily Create Telegram Bot using C#

5.00/5 (3 votes)
23 May 2021CPOL5 min read 49.1K  
A walkthrough and source code for creating telegram bot using C# and deploying it on AWS
It may seem that creating bot telegrams in C# is difficult, but I want to show that it is not. In this article, I will give an example of writing an online bot using C# /. NET and publishing it on AWS. That is, we will create a web application that will spin on a remote host and receive commands from users.

Introduction

Telegram has become popular these days and has more than 500 million users. One of the main "tricks" of Telegram is its supposed security - according to Pavel Durov, all correspondence between users is encrypted. Moreover, no one will have access to your messages. But this article is not about that. Today, I would like to talk about an equally cool feature in Telegram, namely bots. In addition to the fact that the network is already full of information about various kinds of Telegram bots, the messenger opened its API for developers, and now everyone can create their own bot.

It may seem that creating bot telegrams in C# is difficult, but I want to show that it is not. In this article, I will give an example of writing an online bot using C# /. NET and publishing it on AWS. That is, we will create a web application that will spin on a remote host and receive commands from users.

Tools

For developing and deploying telegram bot using .NET /C# code on AWS Lambda, you need:

  1. Visual Studio
  2. AWS Toolkit for Visual Studio
  3. Account on AWS

Registration

First of all, you have to register your bot in telegram. For this step, go to telegram application. It doesn’t matter what kind of application you use, and find @BotFather bot. Using /start command, you can start registration (Image 1).

Image 1 - Registration telegram bot

Next, choose /newbot command, and setup a bot name. Then you will receive a token to access the HTTP API. This you need to use later.

Bot Coding

The next big chapter is developing the telegram bot. For this step, you need Visual Studio because AWS Lambda does not support coding using management console. Moreover, you need to download and setup AWS Toolkit for Visual Studio.

Then you need to create a new AWS Serverless Application (.NET Core – C#). Then, choose an empty application without tests (Image 2).

Image 2 - Creating AWS Serverless Application

Next, we have an empty project, and we have to connect nuget packages for solution. You need to go to Nuget package manager and connect packages:

  • Telegram.Bot
  • Newtonsoft.Json
  • Microsoft.Extensions.Logging.Abstactions
  • AWSSDK.Lambda
  • AWSSDK.Core
  • Amazon.Lambda.Serialization.Json
  • Amazon.Lambda.Core

You can see that in Image 3.

Image 3 - NuGet Packeges for telegram bot

Next, check your .csproj file. It should contain code:

HTML
<ItemGroup>   
    <PackageReference Include="AWSSDK.Core" Version="3.7.0.25" /> 
    <PackageReference Include="Amazon.Lambda.Core" Version="2.0.0" />  
    <PackageReference Include="Amazon.Lambda.Serialization.Json" Version="2.0.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.1.0" />
    <PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.4.0" />
    <PackageReference Include="AWSSDK.Lambda" Version="3.7.0.24" />   
    <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />

    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
    <PackageReference Include="Telegram.Bot" Version="15.7.1" />
  </ItemGroup>

Next, we can write code. We need two classes - first for function, second – for connecting services, where we will write connection methods.

Then, create a new class with name Connect.

Next, we need two members, moreover, they are read only members.

C#
private readonly TelegramBotClient botClient;
private readonly ILogger<Connect> logger;

Then, let’s create a new constructor, where we initialize a Token form Bot Father:

C#
this.botClient = new TelegramBotClient("You token!!!!");

Since our bot works over the Internet, then personally make an asynchronous method.

Next, create a public asynchronous method Echo, it will accept a parameter of type Update from the Telegram.Bot.Types namespace:

C#
public async Task RespFromTelegram (Update update){}

Next, create a check for an empty message.

C#
if (update == null)
            {
                return;
            }

            if (update.Type != UpdateType.Message)
            {
                return;
            }

Next, let's create a new class member for our message:

C#
var message = update.Message;

Do not forget to write down the log:

C#
this.logger?.LogInformation("Received Message from {0}", message.Chat.Id);

Next, we need to create a definition of the type of message, for this example, we have one type - this is a regular text. As an implementation option, create logic using a conditional operator, but I propose to create it by combining switch, since later we can add a new type of response without any problems. Next, let us create a response for a text message using the following code:

C#
await this.botClient.SendTextMessageAsync(message.Chat.Id, message.Text);

As a result, we should get the code for the class:

C#
class Connect
    {
        private readonly TelegramBotClient botClient;
        private readonly ILogger<Connect> logger;
        public Connect()
        {
            this.botClient = new TelegramBotClient("!!!!!!Your token");
        }
        public async Task RespFromTelegram(Update update)
        {
            if (update == null)
            {
                return;
            }
            if (update.Type != UpdateType.Message)
            {
                return;
            }
            var message = update.Message;
            this.logger?.LogInformation("Received Message from {0}", message.Chat.Id);
            switch (message.Type)
            {
                case MessageType.Text:
                    // Echo each Message
                    await this.botClient.SendTextMessageAsync(message.Chat.Id, message.Text);
                    break;               
            }
        }
    }

Next, we are ready for the code in the main function, and here you need two static read only classes.

C#
private static readonly AmazonLambdaClient lambdaClient;
private static readonly Connect connect;

Next, create a new instance of the class in the function and, in principle, everything is ready for us. However, we need to check the work of the bot, which means we will add a little more code to check:

C#
lambdaClient = new AmazonLambdaClient();
connect = new Connect();
public async Task<string> FunctionHandler(JObject request, ILambdaContext context)
        {
            LambdaLogger.Log("REQUEST: " + JsonConvert.SerializeObject(request));
            try
            {
                var updateEvent = request.ToObject<Update>();
                await connect.RespFromTelegram(updateEvent);
            }
            catch (Exception e)
            {
                LambdaLogger.Log("exception: " + e.Message);
            }

            return "Hello from AWS Lambda" + DateTimeOffset.UtcNow.ToString();
        }

aws-lambda-tools-defaults.json file should have similar code:

HTML
"profile": "cloud_deply",
  "region": "us-east-1",
  "configuration": "Release",
  "framework": "netcoreapp3.1",
  "function-runtime": "dotnetcore3.1",
  "function-memory-size": 128,
  "function-timeout": 30,
  "function-handler": "Tel_bot::Tel_bot.Function::FunctionHandler",
  "function-name": "Tel_bot",
  "package-type": "Zip",
  "function-role": "arn:aws:iam::977701475595:role/service-role/Basic_lamda",
  "tracing-mode": "PassThrough",
  "environment-variables": "",
  "image-tag": ""

Next, let us check our bot, and start debugging and check on the “HelloWorld” function (Image 3).

Image 3 - Checking telegram bot code

Bot’s Deploying

Now our bot is ready to be deployed to AWS. Next, we can to publish on AWS Lambda.

Then, we need to configure the AWS service. Go to the AWS Management Console and find the API Gateway service and create a new Rest API there (Image 4).

Image 4 - Bot's deploying

Then we create a new method “ANY” and select the call to our Lambda function (Image 5).

Image 5 - Creating ANY method

Next, we can test our bot in the same way as in Visual Studio (Image 6):

Image 6 - Testing the bot

Then, let's send our API to Deploy.

The next step is we need to create a WebHook. For this, we use the following address:

HTML
https://api.telegram.org/bot<token>/setWebHook?url=<Your url>

The address for WebHook should be taken in the Invoke URL section (Image 7).

Image 7 - Url for the bot

After successful installation of WebHook, the telegram website should write a message:

HTML
{"ok":true,"result":true,"description":"Webhook was set"}

Now you can check the bot. The bot is ready and re-sends messages back from the user.

Conclusion

In conclusion, you will now see how easy it is to create a telegram bot using C # /. NET and deploy it to AWS. In this article, I showed how easy it is to create a Telegram bot in C # /. NET and publish it using AWS services. In the open spaces of the internet, I did not find such an article and this was the motivation for writing an article.

History

  • 23rd May, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)