简体   繁体   中英

I can't send documents in pyTelegramBotAPI

so I'm trying to send a .txt file using pyTelegramBotAPI but it won't work

Error:

Error code: 400. Description: Bad Request: file must be non-empty

code:

@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")

As you see it's impossible for the file to be empty, cuz it won't slip through the if condition in the first place and I also tried to open the file in rb mode

When you did caps.read() you read the file and file object's position went to the end of the file. Then you tried sending same file object caps as a document. I am not 100% sure, but suppose that under the hood bot.send_document() calls read() method of the file object, and it fails with caps file object, because its position is already at the end. To return position to the start you sould call seek(0) method.

And as per examples send_document() expects file object opened in the binary mode.

This code should work:

@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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM