How-To: Send messages to Telegram from C#
Note: Dear readers, the latest docs you can find at https://github.com/sochix/TLSharp. Also, I wrote a simple GUI to send Telegram messages feel free to download and use it.
C# is highly developed language with tons of libraries, but there is no library for working with Telegram API. To change this situation I developed TLSharp - small library to work with Telegram API.
Before diving into techincal details,
I want to notice that in the article will be used Telegram API not Telegram Bot API.
What's the difference? Ok, Telegram Bot API is API for creating bots, so it's very limited.
For example, you can't send messages directly with Telegram Bot API. Telegram API have no such limitations,
it's widely used in all official Telegram clients.
With this in mind, let's start!
Firstly we need to initialize library and create session storage
var store = new FileSessionStore(); var client = new TelegramClient(store, "session");
Than connect to server
Finally, we can create session. Code below will do it for you:
var hash = await client.SendCodeRequest(phoneNumber); //request for session creating var code = "1234"; // received code from Telegram var user = await client.MakeAuth(phoneNumber, hash, code);
Parameters that we have used:
- phoneNumber - your phone number in international format (e.g. 79184981723)
- code - code that you received from Telegram, after SendCodeRequest method was executed
Let's import contact by phone number or username
var userByPhoneId = await client.ImportContactByPhoneNumber("791812312323"); //import by phone var userByUserNameId = await await client.ImportByUserName("userName"); //import by username
and send messages
await client.SendMessage(userId, "Hello from TLSharp!");
I tried to make library interface as simple as possible.
For example, to send media file you need to execute next code:
var mediaFile = await client.UploadFile("cat.jpg", file); var res = await client.SendMediaMessage(userId, mediaFile);
For now in library implemented only basic methods. Source code isn't ready for production, that's why I didn't create NuGet package.
To use TLSharp in your project:
- Copy source code from GitHub
- Compile it in VS 2015
- Add reference to
GitHub repository: https://github.com/sochix/TLSharp
Ask your questions in comments.