How can I get channel messages from telegram channels with TLSharp?
The following links haven't helped me:
How can I get messages from a Telegram channel with the Telegram API
How to obtain all messages from my channel in telegram?
You can use this code
public async Task GatherChannelHistory(string channelName, int offset = 0, int maxId = -1, int limit = 50)
{
_resultMessages.Clear();
await _client.ConnectAsync();
var dialogs = (TLDialogsSlice)await _client.GetUserDialogsAsync();
var chat = dialogs.Chats.ToList()
.OfType<TLChannel>()
.FirstOrDefault(c => c.Title == channelName);
if (chat.AccessHash != null)
{
var tlAbsMessages =
await _client.GetHistoryAsync(
new TLInputPeerChannel {ChannelId= chat.Id, AccessHash = chat.AccessHash.Value}, offset,
maxId, limit);
var tlChannelMessages = (TLChannelMessages) tlAbsMessages;
for (var index = 0; index < tlChannelMessages.Messages.Count-1; index++)
{
var tlAbsMessage = tlChannelMessages.Messages.ToList()[index];
var message = (TLMessage) tlAbsMessage;
//Now you have the message and you can do what you need with it
//the code below is an example of messages classification
if (message.media == null)
{
_resultMessages.Add(new ChannelMessage()
{
Id = message.id,
ChannelId = chat.id,
Content = message.message,
Type = EnChannelMessage.Message,
Views = message.views,
});
}
else
{
switch (message.media.GetType().ToString())
{
case "TeleSharp.TL.TLMessageMediaPhoto":
var tLMessageMediaPhoto = (TLMessageMediaPhoto)message.media;
_resultMessages.Add(new ChannelMessage()
{
Id = message.id,
ChannelId = chat.id,
Content = tLMessageMediaPhoto.caption,
Type = EnChannelMessage.MediaPhoto,
Views = message.views ?? 0,
});
break;
case "TeleSharp.TL.TLMessageMediaDocument":
var tLMessageMediaDocument = (TLMessageMediaDocument)message.media;
_resultMessages.Add(new ChannelMessage()
{
Id = message.id,
ChannelId = chat.id,
Content = tLMessageMediaDocument.caption,
Type = EnChannelMessage.MediaDocument,
Views = message.views ?? 0,
});
break;
case "TeleSharp.TL.TLMessageMediaWebPage":
var tLMessageMediaWebPage = (TLMessageMediaWebPage)message.media;
string url = string.Empty;
if (tLMessageMediaWebPage.webpage.GetType().ToString() != "TeleSharp.TL.TLWebPageEmpty")
{
var webPage = (TLWebPage) tLMessageMediaWebPage.webpage;
url = webPage.url;
}
_resultMessages.Add(new ChannelMessage
{
Id = message.id,
ChannelId = chat.id,
Content = message.message + @" : " + url,
Type = EnChannelMessage.WebPage,
Views = message.views ?? 0,
});
break;
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With