TLSharp
Unofficial Telegram (http://telegram.org) client library implemented in C#. Latest TL scheme supported, thanks to Afshin Arani
Consider donation to speed up development process.
Bitcoin wallet: 3K1ocweFgaHnAibJ3n6hX7RNZWFTFcJjUe
It's a perfect fit for any developer who would like to send data directly to Telegram users or write own custom Telegram client.
Table of contents?
- How do I add this to my project?
- Dependencies
- Starter Guide
- Available Methods
- Contributing
- FAQ
- Donations
- License
How do I add this to my project?
Install via NuGet
Install-Package TLSharp
or build from source
- Clone TLSharp from GitHub
- Compile source with VS2015 or MonoDevelop
- Add reference to
TLSharp.Core.dll
to your awesome project.
Dependencies
TLSharp has a few dependenices, most of functionality implemented from scratch. All dependencies listed in package.conf file.
Starter Guide
Quick Configuration
Telegram API isn't that easy to start. You need to do some configuration first.
- Create a developer account in Telegram.
- Goto API development tools and copy API_ID and API_HASH from your account. You'll need it later.
First requests
To start work, create an instance of TelegramClient and establish connection
var client = new TelegramClient(apiId, apiHash);
await client.ConnectAsync();
Now you can work with Telegram API, but ->
Only a small portion of the API methods are available to unauthorized users. (full description)
For authentication you need to run following code
var hash = await client.SendCodeRequestAsync("<user_number>");
var code = "<code_from_telegram>"; // you can change code in debugger
var user = await client.MakeAuthAsync("<user_number>", hash, code);
Full code you can see at AuthUser test
When user is authenticated, TLSharp creates special file called session.dat. In this file TLSharp store all information needed for user session. So you need to authenticate user every time the session.dat file is corrupted or removed.
You can call any method on authenticated user. For example, let's send message to a friend by his phone number:
//get available contacts
var result = await client.GetContactsAsync();
//find recipient in contacts
var user = result.users.lists
.Where(x => x.GetType() == typeof (TLUser))
.Cast<TLUser>()
.FirstOrDefault(x => x.phone == "<recipient_phone>");
//send message
await client.SendMessageAsync(new TLInputPeerUser() {user_id = user.id}, "OUR_MESSAGE");
Full code you can see at SendMessage test
To send message to channel you could use the following code:
//get user dialogs
var dialogs = await client.GetUserDialogsAsync();
//find channel by title
var chat = dialogs.chats.lists
.Where(c => c.GetType() == typeof(TLChannel))
.Cast<TLChannel>()
.FirstOrDefault(c => c.title == "<channel_title>");
//send message
await client.SendMessageAsync(new TLInputPeerChannel() { channel_id = chat.id, access_hash = chat.access_hash.Value }, "OUR_MESSAGE");
Full code you can see at SendMessageToChannel test
Working with files
Telegram separate files to two categories -> big file and small file. File is Big if its size more than 10 Mb. TLSharp tries to hide this complexity from you, thats why we provide one method to upload files UploadFile.
var fileResult = await client.UploadFile("cat.jpg", new StreamReader("data/cat.jpg"));
TLSharp provides two wrappers for sending photo and document
await client.SendUploadedPhoto(new TLInputPeerUser() { user_id = user.id }, fileResult, "kitty");
await client.SendUploadedDocument(
new TLInputPeerUser() { user_id = user.id },
fileResult,
"some zips", //caption
"application/zip", //mime-type
new TLVector<TLAbsDocumentAttribute>()); //document attributes, such as file name
Full code you can see at SendPhotoToContactTest and SendBigFileToContactTest
To download file you should call GetFile method
await client.GetFile(
new TLInputDocumentFileLocation()
{
access_hash = document.access_hash,
id = document.id,
version = document.version
},
document.size); //size of fileChunk you want to retrieve
Full code you can see at DownloadFileFromContactTest
Available Methods
For your convenience TLSharp have wrappers for several Telegram API methods. You could add your own, see details below.
- IsPhoneRegisteredAsync
- SendCodeRequestAsync
- MakeAuthAsync
- SignUpAsync
- GetContactsAsync
- SendMessageAsync
- SendTypingAsync
- GetUserDialogsAsync
- SendUploadedPhoto
- SendUploadedDocument
- GetFile
- UploadFile
What if you can't find needed method at the list?
Don't panic. You can call any method with help of SendRequestAsync
function. For example, send user typing method:
//Create request
var req = new TLRequestSetTyping()
{
action = new TLSendMessageTypingAction(),
peer = peer
};
//run request, and deserialize response to Boolean
return await SendRequestAsync<Boolean>(req);
Where you can find a list of requests and its params?
The only way is Telegram API docs. Yes, it's outdated. But there is no other source. Latest scheme in JSON format you can find here
Contributing
Contributing is highly appreciated!
What things can I Implement (Project Roadmap)?
Release 1.0.0
- [DONE] Add PHONE_MIGRATE handling
- [DONE] Add FILE_MIGRATE handling
- Add Updates handling
- [DONE] Add NuGet package
- [DONE] Add wrappers for media uploading and downloading
- Store user session as JSON
FAQ
What API layer is supported?
The latest one - 57. Thanks to Afshin Arani for his TLGenerator
I get an error MIGRATE_X?
TLSharp library should automatically handle this errors. If you see such errors, pls create a new issue.
I get an exception: System.IO.EndOfStreamException: Unable to read beyond the end of the stream. All test methos except that AuthenticationWorks and TestConnection return same error. I did every thing including setting api id and hash, and setting server address.-
You should create a Telegram session. See configuration guide
Why I get FLOOD_WAIT error?
Why does TLSharp lacks feature XXXX?
Now TLSharp is basic realization of Telegram protocol, you can be a contributor or a sponsor to speed-up developemnt of any feature.
Nothing helps
Ask your question at gitter or create an issue in project bug tracker.
Attach following information:
- Full problem description and exception message
- Stack-trace
- Your code that runs in to this exception
Without information listen above your issue will be closed.
Donations
Thanks for donations! It's highly appreciated. Bitcoin wallet: 3K1ocweFgaHnAibJ3n6hX7RNZWFTFcJjUe
List of donators:
Contributors
- Afshin Arani - TLGenerator, and a lot of other usefull things
- Knocte
License
Please, provide link to an author when you using library
The MIT License
Copyright (c) 2015 Ilya Pirozhenko http://www.sochix.ru/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.