📜 ⬆️ ⬇️

We send messages to Telegram from C #

TLSharp rocks!

# 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 correct this situation with the help of my small TLSharp library. The article will be a lot of code and one cat.


At once I want to discuss the details, sending a message 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, respectively, it has great limitations. For example, you can not send a message to the user until he added your bot. With the Telegram API there are no such restrictions, all official clients use it.
')

Create a session


First, we 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:



We send the message


To send a message, import the contact by phone number or username.
 var userByPhoneId = await client.ImportContactByPhoneNumber("791812312323"); //     var userByUserNameId = await await client.ImportByUserName("userName"); //    

We send the message.
 await client.SendMessage(userId, "Hello Habr!"); 

I tried to make the library interface as easy 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

Currently, only the most necessary methods are implemented in the library. The library code is not yet ready for use in production, so I did not upload it as a nuget package. To add a library to your project, you need to tighten the source 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

Source: https://habr.com/ru/post/277079/


All Articles