skip to Main Content

I was trying to upload pdf files to telegram bot with python but it is not working. Where is my mistake?

def textbooks(update,context):
    path = r"C:UsersYa'weDownloadsPython Practice Book (en)(1).pdf"

    with open(os.path.join(os.path.dirname(__file__), path), 'r') as input_file:
        content = input_file.read()
    chat_id=update.effective_chat.id
    return context.bot.send_document(chat_id, input_file)

2

Answers


  1. I see several issues in your code snippets:

    1. path is already an absolute Path, so joining it with the current directory will give an invalid path
    2. the file should be opened as 'rb' rather than 'r'
    3. You read the files content into the content variable, but never use that variable
    4. the call to bot.send_message happens outside the context manager (with open(…)), so input_file is a closed file on that line and the contents can’t be read by PTB.

    Please also have a look at PTBs wiki section on sending files.

    Moreover, I’d like to point you to both SOs and PTBs guides on how to ask good questions – see here and here. Specifically, when asking questions it’s helpful if you were more precise about what’s actually happening when you use the code snippet you’re having questions about, e.g. by showing the traceback of the resulting exception.


    Disclaimer: I’m currently the maintainer of python-telegram-bot

    Login or Signup to reply.
  2. this might help https://github.com/python-telegram-bot/python-telegram-bot/wiki/Working-with-Files-and-Media

    Referring to the above link if you change your code as below it should work.

    def textbooks(update,context):
        path = r"C:UsersYa'weDownloadsPython Practice Book (en)(1).pdf"
        chat_id=update.effective_chat.id
        return context.bot.send_document(chat_id,document=open(os.path.join(os.path.dirname(__file__), path), 'rb'))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search