Search code examples
pythonparsingtelegramtelethon

How to parse this result


I want to get the id and first_name of a user using the GetContactsRequest method from the Telethon library so that I can send a message using that id without having to hard code the id of every contact I have. This is the code

from telethon.sync import TelegramClient
from telethon import functions, types

with TelegramClient('session', api_id, api_hash) as client:
    result = client(functions.contacts.GetContactsRequest(
        hash=0
    ))
    print(result.stringify())

This is the output of result.stringify()

Contacts(
    contacts=[
        Contact()
        Contact()
    ]
    users=[
        User(
            id = xxx
            first_name = 'name'
        ),
        User(
            id = xxx
            first_name = 'name'
        )
    ]
)

The problem is I am not sure how to parse this, Any help would be really appreciated


Solution

  • You can refer the documentation for Contacts here. Basically, all you need to do is iterate over the users and access id for each user.

    for user in result.users:
        print (user.id, user.first_name)