Skip to content

Instantly share code, notes, and snippets.

@ohld
Created April 26, 2020 12:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ohld/9c9cbcfa09020be62a635ae111cf3142 to your computer and use it in GitHub Desktop.
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)
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