[英]Using Telethon to download a specific number of messages from a telegram group
I'm trying to follow this answer using Telethon to download a specific number of messages from a telegram group.我正在尝试使用 Telethon 遵循此答案从电报组下载特定数量的消息。 I had to modify the code because there were multiple errors and warnings and the library and its classes had also changed since then.
我不得不修改代码,因为有多个错误和警告,而且库及其类从那时起也发生了变化。 This is what I have got so far:
这是我到目前为止所得到的:
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)
however, running the above code on Jupyter I just get:然而,在 Jupyter 上运行上面的代码我得到了:
<coroutine object MessageMethods.get_messages at 0x1049c8cb0>
<协程对象 MessageMethods.get_messages 在 0x1049c8cb0>
I tried to use the for msg in messages
part to extract/parse the information, but I get the error:我尝试
for msg in messages
部分使用for msg in messages
来提取/解析信息,但出现错误:
TypeError: 'coroutine' object is not iterable
类型错误:“协程”对象不可迭代
I would appreciate if you could help me know what is the canonical and concise way to download the specific number of last messages in a telegram group given the chat ID.如果您能帮助我知道在给定聊天 ID 的情况下下载电报组中特定数量的最后一条消息的规范和简洁的方法是什么,我将不胜感激。
Just set the entitiy like from whom to retrieve the message history and no need to construct InputPeer object.刚刚成立像从他们检索的消息记录,不需要构造InputPeer对象entitiy。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.