Telegram get chat messages /posts - python Telethon

僤鯓⒐⒋嵵緔 提交于 2020-04-10 18:45:07

问题


I am using Telethon and Python 3.6xx

Been able to retreive message from groups, no problem but when it comes to channels I am stuck.

dialogs = client(get_dialogs)
for chat in dialogs.chats:
   getmessage = client.get_messages(chat.id, limit=400)
   for message in getmessage:
        print(message.message)

I've searched the telethon documentation but most answers were in response to the old get_message_history.

When I'm trying with the following chat.id = 1097988869 (news.bitcoin.com) I'm getting an error below (for groups the chat.id works fine):

PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type


回答1:


you can use this code for get messages :

client = TelegramClient('session_name',
                    api_id,
                    api_hash,
                    update_workers=1,
                    spawn_read_thread=False)
assert client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone_number)
    me = client.sign_in(phone_number, input('Enter code: '))

channel_username='tehrandb' # your channel
channel_entity=client.get_entity(channel_username)
posts = client(GetHistoryRequest(
    peer=channel_entity,
    limit=100,
    offset_date=None,
    offset_id=0,
    max_id=0,
    min_id=0,
    add_offset=0,
    hash=0))
# messages stored in `posts.messages`



回答2:


The accepted answer is good, but recent versions of Telethon let you achieve the same more easily. This will iterate over all messages in chat:

from telethon.sync import TelegramClient

with TelegramClient(name, api_id, api_hash) as client:
    for message in client.iter_messages(chat):
        print(message.sender_id, ':', message.text)

Where the variables should be obvious, for example (note these API values won't work, you need your own):

name = 'anon'
api_id = 123
api_hash = 'abcdefgh'
chat = 'me'


来源:https://stackoverflow.com/questions/50975793/telegram-get-chat-messages-posts-python-telethon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!