Telegram Get All Group Members with Telethon
Preface
In the previous post, we obtained a list of active group member IDs by querying the most recent 1000 messages in a group.If I want to be especially kind to the members in this group, anyone who is currently in the group should not be bothered by bots.
So I need to get all the members in the group.
Development with GPT
Don't forget, we just finished the project for querying the most recent messages in a group. To make it easier for myself to read and learn, I copied all the code from the previous project, added the following requirements, and sent it to GPT.
Query all members of a Telegram groupOutput format: yamltelegram userid:uesrname: telegram account's usernamefull_name: telegram account's full nameFor example:6611601789:username: skypatchfull_name: 蛙 女The group may be a public group or a private group
After some simple debugging, the code ran fine. But the retrieved users included users from the exceptions list. This is not what we want; the user list we want should exclude these users.
This step took a long time, and the results returned by GPT had issues.
I used Claude, Gemini, and ChatGPT simultaneously.
Combined with the official Telethon documentation, I finally got it done.
Uploaded to GitHub
Runtime output
Fetching group member list: FuckGFW-Newbie 翻墙新手村
Skipping user ID in the Exceptions list: 816194782
Skipping user ID in the Exceptions list: 6521155977
...omitted...
--- Group Member List ---
6617181826:
username: atefatman
full_name: 子 肥
7919966027:
username: crazypeace_anti_bot_bot
full_name: CZ_antibot_bot
...omitted...
✅ Total of 1216 members retrieved
📄 Saved to file: members_1517821953.yaml
========
Postscript
In Telethon, both ChannelParticipantBanned and ChannelParticipantsBanned are valid "things".
You can import them and then use
from telethon.tl.types import ChannelParticipantBanned, ChannelParticipantsBannedChannelParticipantsBanned
is a filter, used as a parameter for the client.iter_participants() function
See the official documentation
When ChannelParticipantsBanned is used as a filter, calling the client.iter_participants() function returns these kinds of users:The "Exceptions" section in the group's Permissions
ChannelParticipantBanned
is a possible value of a user's "attribute" participant, used to determine whether the user is in this list:
The "Exceptions" section in the group's Permissions (see image above)
The usage is like this:
isinstance(user.participant, ChannelParticipantBanned)

A Few Things to Note
Both of these "things" are called *****Banned. But actually, Exceptions means a setting that takes precedence over the group's default permission settings.
For example, in my group, the default user permission doesn't allow sending stickers. But you can set a specific user to be able to send stickers in the Exceptions list. Do you think that's called "Banned"?

