Andy
Andy

Reputation: 541

Naming File When Using Download_Media in Telethon

I am scraping new images received in a Telegram channel using Telethon. My code works ok (it scrapes messages and download files using the preset naming convention) but I cannot seem to set my own filename for the downloaded images. When I add the file_name argument I get an error.

The docs suggest it is possible to set a name for downloaded media but I get the error below.

What am I doing wrong?

Code:

@client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
    new_message = event.message.message
    print(new_message)
    print()

    file_name = "new_image.jpg"

    if event.message.photo:
        await event.download_media(new_message, file_name)
        print("New image received")

with client:
    client.run_until_disconnected()

Traceback:

Unhandled exception on newMessageListener

Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\client\updates.py", line 454, in _dispatch_update
    await callback(event)
  File "C:/Users/PycharmProjects/TamTelegram/ps_Scrapev1.py", line 27, in newMessageListener
    await event.download_media(new_message, file_name)
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\tl\custom\message.py", line 837, in download_media
    return await self._client.download_media(self, *args, **kwargs)
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\sync.py", line 34, in syncified
    coro = method(*args, **kwargs)
TypeError: download_media() takes from 2 to 3 positional arguments but 4 were given

Upvotes: 3

Views: 1883

Answers (1)

Enmanuel Verdesia
Enmanuel Verdesia

Reputation: 617

As mentioned in the documentation, a NewMessage event can be considered as a normal Message, so can be invoked on it the download_media method, a shorthand for TelegramClient.download_media with the message argument already set to the message of the event. This means if you call event.download_media the only positional argument to pass is the file where to save the data.

Your code should look like this:

@client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
    file_name = "new_image.jpg"

    if event.photo:
        # shorthand for client.download_media(event.message, file_name)
        await event.download_media(file_name)
        print("New image received")

with client:
    client.run_until_disconnected()

Upvotes: 1

Related Questions