How to get all users in a telegram channel using telethon?

I think You can use this code in the new version of Telethon

from telethon import TelegramClient
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.types import ChannelParticipantsSearch

api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXX'
################################################
channel_username = 'tehrandb'
################################################

client = TelegramClient('session_name',api_id,api_hash)

assert client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone_number)
    me = client.sign_in(phone_number, input('Enter code: '))

# ---------------------------------------
offset = 0
limit = 200
my_filter = ChannelParticipantsSearch('')
all_participants = []
while_condition = True
# ---------------------------------------
channel = client(GetFullChannelRequest(channel_username))
while while_condition:
    participants = client(GetParticipantsRequest(channel=channel_username, filter=my_filter, offset=offset, limit=limit, hash=0))
    all_participants.extend(participants.users)
    offset += len(participants.users)
    if len(participants.users) < limit:
         while_condition = False

I used ‍Telethon V0.19, but the previous versions are pretty much the same


Sean answer won't make any difference.

Your code works for older Telethon versions. In the new versions, a new argument hash is added to GetParticipantsRequest method. Therefore, you need to pass hash as an argument too. Add hash=0 like this:

result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100, 0))

Note that the hash of the request is not the channel hash. It's a special hash calculated based on the participants you already know about, so Telegram can avoid resending the whole thing. You can just leave it to 0.

Here is an up-to-date example from official Telethon wiki.


channel = client(ResolveUsernameRequest('channel_name'))
user_list = client.iter_participants(entity=channel)
for _user in user_list:
    print(_user)

or

user_list = client.get_participants(entity=channel)
for _user in user_list:
    print(_user)

from