如何在电报机器人中接收文件,处理它并将其发送回用户?

How to receive a file in telegram bot, process it and send it back to user?

我需要从用户那里得到一个文件,下载它,传递给一个函数来处理它,然后将它发回给用户。

我已经多次阅读文档,但我仍然不明白如何获得 file_id 并使用它。

这是我试过的回显代码。它显示 TypeError: 'NoneType' object is not subscriptable on the fileID line.

    update.message.reply_text('give a file')
    chat_id = update.message.chat_id
    fileID = update.message['document']['file_id']
    context.bot.sendDocument(chat_id = chat_id,
                             caption = 'This is the file that you have sent to bot',
                             document = fileID)

Receive your file like this::

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("filename", '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()

--现在像这样发回文件:

   import requests
    files= { 'file' : open('filepath','rb')}
    
    resp = requests.post('https://api/telegram.org/bot<<token>>/sendfile?chat_id=<>',files=files)
    
    #check response 
    print(resp.status_code)