【问题标题】:Using Telethon to download a specific number of messages from a telegram group使用 Telethon 从电报组下载特定数量的消息
【发布时间】:2020-07-14 10:01:19
【问题描述】:

我正在尝试使用 Telethon 关注 this answer 从电报组下载特定数量的消息。我不得不修改代码,因为有多个错误和警告,并且从那时起库及其类也发生了变化。这是我到目前为止所得到的:

import os
import sys
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerChat

session_name = "<session_name>"
api_id = <api_id>
api_hash = "<api_hash>"
chat_id = <chat_id>

os.chdir(sys.path[0])

if f"{session_name}.session" in os.listdir():
    os.remove(f"{session_name}.session")

client = TelegramClient(session_name, api_id, api_hash)
await client.connect()
chat = InputPeerChat(chat_id)


client.get_messages(chat, limit=10)

然而,在 Jupyter 上运行上面的代码我得到了:

我尝试使用for msg in messages 部分来提取/解析信息,但出现错误:

TypeError: 'coroutine' 对象不可迭代

如果您能帮助我了解在给定聊天 ID 的情况下下载电报组中最后一条消息的特定数量的规范且简洁的方法,我将不胜感激。

【问题讨论】:

  • 该类型表明它是一个协程,因此应该等待。你忘了await。另请注意,问题和答案非常古老,我在当前接受的答案中留下了评论。
  • @Lonami 你能详细回答一下吗?
  • @Lonami 恐怕没有公认的答案here

标签: python telegram telethon


【解决方案1】:

只需设置entitiy like从中检索消息历史,无需构造InputPeer对象。

from telethon.sync import TelegramClient

session_name = '<session_name>'
api_id = <api_id>
api_hash = '<api_hash>'

#chat = <chat id>
#chat = <user id>
#chat = 'https://t.me/group_invite_link'
chat = 'me'

client = TelegramClient(session_name, api_id, api_hash)
client.start()

messages = client.get_messages(chat, limit=5)
print(messages)

client.disconnect()

【讨论】:

  • 谢谢哥们!!这是解决我的问题的最佳方法。只是想知道这是什么格式。我需要它在熊猫数据框中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2017-12-05
相关资源
最近更新 更多