如何从电报聊天中获取消息发件人的用户名

How to get usenames of message senders from telegram chat

如何从电报聊天中获取消息发件人的用户名。现在我只能从下面的代码中获取用户 ID

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 是一种接收此类消息的旧方法。我以this answer作为新样式的示例。


也就是说,您需要使用 m.from_id 才能获得完整的用法,其中名称将可用:

for x in messages:
    participants = await client.get_participants(x.from_id)
    for p in participants:
        print(p.username, p.first_name)

这将显示发件人的用户名和名字列表


我用来获取我的一个组的用户名列表的完整代码:

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())