首页 > 解决方案 > Telegram Telethon:如果您知道频道哈希,如何获取消息

问题描述

当我必须处理这种链接时:https ://t.me/channelName 我通常会从这样的频道收到消息:

async def main():
    channel = await client.get_entity('channelName') 
    messages = await client.get_messages(channel, limit = N ) 

#...Code etc..

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

如果您的链接是这样的,您如何收到消息? https://t.me/joinchat/DDDDDxxxxAAAA

我知道'DDDDDxxxxAAAA'是channel_hash,所以我通过电报客户端加入了频道并尝试获取频道ID和消息对象:

channel_hash = "DDDDDxxxxAAAA"
channel = await client(functions.messages.CheckChatInviteRequest(hash=channel_hash))

现在,频道对象包含频道 ID 和许多其他字段。例如:(chat=Channel(id=123456789,...etcc 所以,我试过这样:

messages = await client.get_messages(channel, limit = N ) 

但它返回:

Traceback (most recent call last):
  File "C:\Users\****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telethon\sessions\memory.py", line 192, in get_input_entity
    return utils.get_input_peer(key)
  File "C:\Users\****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telethon\utils.py", line 235, in get_input_peer
    _raise_cast_fail(entity, 'InputPeer')
  File "C:\Users\****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telethon\utils.py", line 138, in _raise_cast_fail
    raise TypeError('Cannot cast {} to any kind of {}.'.format(
TypeError: Cannot cast ChatInviteAlready to any kind of InputPeer.
TypeError: Cannot cast ChatInviteAlready to any kind of InputPeer.

如果您只知道频道哈希,如何获取消息?感谢帮助

标签: pythonchattypeerrortelegramtelethon

解决方案


推荐阅读