Created
April 26, 2020 12:59
-
-
Save ohld/9c9cbcfa09020be62a635ae111cf3142 to your computer and use it in GitHub Desktop.
How to send a CSV file with Telegram bot from memory (buffer, StringIO, BytesIO)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv, io | |
test_data = [[1, 2, 3], ["please", "follow", "me"]] | |
# csv module can write data in io.StringIO buffer only | |
s = io.StringIO() | |
csv.writer(s).writerows(test_data) | |
s.seek(0) | |
# python-telegram-bot library can send files only from io.BytesIO buffer | |
# we need to convert StringIO to BytesIO | |
buf = io.BytesIO() | |
# extract csv-string, convert it to bytes and write to buffer | |
buf.write(s.getvalue().encode()) | |
buf.seek(0) | |
# set a filename with file's extension | |
buf.name = f'secret_report_for_cool_guys.csv' | |
# send the buffer as a regular file | |
context.bot.send_document(chat_id=update.message.chat_id, document=buf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment