简体   繁体   English

如何使用 Telethon 获取转发消息的频道/聊天/用户名?

[英]How to get channel/chat/user name of forwarded message using Telethon?

I try to get name of channel by channel id:我尝试通过频道 ID 获取频道名称:

result = self._client(GetHistoryRequest(
        entity,
        limit=100,
        offset_date=None,
        offset_id=0,
        max_id=0,
        min_id=last_read_message_id,
        add_offset=0
    ))
for message in result.messages:
    if isinstance(message.fwd_from, MessageFwdHeader):
        fwd_channel_id = message.fwd_from.channel_id
        if fwd_channel_id:
            fwd_result = self._client(GetFullChannelRequest( # problem!!!
                InputPeerChannel(message.fwd_from.channel_id, 0)
            ))

message.fwd_from looks like: message.fwd_from看起来像:

fwd_from=MessageFwdHeader(
  channel_id=1053596007, 
  date=datetime.fromtimestamp(1507891987.0), 
  post_author=None, # None!!!
  from_id=None, 
  channel_post=3030
), 

So, I cant take channel name from message.fwd_from .所以,我不能从message.fwd_from获取频道名称。 And I dont join into this channel.我不加入这个频道。

When I try to call GetFullChannelRequest , I have next error:当我尝试调用GetFullChannelRequest时,出现下一个错误:

ChannelInvalidError(...), 'Invalid channel object. Make sure to pass the right types, for instance making sure that the request is designed for channels or otherwise look for a different one more suited.' ChannelInvalidError(...), '无效通道 object。确保传递正确的类型,例如确保请求是为通道设计的,或者寻找更适合的不同通道。

How to get name of channel properly?如何正确获取频道名称?

Answer here 在这里回答

Example: 例:

result = self._client(GetHistoryRequest(
        entity,
        limit=100,
        offset_date=None,
        offset_id=0,
        max_id=0,
        min_id=last_read_message_id,
        add_offset=0
    ))
for message in result.messages:
    if isinstance(message.fwd_from, MessageFwdHeader):
            entity = self._client.get_input_entity(
                PeerChannel(message.fwd_from.channel_id)
            )
            if message.fwd_from.channel_id:
                fwd_result = self._client(GetFullChannelRequest(entity))
                if hasattr(fwd_result, 'chats') and len(fwd_result.chats) > 0:
                    fwd_title = fwd_result.chats[0].title

In last version telethon you can search it in message object, example from channel name it's上一版telethon可以在消息object中搜索,例如频道名称是

message.forward.chat.title

For user对于用户

message.forward.sender.first_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM