24

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

stop-cran
  • 4,229
  • 2
  • 30
  • 47
AbeeCrombie
  • 597
  • 1
  • 5
  • 22

3 Answers3

42

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 (for this example we use telethon.sync to avoid typing out async):

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'

More examples using async are available in client.iter_messages documentation.

Lonami
  • 5,945
  • 2
  • 20
  • 38
  • This works with `Telethon==1.10.8` while the accepted answer raises an exception because `posts` no longer has an attribute `messages`. – Elias Strehle Nov 12 '19 at 10:46
  • 1
    @EliasStrehle `posts` still should have a `messages`, but maybe it's just missing the `await` call. – Lonami Nov 12 '19 at 10:56
  • Is there a shortcut to forwarding all messages from a chat? I am trying to forward all messages from a chat, starting from oldest and going to newest – Philippe Feb 27 '20 at 08:51
  • @Lonami how to get messages from channel or group. It says `ValueError: No user has "xxx" as username` – Gray Programmerz Apr 08 '21 at 07:52
29

update :

in the new version of Telethon, @Lonami answer is best and use it.

############################################################

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`
Alihossein shahabi
  • 4,034
  • 2
  • 33
  • 53
  • 3
    Thank you Ali! just for anyone else who is a beginner like me, you can access the text of the channel message by adding `for message in posts.messages: print(message.message) ` – AbeeCrombie Jun 22 '18 at 14:58
  • 9
    You forgot `from telethon.tl.functions.messages import GetHistoryRequest` – Lonami Jan 20 '19 at 16:28
  • 4
    Note for other people coming here, in newer versions of Telethon, the library is async and this code will fail. It is necessary to properly await everything or `import telethon.sync`. – Lonami Mar 10 '20 at 19:11
  • 1
    Not every megagroup has a username, in my case it is None, how do you do this in that case? – Ilya Pukhov Oct 06 '21 at 11:33
  • 1
    Also, can you please share how do you get around the 100 messages limit? – Ilya Pukhov Oct 06 '21 at 12:19
4

that work for me!

api_hash from https://my.telegram.org, under API Development.

from telethon import TelegramClient, events, sync

api_id = 'your api_id'
api_hash = 'your api_hash'

client = TelegramClient('session_name', api_id, api_hash)
client.start()
channel_username = 'username'# your channel
for message in client.get_messages(channel_username, limit=10):
    print(message.message)
Mad Javad
  • 494
  • 4
  • 5