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
I see several issues in your code snippets:
path
is already an absolute Path, so joining it with the current directory will give an invalid path'rb'
rather than'r'
content
variable, but never use that variablebot.send_message
happens outside the context manager (with open(…)
), soinput_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
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.