Artem
Artem

Reputation: 1

How to get more than 200 members from a Telegram group?

I don't understand why it's not possible to retrieve more than 200 members from a Telegram group. The only thing that seems to work is iterating through a filter, but it doesn't return deleted Telegram accounts in the group (those that only have a user ID and no other data).

Everything I found is either outdated and irrelevant or doesn't work either.

require('dotenv').config();
const { TelegramClient, Api } = require("telegram");
const { StringSession } = require("telegram/sessions");
const input = require("input");

if (!process.env.API_ID || !process.env.API_HASH) {
  console.error("API_ID и API_HASH в .env файле.");
  process.exit(1);
}

const apiId = parseInt(process.env.API_ID);
const apiHash = process.env.API_HASH;

const stringSession = new StringSession("");
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const generateHash = (ids) => {
  let hash = 0;
  for (const id of ids) {
    hash = hash ^ (hash >> 21);
    hash = hash ^ (hash << 35);
    hash = hash ^ (hash >> 4);
    hash = hash + id;
  }
  return hash;
};

(async () => {
  const client = new TelegramClient(stringSession, apiId, apiHash, {
    connectionRetries: 5,
  });

  await client.start({
    phoneNumber: async () => await input.text("Номер ?"),
    password: async () => await input.text("Пароль ?"),
    phoneCode: async () => await input.text("Код ?"),
    onError: (err) => console.log(err),
  });

  const groupId = await input.text("ID группы: ");
  const allParticipants = [];
  const uniqueParticipants = new Set();

  try {
    let offset = 0;
    const limit = 200;
    let hash = 200;
    let nextBatch = true;

    while (nextBatch) {
      try {
        const participants = await client.invoke(
          new Api.channels.GetParticipants({
            channel: groupId,
            filter: new Api.ChannelParticipantsSearch({ q: "" }), 
            offset: offset,
            limit: limit,
            hash: hash,
          })
        );

        if (participants.participants.length > 0) {
          const ids = [];
          participants.participants.forEach((user) => {
            const userId = user.userId.valueOf();
            if (!uniqueParticipants.has(userId)) {
              uniqueParticipants.add(userId);
              const telegramUser = participants.users.find((u) => u.id.valueOf() === userId);
              const firstName = telegramUser?.firstName || "Не указано";
              const lastName = telegramUser?.lastName || "Не указано";
              const username = telegramUser?.username || "Не указано";

              allParticipants.push({
                group_id: groupId,
                id: telegramUser.id.valueOf(),
                username: username,
                first_name: firstName,
                last_name: lastName,
                phone: telegramUser.phone || "",
                is_premium: telegramUser.premium ? "Yes" : "No",
              });
              ids.push(userId);
            }
          });

          offset += participants.participants.length;
          hash = generateHash(ids);
          nextBatch = participants.participants.length === limit; 
        } else {
          nextBatch = false;  
        }

      } catch (error) {
        console.error("Ошибка при извлечении участников:", error);
        nextBatch = false; 
      }

      await delay(2000); 
    }

    console.log("Извлечённые участники:", allParticipants);
  } catch (error) {
    console.error("Ошибка при загрузке участников:", error);
  } finally {
    await client.disconnect();
    process.exit(0);
  }
})();

Or did Telegram itself block this method of obtaining the list of participants?

Upvotes: 0

Views: 77

Answers (1)

AYMENJD
AYMENJD

Reputation: 83

Use channelParticipantsRecent filter.

Upvotes: 0

Related Questions