Привет, у меня проблема, написал код и ошибка, код должен при срабатывании генерировать ответ и отправлять его, а он не делает этого. Так как работаю с disnake то функция ассинхронная, ну ты крч понял да:


async def check_alarms(file_path):

    while True:
        time.sleep(30)
        # Получаем текущее время
        now = datetime.datetime.now()
        current_time = now.strftime("%H:%M %d.%m.%Y")

        # Читаем файл clock.json
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                alarms = json.load(file, strict=False)
        except FileNotFoundError:
            print(f"Файл {file_path} не найден.")
            return
        except json.JSONDecodeError:
            print(f"Ошибка при чтении файла {file_path}. Проверьте формат JSON.")
            return

        if current_time in alarms:
            print(f"Будильник сработал! Время: {current_time}")
            json__a = alarms[current_time]
            print(f"Содержимое: {alarms[current_time]}")
            # Начинаем наше шоу
            user_name = bot.get_user(int(json__a['id']))
            message__a = f"Будильник: {json__a['name']} ты завела для пользователя {user_name.display_name} напиши то что задумывала написать!"
            chats["global"].append({"role": "user", "content": message__a})

            memory = ""
            memory_json = []
            for mem in json.load(open("memory.json", "r", encoding="utf-8"))["memory"]:
                memory += f" - {mem}\n"
                memory_json.append(mem)

            days_memory = ""
            for day_mem in json.load(open("days_memoty.json", "r", encoding="utf-8"))["memory"]:
                days_memory += f"{day_mem['day']}: {day_mem['message']}\n"

            formatted_datetime = datetime.datetime.now().strftime("%H:%M %d:%m:%Y")
            new_history = [{"role": "system", "content": induction.format(user_name.display_name,"недоступен", "недоступен", memory, formatted_datetime, days_memory)}] + chats["global"]
            # for messag in new_history:
            #     if messag["role"] == "user":
            #         print(f"{messag['role']}: {messag['content'][0]}")
            #     else:
            #         print(f"{messag['role']}: {messag['content']}")
            response = ""
            global_response = ""
            print("Генерация ответа...")
            try:
                stream = client.chat.completions.create(
                    model=model,
                    messages=new_history,
                    temperature=tempertature,
                    stream=True
                )
                print("Генерация ответа... 1")
                for chunk in stream:
                    text_chunk = chunk.choices[0].delta.content or ""
                    response += text_chunk
                    global_response += text_chunk

                print("Генерация ответа... Завершено")
            except Exception as e:
                attempt = 0
                while True:
                    attempt += 1
                    print(f"ошибка генерации {e}... Попытка перегенерации {attempt}")
                    time.sleep(5)
                    if response == "":
                        response = chat(new_history)
                    else:
                        break

                    if attempt > 5:
                        response = f"Не смогу сгенерировать ответ. Попробуйте позже. {e}"
                        break

                global_response = response

            # response = await generative_image(response)

            sendnd = False



            ne_clock, clock_sjon = parse_clock(response)
            if clock_sjon is not None:
                response = ne_clock
                with open("clock.json", "r", encoding="utf-8") as f:
                    json_a = json.load(f)
                with open("clock.json", "w", encoding="utf-8") as f:
                    json_a[clock_sjon["time"]] = {"id": clock_sjon["id"], "type": clock_sjon["type"],
                                                  "name": clock_sjon["name"]}
                    json.dump(json_a, f, ensure_ascii=False, indent=4)

            await user_name.send(response)


            del alarms[current_time]
            with open(file_path, 'w') as file:
                json.dump(alarms, file, indent=2)
        else:
            print(f"{current_time} нету")



def start_clock():
    asyncio.run(check_alarms("clock.json"))

threading.Thread(target=start_clock).start()

We have logged in as Лия#6200
Будильник сработал! Время: 18:04 30.09.2024
Содержимое: {'id': '670548556624429066', 'type': 'ls', 'name': 'Сказать доброе утро'}
Генерация ответа...
Генерация ответа... 1
Генерация ответа... Завершено
Exception in thread Thread-2 (start_clock):
Traceback (most recent call last):
  File "C:\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
    self.run()
  File "C:\Python312\Lib\threading.py", line 1010, in run
    self._target(*self._args, **self._kwargs)
  File "E:\Projects\ai.remeow.ru\discord\main.py", line 795, in start_clock
    asyncio.run(check_alarms("clock.json"))
  File "C:\Python312\Lib\asyncio\runners.py", line 194, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Python312\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python312\Lib\asyncio\base_events.py", line 685, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "E:\Projects\ai.remeow.ru\discord\main.py", line 783, in check_alarms
    await user_name.send(response)
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\disnake\abc.py", line 1649, in send
    channel = await self._get_channel()
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\disnake\user.py", line 476, in _get_channel
    ch = await self.create_dm()
         ^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\disnake\user.py", line 518, in create_dm
    data: DMChannelPayload = await state.http.start_private_message(self.id)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\disnake\http.py", line 338, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\aiohttp\client.py", line 1194, in __aenter__
    self._resp = await self._coro
                 ^^^^^^^^^^^^^^^^
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\aiohttp\client.py", line 504, in _request
    with timer:
  File "E:\Projects\ai.remeow.ru\.venv\Lib\site-packages\aiohttp\helpers.py", line 715, in __enter__
    raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task