使用电报API阅读公共频道文本

时间:2019-11-01 19:56:59

标签: python-3.x telegram channel telethon

我想创建一个小脚本,该脚本将从公共频道(我不是该频道的管理员)中获取电报文本。

我在这里发现了另一个问题: Read the messages of the public channels from Telegram
我已经尝试按照答案中的说明使用Telethon,但是没有用:

from telethon.tl.functions.contacts import ResolveUsernameRequest
import telethon

client = telethon.TelegramClient("session.txt", api_id=XYZ, api_hash='XYZ')
client.connect()
response = client.invoke(ResolveUsernameRequest("test"))
print(response.channel_id)
print(response.access_hash)

引发此错误:

C:/Users/mypc/PycharmProjects/untitled/aa.py:5: RuntimeWarning: coroutine 'TelegramBaseClient.connect' was never awaited
  client.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "C:/Users/mypc/PycharmProjects/untitled/aa.py", line 6, in <module>
    response = client.invoke(ResolveUsernameRequest("test"))
AttributeError: 'TelegramClient' object has no attribute 'invoke'

我尝试阅读API文档,但我不完全了解这些调用的工作原理:

  

https://core.telegram.org/method/channels.exportMessageLink

     

https://core.telegram.org/method/channels.joinChannel

     

https://core.telegram.org/method/channels.getMessages

如果有人能向我解释这些工作原理,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

那个答案很老了。如果我们选中Telethon's Quick-Start,我们将有足够的代码来满足您的需求:

from telethon import TelegramClient

# Remember to use your own values from my.telegram.org!
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)

async def main():
    # You can print the message history of any chat:
    async for message in client.iter_messages('USERNAME OF THE CHANNEL'):
        print(message.sender.username, message.text)

with client:
    client.loop.run_until_complete(main())

答案 1 :(得分:0)

就像它说的那样,TelegramClient没有invoke方法。您尝试过client(ResolveUsernameRequest("test"))吗?