I have a problem about file messages in python telegram bot. How can I receive file and read that file ? Or save it.
Asked
Active
Viewed 1.2k times
9
-
1what did you try? Where is your code? There is [telegram.Voice.get_file](https://python-telegram-bot.readthedocs.io/en/stable/telegram.voice.html#telegram.Voice.get_file) – furas Jun 08 '20 at 03:45
2 Answers
10
You can:
- Register a handler that listens to
Document
- get
File
object from the update (inside the listener usingget_file
) - then simply call
.download()
to download the document
Here a sample code to get you started:
from telegram.ext import Updater, MessageHandler, Filters
BOT_TOKEN = ' ... '
def downloader(update, context):
context.bot.get_file(update.message.document).download()
# writing to a custom file
with open("custom/file.doc", 'wb') as f:
context.bot.get_file(update.message.document).download(out=f)
updater = Updater(BOT_TOKEN, use_context=True)
updater.dispatcher.add_handler(MessageHandler(Filters.document, downloader))
updater.start_polling()
updater.idle()

Tibebes. M
- 6,940
- 5
- 15
- 36
-
-
Yes, but you can pass a custom path. check https://python-telegram-bot.readthedocs.io/en/stable/telegram.file.html?#telegram.File.download – Tibebes. M Jun 08 '20 at 08:15
-
-
yes, pass a writable file handler as `out`. I've updated the answer to show you how to do it – Tibebes. M Jun 08 '20 at 08:59
-
i wrote this:` def file_(update:Update,context:CallbackContext): with open("file.txt","w") as f: context.bot.get_file(update.message.document).download(out=f)` but it didnt write anything in file.txt – DR8002 Jun 08 '20 at 09:09
-
5
Here is some changes for python-telegram-bot v20.
from telegram.ext import Application, MessageHandler, filters
async def downloader(update, context):
file = await context.bot.get_file(update.message.document)
await file.download_to_drive('file_name')
def main() -> None:
application = Application.builder().token('BOT_TOKEN').build()
application.add_handler(MessageHandler(filters.Document.ALL, downloader))
application.run_polling()
if __name__ == '__main__':
main()

jak bin
- 380
- 4
- 8
-
And you can filter by filetype too if needed. Here are the docs: https://docs.python-telegram-bot.org/en/stable/telegram.ext.filters.html – Endogen Jul 26 '23 at 08:41