Skip to content

Repository files navigation

TLSharp

Unofficial Telegram (http://telegram.org) client library implemented in C#. Please refer to (https://github.com/sochix/TLSharp) for the original version and further documentation.

Sample code

usingSystem;usingSystem.Threading.Tasks;usingTeleSharp.TL;usingTLSharp.Core;usingSystem.Linq;usingTeleSharp.TL.Messages;usingSystem.Collections.Generic;namespaceTLSharpPOC{classMainClass{constintAPIId=0;conststringAPIHash="???";conststringphone="???";publicstaticvoidMain(string[]args){newMainClass().MainAsync(args).Wait();}privateasyncTaskMainAsync(string[]args){TelegramClientclient=null;try{// -- if necessary, IP can be changed so the client can connect to the test network.Sessionsession=null;// new Session(new FileSessionStore(), "session")//{// ServerAddress = "149.154.175.10",// Port = 443//};//Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}");client=newTelegramClient(APIId,APIHash,session);// subscribe an event to receive live messagesclient.Updates+=Client_Updates;awaitclient.ConnectAsync();Console.WriteLine($"Authorised: {client.IsUserAuthorized()}");TLUseruser=null;// -- If the user has already authenticated, this step will prevent account from being blocked as it// -- reuses the data from last authorisation.if(client.IsUserAuthorized())user=client.Session.TLUser;else{varregistered=awaitclient.IsPhoneRegisteredAsync(phone);varhash=awaitclient.SendCodeRequestAsync(phone);Console.Write("Code: ");varcode=Console.ReadLine();if(!registered){Console.WriteLine($"Sign up {phone}");user=awaitclient.SignUpAsync(phone,hash,code,"First","Last");}Console.WriteLine($"Sign in {phone}");user=awaitclient.MakeAuthAsync(phone,hash,code);}varcontacts=awaitclient.GetContactsAsync();Console.WriteLine("Contacts:");foreach(varcontactincontacts.Users.OfType<TLUser>()){varcontactUser=contactasTLUser;Console.WriteLine($"\t{contact.Id}{contact.Phone}{contact.FirstName}{contact.LastName}");}vardialogs=(TLDialogs)awaitclient.GetUserDialogsAsync();Console.WriteLine("Channels: ");foreach(varchannelObjindialogs.Chats.OfType<TLChannel>()){varchannel=channelObjasTLChannel;Console.WriteLine($"\tChat: {channel.Title}");}Console.WriteLine("Groups:");TLChatchat=null;foreach(varchatObjindialogs.Chats.OfType<TLChat>()){chat=chatObjasTLChat;Console.WriteLine($"Chat name: {chat.Title}");varrequest=newTLRequestGetFullChat(){ChatId=chat.Id};varfullChat=awaitclient.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(request);varparticipants=(fullChat.FullChatasTeleSharp.TL.TLChatFull).ParticipantsasTLChatParticipants;foreach(varpinparticipants.Participants){if(pisTLChatParticipant){varparticipant=pasTLChatParticipant;Console.WriteLine($"\t{participant.UserId}");}elseif(pisTLChatParticipantAdmin){varparticipant=pasTLChatParticipantAdmin;Console.WriteLine($"\t{participant.UserId}**");}elseif(pisTLChatParticipantCreator){varparticipant=pasTLChatParticipantCreator;Console.WriteLine($"\t{participant.UserId}**");}}varpeer=newTLInputPeerChat(){ChatId=chat.Id};varm=awaitclient.GetHistoryAsync(peer,0,0,0);Console.WriteLine(m);if(misTLMessages){varmessages=masTLMessages;foreach(varmessageinmessages.Messages){if(messageisTLMessage){varm1=messageasTLMessage;Console.WriteLine($"\t\t{m1.Id}{m1.Message}");}elseif(messageisTLMessageService){varm1=messageasTLMessageService;Console.WriteLine($"\t\t{m1.Id}{m1.Action}");}}}elseif(misTLMessagesSlice){booldone=false;inttotal=0;while(!done){varmessages=masTLMessagesSlice;foreach(varm1inmessages.Messages){if(m1isTLMessage){varmessage=m1asTLMessage;Console.WriteLine($"\t\t{message.Id}{message.Message}");++total;}elseif(m1isTLMessageService){varmessage=m1asTLMessageService;Console.WriteLine($"\t\t{message.Id}{message.Action}");++total;done=message.ActionisTLMessageActionChatCreate;}}m=awaitclient.GetHistoryAsync(peer,total,0,0);}}}// -- Wait in a loop to handle incoming updates. No need to poll.for(;;){awaitclient.WaitEventAsync();}}catch(Exceptione){Console.WriteLine(e);}}privatevoidClient_Updates(TelegramClientclient,TLAbsUpdatesupdates){Console.WriteLine($"Got update: {updates}");if(updatesisTLUpdateShort){varupdateShort=updatesasTLUpdateShort;Console.WriteLine($"Short: {updateShort.Update}");if(updateShort.UpdateisTLUpdateUserStatus){varstatus=updateShort.UpdateasTLUpdateUserStatus;Console.WriteLine($"User {status.UserId} is {status.Status}");if(status.StatusisTLUserStatusOnline){try{varpeer=newTLInputPeerUser(){UserId=status.UserId};client.SendMessageAsync(peer,"Você está online.").Wait();}catch{}}}}elseif(updatesisTLUpdateShortMessage){varmessage=updatesasTLUpdateShortMessage;Console.WriteLine($"Message: {message.Message}");MarkMessageRead(client,newTLInputPeerUser(){UserId=message.UserId},message.Id);}elseif(updatesisTLUpdateShortChatMessage){varmessage=updatesasTLUpdateShortChatMessage;Console.WriteLine($"Chat Message: {message.Message}");MarkMessageRead(client,newTLInputPeerChat(){ChatId=message.ChatId},message.Id);}elseif(updatesisTLUpdates){varallUpdates=updatesasTLUpdates;foreach(varupdateinallUpdates.Updates){Console.WriteLine($"\t{update}");if(updateisTLUpdateNewChannelMessage){varmetaMessage=updateasTLUpdateNewChannelMessage;varmessage=metaMessage.MessageasTLMessage;Console.WriteLine($"Channel message: {message.Message}");varchannel=allUpdates.Chats[0]asTLChannel;MarkMessageRead(client,newTLInputPeerChannel(){ChannelId=channel.Id,AccessHash=channel.AccessHash.Value},message.Id);}}foreach(varuserinallUpdates.Users){Console.WriteLine($"{user}");}foreach(varchatinallUpdates.Chats){Console.WriteLine($"{chat}");}}}privatevoidMarkMessageRead(TelegramClientclient,TLAbsInputPeerpeer,intid){// An exception happens here but it's not fatal.try{varrequest=newTLRequestReadHistory();request.MaxId=id;request.Peer=peer;client.SendRequestAsync<bool>(request).Wait();}catch{}}}}

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.

About

Telegram client library implemented in C#

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages