Uploading messages using the Telegram API. Where to begin

On the Internet, you can find many descriptions and examples of creating telegram bot-s. But Telegram Bot Api has limited functionality. To solve the problem of unloading messages from Telegram by keyword, you need to use the Telegram API. The TLSharp library was taken as a basis . It is worth immediately clarifying that further work is possible only for registered users in Telegram.

The start of working with the API is application registration:

  1. We go to the Telegram
  2. website and enter your phone number. Enter the verification code.

  3. We get to the developer's page. To complete the registration, you must fill in the fields that characterize your future application.

  4. We get api_id and api_hash.

Work with the library

Add to the Visual Studio project through the package manager console:

Install-Package TLSharp

To get started, create a client with the api_id and api_hash parameters obtained above - make a connection.

TelegramClient client = new TelegramClient(apiId, apiHash);
await client.ConnectAsync();

To authenticate your account, do the following:

var hash = await client.SendCodeRequestAsync("номер телефона");
var code = "код телеграмма";
var user = await client.MakeAuthAsync("номер телефона", hash, code);

After completing this step, TLSharp creates a session.dat file that stores all user session information. After that, you can execute any request presented in the documentation .

We proceed to unload messages from the channels, a prerequisite, you must first be subscribed to the channel. We get all the dialogs that the user has:

var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

The recorded variable now stores all the dialogs, but in order to select only the channels, the convenient structure allows you to select the dialogs of channels and chats using:


We go through all the chats and channels, separately checking whether the next element is a chat or a channel:

foreach (var element in dialogs.Chats){       
      if (element is TLChat){
TLChat chat = element as TLChat;

The TLSharp library implements all the functions of the official API . Functions are implemented through requests, for example, additional information on the channel can be obtained through a request of the form

TeleSharp.TL.Messages.TLChatFull channelInfo = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>
(new TLRequestGetFullChat(){ChatId = chat.Id});

The SendRequestAsync method is called with the return type and any of the queries proposed in the library should be used as a parameter. The following is the code that receives full information about the channel, in this case, two parameters are needed to get the channel - ChannelId and AccessHash:

if (element is TLChannel){
var offset = 0;
TLChannel channel = element as TLChannel;
var chan = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(new TLRequestGetFullChannel() {  Channel = new TLInputChannel() 
{ ChannelId = channel.Id, AccessHash = (long)channel.AccessHash} });
TLInputPeerChannel inputPeer = new TLInputPeerChannel() 
{ ChannelId = channel.Id, AccessHash = (long)channel.AccessHash };

Message upload

Unloading of messages occurs in portions of 100 messages and the AddOffset parameter configures the unloading of the next portion of messages.

while (true){
TLChannelMessages res = await client.SendRequestAsync<TLChannelMessages>
(new TLRequestGetHistory(){
                        	Peer = inputPeer,
                        	Limit = 400,
                        	AddOffset = offset,
                        	OffsetId = 0
var msgs = res.Messages;

Messages are of two types TLMessage and TLMessageService. The first is a regular text message, possibly containing some kind of media file. The second type of message in most cases is a call or message from the Telegram Service.

                         if (res.Count > offset){
                    		offset += msgs.Count;
                        	foreach (var msg in msgs)
                            	if (msg is TLMessage)
                                	TLMessage sms = msg as TLMessage;
                            	if (msg is TLMessageService)

Search by posts

Add a preliminary search for messages in the channel. To do this, simply use the same query, the structure of which is presented above.

TLInputPeerChannel inputPeer = new TLInputPeerChannel() 
{ ChannelId = channel.Id, AccessHash = (long)channel.AccessHash};
TLChannelMessages search = await client.SendRequestAsync<TLChannelMessages>
(new TeleSharp.TL.Messages.TLRequestSearch(){
                        	Peer = inputPeer,
                        	MaxDate = maxdate,
                        	MinDate = mindate,
                        	Q = searchWord,
                        	Filter = new TLInputMessagesFilterEmpty(),
                        	Limit = 100,
                        	Offset = offset  });        

To form your request, it remains only to fill in the parameters and then process the messages received in the same way.

That's all, I hope someone this article was useful.