【问题标题】:How to send pdf file back to user using python telegram bot?如何使用python电报机器人将pdf文件发送回用户?
【发布时间】:2020-10-08 06:15:48
【问题描述】:

我尝试使用update.sendDocument(chat_id = update.message.chat_id, document = open(something.pdf, 'b')),但它没有返回 pdf 文件。有什么帮助吗?

【问题讨论】:

    标签: python pdf telegram-bot python-telegram-bot sendfile


    【解决方案1】:

    要将文档发送给用户,您必须拥有该文档的file_id

    假设用户将文档发送到bot,而您想发回给用户,这是我的解决方案:

    def file_handler (update, context):
        chat_id = update.message.chat_id
        ## retrieve file_id from document sent by user
        fileID = update.message['document']['file_id']
        context.bot.sendDocument(chat_id = chat_id,
                                 caption = 'This is the file that you've sent to bot',
                                 document = fileID)
    

    def main() 上,您必须添加:

    updater.dispatcher.add_handler(MessageHandler(Filters.document, file_handler))
    

    通过最后一行,您的bot 将了解当用户向其发送一个文档且仅一个文档时,它将调用def file_handler

    【讨论】:

    • OP 没有询问如何处理来自客户端的文件,他询问了如何向客户端发送文件。
    • 恕我直言,完全有效的答案。处理部分是为了说明和做一个完整的例子,连同有效的file_id。
    • 谢谢你,Artem!
    【解决方案2】:

    作为参考,这是一个完整的工作示例,对我有用。 如果它仍然不起作用,请确保您发送的 pdf 文档小于 20 MB 根据https://core.telegram.org/bots/api#sending-files

    #!/usr/bin/python
    import sys
    import time
    import telepot
    import cookie
    from telepot.loop import MessageLoop
    import pdb
    
    def handle(msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        print(content_type, chat_type, chat_id)
        if content_type == 'text' and msg["text"].lower() == "news":
            # let the human know that the pdf is on its way        
            bot.sendMessage(chat_id, "preparing pdf of fresh news, pls wait..")
            file="/home/ubuntu/web/news.pdf"
    
            # send the pdf doc
            bot.sendDocument(chat_id=chat_id, document=open(file, 'rb'))
        elif content_type == 'text':
            bot.sendMessage(chat_id, "sorry, I can only deliver news")
    
    # replace XXXX.. with your token
    TOKEN = 'XXXXXXXXXXXXXXXXXXXX'
    bot = telepot.Bot(TOKEN)
    MessageLoop(bot, handle).run_as_thread()
    print ('Listening ...')
    # Keep the program running.
    while 1:
        time.sleep(10)
    

    【讨论】:

    • 该死的......谢谢伙计。我想知道为什么作者没有给你一个正确的答案。像魅力一样工作。
    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 2017-06-16
    • 2017-12-20
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多