Вопрос Бот тг не отправляет картинку

Начинающий
Статус
Оффлайн
Регистрация
10 Апр 2022
Сообщения
85
Реакции[?]
8
Поинты[?]
4K
есть такой код
Код:
@router.message(CommandStart())
async def cmd_help(message: Message,state : FSMContext):
    await state.clear()
    file_path = "app/other/image.jpg"
    await message.reply_photo(
        photo = FSInputFile(
            path=file_path
        )
    )
если использую для запуска python main.py, все запускается, но я хочу собрать его в exeшник, прописываю
Код:
 pyinstaller --onefile --add-data "C:\Users\Админ\Desktop\tgbot\app\other\tgbotinok.dll;." --add-data "C:\Users\Админ\Desktop\tgbot\app\image.jpg;." -F -i "C:\Users\Админ\Desktop\tgbot\icon.ico" main.py
и начинает вылетать ошибка
Код:
TelegramNetworkError: HTTP Client says - ClientOSError: [Errno 2] Can not write request body for https://api.telegram.org/ bottoken:)/sendPhoto Traceback (most recent call last): File "aiohttp\client_reqrep.py", line 637, in write_bytes File "aiohttp\multipart.py", line 993, in write File "aiohttp\payload.py", line 442, in write File "aiogram\types\input_file.py", line 103, in read File "aiofiles\base.py", line 98, in aenter File "aiofiles\threadpool_init_.py", line 94, in _open File "concurrent\futures\thread.py", line 58, in run FileNotFoundError: [Errno 2] No such file or directory: 'app/other/image.jpg'

        The above exception was the direct cause of the following exception:

            Traceback (most recent call last):
        File "aiogram\client\session\aiohttp.py", line 181, in make_request
        File "aiohttp\client.py", line 1353, in __aenter__
    File "aiohttp\client.py", line 684, in _request
       File "aiohttp\client_reqrep.py", line 999, in start
    File "aiohttp\streams.py", line 640, in read
      aiohttp.client_exceptions.ClientOSError: [Errno 2] Can not write request body for bottoken:)                /sendPhoto

         During handling of the above exception, another exception occurred:

     Traceback (most recent call last):
  File "aiogram\dispatcher\dispatcher.py", line 309, in _process_update
           File "aiogram\dispatcher\dispatcher.py", line 158, in feed_update
        File "aiogram\dispatcher\middlewares\error.py", line 25, in __call__
       File "aiogram\dispatcher\middlewares\user_context.py", line 56, in __call__
         File "aiogram\fsm\middleware.py", line 42, in __call__
    File "aiogram\dispatcher\event\telegram.py", line 121, in trigger
            File "aiogram\dispatcher\event\handler.py", line 43, in call
        File "aiogram\dispatcher\dispatcher.py", line 276, in _listen_update
        File "aiogram\dispatcher\router.py", line 146, in propagate_event
       File "aiogram\dispatcher\router.py", line 141, in _wrapped
      File "aiogram\dispatcher\router.py", line 174, in _propagate_event
        File "aiogram\dispatcher\router.py", line 146, in propagate_event
 File "aiogram\dispatcher\router.py", line 141, in _wrapped
   File "aiogram\dispatcher\router.py", line 166, in _propagate_event
       File "aiogram\dispatcher\event\telegram.py", line 121, in trigger
        File "aiogram\dispatcher\event\handler.py", line 43, in call
      File "app\handlers.py", line 35, in cmd_help
          File "aiogram\methods\base.py", line 84, in emit
       File "aiogram\client\bot.py", line 488, in __call__
        File "aiogram\client\session\base.py", line 254, in __call__
        File "aiogram\client\session\aiohttp.py", line 188, in make_request
     aiogram.exceptions.TelegramNetworkError: HTTP Client says - ClientOSError: [Errno 2] Can       not write request body for https://api.telegram.org/bottoken:) /sendPhoto
 
Эксперт
Статус
Оффлайн
Регистрация
9 Апр 2020
Сообщения
1,446
Реакции[?]
675
Поинты[?]
34K
Конечно не чисто фото, а в принципе файлы, но как вариант
Код:
Bot.send_document(chat_id = Message.ChatID, document = open(Path, "rb"))
 
Начинающий
Статус
Оффлайн
Регистрация
10 Апр 2022
Сообщения
85
Реакции[?]
8
Поинты[?]
4K
Конечно не чисто фото, а в принципе файлы, но как вариант
Код:
Bot.send_document(chat_id = Message.ChatID, document = open(Path, "rb"))
не, так вообще никаким макаром не отправляет
Код:
    file_path = "app/other/image.jpg"
    await message.bot.send_document(chat_id = message.chat.id, document = open(file_path, "rb"))
