AkiRa_py
@AkiRa_py
Начинающий web-разработчик, балуюсь с python и c#

Не работает (не запускается) telegram bot на aiogram 3?

Зашёл на сайт aiogram с документацией и скопировал код ниже для того чтобы посмотреть как работает бот на aiogram 3 (вместо "BOT_TOKEN" разумеется вставил токен своего бота)
import asyncio
import logging
import sys
from os import getenv

from aiogram import Bot, Dispatcher, Router, types
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from aiogram.utils.markdown import hbold

# Bot token can be obtained via https://t.me/BotFather
TOKEN = getenv("BOT_TOKEN")

# All handlers should be attached to the Router (or Dispatcher)
dp = Dispatcher()


@dp.message(CommandStart())
async def command_start_handler(message: Message) -> None:
    """
    This handler receives messages with `/start` command
    """
    # Most event objects have aliases for API methods that can be called in events' context
    # For example if you want to answer to incoming message you can use `message.answer(...)` alias
    # and the target chat will be passed to :ref:`aiogram.methods.send_message.SendMessage`
    # method automatically or call API method directly via
    # Bot instance: `bot.send_message(chat_id=message.chat.id, ...)`
    await message.answer(f"Hello, {hbold(message.from_user.full_name)}!")


@dp.message()
async def echo_handler(message: types.Message) -> None:
    """
    Handler will forward receive a message back to the sender

    By default, message handler will handle all message types (like a text, photo, sticker etc.)
    """
    try:
        # Send a copy of the received message
        await message.send_copy(chat_id=message.chat.id)
    except TypeError:
        # But not all the types is supported to be copied so need to handle it
        await message.answer("Nice try!")


async def main() -> None:
    # Initialize Bot instance with a default parse mode which will be passed to all API calls
    bot = Bot(TOKEN, parse_mode=ParseMode.HTML)
    # And the run events dispatching
    await dp.start_polling(bot)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    asyncio.run(main())

При запуске получаю такие ошибки в консоли
C:\Users\Akira\PycharmProjects\TelegramBot\.venv\Scripts\python.exe C:\Users\Akira\PycharmProjects\TelegramBot\main.py 
Traceback (most recent call last):
  File "C:\Users\Akira\PycharmProjects\TelegramBot\main.py", line 56, in <module>
    asyncio.run(main())
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 649, in run_until_complete
    return future.result()
  File "C:\Users\Akira\PycharmProjects\TelegramBot\main.py", line 49, in main
    bot = Bot(TOKEN, parse_mode=ParseMode.HTML)
  File "C:\Users\Akira\PycharmProjects\TelegramBot\.venv\lib\site-packages\aiogram\client\bot.py", line 267, in __init__
    validate_token(token)
  File "C:\Users\Akira\PycharmProjects\TelegramBot\.venv\lib\site-packages\aiogram\utils\token.py", line 17, in validate_token
    raise TokenValidationError(
aiogram.utils.token.TokenValidationError: Token is invalid! It must be 'str' type instead of <class 'NoneType'> type.

Process finished with exit code 1

Может я чего-то не догоняю, в первый раз использую aiogram в принципе.
  • Вопрос задан
  • 490 просмотров
Решения вопроса 1
@Everything_is_bad
aiogram.utils.token.TokenValidationError: Token is invalid! It must be 'str' type instead of type.
твой getenv("BOT_TOKEN") вернул None

вместо "BOT_TOKEN" разумеется вставил токен своего бота
разумеется это не нужно делать, нужно в переменных окружения завести BOT_TOKEN со значением токена своего бота
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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