How to get Telegram channel users list with Telegram Bot API

后端 未结 7 1763
旧时难觅i
旧时难觅i 2020-12-28 17:53

Anybody give a starter on how may I get information about users from my telegram bot. Imagine my bot in an admin user in my channel and I want to get my channel user list or

7条回答
  •  生来不讨喜
    2020-12-28 18:48

    In order to get user list, you need to use telegram API.

    Telegram API is fairly complicated. There are some clients which can get the job done much faster.

    For python, there is Telethon, and the code to get channel users is:

    from telethon import TelegramClient
    
    from telethon.tl.functions.contacts import ResolveUsernameRequest
    from telethon.tl.functions.channels import GetAdminLogRequest
    
    from telethon.tl.types import InputChannel
    from telethon.tl.types import ChannelAdminLogEventsFilter
    from telethon.tl.types import InputUserSelf
    from telethon.tl.types import InputUser
    
    # These example values won't work. You must get your own api_id and
    # api_hash from https://my.telegram.org, under API Development.
    api_id = ****** # Your api_id
    api_hash = '********************************' # Your api_hash
    phone_number = '+989122594574' # Your phone number
    
    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('tabe_eshgh')) # Your channel username
    
    user = client(ResolveUsernameRequest('amir2b')) # 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
    # param: (join, leave, invite, ban, unban, kick, unkick, promote, demote, info, settings, pinned, edit, delete)
    filter = ChannelAdminLogEventsFilter(True, True, True, False, False, False, False, False, False, False, False, False, False, False)
    
    result = client(GetAdminLogRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), '', 0, 0, 10, filter, admins))
    ##print(result)
    
    for _user in result.users:
        ##print(_user.id)
        with open(''.join(['users/', str(_user.id)]), 'w') as f:
            f.write(str(_user.id))
    

提交回复
热议问题