Код:
  Input should be an instance of InputFile [type=is_instance_of, input_value=<_io.BufferedReader name='app/other/image.jpg'>, input_type=BufferedReader]
    For further information visit https://errors.pydantic.dev/2.7/v/is_instance_of
document.str
  Input should be a valid string [type=string_type, input_value=<_io.BufferedReader name='app/other/image.jpg'>, input_type=BufferedReader]
    For further information visit https://errors.pydantic.dev/2.7/v/string_type
 
Главный модератор
Главный Модератор
Статус
Оффлайн
Регистрация
13 Фев 2018
Сообщения
1,099
Реакции[?]
806
Поинты[?]
151K
не, так вообще никаким макаром не отправляет
Код:
    file_path = "app/other/image.jpg"
    await message.bot.send_document(chat_id = message.chat.id, document = open(file_path, "rb"))
Код:
  Input should be an instance of InputFile [type=is_instance_of, input_value=<_io.BufferedReader name='app/other/image.jpg'>, input_type=BufferedReader]
    For further information visit https://errors.pydantic.dev/2.7/v/is_instance_of
document.str
  Input should be a valid string [type=string_type, input_value=<_io.BufferedReader name='app/other/image.jpg'>, input_type=BufferedReader]
    For further information visit https://errors.pydantic.dev/2.7/v/string_type
В стеке тебе же всё написали.
+ зачем ты используешь конструкцию message.bot.send_document, когда в классе Message УЖЕ есть враппер для этой же функции в лице message.answer_document?
Python:
await message.answer_document(document = types.InputFile("app/other/image.jpg"))
 
Начинающий
Статус
Оффлайн
Регистрация
10 Апр 2022
Сообщения
85
Реакции[?]
8
Поинты[?]
4K
В стеке тебе же всё написали.
+ зачем ты используешь конструкцию message.bot.send_document, когда в классе Message УЖЕ есть враппер для этой же функции в лице message.answer_document?
Python:
await message.answer_document(document = types.InputFile("app/other/image.jpg"))
вылазит такая говна:roflanBuldiga:
Код:
TypeError: Can't instantiate abstract class InputFile without an implementation for abstract method 'read'
Traceback (most recent call last):
  File "aiogram\dispatcher\dispatcher.py", line 309, in _process_update
  File "aiogram\dispatcher\dispatcher.py", line 158, in feed_update
  File "aiogram\dispatcher\middlewares\error.py", line 25, in __call__
  File "aiogram\dispatcher\middlewares\user_context.py", line 56, in __call__
  File "aiogram\fsm\middleware.py", line 42, in __call__
  File "aiogram\dispatcher\event\telegram.py", line 121, in trigger
  File "aiogram\dispatcher\event\handler.py", line 43, in call
  File "aiogram\dispatcher\dispatcher.py", line 276, in _listen_update
  File "aiogram\dispatcher\router.py", line 146, in propagate_event
  File "aiogram\dispatcher\router.py", line 141, in _wrapped
  File "aiogram\dispatcher\router.py", line 174, in _propagate_event
  File "aiogram\dispatcher\router.py", line 146, in propagate_event
  File "aiogram\dispatcher\router.py", line 141, in _wrapped
  File "aiogram\dispatcher\router.py", line 166, in _propagate_event
  File "aiogram\dispatcher\event\telegram.py", line 121, in trigger
  File "aiogram\dispatcher\event\handler.py", line 43, in call
  File "app\handlers.py", line 40, in cmd_help
TypeError: Can't instantiate abstract class InputFile without an implementation for abstract method 'read'
В стеке тебе же всё написали.
+ зачем ты используешь конструкцию message.bot.send_document, когда в классе Message УЖЕ есть враппер для этой же функции в лице message.answer_document?
Python:
await message.answer_document(document = types.InputFile("app/other/image.jpg"))
может проблема в pyinstaller?
на всякий:
как запускаю:
Код:
 pyinstaller main.spec
main.spec:

Код:
# -*- mode: python ; coding: utf-8 -*-

a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=[('C:\\Users\\Админ\\Desktop\\tgbot\\app\\other\\tgbotinok.dll', '.'),
           ('C:\\Users\\Админ\\Desktop\\tgbot\\app\\other\\image.jpg', '.')],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
    optimize=0,
)


pyz = PYZ(a.pure)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.datas,
    [],
    name='main',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon=['C:\\Users\\Админ\\Desktop\\tgbot\\icon.ico'],
)
 
