如何通过 python-telegram-bot 接收 file_id?

How to receive file_id through python-telegram-bot?

我正在使用 python-telegram-bot 制作 Telegram 机器人,我需要某种方式来接收语音消息。为此,我需要下载它们,然后 that,我必须得到它们的 file_ids。但是,MessageHandler 处理...好吧,消息,Handler 给了我一个 NotImplementedError。有没有办法得到 file_id?

下载语音消息的最简单方法是使用语音过滤器注册 MessageHandler。文档提供了有关 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))

我知道这个问题很老,但我在最新版本 (12+) 中遇到了这个问题

看来回调函数中的 bot- pass_user_data 已弃用,从现在开始您应该使用基于上下文的回调。

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

使用 CallbackContext 的新样式:

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

您可以在 Transition-guide-to-Version-12.0

中阅读更多内容

在版本 13+ 中,您需要使用 update.message.voice.file_id 而不是 update.message.音频.file_id。所以代码将是:

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

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()