【问题标题】:Read public channel texts using Telegram API使用 Telegram API 阅读公共频道文本
【发布时间】:2020-02-28 02:26:56
【问题描述】:

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

我在这里发现了另一个问题: 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

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

【问题讨论】:

  • client.invoke(request) 是旧方法。您需要使用client(request)

标签: python-3.x telegram channel telethon


【解决方案1】:

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

【讨论】:

  • 注意invoke 是旧的做法会更有帮助,请参阅解释完整API如何完成的页面。此外,还有一种友好的方法是更好的选择。
  • 公平。我不知道这是旧的做法,因为我对 Telethon 还是很陌生
【解决方案2】:

那个答案很老了。如果我们检查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())

【讨论】:

  • 但是,您如何连接您的机器人来收听公共频道消息?您的代码没有回答问题。
  • 代码很好地回答了问题(“从公共频道获取文本”)。主动监听传入消息是一个不同的问题。
猜你喜欢
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 2018-06-11
  • 2018-02-17
  • 2016-07-14
  • 2016-04-04
相关资源
最近更新 更多