Danila1909
@Danila1909

Пишу бота для телеграма на питоне(aiogram). В консоли всё работает, а сам бот не запускается, и выдаёт ошибку, что делать?

Когда запускаю код - бот не работает, не реагирует на сообщения. Пишу с помощью модуля aiogram. Вот сам код:
код бота
import requests
import datetime
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor

open_weather_token = '46810340e86556ada5f7df13115cd3e5'
tg_bot_token = '5504520376:AAGnbqACeu1odTu0wEVceJUZBgwD_blQvPc'

bot = Bot(token=tg_bot_token)
dp = Dispatcher(bot)

@dp.message_handler(commands=["start"])
async def start_command(message: types.Message):
    await message.reply("Привет!\uF44B Напиши название города, и я отправлю тебе сводку погоды!\uF4AF")

@dp.message_handler()
async def get_weather(message: types.Message):
    code_to_smile = {
        "Clear": "Ясно\u2600",
        "Clouds": "Облачно\u2601",
        "Rain": "Дождь\u2614",
        "Drizzle": "Дождь\u2614",
        "Thundestorm": "Гроза\u26A1",
        "Snow": "Снег\uF328",
        "Mist": "Туман\uF32B"
    }

    try:
        r = requests.get(
            f"http://api.openweathermap.org/data/2.5/weather?q={message.text}&appid={open_weather_token}&units=metric"
        )
        data = r.json()
        city = data['name']
        cur_weather = data['main']['temp']

        weather_description = data["weather"][0]["main"]
        if weather_description in code_to_smile:
            wd = code_to_smile[weather_description]
        else:
            wd = "Посмотри в окно, не совсем понятно что там\uF97A"

        humidity = data['main']['humidity']
        pressure = data['main']['pressure']
        wind = data['wind']['speed']

        await message.reply(f"---{datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}---\n"
              f"Погода в городе {city}:\nТемпература: {cur_weather}°C, {wd}\n"
              f"Влажность: {humidity}%\nДавление: {pressure} мм.рт.ст\n"
              f"Скорость ветра: {wind} м/с\n"
              )
    except:
        await message.reply('\uF628Проверьте название города!\uF628')
if __name__ == "__main__":
    executor.start_polling(dp)


А вот текст выдаваемой ошибки:
текст ошибки
Traceback (most recent call last):
  File "D:\python\lib\site-packages\aiohttp\connector.py", line 986, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
  File "D:\python\lib\asyncio\base_events.py", line 1064, in create_connection
    raise exceptions[0]
  File "D:\python\lib\asyncio\base_events.py", line 1049, in create_connection
    sock = await self._connect_sock(
  File "D:\python\lib\asyncio\base_events.py", line 960, in _connect_sock
    await self.sock_connect(sock, address)
  File "D:\python\lib\asyncio\proactor_events.py", line 705, in sock_connect
    return await self._proactor.connect(sock, address)
  File "D:\python\lib\asyncio\windows_events.py", line 817, in _poll
    value = callback(transferred, key, ov)
  File "D:\python\lib\asyncio\windows_events.py", line 604, in finish_connect
    ov.getresult()
OSError: [WinError 121] Превышен таймаут семафора

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

Traceback (most recent call last):
  File "D:\python\lib\site-packages\aiogram\bot\api.py", line 139, in make_request
    async with session.post(url, data=req, **kwargs) as response:
  File "D:\python\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "D:\python\lib\site-packages\aiohttp\client.py", line 535, in _request
    conn = await self._connector.connect(
  File "D:\python\lib\site-packages\aiohttp\connector.py", line 542, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "D:\python\lib\site-packages\aiohttp\connector.py", line 907, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "D:\python\lib\site-packages\aiohttp\connector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "D:\python\lib\site-packages\aiohttp\connector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "D:\python\lib\site-packages\aiohttp\connector.py", line 992, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Превышен таймаут семафора]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\python\WorldWeatherBot\world_weather_bot.py", line 59, in <module>
    executor.start_polling(dp)
  File "D:\python\lib\site-packages\aiogram\utils\executor.py", line 45, in start_polling
    executor.start_polling(
  File "D:\python\lib\site-packages\aiogram\utils\executor.py", line 320, in start_polling
    loop.run_until_complete(self._startup_polling())
  File "D:\python\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "D:\python\lib\site-packages\aiogram\utils\executor.py", line 372, in _startup_polling
    await self._welcome()
  File "D:\python\lib\site-packages\aiogram\utils\executor.py", line 361, in _welcome
    user = await self.dispatcher.bot.me
  File "D:\python\lib\site-packages\aiogram\bot\bot.py", line 30, in me
    setattr(self, '_me', await self.get_me())
  File "D:\python\lib\site-packages\aiogram\bot\bot.py", line 233, in get_me
    result = await self.request(api.Methods.GET_ME, payload)
  File "D:\python\lib\site-packages\aiogram\bot\base.py", line 231, in request
    return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
  File "D:\python\lib\site-packages\aiogram\bot\api.py", line 142, in make_request
    raise exceptions.NetworkError(f"aiohttp client throws an error: {e.__class__.__name__}: {e}")
aiogram.utils.exceptions.NetworkError: Aiohttp client throws an error: ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Превышен таймаут семафора]
  • Вопрос задан
  • 1166 просмотров
Пригласить эксперта
Ответы на вопрос 1
senku1435
@senku1435
py aiogram develop, c# mid
Игнорируем ошибку

if isinstance(exception, OSError):
            IGNORE_ERRNO = {
                10038,  # operation on non-socket on Windows, likely because fd == -1
                121,    # the semaphore timeout period has expired on Windows
            }

            FORCE_CLOSE_ERRNO = {
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Похожие вопросы