Home » Send Telegram message from C# Code

Send Telegram message from C# Code

In this article, we are going to check how we can send messages in telegram using API or bot.

By using API we can send messages in any Channel or group in a couple of lines of code, We will check this in C# code. Telegram API is completely free, we can use this to automate the task. Personally, I have used this in my multiple production application, and it’s working seamlessly without any complex configuration.

Prerequisite

  1. Basic Knowledge of C# code
  2. Telegram Account

In this article, we are going to target c# language

How to get Telegram bot API token

to set up a telegram bot, you don’t need to write any code. We can use telegram mobile or windows app and will get API tokens within few simple steps.

Here I am going to use the telegram windows app

  1. Enter @botfather in search box , select @BotFather and click on Start

2. Once click on start, you will get multiple commands/options

3. To create a new bot, fire /newbot command in the chatbox, it will ask for Bot name, just enter that and then it will ask for bot username, add that as well.

4. Congratulations! You have successfully created the bot, Here you will get a token Id. Please copy token ID somewhere else so we can use that in our API.

How to send message in Channel/Group or Chat

For demo purposes, I am going to create one demo channel

I have created one demo channel, give the username as @geekfrisk (Username should be unique). Just add the bot as a group member and give it proper access.

I just added few lines of code and run the console application, and received the message in the channel.

please copy the below code to send a message to the channel, Just pass the required parameters and token id.

public static bool TelegramAPI(string chatId, string text)
{
   bool isPosted = false;
   try
   {
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    string urlString = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}";
    string apiToken = "";//Add token id
    urlString = String.Format(urlString, apiToken, chatId, text);
    WebRequest request = WebRequest.Create(urlString);
    request.Timeout = 60000;
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
    StreamReader reader = new StreamReader(response.GetResponseStream());
    isPosted = true;
    }
    return isPosted;
    }
    catch (Exception ex)
    {
            //handle exception   
    }
    return isPosted;
}

Need help?

Read this post again, if you have any confusion or else add your questions in Community