简体   繁体   中英

Telegram API (NOT Telegram Bot API!) - how to get all messages in entire chat/channel?

  1. I need to grab all messages in a chat. I use C# and the TLSharp library.

  2. I authrized, got the token etc. successfully.

  3. But when I'm trying to get the messages in a loop, I'm going to an infinite loop.

  4. So the text with the results is never appeared in the textbox. I'd like to know what I'm doing wrong and how to fix it. Thanks.

     using TeleSharp.TL; using TeleSharp.TL.Messages; using TLSharp.Core; //using other standard... //code for authorization etc. is skipped int VKFID = 1175259547; //ID of the chat int offset = 0; int n = 1; StringBuilder sb = new StringBuilder(); TelegramClient client = new TelegramClient(<key>, <hash>); TLUser user; private DateTime ConvertFromUnixTimestamp(double timestamp) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); return origin.AddSeconds(timestamp); } private async void button3_Click(object sender, EventArgs e) { sb.Append("#\tDate\tTime\tMID\tTUID\tText" + Environment.NewLine); TLDialogsSlice dialogs = (TLDialogsSlice)await client.GetUserDialogsAsync(); TLChannel chat = dialogs.Chats.Where(c => c.GetType() == typeof(TLChannel)).Cast<TLChannel>().FirstOrDefault(c => c.Id == VKFID); TLInputPeerChannel inputPeer = new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = (long)chat.AccessHash }; while (true) { try { TLChannelMessages res = await client.SendRequestAsync<TLChannelMessages> (new TLRequestGetHistory() { Peer = inputPeer, Limit = 1000, AddOffset = offset, OffsetId = 0 }); var msgs = res.Messages; if (res.Count > offset) { offset += msgs.Count; foreach (TLAbsMessage msg in msgs) { if (msg is TLMessage) { TLMessage message = msg as TLMessage; sb.Append(n.ToString() + "\t" + ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("dd'.'MM'.'yyyy") + "\t" + ConvertFromUnixTimestamp(message.Date).ToLocalTime().ToString("HH':'mm':'ss") + "\t" + message.Id + "\t" + message.FromId + "\t" + message.Message + Environment.NewLine); } if (msg is TLMessageService) continue; n++; } Thread.Sleep(22000); //to avoid TelegramFloodException } else break; } catch (Exception ex) { MessageBox.Show(ex.Message); break; } finally { await Task.Delay(22000); //to avoid TelegramFloodException } } textBox2.Text = sb.ToString(); MessageBox.Show("Done"); }

Could you try to refresh your textbox before Thead.Sleep(22000)?

    textBox2.Text += sb.ToString();
    Application.DoEvents();
    Thread.Sleep(22000);

Other way of doing this could be using a BackgroundWorker in the same way as it is used managing a ProgressBar.

There is now the WTelegramClient library, using the latest Telegram Client API protocol (connecting as a user, not bot).

The library is very complete but also very simple to use. Follow the README on GitHub for an easy introduction.

Connecting, finding your chat and retrieving all the messages can be done like this:

using TL;
using System.Linq;

const int TargetChatId = 1175259547;

using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var chats = await client.Messages_GetAllChats(null);
InputPeer peer = chats.chats.First(chat => chat.ID == TargetChatId);
for (int offset = 0; ;)
{
    var messagesBase = await client.Messages_GetHistory(peer, 0, default, offset, 1000, 0, 0, 0);
    if (messagesBase is not Messages_ChannelMessages channelMessages) break;
    foreach (var msgBase in channelMessages.messages)
        if (msgBase is Message msg)
        {
            // process the message
        }
    offset += channelMessages.messages.Length;
    if (offset >= channelMessages.count) break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM