We send messages to Telegram from C #

  • Tutorial
TLSharp rocks!

C # is a developed language with a large number of libraries, but among them there is not a single working implementation of the Telegram API. I want to fix this situation with the help of my small TLSharp library. The article will have a lot of code and one cat.


I want to specify the details right away, sending messages using the Telegram API, and not the Telegram Bot API, will be considered. What is the difference?
Telegram Bot API is an API for creating bots, so it has more restrictions. For example, you cannot send a message to a user until he has added your bot. There are no such restrictions with the Telegram API, all official clients use it.

Create a session


First, initialize the library and create a session repository.
var store = new FileSessionStore();
var client = new TelegramClient(store, "session");

Connect to the server.
client.Connect();

Now we can create a session. To do this, execute the following code:
var hash = await client.SendCodeRequest(phoneNumber); //отсылаем запрос на создании сессии
var code = "1234"; // код который придет от Telegram 
var user = await client.MakeAuth(phoneNumber, hash, code); // создаем сессию

A little about the parameters of the methods:

  • phoneNumber - your phone number in international format (for example, 79184981723)
  • code - the code that you will receive from Telegram, after executing the SendCodeRequest method


Send message


To send a message, we import the contact by phone number or username.
var userByPhoneId = await client.ImportContactByPhoneNumber("791812312323"); // импорт по номеру телефона
var userByUserNameId = await await client.ImportByUserName("userName"); // импорт по юзернейму

We are sending a message.
await client.SendMessage(userId, "Hello Habr!");

I tried to make the library interface as simple as possible so that everyone could figure it out.
For example, to send a picture with cats, it is enough to execute the following code:
var mediaFile = await client.UploadFile("cat.jpg", file);
var res = await client.SendMediaMessage(userId, mediaFile);

Cats in telegram

At the moment, the library implements only the most necessary methods. The library code is not yet ready for use in production, so I did not post it as a nuget package. To add the library to your project, you need to pull the sources from GitHub, compile them and add the reference TLSharp.Core.dll .

Thank you for your attention, I will be glad if you support the library with your commits.

GitHub repository: github.com/sochix/TLSharp

Also popular now: