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