簡體   English   中英

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

[英]How to receive file_id through python-telegram-bot?

我正在使用python-telegram-bot制作電報機器人,我需要某種方式來接收語音消息。 為此,我需要下載它們,為此,我必須獲取它們的file_id 但是, MessageHandler處理......好吧,消息,而Handler給了我一個NotImplementedError 有沒有辦法獲得file_id

我知道這個問題很老,但我在最新版本 (12+) 中遇到了這個問題

因此,回調函數中的 botpass_user_data 似乎棄用,從現在開始您應該使用基於上下文的回調。

CallbackContext 是一個對象,它包含有關更新、錯誤或作業的所有額外上下文信息。

使用 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 中閱讀更多內容

下載語音消息的最簡單方法是使用語音過濾器注冊 MessageHandler。 文檔提供了有關過濾器語音模塊的更多信息。

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

在 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')

我將向您展示一個帶有照片文件的示例,但它適用於任何文件(您只需要更改參數)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM