@bond_1013
Начинающий веб-разработчик

Как отправить файл через бота в телеграмм?

Как можно отправлять файл с расширение боту, у меня при отправке приходит просто документ с названием document, в документации посмотрел https://core.telegram.org/bots/api#senddocument , но ничего не нашел(возможно пропустил что-то). Подскажите как отправлять файл с именем и расширением.
import config
import telebot
name_bot="бот"
bot = telebot.TeleBot(config.token)
@bot.message_handler(commands=['marksSYAP'])
def send_welcome(message):
    with open("D:\\MarksSYAP.xlsx","rb") as misc:
        f=misc.read()
    bot.send_document(message.chat.id,f)
  • Вопрос задан
  • 47017 просмотров
Решения вопроса 2
leahch
@leahch
3Д специалист. Долго, Дорого, Дерьмово.
Добавьтке параметр filename=“myfile.doc”
Вот описание всех атртбутов
Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target channel (in the format @channelusername).
            document (:obj:`str` | `filelike object` | :class:`telegram.Document`): File to send.
                Pass a file_id as String to send a file that exists on the Telegram servers
                (recommended), pass an HTTP URL as a String for Telegram to get a file from the
                Internet, or upload a new one using multipart/form-data. Lastly you can pass
                an existing :class:`telegram.Document` object to send.
            filename (:obj:`str`, optional): File name that shows in telegram message (it is useful
                when you send file generated by temp module, for example). Undocumented.
            caption (:obj:`str`, optional): Document caption (may also be used when resending
                documents by file_id), 0-1024 characters.
            parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
                show bold, italic, fixed-width text or inline URLs in the media caption. See the
                constants in :class:`telegram.ParseMode` for the available modes.
            disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
                receive a notification with no sound.
            reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
                original message.
            reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
                JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
                to remove reply keyboard or to force a reply from the user.
            thumb (`filelike object`, optional): Thumbnail of the
                file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
                A thumbnail's width and height should not exceed 90. Ignored if the file is not
                is passed as a string or file_id.
            timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.
        Returns:
            :class:`telegram.Message`: On success, the sent Message is returned
Ответ написан
@sunrise912812
Отправляй сам файл а не его бинарное значение,
Когда бинарно отправляешь бот имя файла и разрешение не видит поэтому вставляет по умолчанию 'document'.

f = open("D:\\MarksSYAP.xlsx","rb")
bot.send_document(message.chat.id,f)
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 4
alexhouse
@alexhouse
Full Stack Web Developer Python and Django
Рабочий вариант

import requests

with open("MarksSYAP.xlsx", "rb") as filexlsx:
    files = {"document":filexlsx}
    title = "MarksSYAP.xlsx"
    chat_id = "1234567890"
    r = requests.post(method, data={"chat_id":chat_id, "caption":title}, files=files)
    if r.status_code != 200:
        raise Exception("send error")
Ответ написан
@LimerBoy
from io import BytesIO

with open(file, 'rb') as tmp:
    obj = BytesIO(tmp.read())
    obj.name = '1.txt'
    bot.send_document(message.from_user.id, data=obj, caption='your file')
Ответ написан
Комментировать
@rogoz
Отправлять нужно файл, но файл может быть "файлом":
file_obj = io.BytesIO(your_bin_data)
file_obj.name = "MarksSYAP.xlsx"
bot.send_document(message.chat.id,file_obj)
Ответ написан
@khadjiru666
автор, решил проблему?
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы