简体   繁体   English

我无法在 pyTelegramBotAPI 中发送文档

[英]I can't send documents in pyTelegramBotAPI

so I'm trying to send a .txt file using pyTelegramBotAPI but it won't work所以我正在尝试使用pyTelegramBotAPI发送一个.txt文件,但它不起作用

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如您所见,文件不可能为空,因为它不会首先通过if condition ,我还尝试以rb模式打开文件

When you did caps.read() you read the file and file object's position went to the end of the file.当您caps.read()时,您读取了文件并且文件对象的位置到达了文件的末尾。 Then you tried sending same file object caps as a document.然后您尝试将相同的文件对象caps作为文档发送。 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.我不是 100% 确定,但假设在引擎盖下bot.send_document()调用文件对象的read()方法,并且它失败并返回caps文件对象,因为它的位置已经在末尾。 To return position to the start you sould call seek(0) method.要将位置返回到开始位置,您可以调用seek(0)方法。

And as per examples send_document() expects file object opened in the binary mode.并且根据示例send_document()期望以二进制模式打开的文件对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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