-
Notifications
You must be signed in to change notification settings - Fork 0
TLSharp use (using)
Source: https://github.com/sochix/TLSharp
Unofficial Telegram (http://telegram.org/) client library implemented in C#.
It's a perfect fit for any developer who would like to send data directly to Telegram users or write own custom Telegram client.
- How do I add this to my project?
- Starter Guide
- Quick configuration
- First requests
- Working with files
- Available Methods
- Contributors
- FAQ
- License
-
Install via NuGet
-
Install-Package TLSharp
or build from source (or.. decompile it from tlsharp dll! ;)
- Clone TLSharp from GitHub
- Compile source with VS2015 or MonoDevelop
- Add reference to TLSharp.Core.dll to your awesome project.
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.
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
.Where(x => x.GetType() == typeof (TLUser))
.Cast<TLUser>()
.FirstOrDefault(x => x.Phone == "<recipient_phone>");
//send message
await client.SendMessageAsync(new TLInputPeerUser() {UserId = 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 = (TLDialogsSlice) await client.GetUserDialogsAsync();
//find channel by title
var chat = dialogs.Chats
.Where(c => c.GetType() == typeof(TLChannel))
.Cast<TLChannel>()
.FirstOrDefault(c => c.Title == "<channel_title>");
//send message
await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = chat.AccessHash.Value }, "OUR_MESSAGE");
Full code you can see at SendMessageToChannel test
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() { UserId = user.Id }, fileResult, "kitty");
await client.SendUploadedDocument(
new TLInputPeerUser() { UserId = 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()
{
AccessHash = document.AccessHash,
Id = document.Id,
Version = document.Version
},
document.Size); //size of fileChunk you want to retrieve
Full code you can see at DownloadFileFromContactTest
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
SendPingAsync
GetHistoryAsync
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 = new TLInputPeerUser() { UserId = user.Id }
};
//run request, and deserialize response to Boolean
return await client.SendRequestAsync<Boolean>(req);
The only way is Telegram API docs. Latest scheme in JSON format you can find here.
What things can I Implement (Project Roadmap)?
- Latest Release
- [DONE] Add PHONE_MIGRATE handling
- [DONE] Add FILE_MIGRATE handling
- [DONE] Add NuGet package
- [DONE] Add wrappers for media uploading and downloading
- Add Updates handling (https://github.com/sochix/TLSharp/pull/940)
- Store user session as JSON (https://github.com/nblockchain/TgSharp/pull/18)
- Upgrade MTProto protocol version to 2.0 (https://github.com/nblockchain/TgSharp/pull/23)
- SRP/2FA support (https://github.com/nblockchain/TgSharp/pull/17)
The latest layer supported by TLSharp is 66. If you need a higher layer, help us test the preview version of TgSharp (your feedback is welcome!)
TLSharp library should automatically handle these errors. If you see such errors, please open a new Github issue with the details (include a stacktrace, etc.).
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
After you get this, you cannot use Telegram's API for a while. You can know the time to wait by accessing the FloodException::TimeToWait property.
If this happens too often and/or the TimeToWait value is too long, there may be something odd going on. First and foremost, are you using TLSharp to manage more than one telegram account from the same host(server)? If yes, it's likely that you're hitting Telegram restrictions. We recommend that you use TLSharp in a standalone-device app (so that each instance of your program only uses one telegram account), so for example a mobile app, not a web app. If, on the other hand, you're completely sure that you found a bug in TLSharp about this, please open a Github issue.
TLSharp only covers basic functionality of the Telegram protocol, you can be a contributor or a sponsor to speed-up developemnt of any more new features.
If you think you have found a bug in TLSharp, create a github issue. But if you just have questions about how to use TLSharp, use our gitter channel (https://gitter.im/TLSharp/Lobby) or our Telegram channel (https://t.me/joinchat/AgtDiBEqG1i-qPqttNFLbA).
- 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.
- Afshin Arani - TLGenerator, and a lot of other usefull things
- knocte
LIBRARY IS NO LONGER MAINTAINED
As a workaround you can use -> WTelegramClient
WTelegramClient is another C#/.NET open-source library for accessing Telegram Client API and is:
- offering up-to-date API (latest layer)
- safer (latest MTProto v2 implementation and many security checks)
- feature-complete (handling of updates, multiple-DC connections)
- easy-to-use (API calls are direct methods with fully documented parameters in VS)
- designed for .NET 5.0+, but also available for .NET Standard 2.0 (.NET Framework 4.6.1+ & .NET Core 2.0+)
- Build status NuGet version