简体   繁体   English

Telegram API(不是 Telegram Bot API?) - 如何获取整个聊天/频道中的所有消息?

[英]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.我使用 C# 和 TLSharp 库。

  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)?您可以尝试在 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.执行此操作的其他方式可以是使用 BackgroundWorker,其方式与用于管理 ProgressBar 的方式相同。

There is now the WTelegramClient library, using the latest Telegram Client API protocol (connecting as a user, not bot).现在有了 WTelegramClient库,使用最新的 Telegram Client API 协议(以用户身份连接,而不是机器人)。

The library is very complete but also very simple to use.该库非常完整,但使用起来也非常简单。 Follow the README on GitHub for an easy introduction.按照GitHub 上的 README进行简单介绍。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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