Telegram Bot how to use the sendDocument

7.6k Views Asked by At

i can't send *.txt file which is located in the app directory:
i have file in /app and i want to send it with sendDocument method,

  • telepot lib case:
file = open('report.txt', 'w')
file.write('report')
file.close()

telepot_bot.sendDocument(os.environ['ADMIN0'], document=file, caption='report.txt')
# or
telepot_bot.sendDocument(os.environ['ADMIN0'], document=file.name, caption='report.txt')
# or
telepot_bot.sendDocument(os.environ['ADMIN0'], document=os.path.realpath(file.name), caption='report.txt')

return:

ValueError: I/O operation on closed file.
# or
telepot.exception.TelegramError: ('Bad Request: wrong file identifier/HTTP URL specified', 400, {'ok': False, 'error_code': 400, 'description': 'Bad Request: wrong file identifier/HTTP URL specified'})
# or
telepot.exception.TelegramError: ('Bad Request: URL host is empty', 400, {'ok': False, 'error_code': 400, 'description': 'Bad Request: URL host is empty'})

  • python-telegram-bot lib case:
context.bot.send_document(os.environ['ADMIN0'], document=file, filename='report.txt')
# or
context.bot.send_document(os.environ['ADMIN0'], document=file.name, filename='report.txt')
# or
context.bot.send_document(os.environ['ADMIN0'], document=os.path.realpath(file.name), filename='report.txt')

return:

ValueError: I/O operation on closed file.
# or
telegram.error.BadRequest: Wrong file identifier/http url specified
# or
telegram.error.BadRequest: Url host is empty

manual says:
"...upload a new one using multipart/form-data. Lastly you can pass an existing :class: telegram.Document object to send."
but how i should do it ?

1

There are 1 best solutions below

3
On

check if the file exist in current working directory.

the actual code to send a file:

with open("report.txt", "rb") as file:
    context.bot.send_document(chat_id=1234, document=file,  
          filename='this_is_for_tg_name.txt')

refer the correct format of using send_document here