-
I need to grab all messages in a chat. I use C# and the TLSharp library.
-
I authrized, got the token etc. successfully.
-
But when I’m trying to get the messages in a loop, I’m going to an infinite loop.
-
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("#tDatetTimetMIDtTUIDtText" + 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"); }
Question posted in Telegram API
A comprehensive official documentation can be found here.
A comprehensive official documentation can be found here.
2
Answers
Could you try to refresh your textbox before Thead.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: