Hello. The principle is clear only with images, but how to take a random file from a folder, send it to the user and then delete the same file from the folder?

Telegram bot, used by pyTelegramBotAPI (python) Thanks in advance

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky ♦

2 answers 2

GitHub has great file transfer examples. For text files, the send_document method is send_document :

 # sendDocument doc = open('/tmp/file.txt', 'rb') tb.send_document(chat_id, doc) tb.send_document(chat_id, "FILEID") 

Delete files using the standard os.remove () :

 os.remove('/tmp/file.txt') 
  • Thank you, but it is unclear how to take a random file, and delete it after sending. - stow

In order to send a random file and delete it, all you need is to connect the library random, and use an approximately similar method:

 all_files_in_directory = os.listdir(directory) file = random.choice(all_files_in_directory) doc = open(directory + '/' + file, 'rb') bot.send_document(message.from_user.id, doc) os.remove(directory + '/' + file)