[英]I can't send documents in pyTelegramBotAPI
所以我正在嘗試使用pyTelegramBotAPI
發送一個.txt
文件,但它不起作用
錯誤:
Error code: 400. Description: Bad Request: file must be non-empty
代碼:
@bot.message_handler(commands=["CAPTURED"])
def sendcaps(message):
if "captured.txt" in os.listdir():
caps=open("captured.txt","r")
if caps.read() != "":
bot.send_document(chat_id=message.chat.id,document=caps)
else:
bot.reply_to(message,"None")
如您所見,文件不可能為空,因為它不會首先通過if condition
,我還嘗試以rb
模式打開文件
當您caps.read()
時,您讀取了文件並且文件對象的位置到達了文件的末尾。 然后您嘗試將相同的文件對象caps
作為文檔發送。 我不是 100% 確定,但假設在引擎蓋下bot.send_document()
調用文件對象的read()
方法,並且它失敗並返回caps
文件對象,因為它的位置已經在末尾。 要將位置返回到開始位置,您可以調用seek(0)
方法。
並且根據示例send_document()
期望以二進制模式打開的文件對象。
此代碼應該工作:
@bot.message_handler(commands=["CAPTURED"])
def sendcaps(message):
if "captured.txt" in os.listdir():
with open("captured.txt", "rb") as caps:
if len(caps.read()) > 0:
# Return file object's position to the start.
caps.seek(0)
bot.send_document(chat_id=message.chat.id,document=caps)
else:
bot.reply_to(message,"None")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.