Telethon: Fetching list of users with get_full_channel

Created on 24 Jul 2017  Â·  28Comments  Â·  Source: LonamiWebs/Telethon

What is the proper way to fetch all the users in my channel with telethon? I have been struggling with this for the past week as the documentation is.. thin (also, not being a great programmer doesn't help).

From what I saw around, GetFullChannelRequest is the solution but.. I wrote and deleted a lot of lines of code and nothing worked. The current iteration of code looks like this.

from telethon import TelegramClient

from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.messages import GetFullChatRequest
from telethon.tl.types import InputChannel

from telethon.tl.types import InputPeerEmpty

api_id = api_id  # Use your own values here. https://my.telegram.org
api_hash = 'api_hash'
phone_number = '+000000000'

client = TelegramClient('%sessionname%', api_id, api_hash)  # feel free to edit %sessionname% as you want
client.connect() # logining and connecting to Telegram servers

if not client.is_user_authorized():  # authorization (if there is no .session file created before)
    client.send_code_request(phone_number)
    client.sign_in(phone_number, input('Enter the code: '))

# this was as a test to see how do I fetch stuff
result = client(ResolveUsernameRequest('username'))
found_chats = result.chats
found_users = result.users
# end test

def GetFullChannel(self, id):
    self.GetFullChatRequest(id)

users = client(GetFullChannel(self, 'id'))
print(users)

The error that I get when I run this is

NameError: name 'self' is not defined

Any guidance will be greatly appreciated as I am quite clueless. I cannot comprehend how am I supposed to fetch that list of users..or basically anything past that 'test' example above.

RTFM

Most helpful comment

Sure, I've updated the wiki since others may ask the same question.

All 28 comments

The correct way to invoke a request is like this:

response = client.invoke(GetFullChatRequest(id))

the documentation is.. thin

Telegram doesn't bother explaining what the methods do, or what the parameters mean. However, the methods are often very descriptive by themselves. And there's a nice search.

NameError: name 'self' is not defined

Well, clearly, self is not defined… The error is clear enough, you made that up. Also, you're returning nothing. And .GetFullChannelRequest is not a method for anything. It's a request.

You've done the client(ResolveUsernameRequest('username')) part right, it's just changing ResolveUsernameRequest with GetFullChannelRequest. I recommend this Python book.

The correct way to invoke a request is like this:
response = client.invoke(GetFullChatRequest(id))

With the latest update, a simple r = client(GetFullChatRequest(id)) will work.

Hello @Lonami ,

I did not meant to sound harsh or anything, I know you put up a really nice documentation and doing a great job. Before I posted here I think I read most of the posts on stack. Half of the fault I suppose it is mine as I am not a great programmer and I cannot comprehend things so easily.

Indeed the last line of code worked.. or at least I moved a bit forward. Now I got this error:

OverflowError: int too big to convert

Googled it, found this, read it multiple times, added and deleted the "-", "-100". Eventually led me to this.

Invalid object ID for a chat. Make sure to pass the right types.

What's the proper way to get the ID? As I got mine through result.chats[0] from the test code above in the initial post.

Thanks for all the help

LE: I added a bot called @get_my_id to the group (I think it's a supergroup in fact as I may have converted it at some point) and now I got this error

An invalid Peer was used. Make sure to pass the right peer type.

I have tried both with (as seen in the link) and without the chat_id thing.

r = client(GetFullChatRequest(chat_id=int(231399891)))
print(r)

LE2:
So far:
1055018889 - return Invalid object ID for a chat. Make sure to pass the right types.
1001055018889 - return int too big to convert
-1001055018889 - return int too big to convert
231399891 - return An invalid Peer was used. Make sure to pass the right peer type.

(as seen in the link)

And have you read the whole thing?:

Seems like supergroup is subtype of channel (strange, but method getFullChannel works!)

I have read it.. the only thing that came to my mind was
r = client(GetFullChannelRequest(231399891))
which did not worked (type object 'int' has no attribute 'subclass_of_id')

You can't pass an int. Just pass whatever "chat" (or supergroup, or channel) you want.

But I have to fetch the channel..somehow (as an object/array)? Can't seem to find a proper example. Because if I pass simply the username the error is going to be the same, just that I cannot pass a string.

LE: As far as I can see, a 'channel' has two parameters? (correct me if I am wrong).

channel_id | int
access_hash | long

So If I know these two values, making an array of them and passing it in the request should be the solution?

But I have to fetch the channel

Yes.

Because if I pass simply the username the error is going to be the same

Then resolve the username, and whatever chat you get, use that.

So If I know these two values

You could construct the InputChannel.

making an array

No you would use them to construct an InputChannel.

I think I managed to construct the inputChannel yet I am facing another error.

result = client(ResolveUsernameRequest('cofferinta'))
found_chats = result.chats
found_users = result.users

channel = client(InputChannel(result.chats[0].id, result.chats[0].access_hash))
print(channel)

The error:

telethon.errors.rpc_errors.BadMessageError: (BadMessageError(...), 'Odd msg_seqno expected (relevant message), but even received.')

Okay, okay, here we go again.

channel = client(InputChannel(result.chats[0].id, result.chats[0].access_hash))

I've asked this endless times, and I'm yet to get an answer from someone. There's a dedicated section to that. What are you trying to achieve by "invoking" an InputChannel? You can just .invoke() requests!! You already have your result.chats[0], which is a channel. It will be converted to InputChannel, i.e., what you need for GetFullChannelRequest automatically. Either that, or you construct it yourself, InputChannel(id, hash). But you can not invoke anything that is not a request. The error is cryptic, but I just realized why. So I'm going to fix that now. Thanks!

I apologise if my question were put as plain stupid. I did not meant to bother you or anyone here. Thank you for all your assistance. I hope that I am not bold, I'd like a bit more guidance in order how to get the members of the group. I managed to return all the chat info with this code:

result = client(ResolveUsernameRequest('cofferinta'))
found_chats = result.chats
found_users = result.users

r = client(GetFullChannelRequest(result.chats[0]))
print(r)

From what it returned, {ChatFull: {full_chat: {can_view_participants: True, can_set_username: None, id: 1055018889, about: "", participants_count: 15, I should be able to see them. In fact, it showed me the two bots in the conference but no users.

Is this the proper approach to fetch the users? I am searching through the manual, but I do not know entirely how to use all these things.

x = client(GetUsersRequest(found_users[0]))

The problem is that found_users is empty.

LE: I still haven't managed to get past this point. ResolveUsernameRequest does not return any information about the users. I am still trying to figure what am I doing wrong but I would greatly appreciate any help.

@Lonami Is there any chance to re open this issue? I do not want to make another 'issue'. Maybe some other will give a hint on how to solve this final issue.

any chance to re open this issue?

No, this is for Telethon implementation issues, not usage questions. Use StackOverflow for that. Also, I'm no expert in Telegram API _usage_ per se, i.e., I don't know every method and what it does. The only thing I would do would be search, as you can too, sorry.

Well, I am using Telethon. I am doing this half for me and half for a project for my college and I was running a bit on burrowed time, this is why I was quite pushy.

At the moment my last problem is that the resolved users (ResolveUsernameRequest) are always empty. I tried with different groups. Have you ever encountered this @Lonami ? Is this the wrong approach? It returns the peer (chat id), chat with a lot of attributes and users: [] is always like this.

Thank you

Have you ever encountered this @Lonami

If anything, search on the issues, I can't remember. I'd swear that method is just to search, given an username, for someone (channel, group, user, etc.) and nothing else.

Seems like GetParticipantsRequest is a thing.

Can you give an example of using GetParticipantsRequest?

Sure, I've updated the wiki since others may ask the same question.

Thank you very much :3

I use this code bat return only first 200 members

`#!/usr/bin/env python3.4

from telethon import TelegramClient

from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import GetAdminLogRequest
from telethon.tl.functions.channels import GetParticipantsRequest

from telethon.tl.types import ChannelParticipantsRecent
from telethon.tl.types import InputChannel
from telethon.tl.types import ChannelAdminLogEventsFilter
from telethon.tl.types import InputUserSelf
from telethon.tl.types import InputUser
api_id = XXXXXX
api_hash = 'xxxxxxxxxxxxxx'
phone_number = '+3xxxxxxxx'

client = TelegramClient(phone_number, api_id, api_hash)
client.session.report_errors = False
client.connect()

if not client.is_user_authorized():
client.send_code_request(phone_number)
client.sign_in(phone_number, input('Enter the code: '))

channel = client(ResolveUsernameRequest('MY_CHANNEL')) # Your channel username

user = client(ResolveUsernameRequest('Username')) # Your channel admin username
admins = [InputUserSelf(), InputUser(user.users[0].id, user.users[0].access_hash)] # admins
admins = [] # No need admins for join and leave and invite filters

filter = None # All events
filter = ChannelAdminLogEventsFilter(True, False, False, False, True, True, True, True, True, True, True, True, True, True)
cont = 0
list = [0,100,200,300]
for num in list:
result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100))
for _user in result.users:
print( str(_user.id) + ';' + str(_user.username) + ';' + str(_user.first_name) + ';' + str(_user.last_name) )
with open(''.join(['users/', str(_user.id)]), 'w') as f: f.write(str(_user.id))
`

So is it now possible to retrieve full list of members of an entity?

@Sidus00 yes.

I know I maybe asking something obvious, but is there a way to export list of users from groups in which I am not an admin?

@Sidus00 can you from official apps? If the answer is yes, the library can too.

From the GUI app I can view participants and get username but I can't find a way to retrieve it programmatically

@Sidus00 can you tell us what GUI app you use ? you see the whole participants?

Hello Lonami ! ( the question is translated from Russian by Google transalte)

I got a list of contacts and it has a type how do I extract certain data, for example last_name. Should I use a regular expression?

from telethon import *
from telethon.tl import *
from telethon.tl.types import *
from telethon.tl.functions.contacts import *

...
def get_all_contacts(self):
self.client=TelegramClient('session',config.api_id,config.api_hash)
self.client.connect()
#
self.contacts=self.client(GetContactsRequest(0))
print(type(self.contacts))
print(self.contacts)
...

@Sidus00 Is there any way to get the group membercount which I am not an admin?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wdsjxh picture wdsjxh  Â·  3Comments

ghost picture ghost  Â·  4Comments

saeedesfandi picture saeedesfandi  Â·  3Comments

JackCloudman picture JackCloudman  Â·  6Comments

rbabaee2014 picture rbabaee2014  Â·  3Comments