问题描述
情况。
我需要创建内存中的csv文件并将其发送到bot。
根据这份article和bot文档,我假设我可以发送csv文件。区别:我使用另一个api包装器:telebot。根据文档,它还允许发送二进制文件。
所以我正在尝试像这样测试:
def test_buf():
import csv
import io
test_data = [[1,2,3],["a","b","c"]]
# 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 = 'test_data.csv'
return buf
然后
csv_output = test_buf()
bot.send_document(chat_id,csv_output,caption='Caption_text')
"ApiTelegramException occurred,args=("A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: can't parse entities: Can't find end of the entity starting at byte offset 7",)
我做错了什么?也许我不完全了解BytesIO和二进制格式之间的区别?如果不同,如何将bytesio转换为内存中的二进制,以便我可以发送数据
现在,我可以发送文件,但不需要远程机器人库:
requests.post(f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendDocument',data={"chat_id": chat_id,"caption": 'caption_text'},files={'document': csv_output})
所以我不明白图书馆有什么问题。就像我确定自己只是不懂一些基本知识一样。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)