Начинающий
Статус
Оффлайн
Регистрация
10 Апр 2022
Сообщения
85
Реакции[?]
8
Поинты[?]
4K
есть такой код
Код:
@router.message(CommandStart())
async def cmd_help(message: Message,state : FSMContext):
    await state.clear()
    file_path = "app/other/image.jpg"
    await message.reply_photo(
        photo = FSInputFile(
            path=file_path
        )
    )
если использую для запуска python main.py, все запускается, но я хочу собрать его в exeшник, прописываю
Код:
 pyinstaller --onefile --add-data "C:\Users\Админ\Desktop\tgbot\app\other\tgbotinok.dll;." --add-data "C:\Users\Админ\Desktop\tgbot\app\image.jpg;." -F -i "C:\Users\Админ\Desktop\tgbot\icon.ico" main.py
и начинает вылетать ошибка
Код:
TelegramNetworkError: HTTP Client says - ClientOSError: [Errno 2] Can not write request body for https://api.telegram.org/ bottoken:)/sendPhoto Traceback (most recent call last): File "aiohttp\client_reqrep.py", line 637, in write_bytes File "aiohttp\multipart.py", line 993, in write File "aiohttp\payload.py", line 442, in write File "aiogram\types\input_file.py", line 103, in read File "aiofiles\base.py", line 98, in aenter File "aiofiles\threadpool_init_.py", line 94, in _open File "concurrent\futures\thread.py", line 58, in run FileNotFoundError: [Errno 2] No such file or directory: 'app/other/image.jpg'

        The above exception was the direct cause of the following exception:

            Traceback (most recent call last):
        File "aiogram\client\session\aiohttp.py", line 181, in make_request
        File "aiohttp\client.py", line 1353, in __aenter__
    File "aiohttp\client.py", line 684, in _request
       File "aiohttp\client_reqrep.py", line 999, in start
    File "aiohttp\streams.py", line 640, in read
      aiohttp.client_exceptions.ClientOSError: [Errno 2] Can not write request body for bottoken:)                /sendPhoto

         During handling of the above exception, another exception occurred:

     Traceback (most recent call last):
  File "aiogram\dispatcher\dispatcher.py", line 309, in _process_update
           File "aiogram\dispatcher\dispatcher.py", line 158, in feed_update
        File "aiogram\dispatcher\middlewares\error.py", line 25, in __call__
       File "aiogram\dispatcher\middlewares\user_context.py", line 56, in __call__
         File "aiogram\fsm\middleware.py", line 42, in __call__
    File "aiogram\dispatcher\event\telegram.py", line 121, in trigger
            File "aiogram\dispatcher\event\handler.py", line 43, in call
        File "aiogram\dispatcher\dispatcher.py", line 276, in _listen_update
        File "aiogram\dispatcher\router.py", line 146, in propagate_event
       File "aiogram\dispatcher\router.py", line 141, in _wrapped
      File "aiogram\dispatcher\router.py", line 174, in _propagate_event
        File "aiogram\dispatcher\router.py", line 146, in propagate_event
File "aiogram\dispatcher\router.py", line 141, in _wrapped
   File "aiogram\dispatcher\router.py", line 166, in _propagate_event
       File "aiogram\dispatcher\event\telegram.py", line 121, in trigger
        File "aiogram\dispatcher\event\handler.py", line 43, in call
      File "app\handlers.py", line 35, in cmd_help
          File "aiogram\methods\base.py", line 84, in emit
       File "aiogram\client\bot.py", line 488, in __call__
        File "aiogram\client\session\base.py", line 254, in __call__
        File "aiogram\client\session\aiohttp.py", line 188, in make_request
     aiogram.exceptions.TelegramNetworkError: HTTP Client says - ClientOSError: [Errno 2] Can       not write request body for https://api.telegram.org/bottoken:) /sendPhoto
решение:

отправка:
Код:
    file_path = "image.jpg"

    await message.answer_photo(photo=FSInputFile(await resource_path(file_path)))
дополненительная функция:
Код:
import os,sys

async def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)
main.spec:
Код:
a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=[('C:\\Users\\Админ\\Desktop\\tgbot\\app\\other\\tgbotinok.dll', '.'),
           ('C:\\Users\\Админ\\Desktop\\tgbot\\app\\other\\image.jpg', '.')],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
    optimize=0,
)
 
Начинающий
Статус
Оффлайн
Регистрация
12 Июн 2022
Сообщения
40
Реакции[?]
4
Поинты[?]
4K
photo_path = 'путь'
with open(photo_path, 'rb') as photo:
bot.send_photo(message.chat.id, photo,
caption='''`сообщение к фото''',
reply_markup=markup, parse_mode="Markdown")
 
Сверху Снизу