How to get usernames of message senders from telegram chats. Now I can get only user id from the code below
channel_entity=client.get_entity(group_title)
posts = client(GetHistoryRequest(
peer=channel_entity,
limit=limit_msg,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
post_msg = posts.messages
# save the results
all_msg = []
for m in post_msg:
print(m.from_id.user_id) #Here I get user id, but I need user name
GetHistoryRequest
is an old way of receiving such messages. I took this answer as an example for the new style.
That said, you'll need to use m.from_id
to get the complete use, in which the name will be available:
for x in messages:
participants = await client.get_participants(x.from_id)
for p in participants:
print(p.username, p.first_name)
This will show a list of usernames and first names of the sender
Full code I've used to get a list of user names of one of my groups:
import asyncio
from telethon import TelegramClient
from telethon.tl import functions, types
client = TelegramClient('anon', '12345', '12345678901234567890')
client.start()
async def main():
channel = await client.get_entity(-123456789)
messages = await client.get_messages(channel, limit=100)
for x in messages:
participants = await client.get_participants(x.from_id)
for p in participants:
print(p.username, p.first_name)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())