Danya02
Danya02

Reputation: 1386

How to receive file_id through python-telegram-bot?

I'm making a Telegram bot using python-telegram-bot, and I need some way to receive voice messages. For that, I need to download them, and to do that, I have to get their file_ids. However, the MessageHandler handles... well, messages, and Handler gives me a NotImplementedError. Is there a way to get the file_id?

Upvotes: 5

Views: 12135

Answers (4)

Tiago Costa
Tiago Costa

Reputation: 21

I'll show you an example with a photo file, but it works for any file (you'll just need to change the parameters)

from telegram.ext import Updater, CommandHandler
from telegram.ext.callbackcontext import CallbackContext
from telegram.update import Update

def start (update: Update, context: CallbackContext):

    # getting chat_id:
    chatID = update.effective_chat.id

    # sending the photo to discover its file_id:
    photo1 = context.bot.send_photo(chat_id=chatID, photo=open('photo1.jpg','rb'))
    photo1_fileID = photo1.photo[-1].file_id
    context.bot.send_message(chat_id=update.effective_chat.id, text=('file_id photo1.jpg = ' + photo1_fileID))

def main():
    updater = Updater(token='TOKEN', use_context=True)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler('start', start))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Upvotes: 2

AKMalkadi
AKMalkadi

Reputation: 982

In version 13+, you need to use update.message.voice.file_id instead of update.message.audio.file_id. So the code will be:

def voice_handler(update: Update, context: CallbackContext):
    file = context.bot.getFile(update.message.voice.file_id)
    file.download('./voice.ogg')

Upvotes: 2

Elad
Elad

Reputation: 971

I know this question is old but I was facing a problem with this in the latest version (12+)

So it appears that the bot- pass_user_data in the callback function is deprecated and from now on you should use context based callbacks.

CallbackContext is an object that contains all the extra context information regarding an Update, error or Job.

to the new style using CallbackContext:

def voice_handler(update: Update, context: CallbackContext):
    file = context.bot.getFile(update.message.audio.file_id)
    file.download('./voice.ogg')

You can read more in the Transition-guide-to-Version-12.0

Upvotes: 7

Sadık
Sadık

Reputation: 4419

The easiest way to download voice messages is to register a MessageHandler with a voice filter. The Docs provide more information on Filters and the voice module.

import telegram
from telegram.ext import Updater

def voice_handler(bot, update):
    file = bot.getFile(update.message.voice.file_id)
    print ("file_id: " + str(update.message.voice.file_id))
    file.download('voice.ogg')

updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.voice, voice_handler))

Upvotes: 4

Related Questions