簡體   English   中英

我無法在 pyTelegramBotAPI 中發送文檔

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM